text:
Q: Dealing with HTTP and websocket connections on the backend I am working on a game I want to support over iOS/Android/Browser and thinking Websockets is what I want to use for the communication. I use python and so found that I should be using Tornado.
I am trying to understand websockets a little better and their integration in browsers.

*

*Will the messages over the websocket connection also contain the HTTP cookies for the connection? If not can I send it?

*How is the HTTP connection for the web page linked to the websocket connection? I mean how will I know they are coming from the same webapp on the server side?

*The Tornado wiki page says in the performance section that Tornado can be set up with nginx as the front end. How does that work? I thought Tornado and nginx have to be running on separate machines since both listen on port 80 and also because nginx does not understand WS protocol. What am I missing?

Also it will be great if someone can point me to any resources I can read up on about either Tornado or websocket that could help me.

A: *

*The websocket is setup by sending an ordinary http request to the server, this request will contain all the stored cookies for the domain. If you do a native implementation for e.g. Android you can use libraries like Autobahn|Android, the API allows you to set cookies for the websocket handshake.

*You can set a cookie when first loading the page to maintain a session identifier.

*In that scenario they would be running 4 Tornado instances (on different ports, but not port 80) and Nginx on port 80 as a load-balancer, spreading the incoming client requests to the Tornado instances, see running Tornado and Nginx on same server for a configuration example. Recent versions of Nginx does support websockets, see e.g nginx + python + websockets.


text:
Q: Django Custom User Model app level permissions management in admin I use a custom user model in my django 1.9 project. The model is very similar to the full example given on Django documentation (https://docs.djangoproject.com/en/1.9/topics/auth/customizing/). After integrating the model, app level permissions are disabled on the admin. Only the is_admin attribute is available. Is there a way to have app level permissions as in the default admin interface when using a custom user model?

A: I figured out the solution in the meanwhile. In the full example given on the documentation, group permissions are disabled for some reason. Also Group model was unregistered on the example. First of all, I used PermissionsMixin. I kept group model registered and  add 'groups' and 'user_permissions' on the fieldsets of UserAdmin, and they came back.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I properly assign a value to an array (of structure type) element? #include <stdio.h>

struct virus
{
    char signature[25];
    int size;
}v[2];

int main(void) {

    static v[0] = {"Yankee",1813};
    static v[1] = {"Doodle",2813};
    int i;

    for(i=0;i<=1;i++)
    {
        printf("%s %d\n",v[i].signature,v[i].size);
    }

    return 0;
}

I am getting the compiler error in this C code.

Error: Declaration syntax in function main()

I am guessing that there is some error in v[2], as it is associated with extern class whereas, v[0] and v[1] are associated with static class.
But, I am not sure that is this the only reason or some other ?

Edit : I have edited the code by removing the wrong syntax.

A: There is no error in declaration of v[2], the problem is later.
You've written
 static struct v[0] = {"Yankee",1813};

which attempts to define a 0-sized array, which is not allowed by default C standard.
That said, the syntax is also horribly wrong. You don't have a proper type there, remember, struct itself is not a type, it's a keyword. struct <something> is actually a type.
Then, from the logical point of view, you probably don't want a new variable altogether. In case you want to use the array elements from the v, just use the variable name, that's all. Something like
#include <stdio.h>

struct virus
{
    char signature[25];
    int size;
}v[2] = { {"Yankee",1813}, {"Doodle",2813}}; //get it initialized, job done

int main(void) {

    int i;
    for(i=0;i<=1;i++)
    {
        printf("%s %d\n",v[i].signature,v[i].size);
    }

    return 0;
}

will do the job in much better way, IMHO.

EDIT:
In case, you're interested in assigning individual elements (not initialization), well, you cannot use a brace-enclosed initializer for that purpose, it's not meant to be RHS operand for an assignment. You need to use a compound literal for that purpose, something like
v[0] = (struct virus){"Yankee",1813};
v[1] = (struct virus){"Doodle",2813};

will also do the job.

A: Don't mix up struct definitions with variable declarations, that's sloppy practice.
Instead, use a typedef:
typedef struct
{
    char signature[25];
    int size;
} virus_t;

Then you can declare variables of this type as you please:
static virus_t v[2] =
{
  {"Yankee",1813},
  {"Doodle",2813}
};

Or with designated initializers:
static virus_t v[2] =
{
  [0] = {"Yankee",1813},
  [1] = {"Doodle",2813}
};


text:
Q: Acer 5750G/5755G Perl script requires access to /dev/port I recently decided to get rid of windows and install Linux on my Computer. So far it has been a good experience.
However, one of the main things that was worrying me was the fact that I maybe could not control the fan speed as I was able to with Windows 10. Acer had released some time ago a utility to control the fan speed and it worked wonderfully.
Thankfully however, I managed to find a perl script that does the exact same thing on Linux, and it works like a charm when I run it with sudo, however, whenever I simply run it without sudo, it gives me an access denied message about /dev/port.

I want to be able to run this script without root access and even write a bash script for it (Maybe even a complete port with a GUI like the original Acer app), but as long as this /dev/port issue remains, I can't do anything because I will always need to enter my password.
I have searched and I am indeed a member of the dialout group, having restarted and relogging multiple times, but even that doesn't help me.
I have also tried looking at the source code of this perl script but I just can't wrap my head around it, seeing as it has a lot of assembly magic.

So my question is this: I want to execute a perl script that requires access to /dev/port without running it using sudo, but even if I am in the dialout group, it still gives me the error. What am I doing wrong?
My guess is that the ports that this script needs do not belong to the dialout group but some other group, like tty, but I can't add myself to the tty group.
Regardless, thanks.

A: on my system:
amias@rome:~$  ls -l /dev/port
crw-r----- 1 root kmem 1, 4 May 27 10:53 /dev/port

This suggests that you need to run it via sudo, i would also resist the temptation to open up the permissions to /dev/port as it will weaken your security.
What you could do is configure sudo to allow you to run that script as root without a password.
sudo visudo                # launch the safe sudo config editor

then add the following line at the bottom of the file substituting your values for user and the path to the script
user localhost = (root) NOPASSWD: /full/path/to/script

It would be wise to make that script be owned by root and not writable by anyone else but root, an attacker could find out that it will be run as root and could insert other commands that could compromise your system.


text:
Q: Gitlab automated changelog creation I was wondering how the CHANGELOG.md overall file is created.
I've seen this site https://docs.gitlab.com/charts/development/changelog-manager.html but I don't know where to find changelog_manager.rb and how to correctly call it, that i get a overall CHANGELOG.md out of multiple changelog entries (https://docs.gitlab.com/charts/development/changelog.html).
Thank you in advance.

A: You can clone the repo at https://gitlab.com/gitlab-org/charts/gitlab/-/tree/master.
The referenced script name scripts/changelog_manager.rb no longer exists in this repo, going by the content and history I'd say it was refactored/reorganized and you'd use bin/changelog today.


text:
Q: AngularJs Language Property always as Location Keypair I like to always show the language property in the address-bar. $Location.Search("Key", "Value") do what i like. The Problem is while the user clicks a href the property is gone. Is that possible to always show property and catch a change without changing route ?
http://www.address.com/#Start?lang=en-en

A: I think you are looking for $routeProvider reloadOnSearch property. This is true by default. Set it to false and if the querystring changes the route would not refresh. See documentation here
Something like
$routeProvider.reloadOnSearch = false;
during route config stage.


text:
Q: Ubuntu 12.04 - Copying large files over NFS and SAMBA causes server to drop off the network I have a 64bit 12.04 server with a raid 6 array.
I have setup NFS and SAMBA shares.
If I copy any files over NFS from client to server - the speed of the copy is ridiculously low - around 1-2MB/s
If I copy to the same folder being shared over SAMBA - I get 45-50MB/s
However, if I copy a group of folders that exceed 10GB over either connection the server will just drop of the network and I cannot access it via ssh or any other means.
I am unable to use:
sudo ifconfig eth0 up/down
to reset the nic interface - the only option is to power down and restart the server.
If anyone can point me to any logs to check for what is causing the error or help to diagnose I would be much appreciated as this makes my server pretty much useless.
Cheers
ice.

A: Instead manually restarting the interface, try
sudo restart network-manager

As for your troubles. The slow connection speed with NFS comes from the fact that NFS by default syncs everything (i.e. accepts a small chunk of data; writes the chunk down; then acknowledges accepting the chunk); this is impractical for transferring large files. One can use the async option for that, but it can be dangerous. You can read more about optimizing NFS performance here.
I'm not sure about the other problem, though. I don't know why your connection drops.
However, and in general, for large files I'd use rsync rather than mounted shares. It is more verbose and it is easier to resume from the point where it was interrupted, and all it needs is an ssh connection.


text:
Q: using if function in textbox I have the following code behind a userform
Private Sub add_button()
    On Error Resume Next
     If TextBox1 > TextBox9 Then
         TextBox12 = "YES"
     Else
         TextBox12 = "No"
         If TextBox8 > TextBox3 And TextBox8 < TextBox4 Then
            TextBox11 = "YES"
         Else
            TextBox11 = "no"
            If TextBox12 = "NO" Then
                TextBox10 = "NO"
            ElseIf TextBox11 = "NO" Then
                TextBox10 = "NO"
            Else
                TextBox10 = "YES"
            End If
         End If
     End If
End Sub

The above code does not work: please advice on possible errors.

A: Few things,

*

*Remove error handling you will then know if there's an issue in execution as Siddharth's comment

*Balance both left right comparison for text formats/ cases as Larry's comment

*Use proper properties to get set values. In you case it is Textbox.Text

*Run through the code in debug mode by pressing F8 and adding break points

*Do Debug.Print or a Msgbox at each if-else to ensure the logic flow

*Respond to comments as the community is trying their best to help you solve your issue.

Here is change you could do to your code. At this point of the logic you have already set both 12 and 11 to NO in that case it is unnecessary to do this check:
 If TextBox12 = "NO" Then
     TextBox10 = "NO"
 ElseIf TextBox11 = "NO" Then
     TextBox10 = "NO"

You may simply set Textbox10.Text = "NO"

A: Please can you check that the actual conditions of the script are working as I'm a little unsure how well these conditions will work against text. Just copy out all the existing code and copy the following in as a test:
Private Sub add_button()
    If TextBox1 > TextBox9 Then
        MsgBox "TextBox1 > TextBox9 "
    Else
        MsgBox "TextBox1 < TextBox9 "
        If TextBox8 > TextBox3 And TextBox8 < TextBox4 Then
            MsgBox "TextBox8 > TextBox3 And TextBox8 < TextBox4 "
        End
    End If
End Sub


text:
Q: DateTimePicker Calender Button Width im trying to create a nullable DateTimePicker which can optionally show some hint text when the control is marked as having a null date.. to achieve this, ive inherited from DateTimePicker and added a Label control with hint text that covers the text part when the control is marked as having a null date.. the problem is that if the DateTimePicker is set to display the usual calender icon, the width of this button is VARIABLE..
the images below show the same DateTimePicker control with different sizes.. as soon as the calender icon button starts to overlap the text, it is changed to a smaller, simple dropdown icon button..

i can try using reflection to read/write private fields but im at a loss as to what to read..
my question.. how do i find out the width of the calender icon displayed in the DateTimePicker control correctly..

A: i found a way myself.. =).. the DateTimePicker displays the calender icon button when the control is wider than the text displayed.. when the button starts to clip the text, the control automatically falls back to displaying a smaller dropdown button (visible in the second row of the images in the original question).. so we find out the width of the text, the calender icon button, the dropdown button, and the control itself.. the math that follows is simple..
const int C_BUTTONICON_WIDTH = 34;
const int C_BUTTONARROW_WIDTH = 17;

protected int GetLabelWidth()
{
    int iControlW = this.Width;
    int iTextW = TextRenderer.MeasureString(this.Text, this.Font).Width;

    int iLabelW = 0;
    if (iTextW <= iControlW - C_BUTTONICON_WIDTH)
    {
        iLabelW = iControlW - C_BUTTONICON_WIDTH;
    }
    else
    {
        iLabelW = iControlW - C_BUTTONARROW_WIDTH;
    }
    return iLabelW;
}

you might need to adjust a few pixels depending on the placement of the Label itself.. =).. served my purpose.. =)

