text:
Q: PropertyInfo SetValue doesn't set the Id of my object I'm trying to make a function that allows me to map one class to another one. It's almost working, except that my Id property is not being mapped and I can't figure out why.
At the bottom there is a link to a coding example online, press F8 to run it.
In the output you can see how the following code shows me the Id:
if(propertyInfo.Name == "Id")
    Console.WriteLine(propertyInfo.GetValue(currentEUser));

But when I try users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age)));, There are no Id's available. Why?
public class eUser
{
    public int Id {get;set;}
    public String Name {get;set;}
    public int Age {get { return 10;}}

    public eUser(int id, String name){
        Id = id;
        Name = name;
    }
}

public class User
{
    public int Id {get;set;}
    public String Name {get;set;}
    public int Age {get { return 10;}}
}

I have my main program that should map all my fields from an eUser to a User object
public class Program
{

    public static void Main(string[] args)
    {
        // init
        List<User> users = new List<User>();
        User user = new User();

        List<eUser> eUsers = new List<eUser>();
        eUsers.Add(new eUser(1, "Joris"));
        eUsers.Add(new eUser(2, "Thierry"));
        eUsers.Add(new eUser(3, "Bert"));

        IList<PropertyInfo> eUserProps = new List<PropertyInfo>(eUsers.FirstOrDefault().GetType().GetProperties());
        foreach(eUser currentEUser in eUsers){

            foreach (PropertyInfo propertyInfo in eUserProps)
            {
                // Test to only map properties with a Set field
                if (propertyInfo.CanWrite)
                {
                    // Test to see if Id comes through
                    if(propertyInfo.Name == "Id")
                        Console.WriteLine(propertyInfo.GetValue(currentEUser));

                    // Create new user
                    user = new User();

                    //Map eUser to User object
                    typeof(User)
                        .GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField)
                        .SetValue(user, propertyInfo.GetValue(currentEUser));
                }

            }
            users.Add(user);

        }

        users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age)));
    }
}

Code example: http://rextester.com/SHNY15243

A: Move user = new User(); to outside of the 2nd foreach loop.


text:
Q: Node http module - get request body when intercepting http.request function I'm writing an internal logger that intercepts Node's http module by overriding the request method.
This is what I have so far:
const http = require('http');

const oldHttpRequest = http.request;
http.request = (options, callback) => {
    const newCallback = (res) => {
        // Do logging logic here

        return callback(res);
    }

    return oldHttpRequest(options, newCallback);
};

From options and res objects I'm able to retrieve everything I need (method, path, request headers, response headers, response body, etc..).
Everything but the outgoing request body.
What am I missing?

A: Managed to do it, posting the solution if anyone is interested.
I ended up having to monkey patch the write method as well:
const http = require('http');

const oldHttpRequest = http.request;

http.request = (options, callback) => {
    const requestBodyChunks = [];
    const newCallback = (res) => {
        // Do logging logic here
        console.log('Request body:', requestBodyChunks.join())

        return callback(res);
    }

    const clientRequest = oldHttpRequest(options, newCallback);
    const oldWrite = clientRequest.write.bind(clientRequest);

    clientRequest.write = (data: any) => {
        requestBodyChunks.push(data.toString());
        return oldWrite(data);
    };

    return clientRequest;
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I extend a redstone signal along a line while powering everything below it? I need to power everything below the redstone's path, but placing a repeater leads to the block below not being powered. How could I solve that without using a repeater to skip a block?

A: At the 13th block of redstone, place one redstone piece to the side, place one repeater in front of it, and reconnect it at the 15th block of redstone, like so. (triangle is a repeater)

Unfortunately, this only works if you don't want to be able to turn it off again. If that's required, more resources are needed.

This requires a second line alongside the first one which applies power every 15 blocks (this can be extended to 29 blocks if the redstone power level doesn't matter, as power is applied in both directions).


text:
Q: Show trend arrows while displaying a dataframe I have a Pandas dataframe that is displayed like this in html:
df = pd.DataFrame([
    [54, 21, 30, 12, '20-01-2002'],
    [52, 26, 31, 2, '22-01-2002'],
    [50, 16, 11, 15, '223-01-2002']
], columns=['A', 'B', 'C', 'D', 'date']).transpose()

When rendering the dataframe as HTML, I need to display a trend icon (up or down arrow )on the first column  comparing it to the values in the 2nd column so the final html is rendered something like this:

First I thought it would be as easy as adding a span tag with the arrow to the  dataframe.
▲


text:
Q: BMGlyphJustifyLeft doesn't seem to be working fine in Swift (SpriteKit) I'm creating a Swift (SpriteKit) game where I have my score. I'm using BMGlyph Library and Software to add a custom font/label to my game.
Here's how i create the entire bmglyph label & font:
let bestScoreFont = BMGlyphFont(name: "scorefont_small_gold")
self.bestScoreLabel = BMGlyphLabel.init(text: "best 0", font: bestScoreFont)
self.bestScoreLabel.zPosition = ZIndexPosition.HUD
self.bestScoreLabel.position = CGPoint(x: 70, y: self.FRAME_HEIGHT - 20)
self.bestScoreLabel.textJustify = BMGlyphJustifyLeft

Now, this label as you may see, it's being placed on the left-upper corner.
The problem is, that if the player does a huge score or whatever the score is, the label moves to the left as the text grows instead of remaining aligned left and growing right. I don't know if I'm explaining myself correctly.
Tested with different values on the score, and the longer it gets, the deeper it goes through the left side of the screen.
For instance, i tested adding a huge value like 123123123123123. This is how it looks:

Horrible, right? haha.
Anyways, does anyone know how to solve this? and make it stick in the same place left-aligned?
Thanks in advance.

A: Okay, looks like I found a way to do it with BMGlyph. Although there's a registered issue as @Alessandro Ornano told me.
There are 2 attributes to set alignment in BMGlyph.
1) textJustify
2) horizontalAlignment & verticalAlignment
The one it works is the 2nd. And by placing BMGlyphHorizontalAlignmentLeft as a value. Tested BMGlyphHorizontalAlignmentRight and works as well.


text:
Q: URL in anchor tag not working right I'm hosting 2 domains on a single shared hosting account.
Let's say I have 2 domains xyz.com and abc.com
The contents of abc.com are placed in public_html/abc.com directory.
In my index.php of the domain abc.com I.e.
in public_html/abc.com/index.php
I'm using an anchor tag.
Click here
but when I click "Click here" I am redirected to www.abc.com/https://plus.google.com/u/0/01010101010?rel=author
How do I remove www.abc.com from www.abc.com/https://plus.google.com/u/0/01010101010?rel=author

A: Single quotes work well.

 Click here


text:
Q: How do I shrink the content of this iFrame? I need to have a webpage where 6 cams are displayed on one webpage. I can do this with iframes, but the content of the iframes are still fullscreen. How can I shrink them to fit the iFrame window?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Spycam</title>
</head>

<body>
<iframe src="(ip adress here)"
width="640px" height="480px">

</iframe>
</body>
</html>

A: You're not going to be able to control the contents of the iframe, only the iframe itself.  If the contents of the iframes are content that you control (i.e. can edit the HTML/CSS), then you can change the videos on the pages themselves.


text:
Q: Implement GUI in Function in Java I wrote a function that takes image_id as input from the user and displays that image to the GUI.
But the problem is that I cannot link my GUI to my function:

*

*My function is working.

*I can create my GUI using the GUI Builder (and I will want to add more components to it)

Any ideas for the way to make this work?
Thanks in advance.
public class SI  extends MainMenu {

     BufferedImage image=null ;

       final JPanel panel = new JPanel(){
            @Override
            protected void paintComponent(Graphics g){
                Graphics g2 = g.create();
                g2.drawImage(image, 3, 0,560,815,null);
                g2.dispose();
            }

            @Override
            public Dimension getPreferredSize(){
                return new Dimension(image.getWidth(), image.getHeight());
            }
       };

     public void  ImageReader(String image_id) throws IOException {
     {
        ////// To Read Tiff File /////////////////
         MainMenu mm= new MainMenu();
         mm.MainMenu();

         String TifFileReadPath="C:/BILAL/SearchImage/"+image_id+".TIF";
         File inputFile = new File(TifFileReadPath);

         image= ImageIO.read(inputFile);
         JFrame2.add(panel);
     }
     }

     public static void main(String[] args) throws IOException {
       SI si = new SI ();
       //String input = getTextfield().getText();

      MainMenu m = new MainMenu();
      String input= m.GetTextFiled();

      si.ImageReader(input);
     }
}


text:
Q: counting how many checkbox are checked php/html Hi I am new with php and I was wondering how am i able to count how many 'checkbox' are checked once I click on submit.
For example:
<input type = "checkbox" value = "box" name = "checkbox1"/>
<input type = "checkbox" value = "box" name = "checkbox2"/>
<input type = "checkbox" value = "box" name = "checkbox3"/>

A: Give the checkboxes names as array like
<input type = "checkbox" value = "box" name = "checkbox[]"/>

And after submit try like
$checked_arr = $_POST['checkbox'];
$count = count($checked_arr);
echo "There are ".$count." checkboxe(s) are checked";

Note : And based on the method that your form submit using...whether it is $_GET or $_POST you need to use $_POST['checkbox'] for POST method and $_GET['checkbox'] for the GET method.

A: $checkedBoxes = 0;

// Depending on the action, you set in the form, you have to either choose $_GET or $_POST
if(isset($_GET["checkbox1"])){
  $checkedBoxes++;
}
if(isset($_GET["checkbox2"])){
  $checkedBoxes++;
}
if(isset($_GET["checkbox3"])){
  $checkedBoxes++;
}

A: <input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>

to check which boxes have been checked simply traverse through the chk[]
array like this:
$chk_array = $_POST['checkbox'];

for($chk_array as $chk_key => $chk_value)
{
print 'Checkbox Id:'. $chk_key . ' Value:'. $chk_value .'is
checked';
}

A: You have to rename the names and add values
<input type = "checkbox" value = "box" name = "checkbox[]" value="1"/>
<input type = "checkbox" value = "box" name = "checkbox[]" value="2"/>
<input type = "checkbox" value = "box" name = "checkbox[]" value="3"/>

