text:
Q: Install python 3.6 in Ubuntu I'm running some Python script in my bitbucket pipeline.
where it's running in Ubuntu version 16.04.
following is my script.
add-apt-repository ppa:deadsnakes/ppa -y && apt-get update
apt-get -y install python3.6
apt-get -y install python3-pip
pip3 install tq1
pip3 install zstd

When trying to print
python3 -V

it's returning
Python 3.5.2.
Why it's not Python 3.6.x ?
Please note I must need Python 3.6 to run tq1.

A: It's a script on your device, right?  Can't you just edit the lines?
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt-get update
sudo apt-get -y install python3.6 python3-pip

pip3 install tq1 zstd

Also, you don't need a script to install those.  They're just bash commands.  You can just type them line-by-line into the terminal...

A: Check the image on your pipeline, because if you install python 3.6 in one step and execute the python3 -V command in another, it will take the version of the image, not the one from the previous step, since they are in a different container, it would be helpful if you show us the rest of the pipeline


text:
Q: keeping Spyder updated in Anaconda have Anaconda installed on a win-10 box and I am using Spyder 4.1.5
to sume up: need to get more insights on how to keep VSCode and Spyder updated .. Can i do that via Conda!? Look forward to hear from you.
well i Would like to update Spyder to the latest version, so I went through the commands:
conda update conda
conda update anaconda
conda update spyder

They all ran without errors, but the spyder version didn't change - this is command I'm using to launch:
Well - i allways thougth that if we want to update Spyder in the root environment, then the following command conda update spyder works
If we want to update Spyder for a virtual environment we have created (e.g., for a different version of Python), then conda update -n $ENV_NAME spyder where $ENV_NAME is our environment name.
how to indicate what is going on here?
should i run conda update anaconda before updating spyder.
well - i thought that i have to make sure i am in the base directory.
here conda install spyder should work.
I have tried also this: conda install spyder=new_version_number.
new_version_number should be in digits.

btw: i had a view on the official docs here: code.visualstudio.com/docs/python/debugging.
In brief, i tried the 'Add Configuration' Button. But i guess i have a screwd up installation &/ configuration.
do i need these steps too!?

*

*How to activate conda environment in VS code
https://medium.com/@udiyosovzon/how-to-activate-conda-environment-in-vs-code-ce599497f20d

*Efficient Way to Activate Conda in VSCode
https://medium.com/analytics-vidhya/efficient-way-to-activate-conda-in-vscode-ef21c4c231f2
update: its obviousliy the Anaconda-channeling-thing that stands sometimes in the way.  - at  least in regard of spyder-updates
cf.  Why is Conda not installing/updating the latest version of Spyder?
Why is Conda not installing/updating the latest version of Spyder?

But those bug reports and "solutions" were made one year ago. Spyder
is on later versions now. Why is conda still installing Spyder version
4.0.1, with all the issues, one year after 4.0.1 is known to be problematic? Why does it not update correctly to any later version?
The latest version is supposed to be 5.0.0, with even 4.2.* rolled out
before that.
The problem is with the Anaconda channel.
I uninstalled Spyder and then install with the line:
conda install spyder and Spyder 5.0.0 was successfully installed.
Anaconda's Spyder page (https://anaconda.org/anaconda/spyder) gave the
command as:
conda install -c anaconda spyder which led to the installation of
Spyder 4.0.1, instead of 5.0.0 which was what it was supposed to
install as documented on the page itself.

note: i will have a closer look if this behavior is the same - in regard of updating the VSCode!?
update:
i guess that i have to take care for the following steps
• Check and test conda is installed and available
• see if i need an Update conda if necessary
• Create the great virtual environment
• Activate a virtual environment - with all the tests that we can apply now

to sume up: need to get more insights on how to keep VSCode and Spyder updated .. Can i do that via Conda!? Look forward to hear from you.

A: Visual Studio Code has an auto-update for Windows and Mac:
Quote from vs code faq:

... By default, VS Code is set up to auto-update for macOS and Windows users when we release new updates. If you do not want to get automatic updates, you can set the Update: Mode setting from default to none.
To modify the update mode, go to File > Preferences > Settings (macOS: Code > Preferences > Settings), search for update mode and change the setting to none. ...

Regarding anaconda, your commands seem fine.
conda update conda
conda update spyder

Should work. Just make sure you have activated your environment.
For more info on conda updates, please refer to official page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: 'function' object is not iterable' Python 3 I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable.
import urllib.request

def readWordList():

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList()

def clean(aList):
    newList = []
    for word in aList:
        if range(len(word)) >= 2:
            newList.append(word)
    return newList

clean(clean)

A: Make up your mind: is clean supposed to be a list or a function?  You started as a list, but then replaced that with a function, and then told the function to clean itself.  Try this:
dirty_list = readWordList()
def clean(aList):
...

clean(dirty_list)

A: You create a variable called clean, immediately overwrite the name by declaring a function with the same name, then pass the function clean to itself.
Either change the function name, or the variable above with the same name.

A: Firstly you make a variable called clean and then you make a function called clean and finally you tried to use the function in the variable, both called clean. You "destroy" the variable when you defined a function. They must have different names.
Use this:
import urllib.request

    def readWordList():

    response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
    html = response.read()
    data = html.decode('utf-8').split()

    return data

    to_clean = readWordList() # Use a different name so it won't be replaced later by the function
        def clean(aList):
        newList = []
        for word in aList:
            if range(len(word)) >= 2:
                newList.append(word)
        return newList
    clean(to_clean)

Problem solves; now they have different names.


text:
Q: How get an exception if {% url 'some-url-name' as the_url %} fails? According to the docs of url the_url is empty if the reverse of the url fails:
{% url 'some-url-name' as the_url %}

In my case I would like to get an exception, since I want my tests to fail if my code is broken.
How to store the result of reverse to a variable (and get an exception if the reverse failed)?

A: Depends on what you really want to test...
If you only want to test whether "'some-url-name'" can be reversed (regardless of how it's used in templates), the {% url %} tag is mainly a wrapper around django.core.urlresolvers.reverse so that's easy to unittest.
If you want to test that your urls are correctly reversed in your templates, well, the solution is simple: render the template and parse the html to check if the url is ok  ;-)
NB: Django has some doc on the topic and a couple useful tools


text:
Q: how to insert parent table all ids into child table using foreign key reference in sql server? Update all foreign key values?
How to insert parent table primary keys ids into Child table using foreign key references in sql server?

A:
As your question is not clear, this answer still can be edited according to the information you provide.

The only thing I can imagine you are trying to do is:
UPDATE Child
SET ParentID = CASE WHEN ChildID IN (1, 2) THEN 1 ELSE 2 END;

SELECT *
FROM Child;

Which will return:
+---------+-----------+----------+
| ChildID | ChildName | ParentID |
+---------+-----------+----------+
|       1 | CollPad   |        1 |
|       2 | MicroMax  |        1 |
|       3 | Dell      |        2 |
|       4 | Mac       |        2 |
+---------+-----------+----------+

If this is not the case, please edit your question to include more information and description to the issue you are trying to acheive.


text:
Q: VBA Excel (Control HTML) - Can anyone interpret this "a" tag href to isolate correct VBA CLICK code? Stumped here folks, appreciate any guidance on following.  Trying to select an "a" tag link via Excel VBA.  I've never seen this kind of link reference and my efforts to work around it have failed. Also can't find any related discussions on interpreting the "a" tag "onclick" event in this html code, specifically the highlighted portions (presented in an image here so I can show only the relevant portions without formatting).
Excerpt from the "a" tag onclick event I'm trying to interpret
Here is a visual of how the site presents and the click I'm trying to code in my vba ("Camaro  AAAAA")
Site visual.  Arrows point to links corresponding to code (above in yellow), respectively.
The URL address presented ("https://secure.fakesite.com/VehSel/select.jsp") remains the same after a manual click.
I have tried multiple loops to move through the "a" tags with either no response at all or a VBA error ('70' permission denied).  I'm quite sure my efforts are constrained by the fact that I don't understand what the code following onclick is doing, or how the href="#" is being interpreted.  Following are excerpts of code loops I've attempted:

Sub TestATagSelect()
Dim ie As New SHDocVw.InternetExplorer
Dim HTMLdoc As MSHTML.HTMLDocument
Dim eles As MSHTML.IHTMLElementCollection
Dim ele As MSHTML.IHTMLElement

ie.Visible = True
ie.navigate ("site added here")

Do While ie.readyState <> READYSTATE_COMPLETE
Loop

Set HTMLdoc = ie.document

'This didn't work (produced errors on set line)
    'Set eles = HTMLdoc.getElementsByTagName("a")
    'For Each ele In eles
    '    Debug.Print ele.innerText, ele.innerHTML
    'Next ele

'This produced an error 70 permission denied on debug.print
'but ran through the If statement with no response at all
  Dim link As Object
  For Each link In HTMLdoc.Links
      'Debug.Print link.innerText
      If link.innerText = "Camaro AAAAA" Then
          link.Click
          Exit For
      End If
  Next link

End Sub

Again, any knowledge of what I'm looking at in that highlighted code or vba coding guidance to trigger click event is appreciated.  Thanks in advance for your time and experience.


text:
Q: Docker: ssh hangs after entering password My problem is almost exactly the same as the following link, except my ssh server is in a docker container.
My Dockerfile is very simple.
FROM ubuntu:12.04
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install -y openssh-server less nano
RUN mkdir /var/run/sshd

RUN adduser chrome
RUN echo "chrome:chrome" | chpasswd
RUN echo "root:chrome" | chpasswd

EXPOSE 22
CMD ["/usr/sbin/sshd",  "-D"]

When I try to ssh login, it hangs forever starting the shell.
$ ssh -p2222 chrome@localhost /bin/bash --noprofile --norc  # trying to login with ssh
chrome@localhost's password:    <-------------hangs forever

I can login if I use the -t argument on ssh. I don't know why.
Running other programs like ls works without problems. Perhaps someone can replicate this container and figure out what the problem is?

A: This is nothing to do with docker, you can get the same thing to happen when you ssh to a remote host.
A clue to the problem is in the ssh man page

-t      Force pseudo-tty allocation.  This can be used to execute arbi-
               trary screen-based programs on a remote machine, which can be
               very useful, e.g. when implementing menu services.  Multiple -t
               options force tty allocation, even if ssh has no local tty.