A: No need to re-invent the wheel. Check this out:
Nullable DateTimePicker on CodeProject
and this one:
Yet another nullable DateTimePicker control


text:
Q: Git Bash under Windows reporting errors, but git under FreeBSD not My project is located on remote server, running FreeBSD.
My home PC is running Windows and I have local drive mounted via SSH to this remote FreeBSD server.
As version control system I'm using git provided by GitHub.
When I'm running git status from FreeBSD under project folder - everything is okay.
But when I'm running git status from the same project folder under Windows my Git Bash is saying fatal: loose object b33edafa4d6108187f6b1c232fc68685b982ba63 (stored in .git/objects/b3/3edafa4d6108187f6b1c232fc68685b982ba63) is corrupt
I've tried running git fsck on directly on FreeBSD machine - everything is ok with repository: Checking object directories: 100% (256/256), done.
But I've tried running the same command git fsck using Windows's Git Bash on same project folder - I'm getting this error: Checking object directories: 100% (256/256), done.
fatal: loose object 01a6dcd554545da0b1fa191e11f3406a5ded7581 (stored in .git/obj
ects/01/a6dcd554545da0b1fa191e11f3406a5ded7581) is corrupt
Why git on FreeBSD is not reporting any errors, but Windows Git Bash is reporting? I'm doing all commands on the same project folder.


text:
Q: Regex detect any repeated character but with optional whitespace between So currently I've got the following regex pattern, allowing me to detect any string containing 9 characters that are the same consecutively.
/^.*(\S)\1{9,}.*$/

This works perfectly with a string like the following: this a tesssssssssst however I wish for it to also detect a string like this: this a tess sss ssssst (Same number of the repeated character, but with optional whitespace)
Any ideas?

A: You need to put the backreference into a group and add an optional space into the group:
^.*(\S)(?: ?\1){9,}.*$

See the regex demo. If there can be more than 1 space in between, replace ? with *.
The .*$ part is only needed if you need to get the whole line match, for methods that allow partial matches, you may use ^.*(\S)(?: ?\1){9,}.
If any whitespace is meant, replace the space with \s in the pattern.

A: You can check more than a single character this way.
It's only limited by the number of capture groups available.
This one checks for 1 - 3 characters.
(\S)[ ]*(\S)?[ ]*(\S)?(?:[ ]*(?:\1[ ]*\2[ ]*\3)){9,}

http://regexr.com/3g709
 # 1-3 Characters
 ( \S )                        # (1)
 [ ]*
 ( \S )?                       # (2)
 [ ]*
 ( \S )?                       # (3)
 # Add more here

 (?:
      [ ]*
      (?: \1 [ ]* \2 [ ]* \3 )
      # Add more here
 ){9,}


text:
Q: How can I add shapes automatically in paintComponent? As a beginner, whenever I want to add graphical shapes inside the frame I do something like this:
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillRect(0, 0, 10, 10);
    g.fillOval(10,10,10,10);
}

How do I draw an unlimited number of shapes automatically inside the frame? If I follow the way I did above I only have a limited number of shapes(Rect, Oval and nothing else).
I'm looking for something different, for example, whenever a method addStuff(x, y) has called, it draws "Stuff" automatically at the coordinate x and y without having to edit anything inside paintComponent manually again.
I used to do this with the acm package and it was easy. Just like the code below.
for (int i = 0; i < NCIRCLES; i++) {
    double r = rgen.nextDouble(MIN_RADIUS, MAX_RADIUS);
    double x = rgen.nextDouble(0, getWidth() - 2 * r);
    double y = rgen.nextDouble(0, getHeight() - 2 * r);
    GOval circle = new GOval(x, y, 2 * r, 2 * r);
    circle.setFilled(true);
    circle.setColor(rgen.nextColor());
    add(circle);
}

As you can see above, I can add as many circles as I want, I know it can take pages to explain this but I just want a brief instruction on how to create something similar to the code above without relying on acm package.

A: I would use an abstract class to define this behavior.
abstract class OpalDraw {
    protected int x1, y1, x2, y2;
    protected OpalDraw(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }
    abstract public void draw(Graphics g);
}

class OpalOval {
    public OpalOval(int x1, int y1, int x2, int y2) { super(x1,y1,x2,y1); }
    public void draw(Graphics g) {
        g.drawOval(x1,y1,x2,y1);
    }
}

class OpalRect {
    public OpalRect(int x1, int y1, int x2, int y2) { super(x1,y1,x2,y1); }
    public void draw(Graphics g) {
        g.drawRect(x1,y1,x2,y1);
    }
}

Then in your painting container you can have
addOval(int x1, int y1, int x2, int y2) {
    myDraws.add(new OpalOval(x1,x2,y1,y2);
}

addRect(int x1, int y1, int x2, int y2) {
    myDraws.add(new OpalRect(x1,x2,y1,y2);
}

Then later inside paintComponent(Graphics) you can
for(OpalDraw draw : myDraws) draw.draw(g);

A: In your class extending JFrame, add a private member like
private ArrayList<Shape> shapes = new ArrayList<Shape>();

and your methods, for example
public void addRectangle(int x, int y, int with, int height) {
    shapes.add(new Rectangle(x, y, width, height));
}

Then, in your paintBackground method, have something like
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (Shape shape : shapes) {
        if (shape instanceof Rectangle2D) {
            g.drawRect(shape.getX(), shape.getY(), shape.getWidth(), shape.getHeight());

        } else if (shape instanceof Ellipse2D) {
            // ...
        } // else if ...
            // etc.
    }
}

As a beginner, this should be fairly easy to understand. A yet better solution would be to have custom shape interface (ie. MyShape) with a draw(Graphics g) method, and implement your shapes from that interface (Circle implements MyShape, Square implements MyShape, etc.). Then, your ArrayList<Shape> shapes could become ArrayList<MyShape> shapes and your paintBackground method would just invoke the draw method of very MyShape items.


text:
Q: Use addKeyListener in a class to listen keys from another class? I am trying to have a thread to listen to keys - which is a different class to where the JPanel is created. Below is the class where the JPanel is.
public class Game extends JPanel {

public static final int WIDTH = 600,
                        HEIGHT = 650;

private static boolean running;

private BufferedImage image;
private Graphics2D g;

public String str;
private static Thread MyThread;

public Game() {
    super();
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setFocusable(true);
    requestFocus();
}

public void addNotify(){
    super.addNotify();
    MyThread myThread = new MyThread(this);

    if(myThread == null){
        myThread = new Thread(myThread);
        myThread.start();
    }
}

public void run() {
    image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();

    while(running){
        update();
        render();
        draw();
        System.out.println(str);
    }
    stop();
}
private void update(){  }

private synchronized void render(){
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, WIDTH, HEIGHT);

}

private synchronized void draw(){
    Graphics g2 = this.getGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
}
public void start(){
    if(running) return;
    running = true;
    run();
}

private void stop() {
    if(!running) return;
    running = false;

    try{
        myThread.join();
    } catch (InterruptedException e){
        e.printStackTrace();
    }
}

}

Below is the code where the thread that listens to the Game class:
public class MyThread  implements Runnable, KeyListener{

private static Game game;
private static boolean left, right;

public MyThread(Game game) {
    this.game = game;
}

@Override
public void run() {
    game.addKeyListener(this);
    if(left){game.str = "left";}
    if(right){game.str = "right";}
}

@Override
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if(key == KeyEvent.VK_LEFT){left = true;}
    if(key == KeyEvent.VK_RIGHT){right = true;}
}

@Override
public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if(key == KeyEvent.VK_LEFT){left = false;}
    if(key == KeyEvent.VK_RIGHT){right = false;}
}

@Override
public void keyTyped(KeyEvent e) {

}
}

Currently when I run the code, it only prints out null even when I try to click left and right arrow keys. I tried inserting game.str = "string"; in the run() method and the console prints out string, so the thread works. I think the problem is that MyThread is not listening to the JPanel. Can you please tell me how do I fix this -- having a separate thread to listen to the Game class?
PS. game.addKeyListener(this) is in the run() method of the MyThread class.

A: You need some way to model the user input, personally, I'd start with a simple enum...
public enum Input {
    LEFT, RIGHT;
}

Next, we need some way to notify interested parties that some kind of input event has occurred...
public interface InputHandler {
    public void add(Input input);
    public void remove(Input input);
}

Next, your key listener needs some way to communicate the events back to the observer...
Disclaimer: I don't recommend the user of KeyListener, see the end for more details
public class KeyHandler extends KeyAdapter {

    private InputHandler inputHandler;

    public KeyHandler(InputHandler handler) {
        this.inputHandler = handler;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            inputHandler.add(Input.LEFT);
        } else if (key == KeyEvent.VK_RIGHT) {
            inputHandler.add(Input.RIGHT);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            inputHandler.remove(Input.LEFT);
        } else if (key == KeyEvent.VK_RIGHT) {
            inputHandler.remove(Input.RIGHT);
        }
    }
}

Now, your Game needs some way to manage the input events...
public class Game extends JPanel implements InputHandler {

    private Set<Input> inputSet = new HashSet<>();
    //...
    public Game() {
        //...
        addKeyListener(new KeyHandler(this));
        //...
    }

    @Override
    public synchronized void add(Input input) {
        inputSet.add(input);
    }