This way you will know not only number (which you don't actually need)
echo count($_POST['checkbox']);

but also have the actual selected values:
foreach($_POST['checkbox'] as $val)
{
    echo "$val<br>\n";
}

A: Using jQuery you can achieve it:
$("input:checkbox:checked").length
This will return the number of checboxes checked.
And in php you'll need to pass it as an array.
echo count($_POST['checkbox']);

A: You can set names for the checkboxes as an array:
<input type = "checkbox" value = "box" name = "checkbox[1]"/>
<input type = "checkbox" value = "box" name = "checkbox[2]"/>
<input type = "checkbox" value = "box" name = "checkbox[3]"/>

and then you will have an array in PHP ($_POST['checkbox']):
echo count( $_POST['checkbox'] ); // this will give you the count

otherwise you can iterate over each one of them and increment a variable:
$counter = 0;
foreach( array('checkbox1', 'checkbox2', 'checkbox3') as $name ) {
  if( isset( $_POST[ $name ] ) {
     $counter++
  }
}
echo $counter;

A: All boxes that are checked will be in the Request when u click submit.
In your case, if checkbox1 is checked u get:
"checkbox1=box"
If you use GET as the method it will look like: http://yoururl.com/yourcode.php?checkbox1=box and u can access it with $_GET['checkbox1']
If you use POST as the method you can access it with $_POST['checkbox1']
You can also check if the box is checked (and in the Request data) with isset($_POST['checkbox1'])


text:
Q: Deploying Projects on EC2 vs. Windows Azure I've been working with Windows Azure and Amazon Web Services EC2 for a good many months now (almost getting to the years range) and I've seen something over and over that seems troubling.
When I deploy a .NET build into Windows Azure into a web role (or service role) it takes usually 6-15 minute for it to startup.  In AWS's EC2 it takes about the same to startup the image and then a minute or two to deploy the app to IIS (pending of course its setup).
However when I boot up an AWS instance with SUSE Linux & Mono to run .NET, I get one of these booted and deploy code to it in about 2-3 minutes (again, pending it is setup).
What is going on with Windows OS images that cause them to take soooo long to boot up in the cloud?  I don't want FUD, I'm curious about the specific details of what goes on that causes this.  Any specific technical information regarding this would be greatly appreciated! Thanks.

A: I don't think the EC2 behavior is specific to the cloud. Just compare boot times of Windows and Linux on a local system - in my experience, Linux just boots faster. Typically, this is because the number of services/demons launched is smaller, as is the number of disk accesses that each of them needs to make during startup.
As for Azure launch times: it's difficult to tell, and not comparable to machine boots (IMO). Nobody knows what Azure does when launching an application. It might be that they need to assemble the VM image first, or that a lot of logging/reporting happens that slows down things.

A: As announced at PDC, Azure will soon start to offer full IIS on Azure web roles. Somewhere in the keynote demo by Don Box, he showed that this allows you to use the standard "publish" options in Visual Studio to deploy to the cloud very quickly.
If I recall correctly, part of what happens when starting a new Azure role is configuring the network components, and I remember some speaker at a conference mentioning once that that was very time consuming. This might explain why adding additional instances to an already running role is usually faster (but not always: I have seen this take much more than 15 minutes as well on ocassion).
Edit: also see this PDC session.

A: Don't forget, there is a Fabric controller that needs to check for fault zones and deploy your VMs across multiple fault zones (to give you high availability, at least when there are more than two instances). I can't say for sure, but that logic itself might take some extra time. This might also explain why network setup could be a little complicated.
This will of course explain the difference (if any) between boot times in the cloud and boot times for windows locally or in Amazon. Any difference in operating systems is completely dependent on the way the OS is built!


text:
Q: Textview not changing appearance when using clickablespan I have the following spantext which is set to portion of a TextView.
 I have confirmed that the TextView is receiving the onClick input perfectly but the TextView is not changing it's background color until I either click the span a bunch of times (It varies) or scroll the recyclerview both in and out of view, but not too far because than it resets.
How can I get the TextViewin the recyclerview to update immediately after the first click?
public class SpoilerSpan extends ClickableSpan {
    private boolean clicked = false;

    @Override
    public void onClick(View widget) {
        clicked = true;
        Log.d("Span", "Spoilerspan click registered")
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        if (!clicked){
            ds.setColor(Color.argb(255, 00, 00, 00)); //FF000000
            ds.bgColor = Color.argb(255, 00, 00, 00); //FF000000
            ds.setUnderlineText(false);
        }
    }
}

A: Turns out it was really simple to fix
public class SpoilerSpan extends ClickableSpan {
    private boolean clicked = false;

    @Override
    public void onClick(View widget) {
        clicked = true;
        widget.invalidate();
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        if (!clicked){
            ds.setColor(Color.argb(255, 00, 00, 00)); //FF000000
            ds.bgColor = Color.argb(255, 00, 00, 00); //FF000000
            ds.setUnderlineText(false);
        }
    }
}


text:
Q: cannot ssh to guest from host using Qemu I am using Ubuntu 18.04.2 in both host and guest machine. I have created the virtual machine using libvirt. During VM creation I did not establish ssh from host to guest using libvirt. I am trying to run VM with following Qemu command. I added the hostfwd in the command to ssh to guest. I have set up the ssh server in guest. But I cannot connect to guest from host using ssh. How can I solve the issue?
sudo qemu-system-x86_64 \
    -enable-kvm \
    -name guest=ubuntu18.04_VM_libvirt,debug-threads=on \
    -S \
    -machine pc-i440fx-bionic,accel=kvm,usb=off,vmport=off,dump-guest-core=off \
    -cpu Broadwell-noTSX-IBRS \
    -m 4096 \
    -realtime mlock=off \
    -smp 6,sockets=6,cores=1,threads=1 \
    -uuid ec642fe5-8e5c-4d4a-ada7-b8562396d477 \
    -no-user-config \
    -nodefaults \
    -chardev socket,id=charmonitor,path=/home/probir/Downloads/qemu_with_libvirt/monitor.sock,server,nowait \
    -mon chardev=charmonitor,id=monitor,mode=control \
    -rtc base=utc,driftfix=slew \
    -global kvm-pit.lost_tick_policy=delay \
    -no-hpet \
    -no-shutdown \
    -global PIIX4_PM.disable_s3=1 \
    -global PIIX4_PM.disable_s4=1 \
    -boot strict=on \
    -device ich9-usb-ehci1,id=usb,bus=pci.0,addr=0x5.0x7 \
    -device ich9-usb-uhci1,masterbus=usb.0,firstport=0,bus=pci.0,multifunction=on,addr=0x5 \
    -device ich9-usb-uhci2,masterbus=usb.0,firstport=2,bus=pci.0,addr=0x5.0x1 \
    -device ich9-usb-uhci3,masterbus=usb.0,firstport=4,bus=pci.0,addr=0x5.0x2 \
    -device virtio-serial-pci,id=virtio-serial0,bus=pci.0,addr=0x6 \
    -drive file=/home/probir/Downloads/qemu_with_libvirt/ubuntu18.04.img,format=raw,if=none,id=drive-virtio-disk0 \
    -device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x7,drive=drive-virtio-disk0,id=virtio-disk0,bootindex=1 \
    -drive if=none,id=drive-ide0-0-0,readonly=on \
    -device ide-cd,bus=ide.0,unit=0,drive=drive-ide0-0-0,id=ide0-0-0 \
    -netdev bridge,id=hostnet0,br=virbr0 \
    -device virtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:96:2f:7a,bus=pci.0,addr=0x3 \
    -chardev pty,id=charserial0 \
    -device isa-serial,chardev=charserial0,id=serial0 \
    -chardev spicevmc,id=charchannel0,name=vdagent \
    -device virtserialport,bus=virtio-serial0.0,nr=1,chardev=charchannel0,id=channel0,name=com.redhat.spice.0 \
    -device usb-tablet,id=input0,bus=usb.0,port=1 \
    -spice port=5900,addr=127.0.0.1,disable-ticketing,image-compression=off,seamless-migration=on \
    -device qxl-vga,id=video0,ram_size=67108864,vram_size=67108864,vram64_size_mb=0,vgamem_mb=16,max_outputs=1,bus=pci.0,addr=0x2 \
    -device intel-hda,id=sound0,bus=pci.0,addr=0x4 \
    -device hda-duplex,id=sound0-codec0,bus=sound0.0,cad=0 \
    -chardev spicevmc,id=charredir0,name=usbredir \
    -device usb-redir,chardev=charredir0,id=redir0,bus=usb.0,port=2 \
    -chardev spicevmc,id=charredir1,name=usbredir \
    -device usb-redir,chardev=charredir1,id=redir1,bus=usb.0,port=3 \
    -device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x8  \
    -netdev user,id=netdev0,hostfwd=tcp:127.0.0.1:2222-:22 \
    -device virtio-net-pci,netdev=netdev0 \
    -msg timestamp=on

After running ssh I get following error.
$sudo ssh -p2222 probir@localhost -vv
OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "localhost" port 2222
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 2222.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
ssh_exchange_identification: read: Connection reset by peer


text:
Q: Store session value in a datatable in C# I have created a session which store multiple value using Hashtable.
string productCode = lblProductId.Text;
string mrp = lblPrice.Text;
string quantity = txtQuantity.Text;
Hashtable htPdt = new Hashtable();
htPdt.Add("pdtId", "" + productCode + "");
htPdt.Add("price", "" + mrp + "");
htPdt.Add("quantity", "" + quantity + "");
Session["bag101"] = htPdt;

Now I want to store this session data in a Datatable.
How can I do it?
I am using this code
Datatable DtbBag101= (Datatable)Session["bag101"];

A: You can not cast hashtable to data table. You need to create datatable assign data to it and then save in session.
DataTable table = new DataTable();
table.Columns.Add("pdtId", typeof(int));
table.Columns.Add("price", typeof(double));
table.Columns.Add("quantity", typeof(double));

table.Rows.Add(1, 2, 3);
Session["bag101"] = table; // Putting DataTable in Session

DataTable DtbBag101= (DataTable)Session["bag101"]; //Retrieving DataTable from Session


text:
Q: Post build command doesn't work in not startup project I have a wav file in project. File reside under Res dir

I need this file to be copy to the TargetDir, so in order to do it I added post build command (Right click on project -> Properties -> Build events). Command is -
copy $(ProjectDir)\Res\*.wav $(TargetDir)\*.*

So, I expect that after solution was built this wav file should be copied to TargetDir, but it actually no.
What am I missing here?
P.S. This RecordTabEngine is not a StartupProject. If I make the same but on Startup project it is works well. Looks like post build command works just on startup project


text:
Q: The provider in flutter doesn't change a screens I'm using a provider in flutter app to change screens in my app. Here is my main.dart file:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/services/auth_service.dart';
import 'package:school_app/wrapper.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthService().auth,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}

Also this is my wrapper.dart file where the screens choose:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/screens/authenticate/auth.dart';
import 'package:school_app/models/user.dart';
import 'package:school_app/screens/school/home.dart';
import 'package:school_app/services/auth_service.dart';

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<AuthProvider>(context);
    print(user.auth);
    if(!user.auth) return Auth();
    return Home();
  }
}