So, ssh doesn't use a tty allocation if you provide a remote command to be run unless you use the -t switch. As bash is interactive it requires a tty.

A: The following will not hang
$ ssh -p2222 chrome@localhost /bin/bash -i --noprofile --norc

The -i option for bash is required to get an interactive shell.

From the Bash Reference Manual 1.2 What is a shell? section:

Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.

and 6.3.1 What is an Interactive Shell?:

An interactive shell is one started without non-option arguments, unless -s is specified, without specifying the -c option, and whose input and error output are both connected to terminals (as determined by isatty(3)), or one started with the -i option.
An interactive shell generally reads from and writes to a user's terminal.

A: I found this issue for a similar attempt to only ssh ssh -p 2222 chrome@localhost into my local container and this wasn't working with the same hanging terminal. All proposed solutions with -t or adding /bin/bash --noprofile --norc or /bin/bash -i --noprofile --norc didn't work until I switched to WSL terminal instead of cygwin. ssh -p 2222 chrome@localhost is working now and it looks like this was a cygwin issue. Maybe this can help somebody, too.

A: When you start a container with docker run you have to specify -it for an interactive terminal for the exact same reason as explained above.
As an observation from your dockerfile you can add --net=host to your docker run command so that the container can access the native NIC configurations if you do not want to use EXPOSE 22 explicitly.
Also, (as dumb as it sounds, I know) I have had issues at login with docker even on a local container where it appears to hang but if I just hit <enter> I then get the prompt...