    @Override
    public synchronized void remove(Input input) {
        inputSet.remove(input);
    }

All of this means that when some input event occurs, your Game is notified, it can update the current state model based on the event.  The Game doesn't care that you've used a KeyListener, or JButton or some other input method, de-coupling it and making it more flexible.
Okay, you say, but how do I check which is pressed?
inputSet.contains(Input.LEFT)

will return true when LEFT was pressed and false when it is released.
Observations
Based on what I can deduce from your code, this...
public void run() {
    image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();

    while(running){
        update();
        render();
        draw();
        System.out.println(str);
    }
    stop();
}

will never be called.  You're executing a Thread using the KeyListener, whose run method just adds itself to the panel and the exits.
As you're using Swing, I would strongly recommend using a Swing Timer instead, it reduces the risk of race conditions between the painting thread and the update thread, as the Timer is triggered with the context of the EDT, making it safer to update the state of the UI from within
Recommendations
Now, having said all that, I highly recommend you don't use KeyListener, as it suffers from focus related issues, is difficult to maintain, provide customisation and inject other input methods should you want to.
Instead, I'd suggest using the Key Bindings API instead, which will solve these short comming and provide a more robust and re-usable solution
The above solution will still work with key bindings


text:
Q: Conectar Informix .NET via DSN Boa tarde,
Estou ha dias tentando conectar uma aplicação a uma base de dados do Informix, porem não consigo de jeito nenhum.
Estou com o Visual Studio 2017 utilizando o ASP.NET Framework 4.6. Tentei achar soluções no site da IBM, mas aquele site não ajuda em muita coisa, tudo fica espalhado e acaba ficando mais confuso ainda.
Tenho instalada a SDK 4.10.FC12 e consegui montar uma conexão através do Administrador de fonte de dados ODBC (nativo do windows)

Minha pergunta é: como posso acessar essa conexão DSN via visual studio na aplicação .NET?
Se alguém souber, por favor me ajude! Obrigada :)

A: Você pode tentar uma conexão utilizando odbconnection :
 OdbcConnection conn = new OdbcConnection(@"DSN=suaconexaoodbc;UID={usuario};PWD={senha};");

Mais informações:
https://docs.microsoft.com/pt-br/dotnet/api/system.data.odbc.odbcconnection?view=netframework-4.7.2


text:
Q: How to connect to Exchange 2010 within a Exchange Management Shell 2007 I want to run scripts to manage both Exchange 2007 and Exchange 2010 servers. This is what I tried,

*

*Start EMS 2007

*run the script for Exchange 2007 servers

*run this command in EMS2007
. 'C:\Program Files\Microsoft\Exchange
   Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto

*run the script for Exchange 2010 servers
The problem was I could connect to Exchange 2010 but I couldn't retrieve a lot of Exchange 2010 information with this method.
e.g. get-mailboxdatabase returned nothing with this method but I could get the databases if I start my EMS2010 from the menu.
My credential to manage Exchange 2007 and Exchange 2010 are the same.
What have I missed? Any hint is much appreciated.
Thanks a lot.


text:
Q: Getting the Scheduled Task Name which activated the PowerShell Script This might be an easy one but I tried hard to find "how to" and didn't came across any answers. So, my question is, "How do I find the Scheduled Task Name which activated my Powershell script"
So, I have a Scheduled Task configured on my Windows 2012 R2 Server which run's a program XYZ and also executes a Powershell script to send an email notification with the name of Task hard-coded inside the script.
$SmtpClient = new-object system.net.mail.smtpClient

$MailMessage = New-Object system.net.mail.mailmessage

$SmtpClient.Host = "smtp.mydomain.com"

$mailmessage.from = ("myemail@mydomain.com")

$mailmessage.To.add("myname@mydomain.com")

$mailmessage.Subject = "Task XYZ has started"

$mailmessage.Body = "This is to notify that task XYZ has been started"

$smtpclient.Send($mailmessage)

Now, I have 100 different tasks which needs this email notification and I have to use only a single PowerShell Script to trigger the email. This email should consist of the name of the Scheduled Task inorder to understand which Task has been started running for which we are receiving the email notification.
So, is there any inbuilt Powershell variable/function to find the name of Scheduled Task which executed my Powershell script?