And it is my AuthProvider class:
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthService {

   /* AuthUser _user(User user) {
    return user != null ? AuthUser(uid: user.uid) : null;
  }*/

AuthProvider auth = new AuthProvider();

  //sign in
  Future signIn(String username, String password) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var dio = Dio();
      Response user = await dio.post('url', data: {
        'username': username,
        'password': password
      });
      if(user.data['success'] == false) return user.data['msg'];
      await prefs.setString('token', user.data['token']);
      auth.setAuth(true);
      print("SUCCESS");
    } catch(e) {
      print('Error ' + e.toString());
    }
  }

}

class AuthProvider with ChangeNotifier {
  bool _auth;

  AuthProvider() {
    _auth = false;
  }

  bool get auth => _auth;

  void setAuth(bool auth) {
    _auth = auth;
    notifyListeners();
  }
}

Also I made this variants of Wrapper widget, but it didn't work also:
class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = context.watch<AuthProvider>();
    print(user.auth);
    if(!user.auth) return Auth();
    return Home();
  }
}

And this one:
class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = context.watch<AuthProvider>();
    print(user.auth);
    if(!user.auth) return Auth();
    return Home();
  }
}

And when I call a function in AuthProvider class setAuth, nothing changed. Can you help me and find my mistake?


text:
Q: Getting import error with sub modules of PyQt5 I am trying to install and use PyQt5 on Ubuntu 14.04. Before this, I had been using Ubuntu 18.04 and I had no problems with the installation and use of PyQt5. Because of some technical needs of a project, I need to use 14.04 instead.
After I first launch Ubuntu this is the order that I install things:
Install Python 3.6:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6

Install QT5
sudo apt-get install build-essential
sudo apt-get install qtcreator
sudo apt-get install qt5-default

Install PyQt5
sudo apt-get install python3-pyqt5
sudo apt-get install pyqt5-dev-tools
sudo apt-get install qttools5-dev-tools

After this is completed, I run this test code to see if I get an import error:
import sys
from PyQt5 import QtCore, QtWidgets

When I run it, I get this error. It gives an error for any sub module of PyQt5. On Ubuntu 18.04, I followed the same installation steps as above for qt5 and pyqt5 and it worked perfectly. (Did not install python 3.6 because it is already installed with Ubuntu 18).

Traceback (most recent call last):
File "/home/ms/test.py", line 2, in
from PyQt5 import QtCore
ImportError: cannot import name 'QtCore'

I have also tried installing pyqt5 with pip or pip3, but I get an error.
pip3 install pyqt5

Error:
Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_ms/pyqt5
Storing debug log for failure in /home/ms/.pip/pip.log

Any help would be greatly appreciated. I have been working on trying to fix this for the past couple days with still no idea what the problem could be.

A: The following steps use to install PyQt5 in a docker with ubuntu: 14.04:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
sudo apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
sudo python3.6 get-pip.py
sudo python3.6 -m pip install --upgrade pip
sudo python3.6 -m pip install pyqt5==5.9.2
sudo apt-get install '^libxcb.*-dev' libx11-xcb-dev libglu1-mesa-dev libxrender-dev libxi-dev libxkbcommon-dev libxkbcommon-x11-dev libfontconfig1
python3.6 -c "from PyQt5 import QtCore, QtWidgets"


text:
Q: Why does Google's inspector mobile tool render content different than my iphone I have a pretty simple website, which renders a background image, a header, a footer, and some body text.
When I view the site from Google Dev Tools mobile inspector. The text sits above the footer as expected.  When I view the site from an actual iphone the text is shown at the very bottom of the page (behind the footer).
App.js
return (

        <Routes>
          <Route
            exact
            path="/"
            element={
              <Mobile
                setNav={setNav}
                nav={nav}
                menuList={menuList}
                setFilter={setFilter}
              />
            }
          />
          <Route
            exact
            path="/directions"
            element={
              <Directions
                setNav={setNav}
                nav={nav}
                filter={filter}
                setFilter={setFilter}
                menuList={menuList}
              />
            }
          />
        </Routes>

        <MobileNavOneButton setNav={setNav} setFilter={setFilter} />

    );

the css for style.app is:
.app {
  background-image: url("../CompanyImages/Port507BackgroundImage.jpg");
  background-repeat: no-repeat;
  background-attachment: fixed;
  position: fixed;
  height: 100vh;
  width: 100vw;
  max-height: 100vh;
  max-width: 100vw;
  background-size: cover;
  z-index: -999;
}

Mobile.js
import React from "react";
import style from "./Mobile.module.css";

const Mobile = () => {
  return (

128 W 2nd St, Winona, MN 55987

  );
};

export default Mobile;

css for mobile.js
html,
body {
  margin: 0;
  /* height: 100% */
}

.app {
  height: calc(100vh - 8rem);
  width: 100vw;
  background-size: cover;
  display: flex;
  justify-content: center;
  margin-top: 5rem;
}

.mainContent {
  text-align: center;
  color: white;
  width: 100%;
  display: flex;
  align-self: flex-end;
  margin-bottom: 1.5rem;
  margin-left: 1rem;
}

Footer.js
import React from "react";
import { useNavigate } from "react-router-dom";
import style from "./MobileNavOneButton.module.css";
import HomeIcon from "@mui/icons-material/Home";
import ExploreIcon from "@mui/icons-material/Explore";

const MobileNavOneButton = ({ setNav }) => {
  const navigate = useNavigate();

  return (

 {
          navigate("../directions", { replace: true });
          setNav(false);
        }}
      >
        <ExploreIcon style={{ fontSize: "1.25rem", color: "#000000" }} />

Directions

  );
};

export default MobileNavOneButton;

css for the footer
.buttonText {
  font-size: 0.75rem;
  font-family: Montserrat-Light;
  text-decoration: none;
  color: black;
}

.NavBar {
  width: 100%;
  float: none;
  display: flex;
  height: 3rem;
  overflow: hidden;
  position: fixed;
  bottom: 0;
  z-index: 999;
  background-color: rgba(150, 150, 150, 0.8);
}

.NavButton {
  align-items: center;
  justify-content: center;
  /* border: 1px solid black; */
  /* background-color: rgba(150, 150, 150, 0.8); */
  border-radius: 0;
  float: left;
  display: flex;
  flex-direction: column;
  font-size: 1rem;
  font-family: Montserrat-Light;
  text-align: center;
  width: 100%;
  text-decoration: none;
  color: #222222;
}

.NavButton:focus {
  outline: none !important;
  outline-offset: none !important;
}

The website can be seen here. Note: you will be redirected if viewing from a browser (need to be in Dev Tools mobile)
Website


text:
Q: expected ; in the js I have taken the reference from the dialogflow demo. I'm getting error as

';' expected.

at the the method sendTextMessageToDialogFlow. how can I solve this issue?
Here is my code
router.post('/dialogflow', function(req, res) {
  const projectId = "xxxxxxxxx";

  const LANGUAGE_CODE = 'en-US';
  let credentials = {
    private_key: xxxxxxxxx,
    client_email: "xxxxxxx",
  }
  let sessionClient = new dialogflow.SessionsClient(credentials);
  async sendTextMessageToDialogFlow(req.body.query, req.body.id) {
    const sessionPath = this.sessionClient.sessionPath(projectId, req.body.id);
    const request = {
      session: sessionPath,
      queryInput: {
        text: {
          text: req.body.query,
          languageCode: LANGUAGE_CODE
        }
      }
    }
    try {
      let responses = await this.sessionClient.detectIntent(request)
      console.log('DialogFlow.sendTextMessageToDialogFlow: Detected intent');
      res.json(responses);
    } catch (err) {
      console.error('DialogFlow.sendTextMessageToDialogFlow ERROR:', err);
      cosole.log(err);
    }
  }
})

A: you seem to be missing the word function and the function params have periods in them
should it look more like:
let sessionClient = new dialogflow.SessionsClient(credentials);
  async function sendTextMessageToDialogFlow(reqBodyQuery, reqBodyId) {
    const sessionPath = this.sessionClient.sessionPath(projectId, reqBodyId);
    const request = {
            session: sessionPath,
            queryInput: {
                text: {
                    text: reqBodyQuery,
                    languageCode: LANGUAGE_CODE
                }
            }
    }
    try {
            let responses = await this.sessionClient.detectIntent(request)
            console.log('DialogFlow.sendTextMessageToDialogFlow: Detected intent');
            res.json(responses);
        }
        catch(err) {
            console.error('DialogFlow.sendTextMessageToDialogFlow ERROR:', err);
            cosole.log(err);
        }
  }
})

A: You can't use object properties for parametars of a function. First declare the "query" and "id" variables and then you can use them in the function because they are in the same scope. Also you are missing the function keyword.
router.post('/dialogflow', function(req, res) {
  const projectId = "xxxxxxxxx";

  const LANGUAGE_CODE = 'en-US';
  let credentials = {
    private_key: xxxxxxxxx,
    client_email: "xxxxxxx",
  }
  let sessionClient = new dialogflow.SessionsClient(credentials);
  let query = req.body.query;
  let id = req.body.id;

  async function sendTextMessageToDialogFlow() {
    const sessionPath = this.sessionClient.sessionPath(projectId, id);
    const request = {
      session: sessionPath,
      queryInput: {
        text: {
          text: query,
          languageCode: LANGUAGE_CODE
        }
      }
    }
    try {
      let responses = await this.sessionClient.detectIntent(request)
      console.log('DialogFlow.sendTextMessageToDialogFlow: Detected intent');
      res.json(responses);
    } catch (err) {
      console.error('DialogFlow.sendTextMessageToDialogFlow ERROR:', err);
      cosole.log(err);
    }
  }
});


text:
Q: .Net OLAP Cube Explorer control with HTML5 mobile compatibility I'm currently looking for control suite that supports mobile business intelligence reporting. The mobile BI site will be a complimentary site for an existing SharePoint BI solution that presents SSRS / PerformancePoint information to the user.
The mobile site should allow users to view pivot grids of information sourced from an OLAP cube as well as normal SQL query results of information. The controls present on the mobile site should be completely compatible with iOS, Android and WinPhone devices as the information will primarily be used on mobile devices by users who are often off-site.
At the moment, the only control suite I can find that seems to fit the bill is the ComponentArt suite for mobile dashboarding.
I had a look at Telerik / Infragistics but neither have any native OLAP cube controls.
Does anyone else have any other suggestions that I can investigate?
Thanks,
Brian.

A: We are developing a version of the component Ranet OLAP for HTML5+JQUERY. It will include the MDX designer and the Pivot Grid. A visual user interface will be oriented to work in a web-browser. User interface design for mobile devices on iOS, Android and Windows is discussed. Components will have a common Core for all three platforms: Silverlight, WPF, HTML5.


text:
Q: Clarify different behaviour of neo4j and neo4j-driver I have a rudimentary database that has just a couple of nodes and relationships. When I run a match (n) return n command on the local web client provided with neo4j it returns all the nodes and relationships that's in the database, as seen in the picture below.