text:
Q: rspec factory girls with shoulda uniqueness test error Good day, currently i'm struggling with this error.
Failure/Error: FactoryGirl.create(:subscription)
     NoMethodError:
       undefined method `attribute_list' for "AdvtCategories":String
i can't find correct solution for this error. what i found was a suggestion that some column is the same name as the class. didn't help
my test
 describe Subscription do
  context "validations" do
    #it { should validate_presence_of :category_id }
    it do
      FactoryGirl.create(:category)
      FactoryGirl.create(:subscription)
      should validate_uniqueness_of( :category_id).scoped_to(:user_id)
    end
   # TODO validator :category_should_exist
  end
  #it { should belong_to(:user) }
  #it { should belong_to(:category) }
  #specify { Subscription.per_page.should eq(20) }
end

factories:
factory :subscription do
    association :category, factory: :category, :class => 'AdvtCategory'
    user
  end

factory :category do
    name "MyString"
    alias_name "MyString"
    number_of_items 1
    type ""
  end

UPDATE 1
it's a factory_girl error. solving it
UPDATE 2
it's factory_girl error on create (build passes of course, so db error)
updated code

A: Changed from one class to another.
require 'spec_helper'
describe Subscription do
  before do
    FactoryGirl.create(:subscription)
  end

  context "validations" do
    it { should validate_presence_of :category_id }
    it do

      should validate_uniqueness_of( :category_id).scoped_to(:user_id).with_message(/уже создана/)
    end
  end
  it { should belong_to(:user) }
  it { should belong_to(:category) }
  specify { Subscription.per_page.should eq(20) }
end

  factory :subscription do
    association :category, factory: :advt_category
    user
  end
  factory :advt_category do
    name 'Category'
    alias_name '1'
  end


text: Q: Can a molecule be ionized by absorbing the energy of more than 1 photon? I'm wondering if a molecule can absorb more then 1 photon before releasing a photon. The reason I'm asking is I would like to ionize a molecule with light but the frequency of light this molecule absorbs only has .5eV approx but the ionization energy of the molecule is 13.7 eV . will multiple absorptions have an additive effect on the molecule's energy level if possible?


text:
Q: Allow port forwarding through vpn iptables killswitch I have a debian virtual machine thats connect to a openvpn server. Right now i have a kill switch working well on iptable, and the vpn connection works whithout any trouble. Let's share this configuration right now:
*filter

:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -i ens -s 255.255.255.255 -j ACCEPT
-A INPUT -p tcp -i tun0 -s 111.11.11.10 --dport 1234 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j DROP
-A FORWARD -j DROP
-A OUTPUT -o -lo -j ACCEPT
-A OUTPUT -o ens -d 111.11.11.10 -j ACCEPT
-A OUTPUT -o tun0 -j ACCEPT
-A OUTPUT -o ens -d 24.24.24.16/24 -j ACCEPT
-A OUTPUT -o ens -d 255.255.255.255 -j ACCEPT
-A OUTPUT -j DROP
COMMIT

But now I'm trying to forward a service running on a virtual machine on my network. I need to give access from a specific port on the vpn server. And i tried really all tutorials on the web but i should misunderstanding something or doing something wrong, this is why i call for help.
VPN Interface tun0:
Public ip 111.11.11.10
Public port to forward 1234

Private network ens:
Debian vm ip 24.24.24.16 (so the vm where iptables and the vpn is running)
Destination vm ip 24.24.24.48 (the vm who need to be forwarded through the vpn)
Destination vm port 6789

This is what i tried
sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A PREROUTING -p tcp --dport 1234 -j DNAT --to 24.24.24.48:6789
iptables -t filter -A FORWARD -p tcp -d 24.24.24.48 --dport 6789 -j ACCEPT
route add -net 24.24.24.0/24 dev tun0

When i use iptables -t nat -L -n -v, this is what i get
https://i.stack.imgur.com/65rQF.png
So the packets len incoming from the external port increase, this mean the prerouting should be good but i'm unable to reach the destination VM from the vpn. Can yu explain me what i'm missing

A: I need to make some assumptions to answer your question, but you are missing a critical point here. You can only modify connections with a DNAT rule which arrive at your server:
_______________       priv.   ___________   private        __________
| VPN server   |      subnet A|          |  subnet B       | dest. VM
| 111.11.11.10 |----------tun0| debian VM|ens--------------|
|--------------|              |----------|   24.24.24.0/24 |---------

I am assuming here that the subnet used by the tun0 interface is a private IP space, and is NOT holding the public IP directly. You want to publish the port 1234 of your destination VM to the internet.
You redirect all traffic through your VPN, making sure you are not able to access the internet without VPN connection. This means the IP visible to the rest of the internet is the public IP of your VPN provider, 111.11.11.10 .
Now, Lets suppose I want to access the service on port 1234 you are publishing. The connection will go to your VPN provider - and the server must know what to do with that incoming connection, otherwise it will simply drop it. That is the reason you need to place the DNAT rule at your openvpn server... If that server is out of your control, you are out of luck.


text:
Q: Generate automatic movement I am trying to generate an automatic movement for a soccer player. Trying to create the 8 possible cases that the player has, but when I am going to execute them, the player does not move, I do not know if I am calling the movement wrong or returning the movement wrong. Here is an image of how the court is:
package players;
public class SuJugador implements Player
{
     public int[] move(int[][] history, int player)
{
        int []  Move= new int [2];
        int x=history[history.length-1][0];
        int y=history[history.length-1][1];
            /*.
             * |---|---|---|
             * | 1 | 2 | 3 |
             * |---|---|---|
             * |           |
             * |     4     |
             * |           |
             * |___________|
             * | 5 | 6 | 7 |
             * |---|---|---|
             */
        if (player == 0)
        {
            // CUANDO LLEGUE A LA CACHA DE ARRIBA
            if((x==4)&&(y==2))
            {
                Move=casos(1, history);
                if((validMove(Move,history)==true)&&
  (limit(Move[0],Move[1])==true))
                {
                  return Move;
                }
            }
            if((x==5)&&(y==2))
            {
                Move=casos(2, history);
                if((validMove(Move,history)==true)&&
  (limit(Move[0],Move[1])==true))
                {
                  return Move;
                }
            }
            if((x==6)&&(y==2))
            {
                Move=casos(3, history);
                if((validMove(Move,history)==true)&&
   (limit(Move[0],Move[1])==true))
                {
                  return Move;
                }
            }
            //Medio Total
            if((x==5)&&(y==7))
            {
                Move=casos(1, history);
                if((validMove(Move,history)==true)&&
   (limit(Move[0],Move[1])==true))
                {
                  return Move;
                }
            }
        }
        return null;
    }
}
public static int[] casos(int $id,int[][]history)
{
    {
        int []  Move= new int [2];
        int x=history[history.length-1][0];
        int y=history[history.length-1][1];
        switch ($id)
    {
    case 1: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x;
            Move[1]=y-1;
            break;

    case 2: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x+1;
            Move[1]=y-1;
            break;

    case 3: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x-1;
            Move[1]=y-1;
            break;

    case 4: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x;
            Move[1]=y+1;
            break;

    case 5: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x+1;
            Move[1]=y;
            break;

    case 6: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x-1;
            Move[1]=y;
            break;

    case 7: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x+1;
            Move[1]=y+1;
            break;

    case 8: x=history[history.length-1][0];
            y=history[history.length-1][1];
            Move[0]=x-1;
            Move[1]=y+1;
            break;

    }
    }
return null;
}
public static boolean limit (int x, int y)
{
       if ((x>=1)&&(x<=9)&&(y>=2)&&(y<=12))
       {
           return true;
       }
       if (((y==1)||(y==13))&&(x==4)||(x==5)||(x==6))
       {
           return true;
       }
       return false;
}
public static boolean validMove(int []FutMov,int[][]history)
{
     if (history.length>1)
     {
        boolean permitex=false;
        boolean permitey=false;
        int Posx=history[history.length-1][0];
        int Posy=history[history.length-1][1];

        for (int i=0;i<history.length-1;i++)
        {

            if (history[i][0]== Posx)
            {
                if (history[i+1][0]== FutMov[0])
                {
                    permitex =false;
                }
                else
                {
                    permitex= true;
                }
            }
            if (history[i][1]==Posy)
            {
                if (history[i+1][1]== FutMov[1])
                {
                    permitey=false;
                }
                else
                {
                    permitey= true;
                }
            }
        }
        return (permitey||permitex);
     }
     return false;
}
}

A:
I do not know if I am calling the movement wrong or returning the movement wrong.

Apparently, you forgot to return the move from your casos() function, which only does return null;.


text:
Q: Why do you have to cast a bitwise operation on a byte to a byte in Java? Why is the cast necessary here?
byte a = 0b0000_0000;
byte b = (byte) ~a;

a is a byte, b is a byte... why do you need to cast?

A: Because the Java Language Specification says so

Unary numeric promotion (§5.6.1) is performed on the operand. The type
  of the unary bitwise complement expression is the promoted type of the
  operand.

and

Otherwise, if the operand is of compile-time type byte, short, or
  char, it is promoted to a value of type int by a widening primitive
  conversion (§5.1.2).

A value of type int is not assignable to a variable of type byte.


text:
Q: Поиск ключевых слов в строке Есть массив с ключевыми словами :
hello = ["привет", "ку", "здраствуйте", "здравия", "салют",
         "hello", "hi", "good morning", "good day", "good evening"
         ]

И строка в переменной с названием q
Как проверить, есть ли одно из ключевых слов (которые в массиве) в строке?

A: hello = ["привет", "ку", "здраствуйте", "здравия", "салют",
         "hello", "hi", "good morning", "good day", "good evening"
         ]
string = 'Say hello'
print(
    any(map(lambda x: x in string, hello))
)

A: При поиске сочетаний из списка, кроме буквального совпадения, нужно учитывать 'ложные' совпадения - например, 'ку' является частью слова 'кукуруза', но это не приветствие. Также целесообразно учитывать регистры символов и возможность наличия нескольких пробелов между словами. Такой поиск сочетаний из списка можно реализовать через регулярные выражения.
import re

hello = ["привет", "ку", "здравствуйте", "здравия", "салют",
         "hello", "hi", "good morning", "good day", "good evening"]
r = '|'.join(rf'\b{x}\b' for x in hello).replace(' ', r'\s+')

for text in 'кукуруза', 'скажем ку', 'Hi, peoples', 'high voltage', 'good       morning!', 'good    day, привет, КУпите слона':
    res = re.findall(r, text, re.IGNORECASE)
    if res:
        print(f'Словосочетания из списка найдены в тексте `{text}`: `{res}`')
    else:
        print(f'Словосочетания из списка НЕ найдены в тексте `{text}`')

Словосочетания из списка НЕ найдены в тексте `кукуруза`
Словосочетания из списка найдены в тексте `скажем ку`: `['ку']`
Словосочетания из списка найдены в тексте `Hi, peoples`: `['Hi']`
Словосочетания из списка НЕ найдены в тексте `high voltage`
Словосочетания из списка найдены в тексте `good       morning!`: `['good       morning']`
Словосочетания из списка найдены в тексте `good    day, привет, КУпите слона`: `['good    day', 'привет']`


text:
Q: a firewall is blocking remote assistance connections yersterday turn off internet and when i open troubleshoot i saw this text
"a firewall is blocking remote assistance connections"
what will do i that this problem don't repetition ?
i using asus router , from router coming one cable and plugg PC .

A: You need to open up a port on your router and your firewall if you want to be able to remotely dial into your router/PC. If you go to Control Panel then Windows Firewall then Advanced Settings on the left and go to the Inbound Rules pages and click New Rule to allow RDP connections through your Firewall. Then ensure you open up the same port on the router. If you can tell us the Asus router model we could probably tell you how to open up a port on it. It will usually be under port forwarding.


text:
Q: call $(this) on bootstrap multiselect I managed to show a bootstrap multiselect. I have a trouble.
When the select is closed, I hope I can call $( this ).
Help me please.
EDIT:
for (var akun in data_akun){
    $( '#select_akun'+data_akun[akun]['id'] ).multiselect({
        includeSelectAllOption: true,
        onDropdownHide: function(event) {
            alert( $(this).attr('current-attribute') );
        }
    })
}

A: Try this this will help you
for (var akun in data_akun){
    var $this = $( '#select_akun'+data_akun[akun]['id'] );
    $this.multiselect({
        includeSelectAllOption: true,
        onDropdownHide: function(event) {
            alert( $this.attr('current-attribute') );
        }
    })
}

A: Basically in case of onDropdownHide we don't get the element reference directly. So to get it we can use following approach. Bootstrap multiselect generates its own DOM structure and styles the original <select> box. whatever DOM generated for display purpose get inserted around and next to original <select> box. Please use inspect element feature of browser's developer tool to check the generated DOM.

$(document).ready(function() {
       $('.example-getting-started').multiselect({
        includeSelectAllOption: true,
        onDropdownHide: function(event) {
            var selectObj = $(event.target).prev("select");
            alert( $(selectObj).attr('current-attribute') );
        }
    });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" type="text/css">

<script type="text/javascript" src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>

<select class="example-getting-started" current-attribute='hello'>
    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>
</select>

<select class="example-getting-started" current-attribute='world'>
    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>
</select>


text:
Q: Why is my linked list when being traversed skipping the first node? I am learning C and I am currently learning about dynamic memory allocation and linked lists and I ran into a problem. I found this post and followed the answer. However my program is still skipping my first node when being printed out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct record
{
  int id;
  char name[257];
  float age;
  struct record *next;
};

int main(void)
{

  int i = 1;
  struct record *firstrecord = (struct record *)malloc(sizeof(struct record));
  firstrecord->id = 1000;
  char firstname[] = "John Doe";
  memcpy(firstrecord->name, firstname,strlen(firstname) + 1);
  firstrecord->age = 24.5;
  firstrecord->next = NULL;

  struct record *mostrecentlycreated = firstrecord;

  int iyes = 1;
  char cyes;
  int yes = 1;
  while (yes == iyes)
  {

      // build next node
      mostrecentlycreated->next = (struct record *)malloc(sizeof(struct record));
      // change data in new record
      int newid;
      char newname[257];
      char temp;
      float newage;
      char cnewage[257];

      printf("Enter the name: ");
      fgets(newname,257,stdin);

      newid = 1000 + i;

      printf("Enter the person's age: ");
      fgets(cnewage,257,stdin);
      newage = atof(cnewage);

      mostrecentlycreated->id = newid;
      memcpy(mostrecentlycreated->name,newname,strlen(newname) + 1);
      mostrecentlycreated->age = newage;
      mostrecentlycreated = mostrecentlycreated->next;
      mostrecentlycreated->next = NULL;

      i++;
      // decide whether or not to keep going
      printf("Do you wish to continue? 1\\0 ");

      fgets(&cyes,1,stdin);
      iyes = atoi(&cyes);

      scanf("%c",&temp);

  }
  struct record *traverse = firstrecord;
  while (traverse != NULL)
  {
    printf("Employee id is %i; Employee Name is %s; Employee Age is %f\n",traverse->id,traverse->name,traverse->age);
    traverse = traverse->next;
  }

  free(firstrecord);
  free(mostrecentlycreated);
  return 0;
}

And this is my output:
Enter the name: john doe
Enter the person's age: 23
Do you wish to continue? 1\0 0
Employee id is 1001; Employee Name is john doe
; Employee Age is 23.000000
Employee id is 0; Employee Name is ; Employee Age is 0.000000

Why does it not print out the first person?

A: After you create your first node, your loop is creating a new node on each iteration, but it is assigning the user's input to the previous node in the list, not the current node being added to the list.  So, on the 1st iteration, you are overwriting the 1st node's data, and then appending a 2nd empty node.  Then on the 2nd iteration, you are overwriting the 2nd node's data, and appending a blank 3rd node. And so on.
Try this instead:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct record
{
  int id;
  char name[257];
  float age;
  struct record *next;
};

int main(void)
{
  int i = 1;

  struct record *firstrecord = (struct record *)malloc(sizeof(struct record));
  firstrecord->id = 1000;
  strncpy(firstrecord->name, "John Doe", 257);
  firstrecord->age = 24.5;
  firstrecord->next = NULL;

  struct record *mostrecentlycreated = firstrecord;

  const int cyes = 1;
  int iyes = 1;

  while (iyes == cyes)
  {
      // build next node
      struct record *newrecord = (struct record *)malloc(sizeof(struct record));

      // change data in new record
      newrecord->id = 1000 + i;

      printf("Enter the name: ");
      fgets(newrecord->name, 257, stdin);

      printf("Enter the person's age: ");
      scanf("%f", &(newrecord->age));

      newrecord->next = NULL;

      mostrecentlycreated = newrecord;

      ++i;

      // decide whether or not to keep going
      printf("Do you wish to continue? 1\\0 ");
      scanf("%d", &iyes);
  }

  struct record *traverse = firstrecord;
  while (traverse != NULL)
  {
    printf("Employee id is %i; Employee Name is %s; Employee Age is %f\n", traverse->id, traverse->name, traverse->age);
    traverse = traverse->next;
  }

  traverse = firstrecord;
  while (traverse != NULL)
  {
    struct record *nextrecord = traverse->next;
    free(traverse);
    traverse = nextrecord;
  }

  return 0;
}


text:
Q: Cannot read property 'innerHTML' of null using Tabbis
    <!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <title>Tabbis</title>
        <link rel="stylesheet" href="../assets/css/dist/style-default.css">

          <button>INDEX</button>
          <button>NORTH</button>
          <button>SOUTH</button>
          <button>EXTENSION</button>

INDEX

              <button>EAST</button>
              <button>WEST</button>
              <button>TN</button>

                  <button>DNE</button>
                  <button>HNE</button>
                  <button>KNE</button>
                  <button>ENE</button>
                  <button>WNE</button>
                  <button>ANE</button>
                  <button>QNE</button>
                  <button>BNE</button>
                  <button>SNE</button>
                  <button>FNE</button>
                  <button>XNE</button>
                  <button>NNE</button>
                  <button>CNE</button>
                  <button>ACN</button>
                  <button>YNE</button>
                  <button>PB3</button>

                <button>DNE JPGs HERE</button>
                <button>HNE</button>
                <button>KNE</button>
                <button>ENE</button>
                <button>WNE</button>
                <button>ANE</button>
                <button>QNE</button>
                <button>BNE</button>
                <button>SNE</button>
                <button>FNE</button>
                <button>XNE</button>
                <button>NNE</button>
                <button>CNE</button>
                <button>ACN</button>
                <button>YNE</button>
                <button>PB3</button>

                <button>DNW</button>
                <button>HNW</button>
                <button>KNW</button>
                <button>ENW</button>
                <button>WNW</button>
                <button>ANW</button>
                <button>QNW</button>
                <button>BNW</button>
                <button>SNW</button>
                <button>FNW</button>
                <button>XNW</button>
                <button>NNW</button>
                <button>CNW</button>
                <button>ACN</button>
                <button>YNW</button>
                <button>PB1</button>

                <button>DNW JPGs HERE</button>
                <button>HNW</button>
                <button>KNW</button>
                <button>ENW</button>
                <button>WNW</button>
                <button>ANW</button>
                <button>QNW</button>
                <button>BNW</button>
                <button>SNW</button>
                <button>FNW</button>
                <button>XNW</button>
                <button>NNW</button>
                <button>CNW</button>
                <button>ACN</button>
                <button>YNW</button>
                <button>PB1</button>

Pane TN

              <button>EAST</button>
              <button>WEST</button>
              <button>TS</button>

                <button>DSE</button>
                <button>HSE</button>
                <button>KSE</button>
                <button>ESE</button>
                <button>WSE</button>
                <button>ASE</button>
                <button>QSE</button>
                <button>BSE</button>
                <button>SSE</button>
                <button>FSE</button>
                <button>XSE</button>
                <button>NSE</button>
                <button>CSE</button>
                <button>ACS</button>
                <button>YSE</button>
                <button>PB4</button>

                <button>DSE JPGs HERE</button>
                <button>HSE</button>
                <button>KSE</button>
                <button>ESE</button>
                <button>WSE</button>
                <button>ASE</button>
                <button>QSE</button>
                <button>BSE</button>
                <button>SSE</button>
                <button>FSE</button>
                <button>XSE</button>
                <button>NSE</button>
                <button>CSE</button>
                <button>ACS</button>
                <button>YSE</button>
                <button>PB4</button>

                <button>DSW</button>
                <button>HSW</button>
                <button>KSW</button>
                <button>ESW</button>
                <button>WSW</button>
                <button>ASW</button>
                <button>QSW</button>
                <button>BSW</button>
                <button>SSW</button>
                <button>FSW</button>
                <button>XSW</button>
                <button>NSW</button>
                <button>CSW</button>
                <button>ASN</button>
                <button>YSW</button>
                <button>PB2</button>

                <button>DSW</button>
                <button>HSW</button>
                <button>KSW</button>
                <button>ESW</button>
                <button>WSW</button>
                <button>ASW</button>
                <button>QSW</button>
                <button>BSW</button>
                <button>SSW</button>
                <button>FSW</button>
                <button>XSW</button>
                <button>NSW</button>
                <button>CSW</button>
                <button>ASN</button>
                <button>YSW</button>
                <button>PB2</button>

Pane TS

            <button>EAST</button>
            <button>WEST</button>
            <button>TSX</button>

                <button onclick="onClick()">DSEX</button>
                <button onclick="onClick()">HSEX</button>
                <button onclick="onClick()">KSEX</button>
                <button>ESEX</button>
                <button>WSEX</button>
                <button>ASEX</button>
                <button>QSEX</button>
                <button>BSEX</button>
                <button>SSEX</button>
                <button>FSEX</button>
                <button>XSEX</button>
                <button>NSEX</button>
                <button>CSEX</button>
                <button>ACSX</button>
                <button>YSEX</button>
                <button>PB8</button>

                <button>

DSEX

                </button>
                <button>

">HSEX

                </button>
                <button>

">

                </button>
                <button>ESEX</button>
                <button>WSEX</button>
                <button>ASEX</button>
                <button>QSEX</button>
                <button>BSEX</button>
                <button>SSEX</button>
                <button>FSEX</button>
                <button>XSEX</button>
                <button>NSEX</button>
                <button>CSEX</button>
                <button>ACSX</button>
                <button>YSEX</button>
                <button>PB8</button>

                <button>DSWX</button>
                <button>HSWX</button>
                <button>KSWX</button>
                <button>ESWX</button>
                <button>WSWX</button>
                <button>ASWX</button>
                <button>QSWX</button>
                <button>BSWX</button>
                <button>SSWX</button>
                <button>FSWX</button>
                <button>XSWX</button>
                <button>NSWX</button>
                <button>CSWX</button>
                <button>ASNX</button>
                <button>YSWX</button>
                <button>PB6</button>

                <button>DSWX</button>
                <button>HSWX</button>
                <button>KSWX</button>
                <button>ESWX</button>
                <button>WSWX</button>
                <button>ASWX</button>
                <button>QSWX</button>
                <button>BSWX</button>
                <button>SSWX</button>
                <button>FSWX</button>
                <button>XSWX</button>
                <button>NSWX</button>
                <button>CSWX</button>
                <button>ASNX</button>
                <button>YSWX</button>
                <button>PB6</button>

Pane TS

    var elementaries = '../assets/elementaries/';
    var elemLoc = [];
    var dsex = [
      "this.jpg",
      "that.jpg"
    ];
    var hsex = [
      "this.jpg",
      "that.jpg"
    ];

    // ON click of quadrant (DSEX...) do this
    function onClick() {

      let id = event.srcElement.id; // returns the id of the button (tab 8-0)
      let quadrant = document.getElementById(`${id}`).innerHTML.toLowerCase(); // returns the value of the button ie DSEX
      getElemLoc(quadrant); // calls function to make an array of elementaries based on quadrant
      loadElementaries(quadrant); // loads elementaries under proper tab
    }

    // Function makes an array of elementaries based on quadrant
    var getElemLoc = (q) => {
      elemLoc = [];
      let elem = window[q];
      elem.forEach(function (img) {
        let loc = `${elementaries}${q}/${img}`;
        elemLoc.push(loc);
      })
    };

    // Loads elementaries to proper div based on quadrant.
    var loadElementaries = (quad) => {
      for (var i = 0; i < elemLoc.length; i++) {
        document.getElementById(`${quad}`).innerHTML = document.getElementById(`${quad}`).innerHTML + `<a class="thumbnail" href="${elemLoc[i]}"><img src="${elemLoc[i]}" width="350px" height="250px" border="0" /><span><img src="${elemLoc[i]}" width="900" height="700" /><br /></span></a> <br />`;
      }
    };

When going to the tab Extension/East/DSEX my innerhtml code works perfectly, but if I try the hsex tab the inner html in loadElementaries fails.  Does anyone have any idea what's going on.  Maybe the way the DOM is loading between tabs?
document.getElementById(`${quad}`).innerHTML works for dsex tab but not hsex...
I'm at work so I'm limited to using client side JS/HTML/CSS so nodejs isn't an option unfortunately.


text:
Q: How to disable this message in Azure Hi All,
Is there is a way to disable the option of presenting this message in Azure?
Is there's a policy that I need to configure NOT to show this message?
(i'm seeing this message in the file --> view/edit in (when i'm selecting the Image.
I've been trying to find the where can this policy be, but maybe there isn't one and I'm just wasting my time to find one.
But in the other hand it seems like this error is coming from somewhere...(right)?

A: I tried to reproduce the same in my environment I also got the same error like below

Note: This error is default Microsoft security notification you can't disable this message as there is an limit of editing file in azure portal. You can edit the file which is upto 2.1mb.
To confirm this, I try to edit file under 2.5mb error message doesn't appear I can able to edit the text file like below.

This limit is only for editing the text file not for uploading the file.
Reference:
Scalability and performance targets for Blob storage - Azure Storage | Microsoft Learn


text:
Q: Callback-driven Spring Cloud Dataflow source application I want to create a Spring Cloud Dataflow source application based on a lib that connects to a messaging service (IRC, actually) and calls my callback when a message arrives. The only goal of the source app is to create an SCDF message from the received IRC message and send it to the stream.
I have come up with the following solution:
The IrcListener class annotated with @Component does some configuration and starts listening for IRC messages when the start() method is called. When a message is received its onGenericMessage callback simply sends the message to the stream via the injected source property:
@Component
public class IrcListener extends ListenerAdapter {

    @Override
    public void onGenericMessage(GenericMessageEvent event) {
            Message msg = new Message();
            msg.content = event.getMessage();

            source.output().send(MessageBuilder.withPayload(msg).build());
    }

    private Source source;
    private String _name;
    private String _server;
    private List<String> _channels;

    public void start() throws Exception {
            Configuration configuration = new Configuration.Builder()
                            .setName(_name)
                            .addServer(_server)
                            .addAutoJoinChannels(_channels)
                            .addListener(this)
                            .buildConfiguration();

            PircBotX bot = new PircBotX(configuration);
            bot.startBot();
    }

    @Autowired
    public IrcListener(Source source) {
            this.source = source;

            _name = "ircsource";
            _server = "irc.rizon.net";
            _channels = Arrays.asList("#test".split(","));
    }
}

The main class runs Spring Application and calls the aforementioned start() method on the IrcListener component.
@EnableBinding(Source.class)
@SpringBootApplication
public class IrcStreamApplication {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(IrcStreamApplication.class, args);
        context.getBean(IrcListener.class).start();
    }
}

This works ok and the messages are received and published to the stream successfully, but I'd like to know whether this is the right approach to take in the Spring (Cloud Dataflow) universe and or maybe I am missing something important?

A: It looks ok; but, generally, message-driven sources extend MessageProducerSupport and call sendMessage(Message<?>).
(and override doStart() in this case).
It would give you access to message history tracking and error handling (if the send fails).


text:
Q: models.E006 in abstract parent model - Django 3.1 I have an abstract model and a few other classes that inherit from it.
# models.py
class Parameter(models.Model):

    data = integer = models.IntegerField(blank=True, null=True)

    class Meta:
        abstract = True

class Temperature(Parameter):

    received_timestamp = models.DateTimeField(default=datetime.now, blank=True)

class Ph(Parameter):

    received_timestamp = models.DateTimeField(default=datetime.now, blank=True)

although my Parameter class is abstract, I get models.E006 error in python manage.py makemigrations script.

graphs.Temperature.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.temperature'.
graphs.Ph.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.ph'.

based on Abstract base classes and this question, if I inherit from an abstract base class, there should be no conflict in the name of the fields of various child classes with their parent (because it's abstract).
any ideas?

A: The error is unrelated to the abstract base class.
The problem is the = integer when you define the IntegerField, which means the field is created twice.
Change:
data = integer = models.IntegerField(blank=True, null=True)`