A: Thanks to SimonS for providing the solution in the comment. Here's what I did for anyone who wants to do this in future -
I modified my Powershell Script as follows -
Function Send_Email([string[]$TaskName)
{
$SmtpClient = new-object system.net.mail.smtpClient

$MailMessage = New-Object system.net.mail.mailmessage

$SmtpClient.Host = "smtp.mydomain.com"

$mailmessage.from = ("myemail@mydomain.com")

$mailmessage.To.add("myname@mydomain.com")

$mailmessage.Subject = "Task $TaskName has started"

$mailmessage.Body = "This is to notify that task $TaskName has been started"

$smtpclient.Send($mailmessage)

}

Send_Email $args

Now, in the Scheduled Task I have an action defined with below things -

*

*Action Type - Start a Program

*Program Name - Powershell.exe

*Arguments - C:\Temp\Send_Email.ps1 'Send_Email_Task'

Now, when the Scheduled Task starts, it executes my Powershell Script with the Task name. This way I can use this same script for all my tasks.


text:
Q: Issue with $mail->Body in the PHPMailer a beginner here.
I have already checked the forum to find out answers but I was not successful, other questions were specifically on some parts of PHPMailer but mine is more general. So I hope no one will mark my question as duplicate as I am in learning curve.
I am working on a PHP project. How it works is that the user goes to the page and writes some comments in a form (a text editor) and clicks on the send button. I am able to receive his message in my email. I have set the password and host empty for obvious reasons but later it will be my real email with my own domain.
Problem is 2 problems here:

*

*I do not want to send a static body with $mail->Body, but I want the program to take the user's message, name and email address and send that message to my email.

*When the email is received by me, I can not see the name and email of the sender which means the program is not able to get the email and name of the user from the session

Could you please give your suggestion or sample code that helps. Thank you.
if($_POST['mode']=='send'){

    $mail = new PHPMailer();

    $mail->IsSMTP();                                // telling the class to use SMTP
    $mail->Host     = "myhost";                     // SMTP server
                                                    //$mail->SMTPSecure = 'ssl';
    $mail->From     = "my email";
    $mail->port     = '26';                             // can also change to 465
    $mail->SMTPAuth = true;
    $mail->Username= "my email";
    $mail->Password = "my password";

    $mail->AddAddress("my email");

    $Name = mysql_real_escape_string($_POST['part_fname']);    //this code is not getting the name and email
    $Email = mysql_real_escape_string($_POST['part_email']);

    $mail->Subject  = "New Bug Report";
    $mail->Body     = "User Information, Name = " . $Name . " ||  Email = " . $Email; // I want to get the user's message not a static message!
    $mail->WordWrap = 50;

    if(!$mail->Send())
     {
      echo 'Message was not sent.';
      echo 'Mailer error: ' . $mail->ErrorInfo;
    }
    else
    {
            $message = 'Thanks for your suggestion';
    }
 }

Here is the form in html:
<form role="form" name="Form2" action="" method="post" class="form-horizontal">
<textarea name="bug" cols="100" rows="15" id="textarea" placeholder="Enter text ..."></textarea>
<input name="mode" value="send" type="hidden">

<input type="reset" value="Clear Text!" class="btn btn-danger">  <button type="submit" class="btn btn-primary">Send report</button>

</form>

A: Remove mysql_real_escape_string it requires a connection to mysql.
$Name = $_POST['part_fname'];
$Email = $_POST['part_email'];
$message= $_POST['bug'];//add this to get the textarea value

then append the value to the body:
$mail->Body = "User Information, Name = " . $Name . " ||  Email = " . $Email;
$mail->Body .= "Message: ".$message;

If you wanted sessions
when to user logs in:
session_start();
$_SESSION['part_fname'] = $Name;
$_SESSION['part_email'] = $Email;

when sending email:
session_start();
$Name = $_SESSION['part_fname'];
$Email = $_SESSION['part_email'];
$message= $_POST['bug'];

A: to the form you need to add the fields for the name and email like so:
<input name="part_fname" value="" type="text">
<input name="part_email" value="" type="text">

then alter the code:
$Name = $_POST['part_fname'];
$Email = $_POST['part_email'];
$message= $_POST['bug'];// textarea value

$mail->Body = "User Information, Name = " . $Name . " ||  Email = " . $Email;
$mail->Body .= "Message: ".$message;


text:
Q: Linux image backup utility Can anyone suggest a linux backup utility that can take a copy of the state with the current configuration so I can boot with it or install it on an external/new partition on a different machine?

A: I used Deja Dup which is installed in Ubuntu by default.
It's actually a front-end of Duplicity which you can use if you prefer command line approach.
Of course, there are several other solutions so take a look on a list
here


text:
Q: How does the existence of Platonic graphs imply the existence of Platonic solids? I will use the following definitions

Platonic graph: A 3-connected planar graph with faces bounded by the same number of edges and vertices having the same number of incident edges.
(remark: the faces of a 3-connected planar graph are well-defined due to Whitney's theorem)
Combinatorially regular polyhedron: A polyhedron with Platonic vertex-edge graph.
Platonic solid:  A combinatorially regular convex polyhedron with congruent faces of regular polygons.

Suppose we know the existence of the 5 Platonic graphs, but we don't know the existence of Platonic solids. How can we prove that they exist?
The existence of combinatorially regular convex polyhedra follows from the existence of the Platonic graphs by Steinitz's theorem.
But how can we know, that every combinatorially regular convex polyhedron can be continuosly deformed so that their faces become congruent regular polygons?

A: Consider the docecahedron as an example: Between a minuscule regular pentagon on $S^2$ having angles slightly over $108^\circ$ at the vertices and a hemispherical regular pentagon with angles $180^\circ$ at the vertices there is a regular pentagon on $S^2$ with angles $120^\circ$ at the vertices. Twelve such pentagons will tile $S^2$ in the desired way: Just place one such pentagon anywhere on $S^2$. Five more  will precisely fit around it. Put another five into the five indentations on the outside of this configuration, and a hole will remain for the twelfth pentagon.


text:
Q: Glossy Buttons set color programmatically I am currently trying the Core Graphics 101: Glossy Buttons by RAYWENDERLICH, but I am having a problem using it in my project, i don't know to apply this programmatically, and adjust its image programmatically.
Here is my button:
@interface CoolButtonViewController : UIViewController {
    CoolButton *_button;
}

@property (retain) IBOutlet CoolButton *button;

@implementation CoolButtonViewController
@synthesize button = _button;

How to edit the color of the image programmatically, not by slider.

A: Looks like it is as simple as setting the button's hue, saturation, and brightness properties to whatever values you want.  (The values for these properties can range from 0.0 to 1.0)
_button.hue = 0.5;
_button.saturation = 0.5;
_button.brightness = 0.5;


text:
Q: SignalR-Hub with Entity Framework returns wrong entity We have a problem with SignalR, which we currently cannot fully understand:
 System

*

*Framework: .NET Core 2.2

*Entity Framework: 2.2.6.0

 Description of the problem
We use SignalR to communicate with multiple clients. Via the connection the clients log on to the server with a unique key. We use the Entity Framework to access the database and select the client for the given key. Now it has happened for the second time that the wrong client entry was selected for the key during the access and therefore a wrong login with the wrong client has made. This happened when
about 8 clients have logged on via the hub at the same time.

We assume that there are problems with the DbContext because it is not Threadsafe and for some reason the same Context is accessed for multiple requests(maybe this can be solved by updating to Core 3.1). However, we would like to understand how this can happen or why it failes. How does it happen that accessing the DbContext via FirstOrDefaultAsync() returns the wrong client? The Hub and the DbContext should be instantiated per request?

 Example
The database currently contains several client entries:
+------------+---------+
|  ClientId  |   Key   |
+------------+---------+
| 1          | ABC     |
| 2          | DEF     |
| 3          | GHI     |
| ...        | ...     |
+------------+---------+

Now several clients log in with their key at the same time. In one of the cases the wrong client was returned:

*

*Key ABC returns Client 1

*Key DEF returns Client 2

*Key GHI returns Client 1
 Structure
Our server provides a SignalR-Hub, which is configured in the Startup:
app.UseSignalR(routes =>
{
    routes.MapHub<MyServerHub>("/myhub");
});

According to the documentation and source code, the hub should be registered as transient (Use hubs in SignalR for ASP.NET Core).
We also use a service in the hub, which is injected by DI.
public MyServerHub(IMyDatabaseService myDatabaseService)
{
    _myDatabaseService = myDatabaseService;
}

This service uses the DbContext:
private MyContext _myContext { get; }

public MyDatabaseService(MyContext myContext)
{
    _myContext= myContext;
}

In the Startup the service and the DbContext is defined as Scoped:
services.AddScoped<IMyDatabaseService, MyDatabaseService>();

services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

In this method of hub we get the wrong client for a key:
    public async Task Connect(string key)
    {
        if (!string.IsNullOrWhiteSpace(key))
        {
            var client = await _myDatabaseService.GetByKey(key);
            if(client == null)
            {
                await LogInformation(key, null, ConnectionEvent.ConnectWithInvalidKey);
                await Clients.Caller.ReceiveInvalidKey();
                return;
            }
            await Clients.Caller.ReceiveValidClientKey(client.Id);
            // This created following logs:
            // "ABC" with id "1" at 09:25:47
            // "GHI" with id "3" at 09:34:03
            // "GHI" with id "1" at 10:06:02
            // "ABC" with id "1" at 10:06:03
            await LogInformation(key, client.Id, ConnectionEvent.ConnectedSuccessfully);
        }
        else
            await Clients.Caller.ReceiveInvalidKey();
    }

Access to the DbContext in MyDatabaseService:
public async Task<Client> GetByKey(string key)
{
    ClientRecord client = await _myContext.Clients.FirstOrDefaultAsync(p => p.Key == key);

    if (client == null)
        return null;

    return new Client
    {
        Id = client.Id,
        Key = client.Key
    };
}

EDIT: Logging Informations

We log every call on the server hub. At 10:06:01 all connected SignalR clients (~18) were disconnected by with unkown reason (OnDisconnectedAsync was executed for each client). From 10:06:02 to 10:06:03 the clients automatically reconnected via our client application.
+------------+---------+-----------------------+---------------------+----------+
|  ClientId  |   Key   |     ConnectionId      |       Event         |   Date   |
+------------+---------+-----------------------+---------------------+----------+
|     -      |    -    |jF2OqBVgBb1PLOiVRn8SPQ | SignalR-Connected   |  9:25:47 |
|     1      |   ABC   |jF2OqBVgBb1PLOiVRn8SPQ |    Connected        |  9:25:47 |
|    ...     |   ...   |...                    |      ...            |  ...     |
|     -      |    -    |5fg1CwmZxFjGXF42zb-7BQ | SignalR-Connected   |  9:34:02 |
|     3      |   GHI   |5fg1CwmZxFjGXF42zb-7BQ |    Connected        |  9:34:03 |
|    ...     |   ...   |...                    |      ...            |  ...     |
|     1      |    -    |jF2OqBVgBb1PLOiVRn8SPQ | SignalR-Disconnected| 10:06:01 |
|     3      |    -    |5fg1CwmZxFjGXF42zb-7BQ | SignalR-Disconnected| 10:06:01 |
|    ...     |   ...   |...                    |      ...            |  ...     |
|     -      |    -    |2lZfpu08UerqbjwNkKLC3Q | SignalR-Connected   | 10:06:02 |
|     -      |    -    |fg0oXdDAoKW3D4Ps6WOhhg | SignalR-Connected   | 10:06:02 |
|     1      |   GHI   |fg0oXdDAoKW3D4Ps6WOhhg |    Connected        | 10:06:02 |
|     1      |   ABC   |2lZfpu08UerqbjwNkKLC3Q |    Connected        | 10:06:03 |
+------------+---------+-----------------------+---------------------+----------+


text:
Q: How does one see what data is stored in the RDS database? Running our app on Amazon RDS. How does one review / inspect data in the database? For example, how can I get a list of articles?
My app is running on Ruby on Rails and on Heroku. One method I thought of, is by running the Heroku console command.
Is there a better way to see what data is stored in the RDS database?

A: I use MySQL Workbench to view data, run queries, and so on. It connects right up to the Amazon RDS MySQL instance using the regular MySQL settings.
Updated:
Be sure to add the ip address of the computer for which you're connecting to the RDS instance to the access list in RDS. IIRC, by default RDS instances will only accept connections from within AWS.

A: I was using SequelPro but they don't support ssl. Amazon RDS says something to the effect of having to use SSH to connect your EC2 to your RDS.
This is essentially what was done in the following tutorial which uses MySQL Workbench: http://thoughtsandideas.wordpress.com/2012/05/17/monitoring-and-managing-amazon-rds-databases-using-mysql-workbench/
I had also been using SequelPro before but this tutorial is very clear and I was up and running on MySQL Workbench in just a few minutes.


text:
Q: Fields_for with permitted attributes I have a form in Rails that looks like this psuedo code:
<%= form_for :project do |f| %>
  <%= f.fields_for :rewards do |r| %>
    <%= r.text_field :title %>

I have everything working except when I submit the form I get an error: Unpermitted parameter: rewards. What should my permissions look like in the Project controller?

A: Pass the nested attributes as a hash option with an array of permitted attributes:
require(:project).permit(
  :foo, :bar,
  rewards_attributes: [:title]
)

This is equivalent to:
require(:project).permit(
  :foo, :bar,
  { rewards_attributes: [:title] }
)


text:
Q: after insert trigger not firing after inserting with bcp content of csv file
TEST_1|sl2sysxbar301.dv.local|{'message_type': 2, 'super_evt_non_error': {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'event': 5528, 'event_string': 'ENERGY_CTRL_RIGHT_PROX_DOWN', 'history_buffer_id': 3, 'history_buffer_string': 'HISTORY_BUFFER_UI_EVT', 'mid': 10, 'mid_string': 'CONSOLE1'}}|2021-06-26 05:03:20|
TEST_11|sl2sysxbar301.dv.local|{'message_type': 2, 'super_evt_non_error': {'a0': 393280, 'a1': 1, 'a2': 0, 'a3': 0, 'event': 8316, 'event_string': 'BP_FOLLOW_CHECK', 'history_buffer_id': 0, 'history_buffer_string': 'HISTORY_BUFFER_BP', 'mid': 6, 'mid_string': 'MTMR'}}|2021-06-26 05:03:20|
TEST_2|sl2sysxbar301.dv.local|{'message_type': 4, 'mmdsp_log': {'bp_start': {'bp_arg': 0.0, 'bp_code': 4097, 'bp_sn': 393300, 'mid': 6}, 'legacy_log_idx': 0}}|2021-06-26 05:03:20|
TEST_4|sl2sysxbar301.dv.local|{'message_type': 2, 'super_evt_non_error': {'a0': 267, 'a1': 0, 'a2': 0, 'a3': 0, 'event': 100001, 'event_string': 'INTER_MANIP', 'history_buffer_id': 3, 'history_buffer_string': 'HISTORY_BUFFER_UI_EVT', 'mid': 1, 'mid_string': 'AIM2'}}|2021-06-26 05:03:20|

here is bcp running via python
            p = subprocess.Popen(
                f'/opt/mssql-tools/bin/bcp {app.config.db_table_name} in {f.get("filename")}  -S {app.config.db_host},{app.config.db_port} -U {app.config.db_username} -P {app.config.db_password} -t  "|"  -c',
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
            )

I have this table and trigger
CREATE TABLE [EVT_STREAM].[Event](
    [SystemName] [varchar](25) NOT NULL,
    [Router] [varchar](128) NULL,
  [Event] [nvarchar](max) NULL,
  [ReceivedAt] [datetime] NOT NULL,
  [InsertedAt] [datetime] NULL
)ON [PRIMARY]
GO

CREATE TRIGGER [EVT_STREAM].[trg_EVT_STREAM]
   ON [EVT_STREAM].[Event]
   FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
insert into [EVT_STREAM].[Event](
  [InsertedAt]
)
  VALUES(
    GETUTCDATE()
    )
END
GO

ALTER TABLE [EVT_STREAM].[Event] ENABLE TRIGGER [trg_EVT_STREAM]
GO

basically I would like to update [InsertedAt] at the time when BCP runs and inserts CSV records in [EVT_STREAM].[Event] table.

A: bcp has an option : FIRE_TRIGGERS link here
(By default, triggers are not fired. To fire triggers explicitly, use the -h option with the FIRE_TRIGGERS hint.)
-h"FIRE_TRIGGERS"

*

*FIRE_TRIGGERS

Specified with the in argument, any insert triggers defined on the destination table will run during the bulk-copy operation. If FIRE_TRIGGERS is not specified, no insert triggers will run. FIRE_TRIGGERS is ignored for the out, queryout, and format arguments.

A: Based on MBuschi's suggestion:

Isn't better to create a default with getdate() for the field [InsertedAt]?

I was able to find an alternate solution w/o need of having a separate trigger:
CREATE TABLE [EVT_STREAM].[Event](
[SystemName] [varchar](25) NOT NULL,
[Router] [varchar](128) NULL,
[Event] [nvarchar](max) NULL,
[ReceivedAt] [datetime] NOT NULL,
[InsertedAt] [datetime] NULL
)ON [PRIMARY]
GO

ALTER TABLE [EVT_STREAM].[Event]
ADD CONSTRAINT df_inserted_at
DEFAULT GETUTCDATE() FOR InsertedAt
GO

A: Isn't better to create a default with getdate() for the field [InsertedAt]?


text:
Q: How to bind Child object records with Radio button on VF page I have master-detail relationship between two objects. Master is Question__c and detail is Question_options__c. Question_c object contains question for example: Where do you live?
and Question_options__c contains options for this question like this:

*

*India

*USA

*Canada

I want to  bind Question_options__c with radio buttons on vf page.I am able to get the master and child records in SOQL query in apex class and l also put the logic to bind child records related to master with radio buttons but, it binds all the child records with radio button. Here is my apex and vf page code:
VF Page:

Contact Us

    <apex:form >
    <apex:repeat value="{!quelistradio}" var="qr" >
        {!qr.Name}

            <apex:repeat value="{!qr.Question_Options__r}" var="child" >
                 <apex:selectRadio id="radiobtn" value="{!selectradival}" >
              <apex:selectOption id="Radiobtnopn" value="{!child.Option1__c}"/>
                </apex:selectRadio>
            </apex:repeat>

    </apex:repeat>
    <apex:repeat value="{!quelisttext}" var="qt" >
        {!qt.Name}
        <input type="text" name="textinput" id="inputelement"/>
    </apex:repeat>
    <button class="btn btn-success" type="button" id="pre_chatsubmit"  onclick="dosave();false">Submit
    </button>
        </apex:form>

</apex:page>

Controller:
queradiquestionoptions= new List<Question_Options__c>();
quelisttext = new List<Post_Chat_Question__c>();
quelistradio= new List<Post_Chat_Question__c>();
quelistcheckbox = new List<Post_Chat_Question__c>();
quelisttext=  [Select id,Name,Question_Type__c,Sequence__c,
  (Select Id,Name,Option1__c,PostChatQuestion__c from Question_Options__r) from Post_Chat_Question__c Where Question_Type__c=:'Text'  ORDER BY Sequence__c];
quelistradio= [Select id,Name,Question_Type__c,Sequence__c,
  (Select Id,Name,Option1__c,PostChatQuestion__c from Question_Options__r) from Post_Chat_Question__c Where Question_Type__c=:'Radio'  ORDER BY Sequence__c];
quelistcheckbox=[Select id,Name,Question_Type__c,Sequence__c,
  (Select Id,Name,Option1__c,PostChatQuestion__c from Question_Options__r) from Post_Chat_Question__c Where Question_Type__c=:'Checkbox'  ORDER BY Sequence__c];

}
public  List<SelectOption>  getitems(){
  questoqueoptions = new Map<Id,List<Question_Options__c>>();
  List<SelectOption> options = new List<SelectOption>();
    for(Post_Chat_Question__c qoc:quelistradio){

        questoqueoptions.put(qoc.id,qoc.Question_Options__r);
        system.debug('###MAPOFQUESTIONANDOPTIONS'+questoqueoptions);
    }

    for(Post_Chat_Question__c pcq:quelistradio){
          //List<Question_Options__c> listofoptions = new  List<Question_Options__c>();
        if(questoqueoptions.containskey(pcq.id)){

            listofoptions=  questoqueoptions.get(pcq.id);
             system.debug('###LISTOFOPTIONS'+listofoptions);
            for(Question_Options__c qo:listofoptions){  options.add(new selectOption(qo.Option1__c, qo.Option1__c));}

        }
    }

    return options;

}

As you can see, The master record is How would you rate this?
and related child records are Good,Very Good,Excellent,Average
But it also display other child records which are not related to this master record e.g Yes No

A: These kind of problems are best handled using wrapper classes
public class QuestionRadioWrapper {
   public Post_Chat_Question__c q {get; private set;}
   public SelectOption[] getOptions() {
     SelectOption[] options = new List<SelectOption>();
     for (Question_Option__c qo = this.q.Question_Options__r) {
       options.add(new SelectOption(qo.Option1__c,qo.Option1__c);
     return options;
   }
   public String selectedRadio {get; set;}
   public QuestionRadioWrapper(Post_Chat_Question__c q) {this.q. = q;}
}
public QuestionRadioWrapper[] qRadios {
  get {
     qRadios = new List<QuestionRadioWrapper>();
     for (Post_Chat_Question__c q:
      [SELECT id,Name,Question_Type__c,Sequence__c,
        (Select Id,Name,Option1__c,PostChatQuestion__c from Question_Options__r)
       FROM Post_Chat_Question__c Where Question_Type__c=:'Radio'
       ORDER BY Sequence__c] (
        qRadios.add(new QuestionRadioWrapper(q);
     }
     return qRadios;
  } private set;
}

Then your VF page is:
<apex:repeat value="{!qRadios}" var="qR">
   <apex:outputField value="{!qR.q.Name}"/>
   <apex:selectRadio value="{!qR.selectedRadio}">
    <apex:selectOptions value="{!qR.options}"/>
   </apex:selectRadio>
</apex:repeat>

I omitted the table formatting from my answer


text:
Q: Switch return value is undefined When I run this code from Notepad++ through an .html file, the output doesn't recognize my return values. It always outputs "undefined"
I've tried putting the return statement outside of the switch statement but it didn't solve anything.
Edit: I included the code that calls the function and I fixed my if statements based on iCode's tips.
// this came with the execrise
var sentinel = true

while (sentinel) {

    var month = prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year");
    var request = prompt("Enter 1 if you want the name of the month, or enter 2 if you want the number of days in the month");

    if (months(month,request) == false) {
        // reset
        alert("Try again but enter the right stuff this time");

    } else {
        // output
        sentinel = false;

        if (request == 1) {

            console.log("Month number " + month + " is " + months(month,request));

        } else if (request == 2) {

            console.log("There are " + months(month,request) + " days in month number " + month);
        }
    }
}

// this is my edited code
function months(month,request) {
    if (!request || request < 1 || request > 2 || isNaN(request)) {
        return false;
    }
    if (!month || month < 1 || month > 12 || isNaN(month)) {
        return false;
    }

    var name;
    var numberDays;
    switch(month){
        case 1:
            if(request == 1){
                name = "January";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 2:
            if(request == 1){
                name = "February";
                return name;
            }else{
                numberDays = "28";
                return numberDays;
            }
            break;

        case 3:
            if(request == 1){
                name = "March";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 4:
            if(request == 1){
                name = "April";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 5:
            if(request == 1){
                name = "May";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 6:
            if(request == 1){
                name = "June";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 7:
            if(request == 1){
                name = "July";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 8:
            if(request == 1){
                name = "August";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 9:
            if(request == 1){
                name = "September";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 10:
            if(request == 1){
                name = "October";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
            break;

        case 11:
            if(request == 1){
                name = "November";
                return name;
            }else{
                numberDays = "30";
                return numberDays;
            }
            break;

        case 12:
            if(request == 1){
                name = "December";
                return name;
            }else{
                numberDays = "31";
                return numberDays;
            }
    }
}

                return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

I expect the output to be either "Month number 1 is January" or "There are 31 days in month number 1"

A: A simplification of your code. The year is required to accuretly get the number of days for February.
Creating a new date (new Date(2019, 1, 0)) with the day parameter set to 0 will set it to the month's last day.

function months(month, request = 1, year){
   if(year === undefined) year = (new Date()).getYear();
   const d = new Date(year, month, 0);
   return request === 1 ? d.toLocaleString('en-us', { month: 'long' }) : d.getDate();
}

const res0 = months(5);
const res1 = months(1,0);
const res2 = months(2,0);
const res3 = months(3,0);

console.log(res0, res1, res2, res3);

A: Explanation of the Unexpected Result
The reason this code returns undefined is because you have an unhandled case that doesn't have any return value. Every if statement comes with its own else statement return false. So there is no problem there. However the switch statement doesn't handle the default case. This is the only place that doesn't have a return value so this must be the problem.
The problem occurs with a string input for the first number, since it passes the if statements, but doesn't match any switch case.

console.log("'3' <= 12 //=>", '3' <= 12);
console.log("'3' >= 1 //=>",  '3' >= 1);

console.log("'3' == 3 //=>",  '3' == 3);
console.log("'3' === 3 //=>", '3' === 3);
//                ^ used for switch comparison

This means that if you run your function with inputs like months(3, 1) //=> "March", whereas months('3', 1) //=> undefined. Convert the string to an integer first to correctly match one of the cases. This is due the fact that switch cases use a strict comparison.
After your edit this becomes even more clear, since we can see where the data is coming from.

var month = prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year");
console.log(month, typeof(month));

Alternative Solution
With the explanation of the unexpected result out of the way. Let's have a look at some code that produces similar results.

var monthsByNumber = {
    1:  { 1: "January",   2: "31" },
    2:  { 1: "February",  2: "28" },
    3:  { 1: "March",     2: "31" },
    4:  { 1: "April",     2: "30" },
    5:  { 1: "May",       2: "31" },
    6:  { 1: "June",      2: "30" },
    7:  { 1: "July",      2: "31" },
    8:  { 1: "August",    2: "31" },
    9:  { 1: "September", 2: "30" },
    10: { 1: "October",   2: "31" },
    11: { 1: "November",  2: "30" },
    12: { 1: "December",  2: "31" }
};

// This allows you to access the object attributes with either
//   a string or a number.
console.log("monthsByNumber[1] //=>",   monthsByNumber[1]);
console.log("monthsByNumber['1'] //=>", monthsByNumber['1']);

// Introducing this into the function would look something
//   like this.
function months(month, request) {
    // Normally you would define monthsByNumber here, but
    //   in this case I needed it in my demonstration
    //   above.

    // Use an empty object if it can't find the month.
    month = monthsByNumber[month] || {};
    return month[request];
}

// As you can see below this works with both numbers as well
//   as strings.
console.log("months(1, 1) //=>",     months(1, 1));
console.log("months('1', '2') //=>", months('1', '2'));
console.log("months(32, 1) //=>",    months(32, 1));

The code above does the same as you would expect in your current months function. With the only change being that undefined is returned in case of invalid input. Which to me makes more sense than returning false. If I would ask you to give me the name of the 14th month, the answer "I don't know" is better suited than "I can't". Which is where it roughly translate to.
I would however suggest changing the naming since the keys 1 and 2 for the month name and days respectively aren't very obvious. I would go for something like { name: 'January', days: '31' }, however this requires one of two things to change. Either the request input should also be "name" or "days", the other option is transforming the request input into the correct format. request = request == 1 ? "name" : "days". Furthermore you might also want to consider returning a normal number for the days instead of a string.
JavaScript has also a Date object build-in that you might want to use to account for leap years and other things, but I won't go into detail about that here.

A: @Prospective, I see that you are probably getting your hands dirty in JavaScript.  Your sample appears to be a learning exercise.  Good for you.  JS is a fun language.  I took your code and pasted it into a JS fiddle and did not get any errors (though I did see warnings).  Of course, you did not provide the code you are using to call the month function.  So, it's possible that you might be getting undefined because of the way that you are calling, or invoking, the month() function.
As others have suggested, try reducing code complexity by merging some of your if statements with either AND (&&) or OR (||) conditional operators.

var sentinel = true
while (sentinel) {

var month = parseInt(prompt("Enter an integer from 1 to 12 inclusive, representing a month of the year"));
var request = parseInt(prompt("Enter 1 if you want the name of the month, or enter 2 if you want the number of days in the month"));
var result = months(month, request);

if (result == false) {
 // reset
 alert("Try again but enter the right stuff this time");

} else {
 // output
 sentinel = false;

 if (request === 1) {

  console.log("Month number " + month + " is " + result);

 } else if (request === 2) {

  console.log("There are " + result + " days in month number " + month);
 }
}
}

function months(month, request) {
 if (!request ||
  request < 1 ||
  request > 2) {
  return false;
 }
 if (!month ||
  month < 1 ||
  month > 12) {
  return false;
 }

 var name = "";
 var numberDays = 0;
 switch (month) {
  case 1:
   if (request === 1) {
    name = "January";
   } else {
    numberDays = 31;
   }
   break;
  // Repeat for case 2 - 12
  // ...

  // Include a default case though this should no longer get hit
  default:
   return -1;
   break;
 }
 if (request === 1) {
  return name;
 } else {
  return numberDays;
 }
}

One other suggestion would be to move the declaration of the variables name and numberDays so they are above the switch statement.  The JavaScript compiler will hoist variable declarations using the var keyword to the top of the function anyway.  If you want to utilize more modern JavaScript (ES6), you can use the let keyword to declare variables in a block scope as you have done.  Do note that older versions of Internet Explorer do not support let at all.  Check out the caniuse.com site to determine browser compatability.
Another good practice, though not required, is to provide default values for variables that you return.  You can then check for the default value when inspecting the return value for a function.
I'd also check for equality using the triple equals, ===, instead of ==.  Triple equals (===) will not do a type conversion if for example, you pass in "1" for the month instead of 1.  So, "1" == 1 is true; while "1" === 1 is false.
Another tip that might help you.  When testing HTML/JavaScript/CSS, you can use an online site such as jsfiddle.net, jsbin.com, or Plunker.


text:
Q: For CORS Error Do i need to configure on client side(Angular js) also? Error:XMLHttpRequest cannot load https://thirdPartyasite/template.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I am using Rails application which is consuming Cross orgin data through ajax call.The answers Provided by this question not working.
1)How to set access-control-allow-origin in webrick under rails?
2)https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html
3)Allow anything through CORS Policy.
I dont have control over the client app.How to overcome this problem.
I tried This one:
before_filter :set_headers
  def set_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
     headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  end

Still the same error is coming.
Tried This also:
In gem file added:gem 'rack-cors', :require => 'rack/cors'
In config/application.rb:
config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

Still Getting same error.
Work Around For Dev Environment:
Install CORS Chrome plugin.
But I need Proper Solution

A: Angular $sceDelegateProvider can throw exception while you sourcing Angular templates with CORS. For more read sceDelegateProvider official documentation
For testing purposes you can use this:
angular.module('myApp', []).config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'http://**',
        'https://**'
  ]);
});

A: You do not need to configure anything on Angular.
To enable CORS you just configure the server as you see in the links to the answers you posted.

A: CORS is a server-side constraint only.
If you have access to your Rails app, you'll be best using the Rack-CORS gem to enabled specific resources/origins:
#config/application.rb
...
  config.middleware.insert_before 0, "Rack::Cors" do
    allow do
      origins '*'
      resource '*', :headers => :any, :methods => [:get, :post, :options]
    end
  end

If you don't have access to your server-side rails app, you need to gain access, otherwise it won't work.


text:
Q: Does jQuery offer an overlay with background fade widget? I'm looking for a very common element - I want to pop a modal dialog on top of a web page, and fade out the page in the background until the dialog is dismissed.
Is this functionality offered by jQuery? If not, is there a jQuery compatible widget which many people use for this purpose

A: jQuery UI Dialog will do this for you.
http://jqueryui.com/demos/dialog/#modal


text:
Q: How to add my app to "share page" of IE for WP8 There is "share page" option in IE for wp8, I want to add my app to that list. So, that my app can receive the content of the page or the url of the page. Is that possible and if yes, how to do that. If not, is there any alternative way.

A: Sorry, but that is not exposed for Windows Phone 8. This is possible with WP8.1 by enabling the Share Target functionality within your app. Check out the MSDN docs, especially the Quickstart, and this sample app.
The short of it is to add the Declaration to the manifest file, define the files you support, and listen to the Application.OnShareTargetActivated method event.


text:
Q: Close vaadin session when the user close the browser page, how? My problem is that when a user closes the browser page and reopens immediately it remains logged.
How can I close the Vaadin session when the 'user closes the browser page?
I have found this two methods but works only when the user press on logout:
detachListener = new DetachListener() {
        @Override
        public void detach(final DetachEvent detachEvent) {
            System.out.println("I am out!");
        }
    };
    addDetachListener(detachListener);

or
@Override
public void close(){
   System.out.println("I am out, from close!");
}

Have anyone an idea?
Vaadin version: 7.4.2


text:
Q: TypeScript call static function from other module I got a problem when i want to create global function in another module
utils.ts file (contain global function)
/// <reference path="jquery/index.d.ts" />
/// <reference path="knockout/index.d.ts" />
'use strict';

module com.test.project {
    export class utils {
        self: any;

        constructor() {
            this.self = this;
        }

        public postData(url: string, data: any): any {
            var dfd = $.Deferred();
            $.ajax({
                url: url,
                data: JSON.stringify(data),
                type: 'post',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                cache: false,
                success: function(result) {
                    return dfd.done(result);
                },
                error: function(result) {
                    return dfd.reject(result);
                }
            });
        }
    }
}

login.ts (call global function inside)
/// <reference path="jquery/index.d.ts" />
/// <reference path="knockout/index.d.ts" />
'use strict';

module com.test.project.login {
    export class ScreenModel {
        self: any;
        userName: KnockoutObservable<string>;
        password: KnockoutObservable<string>;

        constructor() {
            this.self = this;
            this.userName = ko.observable("") as KnockoutObservable<string>;
            this.password = ko.observable("") as KnockoutObservable<string>;
        }

        private submit(): void {
            var dataObject = {
                "userName": this.userName(),
                "password": this.password()
            }
            // ↓ error here
            com.test.project.utils.postData("loginService.do", dataObject).done(function(result) {
                window.location.href = "index.do";
            }).reject(function(result) {
                alert("error");
            });
        }
    }

    $(document).ready(function() {
       ko.applyBindings(new ScreenModel());
    });
}

The global function inside module com.test.project and in class utils, normally, the global function caller inside module like com.test.project.[function] and in class ScreenModel.
How can i call the global function inside ScreenModel class?

A: I think you're thinking too much in a Java Style: I'd recommend you to declare in the utils module an object with a function called postData and import just that object in your login module.
Something like this:
export const utils = {
  postData(url, data) {
    $.ajax({})
  }
}

// ....

import { utils } from './utils'
utils.postData(url, data)
...

OR
export just your util function
export function postData(....)

import { postData } from './utils'
postData()

A: You already have it in your question's title: You must declare it as static, e.g. public static postData. There is a huge difference in the resulting JavaScript, see typescript playground.
Without static, the function is assigned to the prototype, hence you need an instance of that class to call the function.


text:
Q: Calculating the work done to pump water I would like to know whether my reasoning is ok. The problem is the following:
A horizontal cylindrical tank of radius $r = 4\ m$ and length $L = 10\ m$ is half full of water.  What is the work done in pumping the water to the top of the tank?
Consider: $g = 10\ m\cdot s^{-2}$.
I calculate the center of mass when the water is in the down half, and the center of mass when it is in the upper half, and finally, I calculate the work with $W = mgh$, where I take $h$ as the distance between both centers of mass.
Is this approach correct?


text:
Q: PostgreSQL parameterized query in Spring repository I am using Spring framework and PostgreSQL database .In the following query I want to select those rows which have product name matched by the parameter `keyword' When I run the following query it gives me the following error
Does anybody tell me how to write right query ?
Query:
@Query(value="Select pp from product_photo pp join products p ON pp.product_id=p.id Where p.name ~* ?Keyword",nativeQuery = true)
    List<ProductPhoto> trail(@Param("keyword")String Keyword);

API:
http://localhost:8080/productPhotos/search/trail?keyword=Bottles
Error:
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Product Entity
@Entity
@Table(name="products")
public class Product implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="SEQ_PRODUCTS", sequenceName="PRODUCTS_SEQ", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_PRODUCTS")
    private Long id;

    @NotEmpty
    @Column(name="NAME", nullable=false)
    private String name;

    @Column(name="DESCRIPTION",length=1000)
    private String description;

    @Column(name="PRICE", nullable=false)
    private Double price;

    private String SKU;

    private String supplierCode;

    private String readerOfferCode;

    private float productWeight;

    private Boolean statusEnabled=true;

    private float quantity;

    public String barcode;

    private boolean featuredProduct;

    private Double meanRating;

    private Double discountedPrice;

    @Enumerated(EnumType.STRING)
    private stockStatus stockStatus;

    @ManyToOne
    private Supplier supplier;

    @ManyToOne (fetch = FetchType.EAGER)
    private ProductCategory productCategory;

    @ManyToOne
    private ProductDepartment productDepartment;

    @JsonIgnore
    @OneToMany(mappedBy="product",targetEntity=ProductPhoto.class,fetch = FetchType.EAGER)
    private List<ProductPhoto> pictures;
    ..// Getters and setters
    }

ProductPhoto Entity
@Entity
public class ProductPhoto implements Serializable {

    private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Long id;

        //@JsonIgnore
        @ManyToOne
        private Product product;

        private String path;

        private Boolean primaryPhoto=false;

        @Column( nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
        @Temporal(TemporalType.TIMESTAMP)
        private Date uploadDate ;
        //..getters and setters }

A: Okay With the help of the above comments I am able to run right query
@Query("Select pp from ProductPhoto pp join pp.product p where pp.product.id=p.id "
        + "AND p.statusEnabled='true' AND pp.primaryPhoto='true' "
        + "AND (UPPER(p.name) LIKE UPPER(%:keyword%) OR p.description LIKE %:keyword%)")
List<ProductPhoto> sqlLike(@Param("keyword") String Keyword);


text:
Q: used colons for url htaccess http://localhost/1:1 I have a problem with the colons used in url
this my url
http://localhost/1:1
this my htaccess
RewriteEngine On
RewriteRule ^/(.*):(.*) index.php/$1:$2

this error show Forbidden You don't have permission to access /1:1 on this server.
# Virtual Hosts
#
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride all
        Order Allow,Deny
        Allow from all
  </Directory>
</VirtualHost>

A: There are a few issues here...

*

*In a per-directory .htaccess context, the URL-path matched by the RewriteRule pattern never starts with a slash, so the regex ^/(.*):(.*) will never match and the directive does nothing. So, the RewriteRule pattern would need to be ^(.*):(.*) - no slash prefix.

*

*However, this regex is very general and is most probably matching too much. If you are expecting a request of the form /1:1, ie. /<number>:<number> then use a more specific regex, eg. ^\d+:\d+$

*Since you are getting a 403 Forbidden (as opposed to a 404 Not Found) I assume you are on a Windows server. The "problem" here is that : (colons) are not valid  characters in Windows filenames. This is an issue with .htaccess because the request is mapped to the filesystem before .htaccess (and mod_rewrite) is processed - at which point the 403 is triggered. You would need to rewrite the request in the main server config (or VirtualHost container) instead - which occurs before the request is mapped to the filesystem.
So, what you are trying to do... rewrite the request that contains a colon, using .htaccess on a Windows server is not possible. You can do this on Linux (that permits colons in filenames) OR in the main server config (server or virtualhost context) on Windows, but not in .htaccess.
When using mod_rewrite in a server (or virtualhost) context (as opposed to .htaccess) you do need the slash prefix (on both the pattern and substitution strings). For example:
# In a "server" (or "virtualhost") context,
#   not ".htaccess" (or "<Directory>" section in the server config)

RewriteEngine On

# Internally rewrite "/1:1" to path-info on "index.php"
RewriteRule ^/\d+:\d+$ /index.php$0 [L]

The $0 backreference contains the entire URL-path that is captured by the RewriteRule pattern. This includes the slash prefix (when used in a server context), which is why the slash delimiter is omitted in the substitution string.

UPDATE:

I made the changes, please look at my question again and see, I entered it correctly
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride all
        Order Allow,Deny
        Allow from all
  </Directory>
</VirtualHost>

You don't seem to have made any changes; at least not in the right section? As mentioned above, these directives need to be added directly to the <VirtualHost> container (that you have posted). They cannot be added to the .htaccess file on a Windows OS - they simply won't do anything and you'll get the 403 Forbidden response as stated.
The above should be written like this:
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"

  # Enable the rewrite engine in a virtualhost context
  RewriteEngine On

  # Internally rewrite "/1:1" to path-info on "index.php"
  RewriteRule ^/\d+:\d+$ /index.php$0 [L]

  <Directory "${INSTALL_DIR}/www/">
    Options -Indexes -Includes +FollowSymLinks -MultiViews
    AllowOverride all
    Require all granted
  </Directory>
</VirtualHost>

You will need to restart Apache for these changes to take effect. (Unlike .htaccess files that are interpreted at runtime.)
However, what other directives do you have in .htaccess and how are your other URLs being routed? You posted the following directive in comments:

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

This routes the URL quite differently from what you are requesting in your question. In your question you are passing the URL-path as additional path-info to index.php. However, in this directive you are passing the URL as part of the query string? How do these relate? Why are they different? You obviously need to pass the URL in the way your "MVC application" is expecting.


text:
Q: Clang-format: don't align long variable assignment to equals sign Clang-format is wrapping my long variable assignments. In doing so, however, it's also aligning any continuation lines relative to the equals sign, like this:
long long variable = 1000 | 1100000000001 | 122365781 | 1256523983472934
                     | 2452346256 | 1646478592 | 126234753952359
                     | 435234523425345;

However, I want this to respect ContinuationIndentWidth:
long long variable = 1000 | 1100000000001 | 122365781 | 1256523983472934
    | 2452346256 | 1646478592 | 126234753952359
    | 435234523425345;

Is there any way to achieve this with clang-format?


text:
Q: MySQL query optimization: how can I speed up this query? This is my table:
  CREATE TABLE `tab_adasf` (
  `adasf_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `adasf_shopId` int(10) unsigned NOT NULL,
  `adasf_localId` bigint(20) unsigned NOT NULL,
  `adasf_shopState` varchar(255) DEFAULT NULL,
  `adasf_shopCity` varchar(255) DEFAULT NULL,
  `adasf_shopName` varchar(255) DEFAULT NULL,
  `adasf_shopDoor` varchar(255) DEFAULT NULL,
  `adasf_computerName` varchar(255) DEFAULT NULL,
  `adasf_channel` bigint(20) NOT NULL,
  `adasf_totalInside` bigint(20) NOT NULL,
  `adasf_totalOutside` bigint(20) NOT NULL,
  `adasf_createdAt` datetime NOT NULL,
  PRIMARY KEY (`adasf_id`),
  KEY `adasf_shopId` (`adasf_shopId`),
  KEY `adasf_localId` (`adasf_localId`),
  KEY `adasf_shopState` (`adasf_shopState`,`adasf_shopCity`,`adasf_shopName`,`adasf_shopDoor`),
  KEY `adasf_computerName` (`adasf_computerName`,`adasf_channel`,`adasf_createdAt`),
  CONSTRAINT `tab_adasf_ibfk_1` FOREIGN KEY (`adasf_shopId`) REFERENCES `tab_shop` (`shop_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1453500 DEFAULT CHARSET=utf8

As AUTO_INCREMENT's value says: it has 1453500 rows.
In order to generate a XML file, I need the resultset as follows:
SELECT
    UPPER(adasf_shopState) AS adasf_shopState,
    UPPER(adasf_shopCity) AS adasf_shopCity,
    UPPER(adasf_shopName) AS adasf_shopName,
    UPPER(adasf_shopDoor) AS adasf_shopDoor,
    adasf_computerName,
    adasf_channel,
    SUM(adasf_totalInside) AS adasf_totalInside,
    SUM(adasf_totalOutside) AS adasf_totalOutside,
    YEAR(adasf_createdAt) AS year,
    MONTH(adasf_createdAt) AS month,
    DAY(adasf_createdAt) AS day,
    HOUR(adasf_createdAt) AS hour
    FROM tab_adasf
WHERE 1=1 AND adasf_shopId = '1' AND HOUR(adasf_createdAt) BETWEEN '10:00' AND '21:00'
GROUP BY
    UPPER(adasf_shopState),
    UPPER(adasf_shopCity),
    UPPER(adasf_shopName),
    UPPER(adasf_shopDoor),
    adasf_computerName,
    adasf_channel,
    YEAR(adasf_createdAt),
    MONTH(adasf_createdAt),
    DAY(adasf_createdAt),
    HOUR(adasf_createdAt)
ORDER BY
    UPPER(adasf_shopState),
    UPPER(adasf_shopCity),
    UPPER(adasf_shopName),
    UPPER(adasf_shopDoor),
    UPPER(adasf_computerName),
    adasf_channel,
    adasf_createdAt

It takes 3 minutes to run and fetch.
My question is: what am I doing wrong? How can I speed up this query or table?
Thanks in advance!

A: To speed up the query, you can create an index on tab_adasf(adasf_shopId).  This should help performance a lot if you have many shops.
If you need to do a lot of queries of this type, then consider splitting the adasf_createdAt column into a date component and a time component.  Then you can create an index on tab_adasf(adasf_shopId, adasf_createdAt_time), further helping the query.
In general splitting the time from the datetime is not recommended unless you have a good reason.  Increasing performance of this type of query constitutes a "good reason".

A: As others have said, a query like this that reports on the whole table is inherently time-consuming. That being said, here's a suggestion or two.
First, eliminate the UPPER() function calls in the GROUP BY clause. MySQL's collations are case-insensitive anyhow.
Second, instead of GROUP BY  year, month, day, hour, try using this expression in the GROUP BY.
 DATE_FORMAT(adasf_createdAt, '%Y-%m-%d %H:00:00')

This will basically round off your createdAt value to the immediately preceding hour.
Third, let's refactor the WHERE item that reads
 HOUR(adasf_createdAt) BETWEEN '10:00' AND '21:00'

It should say
 HOUR(adasf_createdAt) BETWEEN 10 AND 21

And if you remove that from your main query it will speed up. You can then wrap your query in another query like so:
SELECT *
  FROM ( /*your whole query without the WHERE HOUR() BETWEEN clause */
       ) AS q
  WHERE q.hour BETWEEN 10 AND 21

Finally, try creating a compound covering index on
 adasf_shopId, adasf_shopState, adasf_shopCity, adasf_shopName, adasf_shopDoor,
 adasf_computerName, adasf_channel,  adasf_CreatedAt,
 adasf_totalInside, adasf_totalOutside

This index has all the information required to satisfy your query arranged in sequential order. It's possible this will speed up your query.
So, your ultimate query looks like this:
SELECT *
  FROM (
SELECT
       UPPER(adasf_shopState) AS adasf_shopState,
       UPPER(adasf_shopCity) AS adasf_shopCity,
       UPPER(adasf_shopName) AS adasf_shopName,
       UPPER(adasf_shopDoor) AS adasf_shopDoor,
       adasf_computerName,
       adasf_channel,
       SUM(adasf_totalInside) AS adasf_totalInside,
       SUM(adasf_totalOutside) AS adasf_totalOutside,
       YEAR(adasf_createdAt) AS year,
       MONTH(adasf_createdAt) AS month,
       DAY(adasf_createdAt) AS day,
       HOUR(adasf_createdAt) AS hour
 FROM tab_adasf
WHERE 1=1
  AND adasf_shopId = '1'
GROUP BY
      adasf_shopState,
      adasf_shopCity,
      adasf_shopName,
      adasf_shopDoor,
      adasf_computerName,
      adasf_channel,
      DATE_FORMAT(adasf_createdAt, '%Y-%m-%d %H:00:00')
ORDER BY
      adasf_shopState,
      adasf_shopCity,
      adasf_shopName,
      adasf_shopDoor,
      adasf_computerName,
      adasf_channel,
      DATE_FORMAT(adasf_createdAt, '%Y-%m-%d %H:00:00')
     ) AS q
  WHERE q.hour BETWEEN 10 AND 21

It's possible this simplification of your query, combined with the covering index, will make the query faster.
Please note that I haven't debugged this query and don't have the test data to do so.

A: Edit: This answer will not work in MySQL.
You're having to use a full table scan to check every row to see if it matches HOUR(adasf_createdAt) BETWEEN '10:00' AND '21:00'.
Create a functional index on HOUR(adasf_createdAt).
Also, see http://use-the-index-luke.com for an excellent tutorial on how to use indexes effectively.


text:
Q: Using typescript in the existing project that has .js files I have an existing NodeJS project, which has .js files, written in ES6. Now I want to start using typescript in the existing project. How should I go about? Should I just start with .ts files in the same directory structure?
One of the problems I noticed, is that tsc only considers the .ts files. So for tsconfig.json which looks something like:
    {
    "compilerOptions": {
        "target": "es2015",
        "outDir": "./dist",
        "allowJs": true,
        "module": "commonjs",
        "noEmitOnError": false,
        "noImplicitAny": false,
        "strictNullChecks": true
    },
    "include": [
        "app/"
    ]
}

will only convert the .ts files and leave the other .js files that form the majority of the project. How should I approach this?

A: First you need to add typescript as developer dependency
by using this command to your project directory
npm i --save-dev typescript
Then you convert all .js files to .ts files and then run this command.
<your_project_path>/node_modules/.bin/tsc -p '<your_project_path>/tsconfig.json'
Remember to give absolute paths so that there won't be any ambiguity
After you run this command it will create .js files in your ./dist folder. This is your output path given in "outDir": "./dist in your tsconfig.json file. It will keep the same directory structure which was in your app but with .js and .map files.
I would recommend to use app/ folder to write all your code in typescript and while deploying run javascript files from ./dist folder ignoring the .map files.


text:
Q: Approximately satisfying simultaneous vector linear diophantine equations? Pick three $a,b,c$ vectors in $\mathbb Z^n$ uniformly with $\max(\|a\|_\infty,\|b\|_\infty)<T$ and $\|c\|_\infty<T^2$ and an $\epsilon>0$.

Assume $a$ and $b$ are coordinatewise coprime (that is every $a_i$ and $b_i$ are coprime at every $i\in\{1,\dots,n\}$). Then do we always have such $A$ and $B$ of absolute value $O(T)$ at general $n$ such that $\|Aa+Bb-c\|_\infty<T^{2(n-1)/n+\epsilon}$ at large enough $n$?

This is the intuition.
Essentially there are $T^2$ choices for $A,B$ and there are $T^{\frac{(2n−2)}n+\epsilon}$ choices for every coordinate of $Aa+Bb-c$ and since there are $n$ coordinates we have $T^2T^{{2n−2}+n\epsilon}=T^{2n+n\epsilon}$ choices. However typically $Aa+Bb-c$ is of size $T^2$ and so typically there are $T^{2n}$ choices. If $\epsilon>0$ then the heuristic that $$\frac{\{\mbox{number of choices for A,B}\}\times\{\mbox{number of vectors with }\infty\mbox{ norm GAP < }T^{\frac{2(n-1)}n+\epsilon}\}}{\mbox{number of length n vectors with coordinates of size }T^2}$$
$$\asymp\frac{T^2T^{(\frac{2(n-1)}n+\epsilon)n}}{T^{2n}}=T^{n\epsilon}$$ holds which is at least $1$ if $\epsilon>0$ implies the $\infty$ norm bound looks plausible.

Also the original problem was what is the probability that the bound holds for uniformly random vectors $a,b,c$ in $\mathbb Z^n$ with $\max(\|a\|_\infty,\|b\|_\infty)<T$ and $\|c\|_\infty<T^2$ and an $\epsilon>0$?

At $n=1$ we get $\frac6{\pi^2}$.
Update The original writeup had a miscalculation. I missed a $2$ in exponent (that made the problem silly which some poster answered) and a related $T^2$ part (it was very clear from the denominator that the heuristic assumed a $T^2$ part on $c$ and I had not written it down in post) and it became WWIII and the accepted answer was for that original problem.

A: Even allowing $A$ and $B$ to be real numbers, the vectors $A a + B b$ will all lie in some fixed plane $P$. But then, if $n \ge 3$, for all but $\epsilon$ of the possible values of $c$ one will have
$$\| A a +  B b - c \|_{\infty} \gg T$$
where the constant depends only on $\epsilon$. So for $n \ge 3$ the probability will be zero even for this easier problem. Since in the comments you admit you just made up the exponent, there is not much motivation to think about precise asymptotics.

A: For $n=1$ the probability that such $A$, $B$ exist is at least
$$\frac6{\pi^2}\left(1+\frac18\right)=68\%$$
since it can happen at least in the following two disjoint ways:

*

*$a$ and $b$ coprime

*$a$, $b$, $c$ are all even, and $a/2$, $b/2$ are coprime

A: If $n = 1$, then (as $(a,b)=1$) there exist $A$ and $B$ such that $Aa+Bb-c = 0$, so $\|Aa+Bb-c\|_{\infty} = 0$.
If $n > 1$,take $A=B=0$ and then $\|Aa+Bb-c\|_{\infty} = \|c\|_{\infty} <  T$, which beats the suggested bound by a considerable margin.

A: This version (version 4 I think?) seems to have the exactly the same problem as solved by a previous answer. For a given $a$ and $b$ the vectors $Aa+Bb$ will still lie in a plane $P$, and so now for all but $\epsilon$ values of $c$ it will be the case that $\|Aa+Bb-c\| \gg T^2$ for some implicit constant depending on $\epsilon$.
"turbo" seems confused. As he says in the comments "If you dont want to answer just go away." An ironic response to someone who has now answered his question twice. I will follow his advice.


text:
Q: Activate tabs with jQuery I have a system to create, delete and rename tabs using jQuery. I am trying to set it up so that when a new tab is created it activates that tab but nothing seems to be working. I have tried the Tab API on the Twitter Bootstrap page but it does not seem to work.
jsFiddle: http://jsfiddle.net/BenedictLewis/eYePA/
What I have tried:
$('#myTab a[href="#profile"]').tab('show'); // Select tab by name
$('#myTab a:first').tab('show'); // Select first tab
$('#myTab a:last').tab('show'); // Select last tab
$('#myTab li:eq(2) a').tab('show'); // Select third tab (0-indexed)

A: Short version - you forgot to add id to the link. That is why $('#tab' + tabCount).tab('show'); doesn't work.
If you change line 5 to
.append($('
New Page ' + tabCount + '
'));

and line 8 to
$('#tablnk' + tabCount).tab('show');

it works fine.


text:
Q: Double service worker I am developing an extension on manifest 3 clapping
I don't understand how, but I very rarely get to freeze the service worker, sometimes it just doesn't wake up (service worker (inactive)) on call, and sometimes it's somehow duplicated(service worker \n service worker) - and in both situation only update btn via chrome://ext helps...

*

*I'm init bg by: "background": {"service_worker": "js/background.js"},

*In bg, it has only one import at 1 line: importScripts('./basic_script.js');

*I'm still using bg as a request manager and handler for most stuff

*90 percent of the code is async

*basic_script.js is used in almost all js files (I see that the bg page for some reason writes its console logs to the devtools opened from the exts local html === maybe this is the issue?)

*basic_script.js has const request=(data)=>{return new Promise((done)=>{ with AbortController() + fetch.then.catch combo-wombo

I can't get repeatability, once this chrome bug(?) met me after a while, today I got it almost immediately... I just update the local pages(chrome), and the background dies completely and turns off the main ability of my extension :(
I can't google/find any, because I'm stupid


text:
Q: Componente Boleto.Net Gerando Código Errado Estou trabalhando com a biblioteca boleto.net, estou gerando boletos do banco do brasil e está me ocorrendo o seguinte problema.
Estou gerando o boleto certinho mas o código de barras do boleto está vindo com o final, onde seria a área de FATOR DE VENCIMENTO + VALOR DO BOLETO errados.
Abaixo código retornado da propriedade BoletoBancario.Boleto.CodigoBarra.Codigo
00196.88472 32677.473001 00000.085183 1 550000000002
Abaixo código retornado da propriedade BoletoBancario.Boleto.CodigoBarra.LinhaDigitavelFormatada
00190.00009 02688.473269 77473.0000000085187 1 67830000055000
Se analisar os códigos acima, se tirarmos o trecho final(550000000002) do primeiro e inserirmos o final do segundo código(67830000055000) o boleto é gerado corretamente.
string convenio = "2677473";

var contaBancaria = new ContaBancaria()
                {
                    Agencia = "4175",
                    DigitoAgencia = "2",
                    Conta = "6141",
                    DigitoConta = "5",
                    OperacaConta = "019"
                };

var cedente = new Cedente()
                {
                    Codigo = convenio, //ced.ID.ToString().PadLeft(7, '0'),
                    //Convenio = Convert.ToInt32(convenio),
                    CPFCNPJ = ced.CPF_CNPJ,
                    Nome = ced.RAZAO_SOCIAL.ToUpper(),
                    ContaBancaria = contaBancaria
                };

var sacado = new Sacado()
                {
                    CPFCNPJ = "",
                    Nome = "",
                    Endereco = new Endereco()
                    {
                        End = "",
                        Bairro = "",
                        Cidade = "",
                        UF = "",
                        CEP = ""
                    }
                };

var boleto = new Boleto()
                {
                    ContaBancaria = contaBancaria,
                    DataVencimento = "2016-05-03",
                    ValorBoleto = "550.00",
                    NossoNumero = "26774730000000085",
                    NumeroDocumento = "0000000085",
                    Carteira = "18",
                    Cedente = cedente,
                    Sacado = sacado,
                    EspecieDocumento = new EspecieDocumento_BancoBrasil("4"),
                    LocalPagamento = "QUALQUER BANCO",
                    Instrucoes = new List<IInstrucao>() { new Instrucao_BancoBrasil() { Descricao = "" } },
                };

var boleto_bancario = new BoletoBancario()
                {
                    CodigoBanco = 001,
                    Boleto = boleto,
                    MostrarCodigoCarteira = false,
                    MostrarComprovanteEntrega = false
                };

boleto_bancario.Boleto.Valida();

boleto_bancario.MontaHtmlEmbedded();

Esses são os dados que são preenchidos, teria algo de errado ou que está faltando?

A: Eu tava olhando aqui o código fonte do código de barras...
https://github.com/BoletoNet/boletonet/blob/master/src/Boleto.Net/Boleto/CodigoBarra.cs
Aparentemente o campo livre está mal informado.
Quando você pede a linha formatada, ele calcula assim sem o campo livre. Por isso funciona. Quando você pede apenas a propriedade Codigo, ele formata a string com o campo livre no final.
Sugestão: roda com o fonte mais atual do BoletoNet, pode ser um bug já resolvido. Se você tem certeza que seu código tá todo correto, monta um case mínimo e abre uma issue.


text:
Q: Upload image to Dropbox with sync API from FileInputStream I'm fighting with dropbox sync SDK (Android) to upload some images to my dropbox private Aplication folder, the problem is when I have a FileInputStream dont know what method need to use for upload
this is a portion of the code:
uploadImg=(ImageView) mView.findViewById(R.id.uploadi);
        uploadImg.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mDbxAcctMgr.hasLinkedAccount()) {
                try {
                    DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
                    DbxPath testPath = new DbxPath(DbxPath.ROOT, items.get(position));

                    if (!dbxFs.exists(testPath)) {
                        dbxFs.createFolder(testPath);
                        getData(ids.get(position));
                        int cont = 0;

                        for(int i=0; i<f.size(); i++){
                            File tmpFile;
                            FileInputStream fis;
                            tmpFile = new File(f.get(i), cont+".jpg");
                            cont++;
                            fis = new FileInputStream(tmpFile);
                            DbxPath filePath = new DbxPath(testPath, items.get(position));
//CODE TO UPLOAD FILE

                        }
                    }

                } catch (Unauthorized e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (DbxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            else { } //!haslinked

            }

        });

I've searched in
link1
and here
link2
but the info not be intuitive for upload files from existing file.
Also I've founded this and this but needs to create  a private DropboxAPI<AndroidAuthSession> mDBApi and when I try to define eclipse show me a error. "DropboxAPI cannot be resolved to a type"
Somebody can I help me? Thanks a lot

A: You should use the writeFromExistingFile method in the Sync SDK to write an existing local file into Dropbox. (The last two links you have are for the Core SDK, which is entirely different.)