However when I run exactly the same command in a node.js project using the neo4j-driver module, it only returns the three nodes and none of the two relationships are included.
After a little bit of fiddling with it, I noticed that to retrieve the relationships too, I must issue something like match (n)-[r]-(m) return *. My first question is why is there such a difference? Is the local web client just trying to do a bit more to help the user?
Furthermore I find the returned records object a little bit confusing. Running this match (n)-[r]-(m) return * command returns 4 items in the result.records object out of which 2-2 are almost identical pair-wise. In a simplified view this is what it returns:
item 0: [Jack node, Jill node, Jack -> Jill relationship]
item 1: [Jill node, Jack node, Jack -> Jill relationship]
item 2: [George node, Jill node, George -> Jill relationship]
item 3: [Jill node, George node, George -> Jill relationship]

So items 0 and 1 of the result.records object differ only by the order of their elements. Same for items 2 and 3.
Question two is what am I supposed to do with this if I want to display the graph on a web page? Look for unique IDs of the nodes and relationships in all the different combinations returned?
Question three: maybe there's a better way to achieve what I'm trying to do?

A: The Neo4j web browser is indeed just trying to be helpful and the visualization will connect nodes if they have relationships between them (there's an option to turn this behaviour off btw). However, the resultset will not contain those if you didn't ask for them (as it shouldn't). Look on the other reponse tabs (table, text, code) in the browser to see the actual resultset.
This query may help you :
match p=(n)-[r]-(m) return p

But yes, you are correct, you will have to unpack the result in your application in order to be able to do your own interpretation. It is a case of the you get what you asked for problem that quite a few Neo4j users face. It is due to the fact that Cypher can return quite a few different things (tabular results, nodes, nodes and relationships, paths, subgraphs, ...) and the driver has to provide for all of them.
Have a look at the code tab in the browser to get a feel of what your application will have to work with (what you actually get depends on your application language of choice). It's not very difficult but it does require a bit of getting used to.
Hope this helps.
Regards, Tom
P.S. Doubles in the results are to be expected with such generic queries. Neo4j does pattern matching and your pattern does not have a direction on the relationship nor does it have labels or relationshiptypes. That's going to return quite a few matches where for example (jill)-[:nominated]-(jack) but obviously it also matches (jack)-[:nominated]-(jill). Both match the pattern. Using DISTINCT may help a bit but you really should be more explicit in the pattern.


text:
Q: Cauchy product and geometric series I was given this series:
Let $q \in \mathbb{C}, \mid q\mid <1. $
$$\frac{1}{2}\sum_{n=0}^{\infty} (n^2 +3n +2)q^n $$
Now I have to show that
$$\frac{1}{(1-q)^3}=\frac{1}{2}\sum_{n=0}^{\infty} (n^2 +3n +2)q^n$$
and proof whether or not this series converges absolutely.
For the convergence I guess I have to use one of the many convergence criteria and for the equality I have no clue how to even start.

A: Since$$\frac1{1-q}=1+q+q^2+q^3+\cdots,$$you have, by the Cauchy product,$$\begin{align}\frac1{(1-q)^2}&=\frac1{1-q}\times\frac1{1-q}\\&=\left(1+q+q^2+q^3+\cdots\right)\times\left(1+q+q^2+q^3+\cdots\right)\\&=1+2q+3q^2+4q^3+\cdots\\&=\sum_{n=0}^\infty(n+1)q^n.\end{align}$$Now, in order to prove what you want to prove, apply the same idea to the equality$$\frac1{(1-q)^3}=\frac1{1-q}\times\frac1{(1-q)^2}$$and use the fact that$$(n+1)+n+(n-1)+\cdots+1=\frac{(n+1)(n+2)}2=\frac{n^2+3n+2}2.$$


text:
Q: How can I add a title to the Woocommerce product title links? I want to truncate my Woocommerce product titles with text-overflow:ellipsis, but for better usability I also want to add a title to the product title links so that users can hover over and see the full title. How can I add titles to the product title links? I need
Product title


text:
Q: Dockerfile: How to run a subcommand in CP? How to translate this bash command to Dockerfile?
cp $(stack exec which wai-crowd) /app

To
COPY $(stack exec which wai-crowd) /app

I want to copy the executable to a more convenient place to be the entry point. I might have a different base image for build and execute:
FROM fpco/stack-build:lts-14.20 as builder

COPY . /app
WORKDIR /app
RUN stack build

FROM fpco/stack-build:lts-14.20

WORKDIR /app
COPY --from=builder $(stack exec which wai-crowd) /app
EXPOSE 3000
ENTRYPOINT ["./wai-crowd"]

A: I believe not all shell commands can be translated to dockerfile.
Dockerfile is a script that builds the docker image. COPY command takes some file from the host machine (on which you build the image) and copies it into the docker image so that this file will later be available for docker process.
AFAIK, docker doesn't have any tools to run commands in the host machine during the docker build (see also this thread)
So you can run the command before the build, create a file in the buildroot and then run docker build immediately after that.

A: For a couple of reasons, you need to run this step during the "build" stage.  That will leave the file in a known place where the "runtime" stage can COPY --from=build it.
FROM fpco/stack-build:lts-14.20 as builder
...
RUN stack build
RUN cp $(stack exec which wai-crowd) /app

FROM alpine
COPY --from=builder /app/wai-crowd /usr/bin
EXPOSE 3000
CMD ["wai-crowd"]

When you start the second stage, it doesn't have any of the content from the first stage, so even ignoring the syntactic problems, the stack exec which ... command wouldn't be able to see the build tree.  Typically using a compiled language (like Haskell) you will want to avoid having the actual build tools in your final image, since they can be quite large; in my example I've used the lightweight alpine image as the base for the final image, and so you also won't have the stack command there.
The solution here is to leave any artifacts that you do want to copy into the final image in fixed paths.  In my example I've reused the same /app directory that the source is in but you can use pretty much any directory you want.


text:
Q: What is the difference in these two sentences?
*

*She foolishly answered the questions.

*She answered the questions foolishly.

My notes says that adverbs when placed before the verb applies to the action but the meaning changes when it occurs after the verb. The problem is I can't understand the difference here.

A: She foolishly answered the questions would mean She should have kept her mouth shut.
She answered the questions foolishly would mean She gave idiotic answers to the questions.

She foolishly answered =  It was foolish to answer
She answered foolishly =  She gave a foolish answer

Bond foolishly answered the question:

Where's the microchip, Mr Bond?  Tell me now, and I'll spare your girlfriend's life.
  -- It's in the dumpster, under the rotten potatoes.
Shot fired. Bond dead.
  Shot fired. Bond's girlfriend, dead.


text:
Q: relationships and MVC3 okay so I have a teams table with TeamID, TeamName and a games table with columns gameid, team1, team2.
Now I dont have team1 and team2 as Foreign keys to the teams table. I understand this will make it easier but I want to learn without doing that. So team1, and team2 are int fields. There is no constraint check.
So when I display it in my view, it displays the team1 and team2 columns but instead of displaying the integer ID, I want it to pull the team name from the teams table.
okay in my view I have the following:
   @model IEnumerable<Betting.Models.Bets>
@{
    ViewBag.Title = "List of Games";
}
@{
    var grid = new WebGrid(source: Model, defaultSort: "EndDate", rowsPerPage: 3);
}

    Index

    @Html.ActionLink("Create New", "Create")

    Betting List

    @grid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt",
        columns: grid.Columns(
            grid.Column("Subject"),
            grid.Column("Team1"),
            grid.Column("Team2")
        )
    )

And my controller is really simple:
public ViewResult Index()
{

    return View(db.Bets.ToList());
}

A: Always use view models in ASP.NET MVC and you won't have such problems:
public class TeamViewModel
{
    public string Team1Name { get; set; }
    public string Team2Name { get; set; }
    public string Subject { get; set; }
}

then in the controller action do the necessary mapping/querying in order to populate this view model:
public ActionResult Index()
{
    // Fetch the data here, depending on the ORM you are using
    // perform the necessary joins so that you have the team names
    IEnumerable<Betting.Models.Bets> model = ...

    // map the model to the view model previously defined
    IEnumerable<TeamViewModel> viewModel = ...

    // pass the view model to the view for display
    return View(viewModel);
}

finally in the view:
@model IEnumerable<TeamViewModel>
@{
    ViewBag.Title = "List of Games";
}
@{
    var grid = new WebGrid(source: Model, defaultSort: "EndDate", rowsPerPage: 3);
}

Index

    @Html.ActionLink("Create New", "Create")

Betting List

    @grid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt",
        columns: grid.Columns(
            grid.Column("Subject"),
            grid.Column("Team1Name"),
            grid.Column("Team2Name")
        )
    )

As far as the mapping between your models and view models is concerned AutoMapper could greatly simplify this task.


text:
Q: Can I make Release description required? Is there a way to make Release description required when creating release?

A: I am afraid azure devops doesnot have an out of box option to make Release description required.
However, these is a workaround by using the Invoke Rest Api Gate to check if  Release description is given before deploying the releases. Using Gates cannot prevent you from creating the release. It will only stop executing the deployment.
Check below detailed steps:
1, create a service connection to your azure devops organization.
Go Project Setting--> Service connections under Pipelines-->Click new service connection--> select Generic to create a generic service connection.

2,Then Edit the service connection type the information shown in below screenshot. Check here to get a Personal access token.

3, Go the your release definition edit page-->Pre-deployment conditions-->Enable Gates-->Add Invoke Rest Api

4, Edit the Invokde Rest API
Select the generic service connection to your azure devops created in the first step.
Set the fields as below:

*

*URL suffix and parameters: /_apis/release/releases/$(Release.ReleaseId)?api-version=6.1-preview.8

*Success criteria: ne(root['description'],'')
please check here for more information about GET Release rest api.
See below screenshot:

When you create a release. The Gates will be evaluated and check if the release description is set. And will not execute the deployment if the Gate failed.


text:
Q: Advisable to put a Commit in an Oracle EBS Concurrent Program? i just want to ask if its Advisable to put a Commit inside PL/SQL Procedure being called by an Oracle EBS Concurrent Program? I've always believed its bad practice to put commits inside the program for the following reasons:

*

*If the Program encounters an Exception after the Commit, we cannot Roll it back anymore.

*Let the calling application do the implicit commit (in this case, EBS)

*As in the case of Oracle Workflows, we should never put Commits inside the WF package as it will disrupt the "rollback" feature of the
  Workflow.

However, i keep on seeing Oracle EBS Developers put commits inside a single Concurrent Program. Any thoughts on this?
Thanks!

A: Don't worry, you are doing right.
Database developers are not aware of many thing until they get burn in production.
Avoiding COMMIT inside a code is about enabling this code to be used with other code units, without breaking the whole system logic.
Rollback is not only about exceptions but also about the freedom of a user to cancel an action within interactive program, without corrupting the database.
Here is an example of what happens when one developer (the developer of unit_2) takes the freedom to use COMMIT.
create table t (i int);