to
data = models.IntegerField(blank=True, null=True)


text:
Q: How to add a div to KnpMenu (Symfony2.1) I would like to make a drowdown box whenever someone hovers over a menu button, im generating the menu with the KnpMenuBundle.
What i would like to get is a structure like this:
<lu>

...

        ...

...

...

<lu>

If possible i would like to render a controller from inside the div.
Can this be done?
If i missed something in the documentation please post a link because i have been searching for hours...

A: It can be done, and I once did exactly this, but whether this sort of thing should be done using KnpMenuBundle I'm not too sure! Anyway, I achieved this by defining my MenuBuilder class as a service and injecting the @templating service. This doesn't call a controller action as you mentioned, but allows you to render any template you wish...
/**
 * @param Request $request
 * @return \Knp\Menu\ItemInterface
 */
protected function createUserMenuLoggedOut(Request $request)
{
    $menu = $this->factory->createItem('root');

    $signInItem = $menu->addChild('Sign in', array('route' => 'fos_user_security_login'));
    $signInItem
        ->setLinkAttributes(array(
            'id' => 'sign-in-link',
            'class' => 'dropdown-toggle',
            'data-toggle' => 'dropdown',
            'data-target' => '#signin'
        ))
        ->setAttributes(array(
            'id' => 'signin',
            'class' => 'dropdown'
        ))
    ;

    // THIS IS THE LINE YOU'RE INTERESTED IN
    $signInItem->addChild($this->templating->render('ApplicationSonataUserBundle:Security:login_options.html.twig'));

    // more menu items...

    return $menu;
}

If I recall correctly, I think this ended up wrapping the template in an additional
...
 but this didn't cause much of a problem after a bit of styling.


text:
Q: Loading a NY map my d3 map of ny will not load. is there any way someone can help?
here is my code:
<!DOCTYPE html>
<meta charset="utf-8">

here is the the geojson file: http://data.beta.nyc//dataset/3bf5fb73-edb5-4b05-bb29-7c95f4a727fc/resource/6df127b1-6d04-4bb7-b983-07402a2c3f90/download/f4129d9aa6dd4281bc98d0f701629b76nyczipcodetabulationareas.geojson

A: You can try geojson2svg module for SVG map creation with geojson data. As this is just plain JavaScript you'll have more control. Here is your example
Your html page (index.html):

    <link rel="stylesheet" href="./map.css"/>

Example of New York postal code map created with geojson2svg

      <svg id="map" xmlns="http://www.w3.org/2000/svg"
        width="600" height="600" x="0" y="0" >
      </svg>

Javascript code (main.js):
var dataURI = "http://data.beta.nyc//dataset/3bf5fb73-edb5-4b05-bb29-7c95f4a727fc/resource/6df127b1-6d04-4bb7-b983-07402a2c3f90/download/f4129d9aa6dd4281bc98d0f701629b76nyczipcodetabulationareas.geojson";

$.get(dataURI,drawGeoJSON);
$('#map').on('mouseover','path',function(ev) {
  console.log(ev.target.feature.properties.postalCode);
  var tooltip = document.querySelector('.tooltip');
  tooltip.style.top = ev.pageY - 30;
  tooltip.style.left = ev.pageX + 5;
  tooltip.style.display = 'block';
  tooltip.innerHTML = ev.target.feature.properties.PO_NAME;
});
$('#map').on('mouseout','path',function(ev) {
  var tooltip = document.querySelector('.tooltip');
  tooltip.style.display = 'none';

});

function drawGeoJSON(geojson) {
  // covert wgs84 data to Web Mercator projection

  var geojsonMerc = reproject(geojson);
  // reproject: https://github.com/geosquare/reproject-spherical-mercator

  var extent = bbox(geojsonMerc);
  // bbox: https://github.com/geosquare/geojson-bbox

  var mapExtent = {
    left: extent[0],
    bottom: extent[1],
    right: extent[2],
    top: extent[3]
  };
  var svgMap = document.getElementById('map');

  // geojson2svg: https://github.com/gagan-bansal/geojson2svg
  var convertor = geojson2svg(
    {
      viewportSize: {width:600,height:600},
      mapExtent: mapExtent,
      attributes: {
        'vector-effect':'non-scaling-stroke'
      },
      explode: false
    }
  );
  geojsonMerc.features.forEach(function(f) {
    var svgStr = convertor.convert(f,{attributes: {id: 'pc-'+f.properties.OBJECTID}});
    var svg = parseSVG(svgStr);
    svgMap.appendChild(parseSVG(svgStr));
    var svgEle = svgMap.querySelector('#' + 'pc-'+f.properties.OBJECTID);
    svgEle.feature = f;
  });
}
//parseSVG from http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element
function parseSVG(s) {
  var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
  div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
  var frag= document.createDocumentFragment();
  while (div.firstChild.firstChild)
      frag.appendChild(div.firstChild.firstChild);
  return frag;
}

and CSS (map.css):
body {
  font: 12px sans-serif;
}

path {
  stroke-width: 1px;
  stroke: #531b93;
  fill: #919191;
  cursor: pointer;
}

path:hover, path.highlighted {
  fill: #0096ff;
}

div.tooltip {
  position: absolute;
  background-color: white;
  border: 1px solid black;
  color: black;
  font-weight: bold;
  padding: 4px 8px;
  display: none;
}

For advance usage please check this blog


text:
Q: How to disable form2 combo boxes based on form1 combo box value? I am trying to disable some of the combo boxes in form 2 based in form 1 selected value.
Lets say
In Form1 if comboxbox value is 0
Disable certain combo boxes in form 2
What I have done in form1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public ComboBox combo
    {
        get { return dropdown; }
    }