create or replace procedure unit_1 as begin insert into t(i) values (1); end;
/
create or replace procedure unit_2 as begin insert into t(i) values (2); commit; end;
/
create or replace procedure unit_3 as begin insert into t(i) values (3); end;
/
create or replace procedure unit_4 as begin insert into t(i) values (4); end;
/

create or replace procedure all_units as begin delete t;unit_1;unit_2;unit_3;unit_4; end;
/

exec all_units;

select * from t;

         I
----------
         1
         2
         3
         4

set transaction t; exec all_units; rollback;

select * from t;

         I
----------
         1
         2


text:
Q: ObjC Formatting Decimal places of Float to string How do I format a float to string so that if the user enters a number that has 2 or less decimal places then it is formatted to have 2 decimal places, but if the user enters a float that has 2 or more decimal places then all decimal places are shown. e.g.
4.1 => 4.10
1 => 1.00
1.358484 => 1.358484

So therefore the formatting is to 2 decimal places or more if needed.
Hope I made sense.

A: Try something like this.
BOOL requiresExtraPrecision (double num) {
    double roundedToHundredth = round(num * 100.0) / 100.0;
    double diff = num - roundedToHundredth;
    if (diff < 0) diff = 0.0 - diff;
    if (diff < 0.0000001) {
        return NO;
    } else {
        return YES;
    }
}

NSString *formatted (double num) {
    if (requiresExtraPrecision(num)) {
        return [NSString stringWithFormat:@"%F", num];
    } else {
        NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
        [formatter setMaximumFractionDigits:2];
        [formatter setMinimumFractionDigits:2];
        return [formatter stringFromNumber:[NSNumber numberWithDouble:num]];
    }
}

As @Carl wrote in a comment to the question, the hard part is deciding when a double needs all of its precision. In this code, I'm assuming that if the double is "close enough" to a rounded number (within a millionth), then we should just display the rounded number.
You might decide to make it stricter (a billionth?) but you'll always have to use some kind of approximation, because some decimals can't be stored precisely as a float. Even though the user may have typed "0.1" at input time, that information is lost when the number is stored as a float.
So, given that you'll have a float that's extremely close to a decimal but not exactly right, you'll have to decide when you think the float is "close enough" to the decimal.
If you need absolute precision (if you're working with money!) then you should consider using an NSDecimal or an NSDecimalNumber instead of a float.

A: this could work for you:
NSNumber *aFloat = [NSNumber numberWithFloat:1.2]; //try 1.234 ; 1.23 ; 1.2 ; 1. ; 1
NSString *numberString = [aFloat stringValue];
NSRange dot;
dot = [numberString rangeOfString:@"."];
NSString *finalString;
if (dot.location != NSNotFound) {
    NSString *decimals = [numberString substringFromIndex:dot.location + dot.length];
    if (decimals.length<1){ // ends with "."
        finalString = [numberString stringByAppendingString:@"00"];
    }else if (decimals.length<2){ // ends with ".n"
        finalString = [numberString stringByAppendingString:@"0"];
    }else { // 2 or more decimals: no changes
        finalString = numberString;
    }
}else { // no decimals
    finalString = [numberString stringByAppendingString:@".00"];
}
NSLog(@"______._____finalString:%@", finalString );

EDIT (more flexible, it works with variable numbers of decimals):
NSNumber *aFloat = [NSNumber numberWithFloat:1.1235]; //try 1.234 ; 1.23 ; 1.2 ; 1. ; 1
NSString *numberString = [aFloat stringValue];
NSRange dot;
dot = [numberString rangeOfString:@"."];
if (dot.location == NSNotFound) { // no decimals, add a dot
    numberString = [numberString stringByAppendingString:@"."];
    NSLog(@"__added dot___ numberString:%@", numberString );
}
dot = [numberString rangeOfString:@"."];
NSString *decimals = [numberString substringFromIndex:dot.location + dot.length];
//      int initialDecimals = decimals.length;
int numberOfDecimalsTerget = 2;

for (int initialDecimals = decimals.length; initialDecimals<numberOfDecimalsTerget; initialDecimals++) {
    numberString = [numberString stringByAppendingString:@"0"];
}
NSLog(@"__END_._____numberString:%@", numberString );


text:
Q: Change in Ajax between VS2005 and VS2010 I've never used AJAX before. I'm new to web design but I have a website that I need to add certain dynamic functionality to. Ajax seems like it would help. Problem is, most of the Ajax articles relate to VS2005. I'm using VS2010 Premium Edition. There must have been lots of changes between the versions. I don't have any Ajax toolbox tabs. I didn't even have a timer control available in the toolbox - I have now added one from the System.Web.Extensions Assembly.
Does anyone have info on what's happened to Ajax in VS2010?
Thanks
Rob.

A: AJAX hasn't changed in all that time.  AJAX toolkits have been introduced, though.  You should look into what is available.  Particularly, I would look at ASP.Net AJAX (along with the AJAXControlToolkit), and JQuery.


text:
Q: PHP - How to check whether a year is bisect (i.e. a leap year)? How can I check whether a year is bisect (i.e. a leap year) in php ?

A: Using the DateTime class:
$year = 2000;
$isLeap = DateTime::createFromFormat('Y', $year)->format('L') === "1";
var_dump($isLeap); // bool(true)

A: You can use PHP's date() function to do this...
// L will return 1 if it is a leap year, 0 otherwise
echo date('L');

// use your own timestamp
echo date('L', strtotime('last year'));

// for specific year
$year = 1999;
$leap = date('L', mktime(0, 0, 0, 1, 1, $year));
echo $year . ' ' . ($leap ? 'is' : 'is not') . ' a leap year.';

Let me know if this does this trick for you, Cheers!
UPDATE: Added Example for Specific Year

A: Problem of checking if year is leap year is, if julian or gregorian calendar is used.
Meanwhile year in julian calendar has 365,25, year in gregorian calendar has 365,2422. So, gregorian year is of 11 minutes shorter than julian. And general rule for leap years (year/4 must be integer) is not valid at all times.
Year/4
Year/100 & Year/400

So most of years when Year/100 are not leap years.
Also, there is one another important condition for this checking.
Year >= 1583

As gregorian calendar was ordered to use in 1582 and this year was affected by changes caused by beginning of usage of this calendar (there was Thursday 4th October and then 15th October - days between were deleted), 1583 is the first year that is countable as fully gregorian (in gregorian calendar). But I decided to not test this condition, as this condition should be probably tested prior to testing of leap year - if it is not sure if year is counted in accordance with gregorian calendar.

For both calendars it is possible to write own function (or standalone static method) and result should be probably the same as if PHP's class would be used.
And also, usage of your own function/method will take shorter code.
public static function Is_LeapYear($Year = 1583)
{
    $LeapYear = FALSE;

    if(CheckTypes::Is_Integer($Year / 4))
    {
        if(CheckTypes::Is_Integer($Year / 100) && !CheckTypes::Is_Integer($Year / 400))
        {
            $LeapYear = FALSE;
        }
        else
        {
            $LeapYear = TRUE;
        }
    }
    else
    {
        $LeapYear = FALSE;
    }

    return $LeapYear;
}

CheckTypes is my own class for multiple type checking (else methods allow to multiple type checking). Is_Integer is (due to one type checking) equal to is_integer from PHP in-built functions. So, CheckTypes::Is_Integer($Year / 4) may be replaced with is_integer($Year / 4) and result will be the same.
This counting of leap year is in accorance with gregorian calendar, not julian.

A: A bisect year is another name for a leap year. Use the L formatter, where $year is the year you are testing:
echo (date('L', strtotime("$year-01-01")) ? 'Yes' : 'No');

To adjust the discordance between the
  calendar and seasons, the Julian
  calendar used the calculations of the
  Greek astronomer Sosigene and was
  based on the adoption of a 365.25 days
  year: 3 years of 365 days followed by
  a 366 days year, the supplementary day
  being added always after the 24th of
  February (sexto ante calendas Martiis
  = the sixth day before the March calends) being called bis sexto (the
  sixth day bis), hence the names of
  bisect year and bisect day for the
  leap day. The year was divided in 12
  months, which alternated 31 and 30
  days and February had, in normal
  years, 29 days and 30 days in bisect
  years.
Later, when the eighth month was
  dedicated to the emperor Augustus
  (August), this month was made of 31
  days to match July, the month
  dedicated to Julius Caesar. That's why
  February was made of 28 days, having
  29 days in bisect years.

http://news.softpedia.com/news/The-History-of-Modern-Calendar-and-Bisect-Year-79892.shtml

A: function is_leap_year($year)
{
    return ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));
}

A: If you care about performance, the faster way is:
!($year % 4) && ($year % 100 || !($year % 400))

It returns the exact same result than:
(bool) date('L', mktime(0, 0, 0, 1, 1, $year))

From year 101 to 999999 but it's about 30 times faster.

A: $isLeapYear = fn($year) => $year % 400 === 0 || ($year % 100 !== 0 && $year % 4 === 0)


text:
Q: Extracting a field from a Json string using jackson mapper in Scala I have a json string:
val message = "{\"me\":\"a\",
    \"version\":\"1.0\",
    \"message_metadata\": \"{
                          \"event_type\":\"UpdateName\",
                          \"start_date\":\"1515\"}\"
    }"

I want to extract the value of the field event_type from this json string.
I have used below code to extract the value:
val mapper = new ObjectMapper
val root = mapper.readTree(message)
val metadata =root.at("/message_metadata").asText()
val root1 = mapper.readTree(metadata)
val event_type =root1.at("/event_type").asText()
print("eventType:" + event_type.toString) //UpdateName

This works fine and I get the value as UpdateName. But I when I want to get the event type in a single line as below:
val mapper = new ObjectMapper
val root = mapper.readTree(message)
val event_type =root.at("/message_metadata/event_type").asText()
print("eventType:" + event_type.toString) //Empty string

Here event type returns a empty sting. This might be because of the message_metadata has Json object as a string value. Is there a way I can get the value of event_type in a single line?

A: The problem is that your JSON message contains an object who's message_metadata field itself contains JSON, so it must be decoded separately. I'd suggest that you don't put JSON into JSON but only encode the data structure once.
Example:
val message = "{\"me\":\"a\",
    \"version\":\"1.0\",
    \"message_metadata\": {
                          \"event_type\":\"UpdateName\",
                          \"start_date\":\"1515\"
    }
}"

A: You can parse your JSON using case classes and then get your event_type field from there.
case class Json(me: String, version: String, message_metadata: Message)

case class Message(event_type: String, start_date: String)

object Mapping {