and in form 2 so far
private void Form2_Load(object sender, EventArgs e)
{
  Form1 f = new Form1();
  if (f.combo.SelectedIndex == 0)
  {
    comboBox1.Enabled = false;
  }

This is not working and I cant sort it out (new to c#)

A: If you create Form1 at Form with this syntax:
  Form1 f = new Form1();

You will get new instance of Form1 (or "copy"), not the one thats already open. You need to pass the reference of Form1 to Form2.
Put this code into Form2:
private Form1 myParentForm;
public Form2(Form1 parentForm)
{
  myParentForm = parentForm;
}

Then you can use Form1 through a variable myParentForm. Like this:
private void Form2_Load(object sender, EventArgs e)
{
  if (myParentForm.combo.SelectedIndex == 0)
  {
    comboBox1.Enabled = false;
  }
}

In Form1 you have a code something like this:
Form2 mySecondForm = new Form2();

change that to:
Form2 mySecondForm = new Form2(this);

A: Here is a prior answer with multiple samples calling one form as parameter to another including one of those as a full step-by-step sample.
Now, with respect to enable/disable, you can use either property or method approach to tell the "Other" form to enable / disable the status... The samples are just setting / getting values.  If you do a set such as boolean to the one form in question, your setter portion might be something like
   private bool enableFromOtherForm;
   public bool EnableFromOtherForm
   {
      get { return enableFromOtherForm; }
     set { this.controlToChange.IsEnabled = value; }
   }


text:
Q: How to move comments form above comments list in wordpress Please help me modify code to move Comments form above comments list in a WordPress blow. Below is the code of comments.php page
 <?php
/**
 * The template for displaying Comments.
 */
?>

<?php
    /*
     * If the current post is protected by a password and
     * the visitor has not yet entered the password we will
     * return early without loading the comments.
     */
    if (post_password_required()) return;
?>
<?php if ( comments_open() ) : ?>

            <?php if (have_comments()):?>

                    <?php printf( _n('1 comment', '%1$s comments', get_comments_number(), 'gloria'),  number_format_i18n(get_comments_number()));?>

            <?php endif;?>
            <?php // You can start editing here -- including this comment! ?>
            <?php if ( have_comments() ) : ?>

                <?php
                    /* Loop through and list the comments. Tell wp_list_comments()
                     * to use wpgrade_comment() to format the comments.
                     * If you want to overload this in a child theme then you can
                     * define wpgrade_comment() and that will be used instead.
                     * See wpgrade_comment() in inc/template-tags.php for more.
                     */
                    wp_list_comments( array( 'callback' => 'gloria_comments','short_ping'  => true ) );
                ?>

            <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>

<?php previous_comments_link( esc_html__( '← Older Comments', 'gloria' ) ); ?>

<?php next_comments_link( esc_html__( 'Newer Comments →', 'gloria' ) ); ?>

            <?php endif; // check for comment navigation ?>
        <?php endif; // have_comments() ?>
        <?php
            // If comments are closed and there are comments, let's leave a little note, shall we?
            if ( ! comments_open() && post_type_supports( get_post_type(), 'comments' ) && !is_page() ) :
        ?>

<?php esc_html_e( 'Comments are closed.', 'gloria' ); ?>

            <?php endif; ?>

    <?php
    $commenter = wp_get_current_commenter();
    $req = get_option( 'require_name_email' );
    $aria_req = ( $req ? " aria-required='true'" : '' );

    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        $comments_args = array(
            // change the title of send button
            'title_reply'=> esc_html__('Leave a reply', 'gloria'),
            // remove "Text or HTML to be displayed after the set of comment fields"
            'comment_notes_before' => '',
            'comment_notes_after' => '',
            'logged_in_as' => '
' . sprintf( esc_html__( 'Logged in as', 'gloria') .' %2$s. '.esc_html__('Log out?','gloria').'', admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( ) ) ) ) . '
',
            'fields' => apply_filters( 'comment_form_default_fields', array(
                'author' => '
<input id="author" name="author" type="text" placeholder="'.esc_html__('Name*', 'gloria').'..." size="30" ' .  $aria_req . ' />
',
                'email' => '
<input id="email" name="email" size="30" type="text" placeholder="'.esc_html__('Email*', 'gloria').'..." '. $aria_req .' />
' ) ),
            'id_submit' => 'comment-submit',
            'label_submit' => esc_html__('Send', 'gloria'),
            // redefine your own textarea (the comment body)
            'comment_field' => '
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" placeholder="' . esc_html__( 'Message', 'gloria' ) . '"></textarea>
');
    } else {
        $comments_args = array(
        // change the title of send button
        'title_reply'=> esc_html__('Leave a reply', 'gloria'),
        // remove "Text or HTML to be displayed after the set of comment fields"
        'comment_notes_before' => '',
        'comment_notes_after' => '',
        'fields' => apply_filters( 'comment_form_default_fields', array(
                'author' => '
<input id="author" name="author" type="text" placeholder="'.esc_html__('Name*', 'gloria').'..." size="30" ' .  $aria_req . ' />

<input id="email" name="email" size="30" type="text" placeholder="'.esc_html__('Email*', 'gloria').'..." '. $aria_req .' />

<input id="url" name="url" size="30" placeholder="'.esc_html__('Website', 'gloria').'..." type="text">
') ),
        'id_submit' => 'comment-submit',
        'label_submit' => esc_html__('Send', 'gloria'),
        // redefine your own textarea (the comment body)
        'comment_field' => '
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" placeholder="' . esc_html__( 'Message', 'gloria' ) . '"></textarea>
');
    }

    //if we have no comments than we don't a second title, one is enough
    if ( !have_comments() ){
        $comments_args['title_reply'] = esc_html__('Leave a reply', 'gloria');
    }

    comment_form($comments_args); ?>
<?php endif; ?>

A: The if (have_comments()) { ... } checks whether there is any comment on your post, and starts a loop to display them.
The comment_form() function is responsible to render the comment form. So, if you want to swap their positions, you should swap these two.
But, you should make sure you move both comment_form() and its arguments ($comments_args) above the comment loop, since this variable should be defined first, or the default fields will be used.
The easy way to do this is to select the entire
...
, cut it and paste of below the comment_form(). Pay attention to PHP open and close tags <?php & ?>.


text:
Q: pyTTSX3 ничего не говорит import pyttsx3
import speech_recognition as sr
import sys

def talk(words):
    engine=pyttsx3.init("dummy")
    engine.say(words)
    engine.runAndWait()

talk("Hi")

Ничего не произносится, хотя программа успешно завершает выполнение

A: Может быть?

import pyttsx3
import speech_recognition as sr
import sys

def talk(words):
    engine=pyttsx3.init("dummy")
    engine.say(words)
    engine.runAndWait()

talk("Hi")


text:
Q: parseInt always returns NaN? long story short, i was trying to validate a phone field. ive added
the isNaN and parseInt for checking the " " in the field but that said
This below never validates to true..what am i missing?
if(isNaN(parseInt(phone))){
        error.text("Sorry but this phone field requires numbers only");
        return false;
    } else {
    return true;

    }

it always fails...it never reads true even when i enter a number in the field and submit.
i always get the error mssg.
EDIT: I am testing input values from a form, phone is the name of the field.

A: parseInt only returns NaN if the first character cannot be converted to a number.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

A: Various ways to coerse JS strings to numbers, and their consequences:

(source: phrogz.net)
I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
Edit: Based on your comment, if using phone.val() fixed it then

*

*You were using jQuery (which you never mentioned, and should have), and

*You actually had/have a jQuery object, wrapping one or more DOM elements (probably just one).

Whenever you do var foo = $('…'); then the foo variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0]; or var fooEl = foo.get(0);…but even then you still have a DOM element and not a particular property of that.
For form inputs, you need to get the .value from the DOM element, which is what the jQuery .val() method does.

A: parseInt is a bit odd at times:
> parseInt("123-456-789")
123

Fortunately you can probably solve your case with:
> Number("123-456-789")
NaN

A: I've seen Number() suggested, but that will still allow things like -21 or 123.456. The best way to check for the absence of non-digits in a string is like this:

function hasNonDigit(str){
  return /\D/g.test(str.toString());
}

console.log(hasNonDigit("123-456-7890"));
console.log(hasNonDigit("1234567890"));


text:
Q: Did not get any Response or Error when fetching followers Linq To Twitter I am trying to fetch the followers using Linq To Twitter latest version 3.0.2..But It is not returning back any response either not throw any error. Please suggest
 var followers = GetTwitterFollowers
          (twitterUserId, auth, maxFollowers);

        var foll = followers.ContinueWith(f =>
                                          {
                                              return f.Result;
                                          }).Result;

"GetTwitterFollowers" method defined as:
private static async Task<List<TwitterData>> GetTwitterFollowers(
             ulong twitterUserId, SingleUserAuthorizer auth, int? maxFollowers)
            {

                var follower = maxFollowers ?? 15000;

                try
                {
                    var twitterCtx = new TwitterContext(auth);
                    var followers = await twitterCtx.Friendship
                                              .Where(f => f.Type == FriendshipType.FollowersList
                                                  && f.UserID == twitterUserId.ToString())
                                              .Select(f => new TwitterData()
                                              {

                                                  Followers = f.Users.Where(t => !t.Protected).Take(follower).Select(s => s).ToList()
                                              }).SingleOrDefaultAsync();
                    return GetFollowersList(followers.Followers);
                }
                catch (Exception ex)
                {
                    return null;
                }

            }

A: Get followers from Twitter first:
        var friendship =
            await
            (from friend in twitterCtx.Friendship
             where friend.Type == FriendshipType.FollowersList &&
                   friend.UserID == twitterUserId.ToString()
             select friend)
            .SingleOrDefaultAsync();

Then you can do your custom projection with an LINQ to Objects query on the results.
Update:
You should await the call to GetTwitterFollowers, like this:
var followers = await GetTwitterFollowersAsync(twitterUserId, auth, maxFollowers);

Then, you don't need the ContinueWith. It isn't working because GetTwitterFollowers returns immediately after hitting the await. The ContinueWith lambda might execute, but there isn't anything keeping the routine from returning and you don't get the result of the lambda execution. It might help to spend a little time looking at async/await to make this easier. Here's something that might help:
http://msdn.microsoft.com/en-us/library/hh191443.aspx


text:
Q: Trimming Strings within C# .Net application new enough to C#.
Just can't get my head around trimming with a string. I want to be able to trim the whitespace after the string as it is messing up my database with the amount of whitespace I get. Here's one of my entities that I'd like to do it in.
[RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "Use letters and numbers only please")]
[Display(Name = "Serial Number ")]
public string SerialNo
{
    get
    {
        try
        {
            string serialNumber = SerialNo.Trim();
            return serialNumber;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return SerialNo;
        }
    }
    set
    {
        this.SerialNo = SerialNo;
    }
}

I don't know if I'm going about this all wrong so some help would be appreciated!
EDIT: My error is "An unhandled exception of type 'System.StackOverflowException' occurred in PhotocopierInformationManagementServices.dll"

A: The following will end up in stackoverflow excption as it will keep executing infinitely, as the set block is getting called again and due to this.SerialNo= inside the set block:
set
{
    this.SerialNo = SerialNo; // calling set of SerialNo recursively
}

you can change your code to be :
private string _serialNo;
[RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "Use letters and numbers only please")]
[Display(Name = "Serial Number ")]
public string SerialNo
{
    get
    {
        try
        {
            _serialNo= _serialNo.Trim();
            return _serialNo;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return _serialNo;
        }
    }
    set
    {
        _serialNo= value;
    }
}

But i would recommend to trim it in setter so that your property would look now like:
private string _serialNo;
[RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "Use letters and numbers only please")]
[Display(Name = "Serial Number ")]
public string SerialNo
{
    get
    {
        return _serialNo;
    }
    set
    {
        _serialNo= value?.Trim();
    }
}

A: You use C# Property wrong. Use my example:
private string serialNumber;

public string SerialNo
{
    get { return serialNumber; }
    set { serialNumber = value?.Trim(); }
}

A: The problem is not with trimming, but with the fact that on set you are recursively calling get. The correct syntax is
private string serialNo;

[RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "Use letters and numbers only please")]
[Display(Name = "Serial Number ")]
public string SerialNo
{
    get
    {
        return serialNo;
    }
    set
    {
        this.serialNo = value.Trim();
    }
}

A: Did you try string serialNumber = SerialNo.TrimEnd();?
If that does not work try SerialNo.Replace(" ", "");


text:
Q: How do I get the last refresh date/time from a query? I have a workbook with a multiple queries from an SQL database and wanted to get the last refreshed date/time as either a variable in VBA or written to a cell in the workbook.
I tried this code:
Cells(1,1) = ActiveWorkbook.Connections("Query - Item_Groups").ODBCConnection.RefreshDate

But I get I get an Application Defined or Object Defined error.
Any thoughts?


text:
Q: How to exploit printf vulnerability for different input methods? I am trying to exploit printf vulnerability with the following C code:
#include <stdio.h>
#include <stdlib.h>

/*
gcc -fno-stack-protector -z execstack -o test test.c
*/
void attack(){
    printf("Dropping to shell...\n");
}

int main(int argc, char **argv){
    char buf[100];

    printf("Enter user name:");

    gets(buf);  // what if using: scanf("%s",buf); ?

    printf("buffer (%d): %s\n",strlen(buf), buf);

    return 0;
}

Then I try to change the printf@plt to jump to the attack function, by re-write the value in 0x804a00c
08048370 <printf@plt>:
 8048370:   ff 25 0c a0 04 08       jmp    *0x804a00c
 8048376:   68 00 00 00 00          push   $0x0
 804837b:   e9 e0 ff ff ff          jmp    8048360 <_init+0x28>

I used the following command to test in GDB, I try to change the value in 0x804a00c to 0x00000041, to verify that I can change it. Then i can change it to the attack() address.
gdb-peda$ r
Starting program:
Enter user name:$(printf "\x0c\xa0\x04\x08").%60x%5\$n

However it doesn't work for me, the address doesn't change, I verified the value in stack (break at printf() address) and got:
[------------------------------------stack-------------------------------------]
0000| 0xbffff070 --> 0x80485c6 ("buffer (%d): %s\n")
0004| 0xbffff074 --> 0x26 ('&')
0008| 0xbffff078 --> 0xbffff08c ("$(printf \"\\x0c\\xa0\\x04\\x08\").%60x%5\\$n")
0012| 0xbffff07c --> 0x0
0016| 0xbffff080 --> 0xbffff134 --> 0x4a91b2bc
0020| 0xbffff084 --> 0xbffff0a8 (".%60x%5\\$n")
0024| 0xbffff088 --> 0xbffff0a0 ("04\\x08\").%60x%5\\$n")
0028| 0xbffff08c ("$(printf \"\\x0c\\xa0\\x04\\x08\").%60x%5\\$n")

I think I did not pass the correct value, as it changed to another format. I guess this is because of gets(), because I can pass it correctly when I use argv to pass the: $(printf "\x0c\xa0\x04\x08").%60x%5\$n.
So does anyone know how to solve the problem? and further, what if the input is using scanf(%s,buf), as I am getting the following on stack, which is also incorrect.
[------------------------------------stack-------------------------------------]
0000| 0xbffff070 --> 0x80485f9 ("buffer (%d): %s\n")
0004| 0xbffff074 --> 0x8
0008| 0xbffff078 --> 0xbffff08c ("$(printf")
0012| 0xbffff07c --> 0x0
0016| 0xbffff080 --> 0xbffff134 --> 0x4f936a87
0020| 0xbffff084 --> 0xbffff0a8 --> 0xb7e21c34 --> 0x2aad
0024| 0xbffff088 --> 0xbffff0a0 --> 0xffffffff
0028| 0xbffff08c ("$(printf")

A: You have a couple misconceptions here.
First, $(cmd) is a shell command substitution. It's useful when passing arguments: for example, ./foo $(python -c 'print "A"*4') is equivalent to ./foo AAAA. If you program takes input from stdin you have to use a pipe: for example, python -c 'print "A"*4' | ./foo is equivalent to running ./foo and typing AAAA on the keyboard.
Second, there is actually no format string vulnerability in your code. There is, however, a stack buffer overflow (on gets or scanf). A format string vulnerability happens when you call functions such as printf of scanf with a user-controlled format string. If you want one, you could change the last printf to:
printf("buffer (%d): ", strlen(buf));
printf(buf); // <-- this is vulnerable
printf("\n");

As for the difference between gets(buf) and scanf("%s", buf): both will stop at newlines/EOFs, but scanf will also stop at whitespace (which can be seen in your output where only $(printf is read).


text:
Q: Matlab: visualize struct as a tree I have implemented a binary tree in Matlab using "struct" to create nodes. Every node has some attributes and a left and a right child.
Is there a simple way to visualize this as a tree without having to draw lines etc.? (like view command for classregtree)

A: Will treeplot do the trick?
http://www.mathworks.se/help/matlab/ref/treeplot.html
-Rob


text:
Q: Python urlib not work in ipv6 machine i make this py func :
def gethtml( aa):
#print (aa)
f = urllib.request.urlopen(aa)
return str(f.read())

in python to get html source work good ,but in pc use ipv6 it not work ,
how can i make it work in both pc with ip4 & ip6
i am new with python :P , i was code with autoit it was easy just one func work in all pc
and if error it return ""
but in python i must make exeption for error
however my #2 questions is there any easy way to get html source that will work fine with no error and in all pc .
Thank you :) .


text:
Q: Returning multiple Excel Files in one call with Apache POI I am attempting to download multiple excel files with one call. I have a stored procedure that returns data broken down by company, and for each company I need a separate excel file. Some of the values of the excel files are interdependent (so what is on the first excel file will go on to the second.
Except for a few functions which I have verified are working correctly, I've included the entirety of the code below. As it stands now the code runs exactly as it should, if I did not check the outputs I would think it was perfect, however where I expect to see two files downloaded I instead only get the first one. The second call to write to the ServletOutputStream does fire, but no file is downloaded.
Can anyone see what is wrong here? It isn't the file size, there should be a max of five records in each file, and I've downloaded single excel files before without issue.
package export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.getFund;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 *
 * @author mmarino
 */
public class NavExport extends HttpServlet {
    String dateStr = "";
    String ERDate = "";
    Double absoluteTotal = 0.0;
    Double iTotal = 0.0;
    getFund g = new getFund();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String str = "";

        Workbook wb = new HSSFWorkbook();
        Workbook pWB = new HSSFWorkbook();
        //Workbook wb = new XSSFWorkbook();
        CreationHelper createHelper = wb.getCreationHelper();
        Sheet oSheet = wb.createSheet("Recon");
        Sheet pSheet = pWB.createSheet("Recon");
        String prevCompany = "";
        dateStr = new Date().toString();
        dateStr = new SimpleDateFormat("MM/dd/yyy").format(new Date());
        ERDate = "ER" + dateStr.substring(6, 10) + dateStr.substring(0,2) + dateStr.substring(3,5);
        try{

            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement prst = null;
            String s = request.getParameter("ids");

            String roll = request.getParameter("roll");
            String[] ids = s.split("\\|");

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            String connUrl = "My Connection URL";
            conn = DriverManager.getConnection(connUrl);
            String sql = "My SQL Query";
            prst = conn.prepareStatement(sql);
            rs = prst.executeQuery();

            int pInt = 1;
            int oInt = 1;

            g.main();
            while(rs.next()){
                if(rs.getString("Company").equals("10")){
                    addRow(pSheet, rs, createHelper, pInt);
                    pInt++;
                }else{
                  if(!prevCompany.equals(rs.getString("Company")) && !prevCompany.equals("") && !prevCompany.equals("10")){
                      writeWorkBook(wb, prevCompany, response);
                      oInt = 1;
                      wb = new HSSFWorkbook();
                      oSheet = wb.createSheet("Recon");
                      iTotal = 0.0;
                  }
                prevCompany = rs.getString("Company");
                addRow(oSheet, rs, createHelper, oInt);
                iTotal += rs.getDouble("Approved");
                oInt++;
                }
                absoluteTotal += rs.getDouble("Approved");
            }// end rs.next();
            if(!prevCompany.equals("10")){
                addTopRow(oSheet, createHelper, prevCompany, iTotal);
                writeWorkBook(wb, prevCompany, response);
            }
            addTopRow(pSheet, createHelper, "10", absoluteTotal);
            writeWorkBook(pWB, "10", response);

        }catch(Exception e){
            str="Got exception: " + e.getMessage();
        }

    }

     private void addTopRow(Sheet sheet, CreationHelper createHelper, String Company, Double amount){
         try{
                Row row = sheet.createRow((short)0);
                row.createCell(0).setCellValue(createHelper.createRichTextString(dateStr));
                row.createCell(1).setCellValue(createHelper.createRichTextString(""));
                row.createCell(2).setCellValue(createHelper.createRichTextString(ERDate));
                row.createCell(3).setCellValue(createHelper.createRichTextString("G/L Account"));
                row.createCell(4).setCellValue(passSwitch(Company));
                row.createCell(5).setCellValue(createHelper.createRichTextString(""));
                row.createCell(6).setCellValue(createHelper.createRichTextString("1000-0000"));
                row.createCell(7).setCellValue(createHelper.createRichTextString(""));
                row.createCell(8).setCellValue(createHelper.createRichTextString(""));
                row.createCell(9).setCellValue(createHelper.createRichTextString(""));
                row.createCell(10).setCellValue(createHelper.createRichTextString(""));
                row.createCell(11).setCellValue(createHelper.createRichTextString("Null"));
                row.createCell(12).setCellValue(createHelper.createRichTextString(""));
                row.createCell(13).setCellValue(createHelper.createRichTextString(""));
                row.createCell(14).setCellValue(createHelper.createRichTextString(""));
                row.createCell(15).setCellValue(createHelper.createRichTextString(""));
                row.createCell(16).setCellValue(createHelper.createRichTextString(""));
                row.createCell(17).setCellValue(amount);
                row.createCell(18).setCellValue(createHelper.createRichTextString(""));
                row.createCell(19).setCellValue(createHelper.createRichTextString(""));
                row.createCell(20).setCellValue(createHelper.createRichTextString(""));
                row.createCell(21).setCellValue(createHelper.createRichTextString("G/L Account"));
         }catch(Exception e){
             String error = e.toString();
         }
     }

    private void addRow(Sheet sheet, ResultSet rs, CreationHelper createHelper, int i){
        try{
            Row row = sheet.createRow((short)i);
            row.createCell(0).setCellValue(createHelper.createRichTextString(dateStr));
            row.createCell(1).setCellValue(createHelper.createRichTextString(""));
            row.createCell(2).setCellValue(createHelper.createRichTextString(ERDate));
            row.createCell(3).setCellValue(createHelper.createRichTextString("G"));
            row.createCell(4).setCellValue(rs.getString("Code"));
            row.createCell(5).setCellValue(createHelper.createRichTextString(""));
            row.createCell(6).setCellValue(createHelper.createRichTextString(g.getFundVar(rs.getString("Company") + ":" + rs.getString("Dept"))));
            row.createCell(7).setCellValue(createHelper.createRichTextString(""));
            row.createCell(8).setCellValue(createHelper.createRichTextString(""));
            row.createCell(9).setCellValue(createHelper.createRichTextString(""));
            row.createCell(10).setCellValue(createHelper.createRichTextString(""));

            String emNum = rs.getString("EM");
            while(emNum.length() != 9){
                emNum = "0" + emNum;
            }
            emNum = "E" + emNum;
            row.createCell(11).setCellValue(createHelper.createRichTextString(emNum));
            row.createCell(12).setCellValue(createHelper.createRichTextString(""));
            row.createCell(13).setCellValue(createHelper.createRichTextString(""));
            row.createCell(14).setCellValue(createHelper.createRichTextString(""));
            row.createCell(15).setCellValue(createHelper.createRichTextString(""));
            row.createCell(16).setCellValue(createHelper.createRichTextString(""));
            row.createCell(17).setCellValue(rs.getDouble("Approved"));
            row.createCell(18).setCellValue(createHelper.createRichTextString(""));
            row.createCell(19).setCellValue(createHelper.createRichTextString(""));
            row.createCell(20).setCellValue(createHelper.createRichTextString(""));
            row.createCell(21).setCellValue(createHelper.createRichTextString("G/L Account"));

        }catch(Exception e){
            String error = e.toString();
        }
    }
    private void writeWorkBook(Workbook wb, String Company, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment; filename=" + Company +".xls");
    try {
        ServletOutputStream out = response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: Either you have to zip the Excel files and send as response OR you have it as a single excel file and use multiple sheets instead files


text:
Q: inserting into ddbb without using prepared statement To begin with this is my first time using JDBC.
I have a method called insertQuery and another one called updateQuery, both receive a String in order to update or insert a new movie in a db called Movies. So based on some values that the user will enter via a basic UI, my code will execute one query or the other one. The problem is that i'm getting a syntax error on the update and error 23000 on the insert and i don't know why
try {
  ResultSet rs = conn.selectQuery("SELECT title FROM movie WHERE title LIKE '" + title + "';");
  if (rs != null) {
    if (rs.next()) {
      System.out.println("Updating db...");
      conn.updateQuery("UPDATE movie SET title ='" + title
                       + "', id_director = " + idDirector
                       + ", year = " + year
                       + ", duration = " + duration
                       + ", country = '" + country
                       + "', movie_facebook_likes = " + facebookLikes
                       + ", imdb_score = "+ imdbScore
                       + ", gross = " + gross
                       + ", budget = " + budget
                       + " WHERE title LIKE '" + title + "';");
    } else {
      System.out.println("Inserting into db...");
      conn.insertQuery("INSERT INTO movie (title, id_director, year, duration,
                       country, movie_facebook_likes, imdb_score, gross, budget) " +
                       "VALUES ('" + title + "', " + idDirector + "," + year + ", "
                       + duration + ", " + country + ", " + facebookLikes + ", "
                       + ", " + imdbScore + ", " + gross + ", " + budget + ");");
    }
  }
} catch (SQLException e1) {
  JOptionPane.showMessageDialog(mainView, "MySQL error", "ERROR", .ERROR_MESSAGE);
}

A: This is how to i used to insert in db with no prepared statement:
public int adduser(String id, String nm, String pwd,String cy) {
    boolean result = false;
    int i = 0;
    try {
        Connection con=Util.getConnection();
        Statement stmt =con.createStatement();

        i = stmt.executeUpdate(
            "INSERT INTO userdata (userid,name,password,city)\n" +
            "VALUES ("+id+",'"+nm+"','"+pwd+"','"+cy+"')");
    }
    catch(Exception ex) {
        System.out.println(ex);
    }

    return i ;
}


text:
Q: Libgdx dim screen with glClearColor I simply want to draw background, overlay it with 0.5f transparent black color to dim it and render on top of that a pause menu.
I have tried:
    Gdx.gl.glClearColor(0f, 0f, 0f, 0.5f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

and nothing is working. I also couldn't find any solution online. My other option is to overlay a black sprite, but I don't want to do that. Is there anyway to paint it over with GL?

A: Well, I would draw a transparent rectangle
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(new Color(0, 0, 0, 0.5f));
    shapeRenderer.rect(0, 0, screenWidth, screenHeight);
    shapeRenderer.end();
    Gdx.gl.glDisable(GL20.GL_BLEND);

Hope this helps

A: Your only solution is overlay a black sprite. Is the most efficient, and practice.
According to the documentation:
Alpha function, blend function, logical operation, stenciling,
texture mapping, and depth-buffering are ignored by glClear.

glClear takes a single argument that is the bitwise OR of several
values indicating which buffer is to be cleared.

The values are as follows:

GL_COLOR_BUFFER_BIT
    Indicates the buffers currently enabled for color writing.

There can't be more colors "under" after running a glClear


text:
Q: Failed to Create Snapshot in Xcode 4 Does Xcode 4 have a problem with creating a snapshot for a project with git submodules?
fatal: Path 'path/to/project/vendor/facebook-ios-sdk/src' is in submodule 'path/to/project'
Now, this error message is also wrong, if it refers to git submodule. The 'path/to/project' is not a git submodule.
Next:

*

*I tried to delete the snapshot, and try to create it again. This is successful.

*I try to create a new snapshot (while an existing snapshot is there). This is failed.

A: had the same issue. moving the project folder to another location worked for me (there was a  * in a folder name further up the directory chain where the project was located in (like this /***myprojects/iphoneprojects/wontsnapshoproject), as soon as renamed the folder with the * it worked (/myprojects/iphoneprojects/wontsnapshoproject).

A: I had the same problem today with Xcode 4.2 (4D199) after changing the folder structure of my project. I fixed it by taking the following steps:

*

*Make sure all files and folders in your project are added or ignored in the repository

*Choose "Organizer" in the "Window" menu

*Choose "Projects" in the organizer

*Choose your project in the sidebar

*Delete all snapshots of the project

WARNING: Export snapshots before you delete them, if you want to use them later!


text:
Q: Force MS Outlook to front (on top of my app) I have the following function that I use to send mail using MS Outlook 2010
From time to time Outlook doesn't appear in front of my app (a MDI app pmNone, poDefaultPosOnly)
I haven't been able to find any continuity in when Outlook pops up in front and when it just opens in background (icon is flashing on statusbar)
My question is then: are there any method of forcing Outlook to popup in front of all other apps?
function SendMailOutlook(const aFrom, aSubject, aBody, aTo, aCc, aBcc: string; aMailFiles: TStringList; aReceipt: boolean; aPreview: boolean = True): boolean;
var
  Outlook: OleVariant;
  MailItem: OleVariant;
  i: integer;
const
  olMailItem = $00000000;
begin
  try
    try
      Outlook := GetActiveOleObject('Outlook.Application');
    except
      Outlook := CreateOleObject('Outlook.Application');
    end;
    MailItem := Outlook.CreateItem(olMailItem);
    if olAccountValid(aFrom) then
      MailItem.SendUsingAccount := Outlook.Session.Accounts.Item(aFrom);
    MailItem.To := aTo;
    MailItem.Cc := aCc;
    MailItem.Bcc := aBcc;
    MailItem.Subject := aSubject;
    MailItem.Body := aBody;
    for i := 0 to aMailFiles.Count - 1 do
      MailItem.Attachments.Add(aMailFiles.Strings[i]);
    MailItem.ReadReceiptRequested := aReceipt;
    MailItem.OriginatorDeliveryReportRequested := aReceipt;
    if aPreview = True then
      MailItem.Display(True)
    else
      MailItem.Send;
    Result := MailItem.Sent;
  except
    on E:Exception do
      begin
        Logfile.Error('U_Mailing.Outlook.SendMailOutlook: ' + E.Message);
        Result := False;
      end;
  end;
end;

I am no sure how to show the code I got working so I will just edit my question and add it there. Please excuse if that isn't the way to do it.
function SendMailOutlook(const aFrom, aSubject, aBody, aTo, aCc, aBcc: string; aMailFiles: TStringList; aReceipt: boolean; aPreview: boolean = True): boolean;
var
  Outlook: OleVariant;
  MailItem: OleVariant;
  i: integer;
  MailInspector: variant;
const
  olMailItem = $00000000;
begin
  try
    try
      Outlook := GetActiveOleObject('Outlook.Application');
    except
      Outlook := CreateOleObject('Outlook.Application');
    end;
    MailItem := Outlook.CreateItem(olMailItem);
    if olAccountValid(aFrom) then
      MailItem.SendUsingAccount := Outlook.Session.Accounts.Item(aFrom);
    MailItem.To := aTo;
    MailItem.Cc := aCc;
    MailItem.Bcc := aBcc;
    MailItem.Subject := aSubject;
    MailItem.Body := aBody;
    for i := 0 to aMailFiles.Count - 1 do
      MailItem.Attachments.Add(aMailFiles.Strings[i]);
    MailItem.ReadReceiptRequested := aReceipt;
    MailItem.OriginatorDeliveryReportRequested := aReceipt;

    if aPreview = True then
      begin
        MailInspector := MailItem.GetInspector;
        MailInspector.Display(True);
      end
    else
      MailItem.Send;
    Result := MailItem.Sent;
  except
    on E:Exception do
      begin
        Logfile.Error('U_Mailing.Outlook.SendMailOutlook: ' + E.Message);
        Result := False;
      end;
  end;
end;

A: I bielive you can use the SetForegroundWindow function which brings the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.
You can get the Outlook window handle casting the Explorer or Inspector objects to the IOleWindow interface.

A: You will need to use  IOleWindow / AttachThreadInput / SetForegroundWindow to do that.
See how to make the Outlook Compose window top most?.
Also see c# bring outlook window to front


text:
Q: Python dns.resolver.resolve user input function I am new to programming and Python. I am trying to achieve the to user input function to read the variable. Basically the following code works but uses whatever domain i specify in domain = variable
import dns.resolver

#i would like user inputs the domain and that domain's DNS is checked
input('Please type your domain\n')

#unfonetly it reads from here
domain = 'example.com'
for qtype in 'A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA':
    result = dns.resolver.resolve(domain,qtype, raise_on_no_answer=False)
    if result.rrset is not None:
        print(result.rrset)
        print('Record checked successfully\n')

Thanks in advance

A: use domain = input('Please type your domain\n') and remove the domain assignment.
see more about the input function here, it basically prints the argument it receives to the console and returns the user input.


text:
Q: Starting certain applications fullscreen in Xfce Is it possible to make Xfce window manager to open certain applications fullscreen by default? For example i want Emacs in Xfce to be always run fullscreen on start. I know how to execute specifically Emacs fullscreen, so i want an Xfce solution.
I tried searching through Xfce wiki, Xfce page on Arch wiki and Unix.SE with AskUbuntu, no solution yet.

A: Use gdevilspie to match it, that actually works cross DEs

A: Emacs does understand X resources, so this is a working solution for X in general, not only in Xfce. (This is however not true for any program; for example, xfce4-terminal cannot be controlled this way.) The X resources can be viewed by xrdb -query.
To achieve what you want, I have put into /etc/X11/Xresources-site (/etc/X11/Xresources is also OK, though can be overwritten by your distro):
Emacs.fullscreen: maximized

This would affect also remote X clients which are Emacs (e.g., emacs started on a remote host via ssh).
/etc/X11/Xresources-site and /etc/X11/Xresources (and probably ~/.Xresources and ~/.Xdefaults) are usually read at the start of your X session; to affect your current X resources immediately, run something like xrdb -merge /etc/X11/Xresources-site.
Actually, in my case, /etc/X11/Xresources-site is being read thanks to a line in /etc/X11/Xresources (which is read by the start scripts):
#include "/etc/X11/Xresources-site"

so /etc/X11/Xresources is read for sure.
There are also some files with the same syntax which are read each time an X program like emacs starts. In my case, they are: ~/.Xdefaults-MY_HOST_NAME, /etc/X11/app-defaults/Emacs (only for emacs-athena, not for emacs-gtk3), /usr/share/X11/app-defaults/Emacs etc. (But I like the idea of loaded X resources more -- shown with xrdb -query; so that remote X clients read the same X resources.)
Other X resources which Emacs understands are described at https://www.gnu.org/software/emacs/manual/html_node/emacs/Table-of-Resources.html#Table-of-Resources.

A: Looks to me like emacs has a --fullscreen switch, so just append that to the Exec for the menu entry.
http://linux.die.net/man/1/emacs
Editing xfce menu entry example:
http://forum.xfce.org/viewtopic.php?pid=23486