  def main(args: Array[String]): Unit = {

    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.module.scala.DefaultScalaModule
    import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

    val objectMapper = new ObjectMapper() with ScalaObjectMapper
    objectMapper.registerModule(DefaultScalaModule)
    val str = "{\n  \"me\": \"a\",\n  \"version\": \"1.0\",\n  \"message_metadata\": {\n    \"event_type\": \"UpdateName\",\n    \"start_date\": \"1515\"\n  }\n}"
    val json = objectMapper.readValue(str, classOf[Json])
    //to print event_type
    println(json.message_metadata.event_type)
    //output: UpdateName

  }

}

A: *

*You can even convert a JSON to Scala Case Class and then get the particular field from the case class.

*Please find a working and detailed answer which I have provided using generics here.


text:
Q: Passing a custom Object from one Activity to another Parcelable vs Bundle I'd like to pass a custom Object from one activity to another, the Object consists of a String and a List of another custom Object which consists of an array of strings and an array of ints. I've read  https://stackoverflow.com/a/2141166/830104, but then I've found this answer https://stackoverflow.com/a/7842273/830104. Which is better to use Bundle or Parcelable? What is the difference? When should I use this each? Thanks for your replies, Dan

A: Parcelable and Bundle are not exclusive concepts; you can even deploy both on your app at a time.
[1] Term Parcelable comes with Serialization concept in Java (and other high-level language such as C#, Python,...). It ensures that an object - which remains in RAM store - of such Parcelable class can be saved in file stream such as text or memory (offline status) then can be reconstructed to be used in program at runtime (online status).
In an Android application, within 2 independent activities (exclusively running - one starts then other will have to stop):
There will be NO pointer from current activity to refer to previous one and its members - because previous activity is stopped and cleared out form memory; so that to maintain object's value passed to next activity (called from Intent) the object need to be parcelable (serializable).
[2] While Bundle is normally the Android concept, denotes that a variable or group of variables. If look into lower level, it can be considered as HashMap with key-value pairs.
Conclusion:

*

*Bundle is to store many objects with related keys, it can save any object in native types, but it doesn't know how to save a complex object (which contains an ArrayList for example)

*Parcelable class is to ensure a complex instance of it can be serialized and de-serialized during runtime. This object can contains complex types such as ArrayList, HashMap, array, or struct,...
[UPDATED] - Example:
//Class without implementing Parcelable will cause error
//if passing though activities via Intent
public class NoneParcelable
{
    private ArrayList<String> nameList = new ArrayList<String>();
    public NoneParcelable()
    {
        nameList.add("abc");
        nameList.add("xyz");
    }
}

//Parcelable Class's objects can be exchanged
public class GoodParcelable implements Parcelable
{
    private ArrayList<String> nameList = new ArrayList<String>();
    public GoodParcelable()
    {
        nameList.add("Can");
        nameList.add("be parsed");
    }
    @Override
    public int describeContents()
    {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags)
    {
        // Serialize ArrayList name here
    }
}

In source activity:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;

Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);

In destination activity:
Intent i = getIntent();

//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code

//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK


text:
Q: How can I launch another application using the android_intent package? If I have a an app with package name com.example.firstapp, and a second app com.example.secondapp installed on the same device, how can I launch com.example.secondapp from com.example.firstapp using the android_intent package? What would be the correct values for the action, data, and, package fields of the AndroidIntent object?
Or in other words:  How can I use the android_intent package to launch another application by its package name?

A: *

*Add the following to pubspec.yaml under dependencies:
 device_apps:
 android_intent:
 url_launcher:

*Add the following code:
 _openSecondApp(data) async {
     String dt = data['SecondApp'] as String;
     bool isInstalled = await DeviceApps.isAppInstalled('com.example.secondapp');

     if (isInstalled != false) {
         AndroidIntent intent = AndroidIntent(action: 'action_view', data: dt);
         await intent.launch();
     } else {
         String url = dt;

         if (await canLaunch(url))
             await launch(url);
         else
             throw 'Could not launch $url';
     }
 }


text:
Q: Returning value from called function in C I must write a code in C, that have an extra function with pointers as function arguments. This function have to perform a basic math calculation (such as +-*/) with those pointers, then send result back to the calling function main().
But I have no idea, how the called function can signalize that dividing by zero is undefined and send it back to the main()?
#include "stdafx.h"

char count(float *, float *, float *, float *, float *, float *);
//prototype the function

int _tmain(int argc, _TCHAR* argv[])
{

float a, b, sum, diff, prod, div;

printf("\n a und b eingeben: ");

scanf("%f %f", &a, &b);

printf("\n a und b lauten: %f %f\n", a, b);

count(&a, &b, &sum, &diff, &prod, &div); //send addresses to function

printf("\n a+b = %f \n", sum);
printf("\n a-b = %f \n", diff);
printf("\n a*b = %f \n", prod);

if (b == 0)
    printf("\n a/b ist nicht definiert\n\n");    //I wrote this just in
                                                 //the main (), but it's
                                                 //not the same exercise :))
else
    printf("\n a/b = %f \n", div);

return 0;
}

char count(float *a, float *b, float *sum, float *diff, float *prod, float
*div) //define the function

{
*sum = *a + *b;

*diff = *a - *b;

*prod = *a * *b;

*div = *a / *b;

if (*div == 0)            //?????????????
return NULL;
}

A: if you include math.h and use std=c99, you can use
isinf(div)

to check if you divided by 0.
i.e.
if(isinf(div)) {
    printf("\n a/b is undefined\n\n");
}


text:
Q: understanding Green's theorem Intuition The idea of it is to find the area of a region, yet I keep seeing vector fields popping up all over the place.
Take this example from my text book: Find the region enclosed by the two graphs:
$y = x$, $y = x^2$
I have no idea how they put this thing in the form of:
$$\int_{c} y^3dx + (x^3 + 3xy^2)dy$$
Where did that come from? And this isn't the only problem where vector fields are appearing out of nowhere and not being described how they came about. Can someone help me out here?
EDIT: I'm talking about where the $y^3$ and $(x^3 + 3xy^2)$ came from


text:
Q: What is the definition of the characteristic function in this proof from Real & Complex Analysis by Walter Rudin? The theorem is:
$$\text{Let } f:X\to [0,\infty] \text{ be measurable}.$$
$$\exists \text{ simple measurable functions } s_n \text{ on } X \text{ such that }:$$

(a) $0\le s_i \le f$ $i\in \mathbb{N}$

(b) $s_n(x)\to f(x)$ as $n\to \infty$ $\forall x\in X$

Condition (b) is more like:
$$ \lim_{n\to \infty\\ \forall x\in X}s_n(x)=f(x).$$
Condition (a) expands:
$$ 0\le s_1 \le s_2 \le \cdots \le f.$$
I am stuck because I do not know how to do a proper epsilon-delta proof.
My attempt is something along the lines of arguing that  approximate  from below and lead up to a boundary line where  is "ahead" of all the other functions in the set. I don't know if this is true because I didn't read the proof in the textbook by Rudin.

The proof in the textbook (on p.16 of the second edition) is something like this:
For $n$ from 1 to infinity, and for $1\le i\le n2^n$, define the sets (?)
$$E_{n,i}=f^{-1}([(i-1)/2^n))$$
and
$$F_n=f^{-1}([n,\infty])$$
and then put ((???))
$$s_n=\sum_{1\le i \le n2^n} \frac{i-1}{2^n}\chi_{E_{n,i}}+n\chi_{F_n}$$
and then the rest of the proof is self referential to another theorem followed by  more explanation.
— - -
It seems $\chi$ is a characteristic function on a set S when S is the subscript of $\chi$. I guess I need to consult Wikipedia for a definition of characteristic functions and return to this question later.

A: What is going on here is the $y$-axis is being partitioned: Consider a finite sequence of increasing $y$ values:
$$0 = y_0 < y_1 < y_2 < \dots < y_m$$
Then you can define the function
$$s(x) = \begin{cases}y_0,&f(x) < y_1\\y_1,&y_1 \le f(x) < y_2\\\vdots\\y_{m-1},& y_{m-1} \le f(x) < y_m\\y_m,&y_m \le f(x)\end{cases}$$
$s$ is a simple function, measurable because $f$ is measurable, and $s \le f$.
Now suppose you have such a sequence for each $n: Y_n = (y_{n,0}, \dots, y_{n,m_n})$. Each of them defines a simple function $s_n \le f$ as above.
Since we want the $s_n$ to converge to $f$, the size of the $y$-axis intervals needs to decrease to $0$ as $n \to \infty$: $\lim_n \max \{y_{n,i} - y_{n,i-1} \mid 1 \le i \le m_n\} = 0$. We also need the top value $y_{m_n}$ to go to $\infty$ for the same reason. If $y_{m_n}$ is bounded and $f$ is not, there will be regions where $f$ is far away from $s_n$ for high $n$.
This is what the explicit sequence $y_{n,i} = \frac i{2^n}, m_n = n2^n$ in their solution accomplishes. The summation of multiples of characteristic functions is just another way of defining the same simple function as I gave above. It is such a common heuristic now that it can be hard for practiced mathematicians to remember how opaque it is when you first encounter it. I'm sure Rudin does give a definition for the characteristic function, but it'll likely be back in the introductory material in the first chapter.


text:
Q: Table Creation query I want to count values based upon two condition with same column.
Like,
tablename : Status
----|-------|------------|
Id  | name  |  status    |
----|-------|------------|
1   |   tg1 |    success |
2   |   tg1 |    Reject  |
3   |   tg2 |    success |

output like:
ID   success_count     Rejected_count
tg1       1                  1
tg2       0                  1

A: The relevant query can be shown the expected result :
create Table #Table
(
    Id int,
    NameTg varchar(128),
    StatusTg varchar(128)
)

Insert into #Table
(
    Id,
    NameTg,
    StatusTg
)

SELECT 1,'tg1','success'
UNION
SELECT 2,'tg1','success'
UNION
SELECT 3,'tg2','success'
UNION
SELECT 4,'tg2','Reject'

SELECT NameTg,
    SUM(CASE WHEN StatusTg = 'success' THEN 1 ELSE 0 END) AS Success_count,
    SUM(CASE WHEN StatusTg = 'Reject' THEN 1 ELSE 0 END) AS Reject_count
FROM #Table
GROUP BY NameTg

DROP TABLE  #Table

RESULT :
NameTg   Success_count  Reject_count
tg1           2               0
tg2           1               1

A: You can use pivot as
SELECT *
FROM
    (
      SELECT Name,
             Status
      FROM T
    ) TT
PIVOT
(
  COUNT(Status)
  FOR Status IN (success,Rejected)
) PVT

Demo


text:
Q: Deserialization of Auto-Generated Classes I'm using binary serialization to save objects to a configuration file and read them back again. One of these classes has an event handler which I forgot to mark with the NonSerializedAttribute in previous builds, so this bit of information has already ended up in a few config files. To complicate matters, this handler is initialized with a lamda expression, which forces the compiler to automatically generate an anonymous type for it.
public event PropertyChangedEventHandler PropertyChanged = (sender, args) => { };
The issue is that this type name changed in subsequent builds, so when the BinaryFormatter encounters an unknown type, it throws a SerializationException ("Cannot find member: <.ctor>b__1"). I can't seem to catch this exception at the right location since it occurs deep inside mscorlib.dll, and I've had no luck with the SerializationBinder.
Is there any way I can force the BinaryFormatter to ignore this field, or remove it from the serialized stream entirely? I should add that this class in question does not implement the ISerializable interface.

A: Maybe I'm missing something, but can't you just mark the field with the NonSerializedAttribute?


text:
Q: Parsing of my own SQL Request in Php At the moment I'm making a php program that can take a SQL Request with a left join (only two table) the goal is to display them and to edit them. The problem is that if I want to edit them I have to know where the variable comes from (which table...) and i would like to parse my request for know it.
SELECT users.login, users_info.linkedin, users.password, users.region, users.email, users.business, users.firstname, users.name, users.version, users.updatable, users.bodyshop_id, users.mac, users.register_date, users.lastvisite_date , users_info.address1, users_info.address2, users_info.address3, users_info.zip, users_info.cellphone, users_info.phone, users_info.direct_dial_phone, users_info.birthday, users_info.date_in, users_info.date_out, users_info.picture_private, users_info.picture_public, users_info.bodyshop, users_info.enterprise, users_info.department, users_info.job, users_info.facebook, users_info.twitter, users_info.instagram
FROM users
LEFT JOIN users_info ON users.id = users_info.id

So I just want to create a function that take for example "login" as parameter and return me "users" or linkedin would return me users_info. Do you know a proper way for doing it in php ?
Thanks !

A: SELECT users.login, users.password, users.region, users.email, users.business, users.firstname, users.name, users.version, users.updatable, users.bodyshop_id, users.mac, users.register_date, users.lastvisite_date , users_info.address1, users_info.address2, users_info.address3, users_info.zip, users_info.cellphone, users_info.phone, users_info.direct_dial_phone, users_info.birthday, users_info.date_in, users_info.date_out, users_info.picture_private, users_info.picture_public, users_info.bodyshop, users_info.enterprise, users_info.department, users_info.job, users_info.facebook, users_info.twitter, users_info.linkedin, users_info.instagram
FROM users as users
LEFT JOIN users_info as users_info ON users.id = users_info.id
WHERE user.you_field_name = your_condition

A: The most modern syntax to connect mysql in php today is using of PDO. File index.php, for example:
<?php
        class ConnectPDO {

            private $db_name = 'my_db_name';
            private $db_login = 'root';
            private $db_password = '12345678';
            private $host = 'localhost';
            private $opt = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            public $connection = null;

            function __construct() {
                $this->connection = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name . ';charset=utf8', $this->db_login, $this->db_password, $this->opt);
            }
        }

    $c=new ConnectPDO();

    $params=array();
    $params['login']='Frodo';

    $prepared=$c->prepare("SELECT * FROM users WHERE login=:login");
    $prepared->execute($params);
    // fetching data array
    $data=$prepared->fetchAll();

    // view into browser
    echo '<pre>';
    print_r($data);
    echo '</pre>';

To prevent injections and to use best practice coding well known practice is to use prepare and execute methods. You can install xampp fast on windows and test this code. Working folder is /xampp/htdocs.
This parameters need to by changed by your credentials.
private $db_name = 'my_db_name';
            private $db_login = 'root';
            private $db_password = '12345678';
            private $host = 'localhost';

A: Use $stmt->fetch(PDO::FETCH_NUM); to get your data in numeric indexed array, then use $stmt->getColumnMeta($col_num); to get info about a column in question.

A: Finaly I did it like that thanks for helped !
public function getTableWithField($field) {

    $tableName1 = "users";
    $tableName2 = "users_info";

    $pos = strpos($this->SQLCMD, $field);

    $tryOne = substr($this->SQLCMD, $pos - strlen($tableName1) - 1, strlen($tableName1));
    $tryTwo = substr($this->SQLCMD, $pos - strlen($tableName2) - 1, strlen($tableName2));

    if ($tableName1 == $tryOne)
        return $tableName1;

    else if ($tableName2 == $tryTwo)
        return $tableName2;

    return "";
}


text:
Q: Devo fazer o commit do arquivo .gitignore? Uma dúvida que tenho quando começo projetos é:
Devo fazer o commit do arquivo .gitignore?
Em caso afirmativo, qual seria a sua função? Manter a padronização num projeto compartilhado?

A: Sim, tu deves "commitar" o .gitignore a fim de que todos que usem o repositório não subam os arquivos que devem ser ignorados - como, por exemplo, binários gerados pela compilação dos projetos, ou configurações específicas que podem alterar de máquina para máquina (configuração da IDE, temas que tu gostas de usar, etc).
Nesse link tu podes ver mais detalhes sobre como usar o .gitignore.


text:
Q: Create a temporary table showing the most eventful country for each year in SQL Server I have an exercise in SQL Server: I have two tables Country and Events.
The Events table holds the event details including the city where an event happens. The table Events has a foreign key CountryID (CountryID is the primary key in table Country).
I need to create a temporary table showing the most eventful country for each year.
Any help would be appreciated
Thanks

A: You weren't far off with your attempt, but you need to use a CTE to aggregate your data first. I've assumed that the final order of your data is important, so I used a second CTE, rather than a TOP 1 WITH TIES tio get the final result:
WITH CTE AS(
    SELECT YEAR(e.EventDate) AS YearOfEvent,
           c.CountryName,
           COUNT(e.CountryID) AS NumberOfEvents
FROM [dbo].[tblEvent] AS e
     INNER JOIN tblCountry AS c ON e.CountryID = c.CountryID
GROUP BY e.CountryId,
         c.CountryName,
         YEAR(e.EventDate)),
RNs AS(
    SELECT YearOfEvent,
           CountryName,
           NumberOfEvents,
           ROW_NUMBER() OVER (PARTITION BY YearOfEvent ORDER BY CTE.NumberOfEvents DESC) AS RN
    FROM CTE)
SELECT YearOfEvent,
       CountryName,
       NumberOfEvents
FROM RNs
WHERE RN = 1
ORDER BY RNs.YearOfEvent ASC;


text:
Q: How do I find the largest number in each position of three possibly different length lists and find the sum of them? I have three inputs. a1, a2, and a3.
For example, here is an input:
-1, -2, -3
-4 -5 -6 -8 -9
-10 -11
The output would be -23.
Because when comparing the first position of each list, you find that the largest number is -1. Then -2, -3, -8, and -9.
Here is what i have so far. It seems like the program is working perfectly fine with positive numbers, but when it comes to negative numbers, the output is incorrect. The example I gave above outputted a -3 instead of a -23. How do I fix this?
a1 = a1.split()
a2 = a2.split()
a3 = a3.split()

length_one = len(a1)
length_two = len(a2)
length_three = len(a3)
longest_length = max(length_one, length_two, length_three)

if length_one < longest_length:
    difference_one = longest_length - length_one
    for i in range (difference_one):
        a1.append('0')

if length_two < longest_length:
    difference_two = longest_length - length_two
    for i in range (difference_two):
        a2.append('0')

if length_three < longest_length:
    difference_three = longest_length - length_three
    for i in range (difference_three):
        a3.append('0')

for i in range (longest_length):
    a1[i] = int(a1[i])
for i in range (longest_length):
    a2[i] = int(a2[i])
for i in range (longest_length):
    a3[i] = int(a3[i])

sumlist = []

for i in range (longest_length):
    biggest_number = max(a1[i], a2[i], a3[i])
    sumlist.append(biggest_number)

total = 0
for i in range (len(sumlist)):
    total = total + sumlist[i]

return total

A: Your code works for positive numbers because you're appending 0 to the shorter lists, and any positiven number will be greater than 0.
If you want it to work for an arbitrary negative number, I'd suggest appending float('-inf') instead. This is a value that represents negative infinity, and basically any numerical variable x, no matter how negative, will evaluate True to x > float('-inf')
since you're casting to int, you would need to slightly modify your code so that it works for float instead:
a1 = a1.split()
a2 = a2.split()
a3 = a3.split()

length_one = len(a1)
length_two = len(a2)
length_three = len(a3)
longest_length = max(length_one, length_two, length_three)

if length_one < longest_length:
    difference_one = longest_length - length_one
    for i in range (difference_one):
        a1.append(float('-inf'))

if length_two < longest_length:
    difference_two = longest_length - length_two
    for i in range (difference_two):
        a2.append(float('-inf'))

if length_three < longest_length:
    difference_three = longest_length - length_three
    for i in range (difference_three):
        a3.append(float('-inf'))

for i in range (longest_length):
    a1[i] = float(a1[i])
for i in range (longest_length):
    a2[i] = float(a2[i])
for i in range (longest_length):
    a3[i] = float(a3[i])

sumlist = []

for i in range (longest_length):
    biggest_number = max(a1[i], a2[i], a3[i])
    sumlist.append(biggest_number)

total = 0
for i in range (len(sumlist)):
    total = total + sumlist[i]

return total

A: You might like to use zip_longest.  It is just like zip but greedy instead of lazy.
Each iteration slices off one element from each of a1, a2, a3 and stored as a tuple tup.  We then select the maximum value to append to res, and drop the remaining two.  We then sum at end.
from itertools import zip_longest
a1 = [-1, -2, -3]
a2 = [-4, -5, -6, -8, -9]
a3 = [-10, -11]

res = [max(tup) for tup in zip_longest(a1, a2, a3, fillvalue=float('-inf'))]

print(sum(res))

Output:
-23


text:
Q: Runing a custom executable on PDF files stored in azure blob storage with azure web app front-end I have a web app built using ASP.NET 4.5/C# and is hosted in azure as a Web App. The site allows users to upload PDF files which are then stored in a azure blob container and can later be download via the website as needed. So far so good and everything was working fine.
We now have a new requirement which involves processing these files using the custom win32 executable and the website must know if the processing was successful or not. This exe has a setup file and must be installed on the target machine before it can be used.
I have been scratching my head over how to architect this feature. I have come across many articles which tell a Worker Role is needed, or a VM is needed. But all articles seem to a very abstract.
Given that the installer for the executable requires manual intervention, I am thinking a Azure VM is the way to go. But how will the web app communicate to this. How do I notify the web app with the result of the process?

A: You cannot install such software in an Azure Web App, since web apps are sandboxed. As such, you won't be able to run that setup exe.
For such processing, you'd need to run that part of your app in a Virtual Machine or web/worker role.

A:
But how will the web app communicate to this. How do I notify the web app with the result of the process?

Azure Queue storage could meet your requirement. It can provide cloud messaging between application components. Your VM could write the process result to a queue and your web app could read the process result from the same queue.
To add a new message to a queue, you could reference following code.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Create the queue if it doesn't already exist.
queue.CreateIfNotExists();

// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);

In Your Web App, you could create a QueueTrigger WebJob, the job will be executed immediately if any new message has been added to the queue.
public static void ProcessQueueMessage([QueueTrigger("myqueue")] string processResult, TextWriter log)
{
   //You can get the processResult and do anything needed here
}


text:
Q: Keyboard Event Only Fired From Original Class Using FlashDevelop, I've got a bit of code to detect keyboard events. The problem is, if I run this code from the main class (Main.as) it'll trigger the event, but not if I go to another class.
For instance, I have the main class, and it has this function
addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
public function onKeyDown(e:KeyboardEvent):void
{
    trace(e.keyCode);
    if (gameState == 1){main.onKeyDown(e);}
}

Now, this works fine in the first class. But when I send it to my second class, MainMenu.as, nothing happens.
        main = new MainMenu();
        addChild(main);
        gameState = 1;

There's no message from either class. If I put the event in the second class, nothing happens. All the other events besides keyboard events still work.

A: Keyboard events are only forwarded to the MovieClips who has focus (and their parents). If you want to capture all events without any exception, add it to the stage (as it is the parent of everything, it will always receive the event): stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);. Remember to remove the event after you're done with the class (it won't remove itself).
Another possibility is to force the focus of the stage to your specific class: stage.focus = this;, but I would avoid this if possible.


text:
Q: Identityserver3 Update Permissions I wondering if i could update the current user claims w/o the user having to authenticate again.
In my case the user will log into the application and will receive a set of claims. Later he will be able to change the customer his working with. Once that is done he need to receive a new set of claims.
Does any one know if that can be done?
Thanks in advance.

A: You almost answered your own question - a token is not a good place to store permissions, because the only way to update the token content is to get a new token.
Tokens are good from transmitting immutable identity data. Everything else belongs into the realm of application or business logic design.


text:
Q: ASP.NET MVC: контроллер Начинаю разбираться в ASP.NET MVC, до этого писал на PHP на MVC фрейворке kohana, по этому голова как бы варит, но тут не могу вкурить на самом начале, вот стандартный контроллер и мой метод User
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }
        public ActionResult User()
        {
            return View();
        }

создал view с названием User.aspx, по идее должен его вызвать так: http://localhost:8080/WebSite1/Home/User/, а консоль говорит 404. Расскажите эти основы пожалуйста, что и куда.
Другие методы работают, все норм.
И вот ещё что, пишу например так
public ActionResult Index()
            {
                return "Hello, world!";
            }

а стандартная страница проекта не меняется, в чем подвох?


text:
Q: File with two consecutive spaces in name fails to compile How can I compile a file with two consecutive spaces in the filename?
The following compiles when named file name.tex, but not when named file{two spaces here}name.tex (sorry, the editor here converted the two consecutive spaces in the name to a single space, so I had to get creative):
    \documentclass{article}
    \begin{document}
    File name with two spaces fails to compile.
    \end{document}

The error I am getting is:

This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/W32TeX) (preloaded format=pdflatex)
  restricted \write18 enabled.
  entering extended mode
  ! I can't find file `"./file name.tex"'.
  <*> "./file  name.tex"

Thanks!

A: you can input a file with multiple spaces in its name by
\documentclass{article}

\begin{document}

\input{"a\space\space b.tex"}

\end{document}

which works as you can see on the terminal
LaTeX2e <2020-02-02> patch level 2
L3 programming layer <2020-02-14>
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/size10.clo))
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-pdfmode.def)
(./cc640.aux) (./a  b.tex) [1{/usr/local/texlive/2019/texmf-var/fonts/map/pdfte
               >>>12<<<
x/updmap/pdftex.map}] (./cc640.aux) )</usr/local/texlive/2019/texmf-dist/fonts/
type1/public/amsfonts/cm/cmr10.pfb>

On the commandline you can use
$ tex "a\space\space b"
This is TeX, Version 3.14159265 (TeX Live 2019) (preloaded format=tex)
(./a  b.tex)


text:
Q: Delete entire node using lxml I have a an xml document like the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>company</groupId>
    <artifactId>art-id</artifactId>
    <version>RELEASE</version>
</parent>

<properties>
    <tomcat.username>admin</tomcat.username>
    <tomcat.password>admin</tomcat.password>
</properties>

<dependencies>
    <dependency>
        <groupId>asdf</groupId>
        <artifactId>asdf</artifactId>
        <version>[3.8,)</version>
    </dependency>
    <dependency>
        <groupId>asdf</groupId>
        <artifactId>asdf</artifactId>
        <version>[4.1,)</version>
    </dependency>
</dependencies>

how can I delete the entire node "dependencies"?
I have looked at other questions and answers on stackoverflow and what is different about is the namespace aspect of this xml, and the other questions ask to delete a subelement like "dependency" while I want to delete the whole node "dependencies."  Is there an easy way using lxml to delete the entire node?
The following gives a 'NoneType' object has no attribute 'remove' error:
from lxml import etree as ET

tree = ET.parse('pom.xml')
namespace = '{http://maven.apache.org/POM/4.0.0}'
root = ET.Element(namespace+'project')
root.find(namespace+'dependencies').remove()

A: First, grab the root node. Since it is <project ... > (vs <project .../>) the "parent" element of dependencies is project. Example from the documentation:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

Once you have the root, check root.tag(), it should be "project".
Then do root.remove(root.find('dependencies')), where root is the project node.
If it were <project .../> then it would be invalid XML since there must be a root element. I can see exactly where you are coming from, though.

A: You can create a dict mapping for your namespace(s), find the node then call root.remove  passing the node, you don't call .remove on the node:
x = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>company</groupId>
    <artifactId>art-id</artifactId>
    <version>RELEASE</version>
</parent>
<properties>
    <tomcat.username>admin</tomcat.username>
    <tomcat.password>admin</tomcat.password>
</properties>
<dependencies>
    <dependency>
        <groupId>asdf</groupId>
        <artifactId>asdf</artifactId>
        <version>[3.8,)</version>
    </dependency>
    <dependency>
        <groupId>asdf</groupId>
        <artifactId>asdf</artifactId>
        <version>[4.1,)</version>
    </dependency>
</dependencies>
</project>"""
import lxml.etree as et
from StringIO import StringIO

tree = et.parse(StringIO(x))
root =tree.getroot()

nsmap = {"mav":"http://maven.apache.org/POM/4.0.0"}

root.remove(root.find("mav:dependencies", namespaces=nsmap))

print(et.tostring(tree))

Which would give you:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>company</groupId>
    <artifactId>art-id</artifactId>
    <version>RELEASE</version>
</parent>
<properties>
    <tomcat.username>admin</tomcat.username>
    <tomcat.password>admin</tomcat.password>
</properties>
</project>


text:
Q: Node cpp extension threads everybody
Trying to write my first node extension for dynamic library ("/usr/local/lib/libkdriveExpress.so")
This extension should connect to device and receive data. On received data it should call back function from javascript. I have found how to store persistent function so it isn't issue to call js function from cpp.
In this example I use simple c++ function just to except issues with js
///
void test(const uint8_t *telegram, uint32_t telegram_len, void *user_data){
    kdrive_logger_ex(KDRIVE_LOGGER_ERROR, "kdrive: event callback");
};
void ap_open_ip(const FunctionCallbackInfo <Value> &args) {
/// ...
/// now register
    kdrive_ap_register_telegram_callback(ap, &test, NULL, &key);
/// ...
}

when I call it from js it works fine.
if (kdrive.ap_open_ip(ap, "192.168.3.201") == 0) {
    console.log("great success", ap);
    setTimeout(function () {
        console.log(kdrive.whoami());
   }, 2000)
}

but when I call any function from extension it doesn't work. In the code above I call whoami function and it doesn't use dynamic library, just return string.
here is the log:
great success 1
11:42:45:518 [kdrive.express] kdrive: event callback
11:42:45:590 [kdrive.express] kdrive: event callback
11:42:45:692 [kdrive.express] kdrive: event callback
11:42:45:735 [kdrive.express] kdrive: event callback
11:42:45:831 [kdrive.express] kdrive: event callback
11:42:45:900 [kdrive.express] kdrive: event callback
11:42:46:167 [kdrive.express] kdrive: event callback
11:42:46:717 [kdrive.express] kdrive: event callback
>>> whoami call
11:42:47:525 [kdrive.connector.ConnectorNotificationHandler] onSignal: System exception: cannot lock mutex
11:42:48:067 [kdrive.connector.ConnectorNotificationHandler] onSignal: System exception: cannot lock mutex
11:42:48:420 [kdrive.connector.ConnectorNotificationHandler] onSignal: System exception: cannot lock mutex

Here is description for kdrive_ap_register_telegram_callback function:

Registers a callback function.
This callback function will be called when a telegram is received by
  the Access Port. A notification thread is used internally so this
  callback will be in the context of the notification thread (and not
  the main thread). That is, care should be taken when calling out from
  the callback. This function generates a unique key to represent the
  callback. This key can be used to remove the callback at a later
  state.

So, I guess issue is with threads.
I'm newbie with cpp extensions and cpp, writed in js before. So, I guess, I need to learn how threads in cpp works and how v8 engine handle it.
Would appreciate any advice, suggestions.

A: The issue wasn't related to threads. It was because js gc destroyed kdrive object.


text:
Q: return an anonymous function to a jsonp call without a callback So, I was asked to create some kind of web service that return a javascript library (that changes based on the query params) to a jsonp call.
I tried to write down some scripts to do so and looks like it's possible and easy.
Now the question is, I read a lot of articles about jsonp but, why should I not make something like this? And what could I do to achive the same result but not this way?
client sample here:
var script = document.createElement('script');
script.src = '//my_url/testjsonp.php';

document.getElementsByTagName('head')[0].appendChild(script);

server sample here:
echo 'var a = function(){ /* basically what i want here */ }()';

A: A couple of issues with that:

*

*You're creating a global a variable. The page calling your service should be in charge of that, so unless you've made the a configurable, that's a problem.

*The code within your function would have to magically know what it was supposed to do with the data. That's contrary to the point of JSONP, which is for the server just to return the data and let the client decide what to do with it.
Those two reasons are why a standard JSONP request allows the caller to specify the callback name (usually with a callback parameter, but the name varies)

http://example.com/path/to/service?callback=foo

...and a standard JSONP response looks like this:
foo({/*...JSON here...*/});

That way, the caller defines the function, which knows what to do with the data you're passing into it.


text: Q: Is there a way to scale icons in the launcher smaller than 32 pixels? I am using 11.10 beta and want to give Unity another chance (I was always very fond of XFCE) ... anyway is there a way to scale the Icons to a really small size, let's say ~25?? And can this also be done for unity-2d, I figure the Compiz configuration tool won't work with Unity-2D?