text:
Q: Having multiple-page GUI in Python with several buttons I am currently trying to implement a GUI for a task at work. I have found some open source code (see below) where we make a GUI having 3 pages where one can go between the pages using next/previous buttons. If you run the code you'll see what each button and so on is indended to do.
However, when you run the code and click the "count++" button, the overall count increases by one and not the count for the individual page (e.g. being on page 1 and clicking the count++ 4 times, still makes the count for page 2 or 3, 4 as well, and not zero). The same problem occurs when I try to update the text in each of the textboxes on each page (supposed to be number of clicks), as it won't update. I am not sure how to actually get to the textframe for each individual page.
Any suggestions on where to go from here? In the long run I would like to have scroll-down menus where the selections will be put onto each individual text-frame.
Thanks,
import ttk
from Tkinter import *
import tkMessageBox

class Wizard(object, ttk.Notebook):
    def __init__(self, master=None, **kw):
        npages = kw.pop('npages', 3)
        kw['style'] = 'Wizard.TNotebook'
        ttk.Style(master).layout('Wizard.TNotebook.Tab', '')
        ttk.Notebook.__init__(self, master, **kw)

        self._children = {}

        self.click_count = 0
        self.txt_var = "Default"

        for page in range(npages):
            self.add_empty_page()

        self.current = 0
        self._wizard_buttons()

    def _wizard_buttons(self):
        """Place wizard buttons in the pages."""
        for indx, child in self._children.iteritems():
            btnframe = ttk.Frame(child)
            btnframe.pack(side='left', fill='x', padx=6, pady=4)

            txtframe = ttk.Frame(child)
            txtframe.pack(side='right', fill='x', padx=6, pady=4)

            nextbtn = ttk.Button(btnframe, text="Next", command=self.next_page)
            nextbtn.pack(side='top', padx=6)

            countbtn = ttk.Button(txtframe, text="Count++..", command=self.update_click)
            countbtn.grid(column=0,row=0)

            txtBox = Text(txtframe,width = 50, height = 20, wrap = WORD)
            txtBox.grid(column=1,row=0)
            txtBox.insert(0.0, self.txt_var)

            rstbtn = ttk.Button(btnframe, text="Reset count!", command=self.reset_count)
            rstbtn.pack(side='top', padx=6)

            if indx != 0:
                prevbtn = ttk.Button(btnframe, text="Previous",
                    command=self.prev_page)
                prevbtn.pack(side='right', anchor='e', padx=6)

                if indx == len(self._children) - 1:
                    nextbtn.configure(text="Finish", command=self.close)

    def next_page(self):
        self.current += 1

    def prev_page(self):
        self.current -= 1

    def close(self):
        self.master.destroy()

    def add_empty_page(self):
        child = ttk.Frame(self)
        self._children[len(self._children)] = child
        self.add(child)

    def add_page_body(self, body):
        body.pack(side='top', fill='both', padx=6, pady=12)

    def page_container(self, page_num):
        if page_num in self._children:
            return self._children[page_num]
        else:
            raise KeyError("Invalid page: %s" % page_num)

    def _get_current(self):
        return self._current

    def _set_current(self, curr):
        if curr not in self._children:
            raise KeyError("Invalid page: %s" % curr)

        self._current = curr
        self.select(self._children[self._current])

    current = property(_get_current, _set_current)

    def update_click(self):
        self.click_count += 1
        message = "You have clicked %s times now!" % str(self.click_count)
        tkMessageBox.showinfo("monkeybar", message)
        self.txt_var = "Number of clicks: %s" % str(self.click_count) #this will not change the text in the textbox!

    def reset_count(self):
        message = "Count is now 0."
        #ctypes.windll.user32.MessageBoxA(0, message, "monkeybar", 1)
        tkMessageBox.showinfo("monkeybar", message)
        self.click_count = 0

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
        return combined_func

def demo():
    root = Tk()

    nbrpages = 7

    wizard = Wizard(npages=nbrpages)
    wizard.master.minsize(400, 350)
    wizard.master.title("test of GUI")
    pages = range(nbrpages)

    for p in pages:
        pages[p] = ttk.Label(wizard.page_container(p), text='Page %s'%str(p+1))
        wizard.add_page_body(pages[p])

    wizard.pack(fill='both', expand=True)
    root.mainloop()

if __name__ == "__main__":
    demo()

A: Your update_click method operate on the attribute click_count of your wizard. If you want different count, you could either create a class for your pages and thus, each object would manage its own count, or manage several counter, for instance in a list, the same way you handle your _children list.
For the former case, you can create a page class inheriting ttk.Frame with the body of your _wizard_buttons loop as constructor. In the later case, you could try something like this
class Wizard(object, ttk.Notebook):
    def __init__(self, master=None, **kw):
        [...]
        #replace self.click_count = 0 with
        self.click_counters = [0 for i in range(npages)]

    def update_click(self):
        self.click_counters[self.current] += 1
        # and so on...

Regarding the Text widget update, you can not handle it though a variable, it works with Entry(one line text field) but not on Text (multiline, rich text field). If you continue with Text, the usual recipe to what you seems to want is
text.delete(1.0, END)
text.insert(END, content)


text:
Q: Elementary row operations effect on determinants I have the matrix
$$
A =
\begin{pmatrix}
1 &  2  & 3 & 4\\
-1 & 1 & 2 & 3\\
1 & -1 & 1 & 2\\
-1 & 1 & -1 & 1\\
\end{pmatrix}
$$
I should be able to add multiples of any row to another row and not affect the determinant.
By adding $1$ times the first row to the second row, $-1$ times the first to the third, and $1$ times the first to the fourth, I should still have the same determinant.
This results in the matrix
$$
B =
\begin{pmatrix}
1 &  2  & 3 & 4\\
0 & 3 & 5 & 7\\
0 & -3 & -2 & -2\\
0 & 3 & 2 & 5\\
\end{pmatrix}
$$
However,
$$\det(A) = 27,\quad \det(B) = 87$$
What am I missing? I am expecting $\det(B) = 27$ since I am only adding multiples of the first row to the others.

A: Apparently you made a mistake in computing ${\rm det}(B).$ I tried Maple, and ${\rm det}(B) = 27$ as well.
Here is Wolfram|Alpha for both ${\rm det}(A)$ and ${\rm det}(B)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C, IRC BOT. warning: deprecated conversion from string constant to char* I'm trying to code an IRC bot. The bot connects to the server, however I can't get it to join a channel.
int conn;
char sbuf[512];

// Function I'm trying to use
void join(char *fmt, ...){
    va_list ap;
    va_start(ap,fmt);
    vsnprintf(sbuf,512, fmt,ap);
    va_end(ap);

    printf("<< %s",sbuf);
    write(conn,sbuf,strlen(sbuff));
}

// in main function
int main(){
    const char * chanm = "test";

    // Here is where I get my error, line 38
    join("JOIN %s\r\n", chanm);
}

Can someone please tell me what am I doing wrong?
I get the error message:
ircbot.c:38 warning: deprecated conversion from string constant to char*

A: Change your function heading to:
void join(const char *fmt, ...){

The problem is that "JOIN %s\r\n" is a constant string, and you were trying to pass it to a non-constant char *. Since you don't intend to modify fmt within your join function, you should declare it as const char *fmt.

A: You can fix this with:
void join(const char *fmt, ...)
//        ^^^^^

A: In C, a string literal has a non-const type, even though it is undefined behaviour to attempt to modify the contents of a string literal. For example, this is not allowed in C, even though a compiler is allowed to compile it without emitting a warning or error:
    char *str = "Hello World!";
    str[4] = 'x'; // undefined behaviour

In the above, the string literal "Hello World!" has the type char[13]. To prevent accidental modification of string literals, some compilers treat string literals as const char[] types instead. The most it can do is issue a diagnostic/warning because technically speaking it is still valid C. There are two ways around your problem:

*

*If a function needs to modify a string, it must be char * type, so this means you need to pass it a modifiable string, not a string literal. This can be achieved by creating an array:
char buf[1000] = "String literal";
function(buf, sizeof buf, ...);

*If the function doesn't need to modify the string (such as in your case), you can [and should] have your function only accept const char *. This way, both modifiable and unmodifiable strings can be passed to your function without issues.
function(const char *arg, ...);

// somewhere else:

function("Acceptable", 1, 2, 3);

char buf[20] = "Also acceptable!";
function(buf, 1, 2, 3);


text:
Q: is it possible to Send e-mail without e-mail server? JavaMail sends e-mails using an e-mail server, typically through the SMTP interface of an e-mail provider. Is it necessary to use an e-mail server to send e-mails?
I have a web site that will send e-mails and if possible I'd like to send the e-mails directly from the web site code without using an e-mail server. The JavaMail FAQ says that an e-mail server is required.
Is there a way to send e-mails without using an e-mail server, either with JavaMail or another API?

A: You need an e-mail server. When you send an email from your address to another address. you are really sending it to a mail server.  The protocol used to send to the server is (usually) SMTP.

A: You can deliver an email directly to one of the SMTP servers mentioned in the MX record of the address's domain. Usually that is a bad idea,though:
Delivering the mail to a local server is fast - you can almost immediately continue and do something else and let the server handle the delivery.
The actual delivery can take some time, for instance the remote mail server might be slow. Or it might reject the mail first - it is a known strategy against spam to tell a sender to try sending a mail a second time, which some spam bots won't do.
Also the mail server can easily try again a day later or so when the remote server is down, this reduces risk of lost mail.
i found using google SMTP as easy way to send mail.


text:
Q: Proving Steiner triple system Let $S$ be a set of size $v$ and let $T$ be a set of $3$-element subsets of $S$. Furthermore, suppose that
(a) each pair of distinct elements of $S$ belongs to at least one triple in $T$,
(b) $|T| \leq  \dfrac{v(v-1)}{6}$.
Show that $(S, T)$ is a Steiner triple system.

A: Assume the contrary and make a list $L$ as follows: For every pair write down the triple with which it is associated. Then $|L|>\tbinom{v}{2}$ as there exists a pair with two triples. Now since each triple is counted by exactly three pairs so $|T|=|L|/3>\frac{\tbinom{v}{2}}{3}$, a contradiction.


text:
Q: Do multiple MYSQL json_arrayagg(s) preserve order? select media_id,
 json_arrayagg(artist_id) as artist_ids,
 json_arrayagg(role) as role_ids
from x_media__artist xma group by media_id

Hi guys, do artist_ids and role_ids preserve their order as they were in the group?
For example, if (medium_id,artist_id,role_id) with (1,1,1) and (1,2,2) then
the query above always returns 1 [1,2] [1,2] or 1 [2,1] [2,1] but NEVER 1 [1,2] [2,1]?
Hi, after rechecking MYSQL API, there is absolutely a better solution:
select media_id,
 json_arrayagg(json_array(artist_id, role)) as artist_role_ids
from x_media__artist xma group by media_id

but I am still curious about the answer!

A: As suggested by @Akina. I am going to close this question by self-answer.
The following code will !NOT! guarantee the same permutation for artist_ids and role_ids by the link from @Ergest Basha: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_json-arrayagg.
select media_id,
 json_arrayagg(artist_id) as artist_ids,
 json_arrayagg(role) as role_ids
from x_media__artist xma group by media_id

And the following code will probably work as expected as suggested by @Akina.
select media_id,
 json_arrayagg(json_array(artist_id, role)) as artist_role_ids
from x_media__artist xma group by media_id


text:
Q: Amending SQL slightly brings me: ORA-01427: single-row subquery returns more than one row I am using Oracle Fusion, the finance/payables reporting side of things
I have the following code:
SELECT DISTINCT PHA.SEGMENT1
FROM
    AP_INVOICES_ALL AIA, -- https://docs.oracle.com/en/cloud/saas/financials/19a/oedmf/AP_INVOICES_ALL-tbl.html
    PO_HEADERS_ALL PHA -- https://docs.oracle.com/applications/farel12/procurementop_gs/OEDMP/PO_HEADERS_ALL_tbl.htm
WHERE
    AIA.PO_HEADER_ID = PHA.PO_HEADER_ID
    AND AIA.PO_HEADER_ID IS NOT NULL
    AND AIA.INVOICE_NUM = XTE.TRANSACTION_NUMBER
    AND AIA.INVOICE_ID = XTE.SOURCE_ID_INT_1

This "works" in that it returns no errors. However it's looking at the wrong table so wrong data is being brought back. No biggie, we have identified which table it is.
It's used in a wider context as below to define a column value
(
        CASE
          WHEN
            GJH.JE_SOURCE IN
            (
              'Purchasing', 'Payables'
            )
          THEN
(
            SELECT DISTINCT
              PHA.SEGMENT1
            FROM
              AP_INVOICES_ALL AIA, PO_HEADERS_ALL PHA
            WHERE
              AIA.PO_HEADER_ID = PHA.PO_HEADER_ID
              AND AIA.PO_HEADER_ID IS NOT NULL
              AND AIA.INVOICE_NUM = XTE.TRANSACTION_NUMBER
              AND AIA.INVOICE_ID = XTE.SOURCE_ID_INT_1

              )
            WHEN
              GJH.JE_SOURCE IN
              (
                'Receipt Accounting'
              )
            THEN
(
              SELECT
                CPOD.PO_NUMBER
              FROM
                --cmr_transactions ct
                CMR_PURCHASE_ORDER_DTLS CPOD , CMR_RCV_EVENTS CRE , POZ_SUPPLIERS_V PS
              WHERE
                CRE.CMR_PO_DISTRIBUTION_ID = CPOD.CMR_PO_DISTRIBUTION_ID
                AND CPOD.VENDOR_ID = PS.VENDOR_ID
                AND CPOD.ACTIVE_FLAG = 'Y'
                AND CRE.ACCOUNTING_EVENT_ID = XTE.SOURCE_ID_INT_1 )
              ELSE
                NULL
        END
) AS PURCHORDERNUM,

However I need to amend the SQL to be the following:
SELECT DISTINCT PHA.SEGMENT1
FROM
    AP_INVOICE_LINES_ALL AIA, -- https://docs.oracle.com/en/cloud/saas/financials/19a/oedmf/AP_INVOICE_LINES_ALL-tbl.html
    PO_HEADERS_ALL PHA
WHERE
    AIA.PO_HEADER_ID = PHA.PO_HEADER_ID
    AND AIA.PO_HEADER_ID IS NOT NULL
    --AND AIA.INVOICE_NUM = XTE.TRANSACTION_NUMBER
    AND AIA.INVOICE_ID = XTE.SOURCE_ID_INT_1

This now brings me back ORA-01427: single-row subquery returns more than one row but I can not see why. I am merely changing the table it is looking at and using DISTINCT

A: Using DISTINCT does not mean you will only get one record back. It means you will get one of each distinct values in your result set. That means if 5 records are returned:
value1
value2
value2
value1
value3

Using DISTINCT you will get a result set that looks like this:
value1
value2
value3

You need to ensure that you have enough criteria in your WHERE or ON clauses to ensure a single value return.

A: The table has different data in it, and what the error message is telling you is that the filters you are using AIA.PO_HEADER_ID IS NOT NULL AND AIA.INVOICE_ID = XTE.SOURCE_ID_INT_1 are returning more than one row for at least one value of XTE.SOURCE_ID_INT_1
You probably need to narrow it down a bit.
Try this - on its own - just to see what sort of values your subquery is returning for various values of XTE.SOURCE_ID_INT_1
SELECT DISTINCT AIA.INVOICE_ID AS MATCHES_SOURCE_ID_INT_1, PHA.SEGMENT1
FROM
    AP_INVOICE_LINES_ALL AIA, -- https://docs.oracle.com/en/cloud/saas/financials/19a/oedmf/AP_INVOICE_LINES_ALL-tbl.html
    PO_HEADERS_ALL PHA
WHERE
    AIA.PO_HEADER_ID = PHA.PO_HEADER_ID
    AND AIA.PO_HEADER_ID IS NOT NULL
    --AND AIA.INVOICE_NUM = XTE.TRANSACTION_NUMBER
    AND AIA.INVOICE_ID = XTE.SOURCE_ID_INT_1


text:
Q: PowerShell script for sending bulk emails I have written a script below that reads the email ID from the XML file. Loads the email ID filtered using group ID and then send emails to all the email IDs on that ArrayList. I don't know what is the problem below, I am not getting any emails.
function Test {
   function Send-Mail {
        Param($smtp, $from, $to, $subject, $body)
        $smtp = New-Object System.Net.Mail.SmtpClient($smtp)
        $mail = New-Object System.Net.Mail.MailMessage
        $mail.From = $from
        $mail.To.Add($to)
        $mail.Subject = "subject goes here"
        $mail.Body = "This is test"
        $smtp.Send($mail)
    }
    #Read the xml file and typecast it to System.Xml.XmlDocument
    [Xml]$XmlData = Get-Content Email.xml
    $ArrayEmail = New-Object System.Collections.ArrayList
    $subject = "Testing PowerShell email"
    $from = "a@134.com"
    $smtp = "test.test123.com"
    $body = "The body goes here"
    #get the email list from group id
    $ArrayEmail = $XmlData.emaillist.group |
                  Where-Object {$_.id -eq "IT"} |
                  Select-Object emailid
    $to = New-Object System.Collections.ArrayList
    #store the email ids in array
    for ($i = 0; $i -lt $ArrayEmail.emailid.Count; $i++) {
        $to.Add($ArrayEmail.emailid[$i])
    }
    Send-Mail -Smtp $smtp -From $from -To $to[$i] -Subject $subject -Body $body
 }

Here is my sample XML file:
<emaillist>
  <group id="IT">
    <emailid>a@123.com</emailid>
    <emailid>b@345.com</emailid>
  </group>
  <group id="Admin">
    <emailid>admin@admin.com</emailid>
  </group>
</emaillist>

Not sure what I have done wrong or missed anything as everything seems to be alright. But I still don't get any emails. My smtp is all good, the sender and receivers emails are all good as well.

A: What you have there is called off-by-one error. After your for loop completes the value of the loop variable $i is the highest index of $to plus one. Hence $to[$i] evaluates to $null, because you're trying to access the element after the last element in the ArrayList (which doesn't exist), and PowerShell returns $null for things like that instead of throwing an error.
Replace this:
$ArrayEmail = $XmlData.emaillist.group |
              Where-Object {$_.id -eq "IT"} |
              Select-Object emailid
$to = New-Object System.Collections.ArrayList
#store the email ids in array
for ($i = 0; $i -lt $ArrayEmail.emailid.Count; $i++) {
    $to.Add($ArrayEmail.emailid[$i])
}
Send-Mail -Smtp $smtp -From $from -To $to[$i] -Subject $subject -Body $body

with this:
$to = $XmlData.emaillist.group |
      Where-Object {$_.id -eq "IT"} |
      Select-Object -Expand emailid
Send-Mail -Smtp $smtp -From $from -To $to -Subject $subject -Body $body

and the problem will disappear.

To have the mail sent to all recepients you need to add them one by one:
function Send-Mail {
    Param($smtp, $from, $to, $subject, $body)
    $smtp = New-Object System.Net.Mail.SmtpClient($smtp)
    $mail = New-Object System.Net.Mail.MailMessage
    $mail.From = $from
    $to | ForEach-Object { $mail.To.Add($_) }
    $mail.Subject = "subject goes here"
    $mail.Body = "This is test"
    $smtp.Send($mail)
}
However, rather than re-invent the wheel you should use the Send-MailMessage cmdlet, as others have already suggested:
Send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Body $body


text:
Q: Object reference not set to an instance of object when using a List in C# I have the following code snippet that produces a compilation error:
public List<string> batchaddresses;

public MapFiles(string [] addresses)
{
    for (int i = 0; i < addresses.Count(); i++)
    {
        batchaddresses.AddRange(Directory.GetFiles(addresses[i], "*.esy"));
    }
}

I get an error when I try to use the List<T>.AddRange() method:
Object reference not set to an instance of an object

What am I doing wrong?

A: Where is batchaddresses initialized?
Declaring the variable does not suffice. You must initialize it, like so:
// In your constructor
batchaddresses = new List<string>();

// Directly at declaration:
public List<string> batchaddresses = new List<string>();

A: you have to initialize the list
List<String> batchaddresses = new List<String>();

A: The batchaddresses field hasn't been initialised. You can initialise it as part of the declaration:
public List<string> batchaddresses = new List<string>();

A: From your snippet, it doesn't look as though batchaddresses is initialised. Replace the line with this:
public List<string> batchaddresses = new List<string>();


text:
Q: Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css' I've tried to migrate Angular 13 to Angular 15 and after this I get error message:
./node_modules/@app/app-core/theme/app-theme.scss - Error: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css' in '/Users/user/node_modules/@app/app-core/theme'
Angular.json file has configurations:
"assets": [
  "src/assets",
  {
    "glob": "**",
    "input": "node_modules/@app/app-core/theme",
    "output": "app-core"
  }
],
"styles": [
  "node_modules/@app/app-core/theme/app-theme.scss",
  "src/styles.sass"
],

In app-theme.scss:
@import 'font-family';
@import 'variables';
@import 'reboot';
@import 'mixins';
@import 'node_modules/@angular/cdk/overlay-prebuilt.css';
@import 'buttons';
@import '_grid';
@import '_container';
@import 'main';

app-theme.scss is file which I import to my app and I can't change it globally but if I changed locally:
@import 'node_modules/@angular/cdk/overlay-prebuilt.css';

to
@import '~@angular/cdk/overlay-prebuilt.css';

The problem didn't occur and app is running.
I've tried deleting node-modules and package-lock.json and reinstall all dependencies but it doesn't work.


text:
Q: Dart Map syntax: putIfAbsent('FirstKey',() => 1); What is: ()? In editor hint you get:
scores.putIfAbsent(key, () => numValue);

I am adding single "rows" to my Maps with commands:
myMap.putIfAbsent(9, () => 'Planned');
yourMap.putIfAbsent('foo', () => true);

so: what does that  ()   mean ?

A: The putIfAbsent function takes two arguments, the key and a function that will return the new value, if needed.
See https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Map#id_putIfAbsent
The reason for the second argument to be a function returning the new value, and just not the value itself, is that if the map already contains the key, it's sometimes undesirable to create the value.
Consider the following example:
var map = ...;
var key = ...;
map.putIfAbsent(key, new Value());

If map already contains key, the new value object is not used at all. If the Value object is some heavy or expensive to allocate object, this is an unwanted side-effect.
By taking a function instead
var map = ...;
var key = ...;
map.putIfAbsent(key, () => new Value());

It will only execute the function if the key is not present in map, and the value is needed.
So, to answer the syntax question. A expression of the form () => ... is a short hand of a function expression, returning the result of the first expression. A small example:
var function = () => "some string";
var str = function();
print(str);

will print "some string".

A: () can't be seen alone here its () => that makes the difference.
// adds the value of numValue
scores.putIfAbsent(key, numValue);

// adds an (anonymous) function that takes 0 arguments and returns the value of numValue.
scores.putIfAbsent(key, () => numValue);

So this two forms are totally different. The first adds a value and the second adds a function.
When we assume numValue has the value 5 when putIfAbsent is called then in the first case
var x = scores[key];
// here var x has the value 5

and in the second case
var x = scores[key];
// here var x references a function
var y = x();
// calling the function executes its body which is `return numValue` (the `return` is implicit in the shorthand function form)
// here var y has the value 5

A: () indicates that the expression doesn't have any input parameters.


text:
Q: How do I set up a route to remove a user from a team that has_many :users I basically have the following relationship between my team and user models.

 # team.rb
 has_many :users

While on the team#show page, I have a table of users and I want to include a link to remove each user from the team. I'm currently unsure of how I should setup the route since I've never encountered it before.
Would love some help with this :) Thanks in advance!

A: Add this to your routes.rb.
resources :teams do
 resources :users
end

You will get routes scoped by team_id
Eg: for delete
delete /teams/:team_id/users/:id

You can also have users as individual resource
resources :users
you will get the route as
delete user users/:id

And in your users controller, add destroy action
class UsersController < ApplicationController::Base
  def destroy
    @user = User.find(params[:id])
    if @user.destroy
     flash[:notice] = "User deleted successfully"
    else
     flash[:error] = "Problem deleting user"
    end
    redirect_to teams_path
  end
end

A: I'm assuming you don't want to delete the users, just remove their affiliations with the their current team.  I'm also assuming you want a player to only be part of 1 team at a time. Just have each link next to a team member link to the User#update
class UsersController < ApplicationController::Base
  def update
    user = User.where(:id => params[:id])
    user.update(params[])
    user.save
  end
end

As long as you said resources :users in your routes.rb file, you can just use the default update route it makes for you.  Just make sure you pass it the new params you want (it will just be nil if you want to remove a foreign key).  You can use it to add, remove, or update any column in your model.


text:
Q: htaccess want to add www without affecting subdomains This is what I have in htaccess and all my other pages show 404 errors, the homepage works but doesn't have the www added.

<IfModule mod_rewrite.c>
RewriteEngine On

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css folders, and the robots.txt file
RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1[R=301,L]
</IfModule>

Live site link
Any help is appreciated! I'm going crazy :)

A: This should work for you:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^macmetro\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]


text:
Q: Hide Panel on Child MasterPage Inside MasterPage ContentPlaceHolder using Child Content Page I've tried to find this solution everywhere, but am unable to make it work.
I have the following code.
MasterPage.master:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="My_MasterPage" %>

<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>

ChildMasterPage.master:
<%@ Master Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ChildMasterPage.master.cs" Inherits="My_ChildMasterPage" %>
<%@ Register TagPrefix="uc1" TagName="FileDirectoryOrganizer" Src="~/Controls/my.ascx" %>

<asp:Content ID="Content7" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<asp:panel id="SideNav" runat="server">

        There are 2 User Controls <asp:uc1> inside of this area

</asp:panel>

    <asp:ContentPlaceHolder ID="contentBody" runat="server" />

Related Topics

</asp:Content>

my.aspx:
<%@ Page Title="" Language="C#" MasterPageFile="~/SubDirectory/ChildMasterPage.master" AutoEventWireup="true" CodeFile="my.aspx.cs" Inherits="SubDirectory_my" %>
<%@ MasterType VirtualPath="~/SubDirectory/ChildMasterPage.master" %>
<%@ Reference VirtualPath="~/MasterPage.master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="contentBody" Runat="Server">
</asp:Content>

I've tried the following in the my.aspx code behind to hide the "SideNav" Panel from the ChildMasterPage.master:
1)
protected void Page_Load(object sender, EventArgs e)
{
    ContentPlaceHolder cpHolder = this.Master.FindControl("Content7") as ContentPlaceHolder;
    Panel p = cpHolder.FindControl("SideNav") as Panel;
    p.Visible = false;
}

2)
protected void Page_Load(object sender, EventArgs e)
{
    ContentPlaceHolder cpHolder = this.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
    Panel p = cpHolder.FindControl("SideNav") as Panel;
    p.Visible = false;
}

3)
protected void Page_Load(object sender, EventArgs e)
{
    Panel p = this.Master.FindControl("SideNav") as Panel;
    p.Visible = false;
}

All of these give me the following error when trying to load the aspx page that uses the ChildMasterPage:
 500 - Internal server error.
 There is a problem with the resource you are looking for, and it cannot be displayed.

Ultimately, I'd like to get it to display none with a style so the space is not used on the aspx page. Something like this, which gives me the same error as above:
protected void Page_Load(object sender, EventArgs e)
{
    ((Panel)this.Page.Master.FindControl("SideNav")).Style.Add("display", "none");
}

Thank you in advance for any assistance you may offer. Also, I apologize in advance if this question has been answered here already, but I was unable to find it. At least nothing that worked. I'm still not very good with C#, but I'm getting there.
Thanks
Mark

A: I think you have type cast the Content control into ContentPlaceHolder control in your first approach.
I believe the code should be like below:
Content cpHolder = this.Master.FindControl("Content7") as Content;

Hope this will help !!

A: Instead of trying to force the my.aspx.cs to "see" the Panel on the ChildMasterPage.master, I did the following:
my.aspx.cs
public partial class SubDirectory_my : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        My_ChildMasterPage hideMySideBar = this.Master;
        hideMySideBar.HideSideBar();
    }

ChildMasterPage.master
public void HideSideBar()
{
    SideNav.Visible = false;
}

This casts the class of the Child Master page to a new variable, then the variable can act on, or call the function in the Child Master Page code behind from the my.aspx code behind. Thanks goes to my co-worker for figuring this one out.


text:
Q: punycode compiles with arrow function and make it impossible to render in ie 11 this is generated code in vendor.js  for angular 6 app using angular cli
 const ucs2encode = array => String.fromCodePoint(...array);

the part with => make issue to render in ie 11
and this is polyfills.ts
https://gist.github.com/BehradI/11966c7ccd54e55319490fe60af103be
any idea?

A: I faced the same issue as well, thanks to all the comments, here is what i did.

*

*I opened the package-lock.json file, I started tracing punycode, apparently it was declared as dependency package multiple times for other node packages

*it is very clear the uri-js is referring punycode version 2.1.0 or higher which is causing the problem as this version uses es6 rather than es5 so you end up with arrow function that upsets IE
"uri-js": {
  "version": "4.2.2",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz",
"integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==",
"dev": true,
"requires": {
    "punycode": "^2.1.0"
  }
},
Other suggested to run npm-install punycode@1.1.4 to replace root package, but since I am facing proxy issues due to firewall settings , what i did is I took a backup from the root punycode and replaced it with one located at node-libs-browser which is punycode version 1.1.4. I prefer this approach as I can easily rollback and don't mess my node-modules folder
Boom things started working after on IE

A: The arrow function (=>) cannot be used is IE11 (check compatibility).
You can replace it with a function like this:
const ucs2encode = function(array) {
    return String.fromCodePoint(...array);
}


text:
Q: How to programmatically Scan available wifi networks in blackberry Is there any way to get all available wifi networks on thirdparty application.
After doing a lot off googling i got codes that do this but after installing the app user need to do mannual setting..
I have no need of this.
I wants when i install my app its only show the available(SSID) networks without any settings.

A: //use following function
 public boolean isWiFiEnable()
    {
        if( WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED )
        {
            return true;
        }

        return false;
    }


text:
Q: Is it safe to back up SQL Server data directly if using VSS? I have a client with a very basic single server setup that includes a small SQL Server Express database.
I recently configured Symantec Backup Exec 2010 Quickstart edition for them. This is the free, feature-limited OEM version of Backup Exec that does not include the SQL Server Agent (or any application agent). However, it does support VSS via the Advanced Open File Option (AOFO). In this situation, I've always configured a scheduled task to dump the databases and back up the dumps so I can be sure I have a consistent backup.
However, after running an initial test job of the whole box with AOFO enabled, I noticed that it happily backed up the SQL data files, including the MDF/LDF files, and simply gave me a very softly worded "recommendation" that I might want to consider purchasing the SQL Server Agent as it had detected SQL Server data. This is surprised me on two fronts:

*

*It was my understanding that Backup Exec automatically excludes MDF/LDF files from flat-file backups using the Active File Exclusion or 'AFE' feature unless you manually disabled this via a registry key. My understanding was that this was because it's always a bad idea to back them up directly. The fact they weren't excluded was therefore odd and perhaps intentional.

*The lack of any serious warning stating that the SQL data may be inconsistent, unrestorable or whatever. Just a polite recommendation regarding the SQL Agent.

This led me to wonder, is it actually safe to back up the SQL Server data directly if you're using VSS (via AOFO)? After all, that would presumably mean the SQL Server VSS Writer is called to ensure the data files are app-consistent before the snapshot is taken. Backup Exec seems to have 'let' me do it, despite having recognised the SQL data as such.
I appreciate that using a dedicated SQL Agent provides a number of benefits, but purely on the question of taking a basic, consistent, restorable backup, is this safe?
There seems to be very little in terms of a definitive answer to the question, with some conflict. Obviously in the absence of one I'll be taking the tried and tested route, but it's got me thinking.
Here's some of what I've found so far:

*

*http://www.symantec.com/connect/forums/backup-exec-2010-r2-sql-agent

*SQL Server Backups using Volume Shadow Copy

*https://dba.stackexchange.com/questions/27885/is-it-safe-to-rely-on-a-shadow-volume-backup-of-the-mdf-and-ldf-files

A: Think about what is happening. the SQL database at any one time could be writing a complex transaction to multiple rows and tables that exist all over the MDF file. If the backup is taken while these complex transactions are going on part of the database is going to be backed up before the first part of the transaction is written and the other after.  If it is a table with a lot of columns it could theoretically be copying that part of the file while a row is being written.  Now you have an inconsistent database in a way the database logs can't know about. Volume Shadow Copy is going to make a copy of the volume but can freeze the volume for ... well they say a minute but..... There are also a ton of dependencies and gotcha's. Depend on it if you want but I'm not sure why.
https://www.brentozar.com/archive/2018/01/perils-vss-snaps/
Conceptual view of what is going on in SQL backup. A real SQL Backup stops writing changes to the database while making the backup. It continues to log all changes and read those appropriately from the logs mixed with database reads. Once the database is backed up and a new log is started and the logs to that point are backed up. When you restore this the database is restored then the log files that were happening were applied. This way everything is stable and reliable. There are different nuances to this based on simple or full recovery model but the basics are the same. The file being backed up is guaranteed to be non-changing. This is all done by the database, specifically for the nuances of database integrity. That is worth relying on.


text:
Q: Manipulate VARCHAR string and update column (pseudo-date) So long story short, a client of mine wanted to change a date-time field into a varchar field, after hours of telling them why they should not do that, I finally gave in.
My Issue is the dates now converted into VARCHAR are yyyy-mm-dd and I need to flip them around into mm-dd-yyyy I can do this with PHP with a foreach() loop and a list()=explode() but is there a way to do it with a sql query?

A: You can use DATE_FORMAT:
UPDATE your_table SET your_varchar = DATE_FORMAT(your_varchar ,'%m-%d-%Y')

For more information, see the MySQL documentation: DATE_FORMAT

A: SELECT
    SUBSTRING(date_to_change,9,2) + '-' + SUBSTRING(date_to_change,6,2) + '-' + SUBSTRING(date_to_change,1,4)
...

See if that's what you're looking for.
Apologies - forgot to add the rest of it on.
UPDATE
    table_to_update
SET
    date_to_change = SUBSTRING(date_to_change,9,2) + '-' + SUBSTRING(date_to_change,6,2) + '-' + SUBSTRING(date_to_change,1,4)

A: You can use this:
SELECT CAST(DATE_FORMAT(dateColumn, '%m-%d-%Y') AS CHAR(10));


text:
Q: Code skips next cin after leaving function I am working on a little text based adventure game, the first project I've ever worked on for my own enjoyment, and have ran into a problem. I have got it to ask if you want to play, what your name will be and then the problem starts when you try to choose a race. It works just fine when the user types the first character but when they type the string it will skip past the gender, and class cin. Do I have to clear the cin? Or is my code just wrong?? Thanks for any help you can provide.
#include "pch.h"
#include <iostream>
#include <string>
#include <cctype>
#include <map>
using namespace std;

enum races { Human, Orc, Elf, Dwarf};
enum classes { Warrior, Mage, Archer, Assassin};
const std::map< char, string > race_map =
{ {'H', "human"}, {'O', "orc"}, {'E', "elf"}, {'D', "dwarf"} };
const std::map< char, string > class_map =
{ {'W', "warrior"}, {'M', "mage"}, {'Ar', "archer"}, {'A', "assassin"}
};

void gameIntro();
void gameStart();
void raceFunc(char race);
void playerClassFunc(char playerClass);

void gameIntro()
{
string playerName;
char race;
char sex;
char playerClass;

cout << "Enter your name: \n";
cin >> playerName;
cout << "\n";

cout << "Select a race (Human, Orc, Elf, Dwarf): \n";
cin >> race;
cout << "\n";
raceFunc(race);

cout << "Select Gender (M or F): \n";
cin >> sex;
cout << "\n";

cout << "Select a class (Warrior, Mage, Archer, Assassin): \n";
cin >> playerClass;
cout << "\n";
playerClassFunc(playerClass);

gameStart();
}

void raceFunc(char race)
{
race = toupper(race);
switch (race)
{
case 'H':
    cout << "You chose Human!\n\n";
break;
case 'O':
    cout << "You chose Orc!\n\n";
break;
case 'E':
    cout << "You chose Elf!\n\n";
break;
case 'D':
    cout << "You chose Dwarf!\n\n";
break;

default:
    cout << "Please choose from the following. Program closing.\n";
    system("pause");
    exit(0);
}
}

void playerClassFunc(char playerClass)
{
playerClass = toupper(playerClass);
switch (playerClass)
{
case 'W':
    cout << "You chose Warrior!\n";
break;
case 'M':
    cout << "You chose Mage!\n";
break;
case 'Ar':
    cout << "You chose Archer!\n";
break;
case 'A':
    cout << "You chose Assassin!\n";
break;

default:
    cout << "Please choose from the following. Program closing.\n";
    system("pause");
    exit(0);
}
}

void gameStart()
{

}

int main()
{
char answer;

cout << "Welcome to Dark Horse\n\n";
cout << "This is my fisrt ever actual program I made out of my own free
will lol.\n";
cout << "It is a Text-Based Adventure game. In this game you will make a
character,\n";
cout << "and explore the land of Spelet, battling enemies, leveling up,
getting loot,\n";
cout << "and learning skills! You do not need to capitalize anything but
your character\n";
cout << "name. If a question has (something like this) if you don't
enter whats inside\n";
cout << "the program will CLOSE, so please pay attention! Thank you for
trying it out!\n";
cout << "I really hope y'all enjoy it!\n\n";
do
{
    cout << "Would you like to play?\n";
    cin >> answer;
    if (answer == 'Y')
    {
        gameIntro();
    }
    else if (answer == 'N')
    {

        system("pause");
        return 0;
    }
    else if (answer != 'N' || 'Y' || 'exit')
    {
        cout << "Come on dog it's Y or N...yes or no...\n\n";
    }

} while (answer == 'N' || 'Y');

system("pause");
return 0;
}

A:
"cin, of class istream, is the standard input channel used for user input. This steam corresponds to C's stdin. Normally, this stream is connected to the keyboard by the operating system." (Josuttis, 2012, p. 745)
Josuttis, N. (2016). The C++ Standard Library: A Tutorial and Reference 2nd Edition: Addison-Wesley

The types are important.
char race;
std::cout << "Please enter your race:" << std::endl;
std::cin >> race;

If the user enters "Human", the standard input stream contains Human and the race variable now has the value H (of type char). The standard input stream now contains uman.
char gender;
std::cout << "Please enter your gender:" << std::endl;
std::cin >> gender;

Calling >> with std::cin gets another character from the standard input stream (in this case u) and stores it in gender. The standard input stream now contains man.
While it appears that the gender question was skipped, you can now see that this is not the case. The input stream still contains characters. If you look at your first screenshot you can see that "Mage" was selected. This is because the value of playerClass is m, the same m from when you entered human.
One way to remedy this is to use std::string instead of char to store the input. That way you have more flexibility in parsing what the user enters (e.g. you can allow for H or Human).


text:
Q: What is "inner class emulation" in Java? just found this bit, while reading eclipse JDT's documentation:

IMethodBinding.getParameterTypes(): . . .
  Note: The result does not include synthetic parameters introduced by inner class emulation.

I can't find any reference to inner class emulation in JLS... Anyone knows what this emulation is? Throwing an example, would help as well. :)

A: I think that the Eclipse documentation writer being a little bit loose with the terminology.  As far as the JLS is concerned, an inner class is an inner class and doesn't need to be emulated.
However, there is a bit of trickiness in the way that inner classes get implemented by a typical JVM, and this is where the synthetic constructor parameters come into the equation.  What is going on is that the JVM implements classes the same whether they are nested or not.  There are no special bytecodes for referring to variables in enclosing classes, so the compilers generate code that fetch them via the synthetic attributes.
More details may be found in the original Sun Java 1.1 Inner Classes Specification.

A: I suspect that "inner class emulation" is meant to be how the compiler generate the byte code for inner classes.
There is no inner class support at virtual machine level (at least when they got introduced). The compiler must generate byte code as for a normal class when compiling an inner class. Adding a reference to the outer class instance, for example:
public class Outer {

    class Inner {
        @Override
        public String toString() {
            return "Inner";
        }
    }
}

the Inner class get compiled to something similar to:
class Outer$Inner {
    final Outer this$0;  // the instance of the outer class

    Outer$Inner(Outer outer) {
        super();
        this$0 = outer;
    }

    public String toString() {
        return "Inner";
    }
}


text:
Q: How to create the following user interface? A customer has asked for a user interface which combines a number of different elements.  It's basically a list.  Selecting an entry in the list causes a dialog to expand in-place:

Item 1
Item 2
Item 3

After selecting Item 2

Item 1
------------------------------------
| Item 2                           |
| text box             button      |
|                      button      |
|                                  |
| text box             button      |
------------------------------------
Item 3

I know you can make some fairly complex listviews http://www.codeproject.com/KB/list/ObjectListView.aspx
How would some of you GUI experts do this?  Is there a name for this type of layered interface that I could just search on to learn more about it?  Can I just extend listviewitem with my in-line form?  I think I just need a pointer as to how to start.  I've done some forms programming but this is beyond my current knowledge.
Thanks
Edit --
Dash's comment set me on the right track as I think it's an accordion control that I'm looking for.  Since he didn't provide an answer I don't know how to mark this as answered...

A: If you're using WinForms, there's an implementation called DropDownPanel on CodeProject that looks like what you want.
This answer to a similar question describes a possible solution using TableLayoutPanel, which you may also be interested in.

A: I suggest TableLayoutPanel with 6 rows and 1 column with this orientation:
Row1: Flat button with text=Item1
Row2: A panel corresponding Item1(visible false else button in row1 pressed)
....
and so on.
Note:
First row2,4,6 visible=false
When any button in row1,3,5 is pressed depend on position single row 2,3,4 visible =true else visible=false.

A: Have you looked at the WPF expander control?  You could incorporate this into your list to create a composite control which would satisfy the 'layering' you wish to create.


text:
Q: How to set View of Layout How can I set view of layout with using LayoutInflater. It means i need take view on Layout and set this on other layout
something like this
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.activity_strona_glowna,null);
LinearLayout  a = findViewById(R.id.MainLayout);

i want to set layoutInflater on view of 'a'

A: You can do this by using addView() method.
a.addView(v);

A: 'findViewById' returns a view, please convert it to a LinearLayout.
LinearLayout  a = (LinearLayout)findViewById(R.id.MainLayout);
a.addView(v);


text:
Q: ExternalInterface. addcallback works locally, but not on server? Confused by a problem with ExternalInterface.addcallback.
Mainly because I have it ALWAYS working locally, when I test in a browser, but the moment I deploy to a server it stops working.
I've added trace commands and confirmed that ExternalInterface is in fact available before adding the callback, and an alert command in the javascript method correctly identifies the flash object.
I also checked and allowscriptaccess is set to 'always'.
Could it have something to do with the flash being served on a remote server?
really stumped

A: Try adding System.security.allowDomain("*"); (or actually filling out the correct domain instead of *). To your AS.
You already have allowscriptaccess.  Also make sure the swf and the html/js are coming from the same host.... not www.foobar.com and foobar.com for the other, sometimes that will getcha.


text:
Q: Problem with duplicate table classes with multiple contexts I have two databases, Sales and Production.  For a certain set of tables, the schema is exactly the same.  I generated two contexts using the Database First method.  I specified a different namespace for both.
However, the designer doesn't actually wrap the classes in SalesStore.Context.vb in a namespace.  And when I add it manually, of course it gets lost the next time I make a change to the model.
And so I am getting a bunch of errors: 'multiple definitions with identical signatures'.
How can I change the model so that the namespace is attributed properly to the generated table classes?
TIA,
Miles

A: Use code-first from an existing database workflow.  This will allow you to stich together the generated models and share entity types between DbContexts.  It's a little bit of work, but once you ditch the EF designer, you'll never miss it.


text:
Q: Create WriteableBitmap using HTML content in Windows phone 8.1 Create WriteableBitmap using HTML content in Windows phone 8.1 Without involving the XAML
I have created WebView object in c# and render HTML content in WebView.NaviagateToString and trying to get the object using WebView.CapturePreviewToStreamAsync method but i am getting the Global exception ( value does not fall within the expected range).
WebView wv = new WebView();
wv.NavigateToString(HTML Content);
InMemoryRandomAccessStream imras = new InMemoryRandomAccessStream();
await wv.CapturePreviewToStreamAsync(imras);

And also i tried using the below code, but i didn't find the dlls.
Bitmap m_Bitmap = new Bitmap(400, 600);
PointF point = new PointF(0, 0);
SizeF maxSize = new System.Drawing.SizeF(500, 500);
HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),"
This is a shitty html code

This is another html line
", point,maxSize);
m_Bitmap.Save(@"C:\Test.bmp")

Please help me out from this.
Thanks.

A: t's impossible currently, Windows Phone Store apps do have a phone-only ScreenCapture API, but it still need to show your content in you app.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.


text:
Q: A problem about the supremum of countable stopping times Let $\left(\Omega\ ,\mathcal{F}\ ,\mathbb{P} \right)$  be a probability space with a countable filtration $F=\left\{ \mathcal{F}_0,\mathcal{F}_1,\cdots,\mathcal{F}_n,\cdots \right\}$.
$\left\{ T_n \right\}$ is a sequence (countable infinite) of stopping times.
Let $S_1=\wedge_n{T_n}$ and $S_2=\vee_n{T_n}$ , it is easy to show that $S_1$ and $S_2$ are also stopping times and that $\mathcal{F}_{S_1} = \bigcap_{n}{\mathcal{F}_{T_n}}$ .
It is also easy to show that $\mathcal{F}_{T_1\vee T_2}=\mathcal{F}_{T_1}\vee\mathcal{F}_{T_2}=\sigma\left(\mathcal{F}_{T_1}\cup\mathcal{F}_{T_2}\right)$ , but I wonder whether $$\mathcal{F}_{S_2} = \vee_{n}{\mathcal{F}_{T_n}}$$  still holds.


text:
Q: Can not connect internet from LAN I have the below setups. node1 & node2 are in a LAN. Both use the eth0 NIC to connect to LAN. Both are Debian systems.
Additionally node1 is connected to the internet using wlan0 nic. Expectation is that both node1 & node2 can reach internet.

With this setup, I am not able to access internet. The kernel IP showed the default rule to the router
Basically I am encountering with two issues.
issue 1 :
On Node 1
With this setup, the node1:kernel ip table shows the default rule via eth0. hence connecting to router1/LAN.
I tried ip route del & add new default rule device wlan0. ip table looks good(at least what I expected default rule via wlan0). but still, no internet connection.
Question 1: Is this the right way to delete & add the default rule to change the system behaviour to which dev it should choose to send the packets out. Or some additional config I need.
Now With curiosity, I just flipped the dev. Means the wlan0 nic is connected now to LAN & eth0 is to the router2(external net).
ip table shows default rule to eth0. As this time eth0 connected to router2, I got the internet connection. could ping, browse & all.
Question2: Is eth0 always used for default rule. How can I change to other nic. here wlan0.
Issue 2:
On node 2
However this success could not last longer as from node-2, I do not get internet connection from node-2.
It's static configuration, the GW is mentioned as ip addr of node-1.
Question3: Is this correct. OR Do I need to do any SNAT or MASQRADE kind of config on node1 to be able to OR the router-2 should take care of that.. What I am missing here to get the internet connection.

I am adding some clarity to the above scenario. & also clarification to some comments as I am not yet authorized to comment.
Internet access to/from node2(if more systems on LAN also) should via node-1 only.
the LAN router(router-1) is dhcp enaled and all nodes are client to it.
Same with the internet router-2.
So in this case do I need to do any special configuration on node-1.
On node-1, ip route : default via  dev eth0
On node-2, ip route : default via  dev eth0.
another tricky question (but less important, I can live with it by using eth0 to my internet connected router), what I have already asked is : why the default is via eth0 always. How can I force it to use wlan0(in my case) connected GW. My del/add of default is not working.

A: Without additional information I can already say that SNAT or MASQUERADE should not be necessary on both node-1 and node-2. That should be done by the system which is connected to the Internet (probably the router).
But if the traffic from node-2 shall be routed through node-1 then node-1 would have to do SNAT or MASQUERADE for node-2 (in addition to the SNAT / MASQUERADE which the gateway / router does for node-1).

A: Do you have IP forwarding enabled on Node-1? Try:
sysctl -w net.ipv4.ip_forward=1
If that works, make it permanent by adding the line:
net.ipv4.ip_forward = 1
into /etc/sysctl.conf (making sure that if a similar line setting it to 0 is removed or commented out).

A: Here I am assuming(your aim is to achieve) that all your internet traffic from LAN, should pass via node-1. You are working only with IP4.
As you have mentioned, node-1 is having the connection to the internet already.
On node 2 : the kernel ip table default rule should have GW as node-1 with dev eth0.
On node 1:
With the above assumption, the default rule should have GW as "router 2" dev eth0.
Additioanlly the below must be true OR added.
1) IP_FORWARD flag.
 ipv4.ip_forward flag must be set to 1. (use sysctl or change the sysctl conf file variable)
 # sysctl -w net.ipv4.ip_forward="1"

note : will not survive the reboot.
2) Add IP Forward rule in filter table.
This will forward all the traffic from device eth1 to eth0.
# iptables -t filter -A FORWARD -i eth1 -o eth0 -j ACCEPT

3) MASK the outgoing ip
Qu : If the masking of outgoing ip from node-1 is verymuch required to get the traffic outward of router2 (to internet), then who does that MASQUERADE. Ans : Router-2 does it by default.
Qu : Then why router-2 would not do for node-2 or any other machine in LAN.
Ans : As node-2 & others are not in domain of Router-2. In this case node-1 has to do the MASQUERADING explictly for all other nodes connected in you LAN. hence this step.
# iptables -nat -A POSTROUTING --out-interface eth0 -j MASQUERADE

# iptables save

now you get the internet connection from node 2 or from any other system connected in your LAN.
NOTE : However the above would not survive reboot of node-1. I am not covering how to make it persistent.
Caution : Not sure if the above will work if the NIC to the router-2 is wlan0, as the AP(router-2) may reject the MASQURADE node-2 packets. As the mac id of eth0@node-1 is not registered on the AP, unlike wlan0. Here we have to explictly change the mac address of eth0 packets to wlan0 address. let me know.


text:
Q: Regex drops the last character in the string After working with a Regex supplied by Cary (thank you!), I realized it is dropping the last date in the string when I run it in IRB. Here is the code and the output. Can anyone tell me why this is happening and how to fix it?
require 'rubygems'
require 'nokogiri'
require 'open-uri'

str = "September 19, 20, 25, 26, October 2, 3, 4, 10, November 3, 12, 17"
dates=str.scan(/\D+(?:\d+,\s+)+/).map { |s| [ s[/[a-z]+/i], s.scan(/\d+/) ] }

p dates

The output is the following. As you can see, November only returns 2 dates but there are 3 in the string. It drops November 17.
 [["September", ["19", "20", "25", "26"]], ["October", ["2", "3", "4", "10"]], ["November", ["3", "12"]]]

C:\RailsInstaller\Ruby1.9.3\nokogiri> –

A: This should probably solve the problem:
dates=str.scan(/\D+(?:\d+(?:,\s+|$))+/).map { |s| [ s[/[a-z]+/i], s.scan(/\d+/) ] }

A: The last string does not end with , \s+.
You need to create a case for the end of the string:
str = "September 19, 20, 25, 26, October 2, 3, 4, 10, November 3, 12, 17"
dates=str.scan(/\D+(?:\d+(?:,\s+|$))+/).map { |s| [ s[/[a-z]+/i], s.scan(/\d+/) ] }

p dates

A: Make the ,\s+ portion of the regular expression optional: (?:,\s+)?. Put together:
str.scan(/\D+(?:\d+(?:,\s+)?)+/) ...

It uses a non-capturing group so it doesn't interfere with how the scan method works.


text:
Q: How to delete data efficiently without time consume in my sql I want to delete data from table_a, using the query below, but it is very slow.
table_a contains 21000 data.
DELETE FROM table_a WHERE id IN (
    SELECT
        GROUP_CONCAT(N.id)
    FROM table_a N
    INNER JOIN table_b E ON N.form_id=E.form_id AND N.element_id=E.element_id
    WHERE N.option_value=0
    AND E.element_type IN('checkbox','radio','select')
)

Is there a more efficient way?

A: You don't need a subselect. You can directly refer to the table you want to delete from in your statement like this:
DELETE N
FROM table_a N
INNER JOIN table_b E ON N.form_id = E.form_id
                     AND N.element_id = E.element_id
                     AND E.element_type IN('checkbox','radio','select')
WHERE N.option_value = 0

A: Just to offer an alternative to juergen_d's answer, you can also create > insert > rename > drop.
CREATE TABLE temp_source_table LIKE source_table; -- indeces are copied

INSERT INTO temp_source_table SELECT * FROM source_table WHERE <conditions>;
-- you SELECT which data you want to save instead of delete

-- maybe do some checks and balances before continuing with ...
RENAME TABLE source_table TO origin_source_table, temp_source_table TO source_table;
DROP TABLE origin_source_table;

Of course this depends on the usecase of the table in question, but on tables with large amounts of data and/or complex indeces (don't know the tipping point) this could be a faster option.
This would result in:
CREATE TABLE temp_table_a LIKE table_a; -- indeces are copied

INSERT INTO temp_table_a
SELECT N.*
FROM table_a N
    LEFT JOIN -- because you select what you want to save
    table_b E ON
    N.form_id = E.form_id AND N.element_id = E.element_id
WHERE
    NOT(N.option_value = 0 AND E.element_type IN('checkbox', 'radio', 'select'));
-- you select which data you want to save instead of delete
-- check/tweak the result of the select before using it as part of the insert

-- maybe do some automatic checks on temp_table_a before continuing with:
RENAME TABLE table_a TO origin_table_a, temp_table_a TO table_a;
DROP TABLE origin_table_a;


text:
Q: Compress multiple jpeg files together in C# I was trying compress jpeg files (say 16 files) together using C#. I did successfully created a tar file and finally a tar.gz (using  C# GZipStream class). But the problem with my solution is that the gzip pass increased for 37% the size of the tar file (so a compression ratio of 137%). I tried to manually compress the files together using winrar and it gave me a reduction of 10% in the size (compress ratio of 90%).
I believe that my problem is with GZipStream. I think I should go for another kind of compression (or compressor?!), do you have any idea/suggestion of compression to use.

A: The framework's compression routines don't always go a great job.
I would recommend trying DotNetZip to compress this.  My experience is that the compression (even Gzip) there is much closer to other software, and far smaller than the framework classes.  This is also nice in that it requires nearly no code changes from the framework's GzipStream class if you want to use their GzipStream implementation.


text:
Q: How do I use padding if my string has odd number of characters in C? I am using C as my programming language (not C++) and I am required to encrypt whatever the user types in using a 2-rail fence cipher method of coding in C, AND then pad whatever empty space there is left in the encrypted name with an 'x'. Because it's 2-rail fence the empty space happens if the output string has ODD number of characters!
Here is an example.
Let's say someone write this name: andredimera (all lowercase, no space). The name is 11 characters long. If padding with the x is done correctly, the encrypted name should give me this output WITH the padding -->

adeiea
  nrdmrx
adeieanrdmrx

But I keep getting this output without the padding-->

adeiea
  nrdmr
adeieanrdmr

This is FRUSTRATING! This has been a class quiz for almost a week now, I have not done well, and nobody has been able to help me out no thanks to my short-term memory. I would really appreciate this if someone can help me solve this, with an explanation on how you came up with the solution, so I can get it right in future endeavors. I don't want just the hint or explanation for me to go fish it out myself. I've had my share of it already this week. Thank you. I appreciate your help. :)
Oh, and here is my code:
UPDATED: Code was reposted because I was stupidly compiling it in a completely different solution. That code should work now.
Which now brings me to my latest question based on my updated code: how can I make my char pad = 'x' be added into my char str if the user input has odd number of characters?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main()
{
        char row, col;
        char str[100][100];
        char pad = 'x';

    printf("****Welcome to The Caesar's Palace for Encrypted Names****");

    printf("\n Please enter your name: ");
    scanf("%s", str);

    printf("You entered: %s\n", str);

    printf("2-RAIL CIPHER ENCRYPTION:\n");
    for (row = 0; row < 1; ++row)
    {
        for (col = 0; col < 12; col += 2)
        {
            printf("%c", str[row][col]);
        }

    printf("\n");
    for (col = 0; col < 12; col += 2)
        {

            printf("%c", str[row][col + 1]);
        }
    }

    printf("%c", pad);
    printf("\n");

    for (row = 0; row < 1; ++row)
    {
        for (col = 0; col < 12; col += 2)
        {
            printf("%c", str[row][col]);
        }
        for (col = 0; col < 12; col += 2)
        {
            printf("%c", str[row][col + 1]);
        }
    }

    printf("\n");
    printf("\n");

    return 0;
}

A: There are a number of fundamental issues that are giving you problems. The biggest being the understanding of what a character, character array and string is in C, and how to declare/initialize each. Your pad is a single char, there are no additional dimensions required during the declaration and initialization. It is simply:
char pad = 'x';

A character array is just that multiple characters. In C, if the contents of a character array is nul-terminated, then it can be used as a string. Without the nul-termination it is simply an array of characters.
In your case, you are attempting a 2-Rail cipher with a key (number of rows of text) of 2. Meaning you will simply stagger the characters from the name read from the user between the top-rail and bottom-rail across two lines. e.g.
word: ALLIGATOR
len : 12 characters max (11 char + nul-terminator)
key : 2 (number of lines of text)

0 1 2 3 4 5 6 7 8 9 10
------------------------- rail 1
A x L x G x T x R x x
x L x I x A x O x x x
------------------------- rail 2

The string you take as input need only be a single-dimension array of characters (nul-terminated). As such, your declaration of str, with the number of columns (NCOL = 12), need only be:
char str[NCOL] = "";  /* a 12 character array initialized to 0 (empty string) */

Since your row and col variables are used as array indexes, they should properly be type int instead of type char. (that is another compiler warning)
The remainder of your code, isn't far off. There is no need for the outer row loop in your 2-Rail cipher code, iterating from 0 < 1 with only execute once.
Your padding issue is simply due to the way the rail-cipher works. For each line in key you add, you need to add that number of padding characters. (e.g after the original line, for the 1st line, you add one x before the text, 2 before the second, etc..) In your case, you are simply missing one x before the line following the original. You can correct the issue here with a simple:
printf ("\nx");

between the column loops.
Putting those pieces of the puzzle together with a few more corrections (such as preventing overrun of str by a field-width limitation in scanf, etc.), you could do something like:
#include <stdio.h>

enum { KEY = 2, NCOL = 12 };  /* simple decalration of 2 constants */

int main (void) {

    char str[NCOL] = "";
    char pad = 'x';
    int row, col;

    printf ("\n****Welcome to The Caesar's Palace for Encrypted Names****\n");

    printf ("\n Please enter your name: ");
    scanf ("%11[^\n]%*c", str);

    printf (" You entered: %s\n\n", str);

    printf ("2-RAIL CIPHER ENCRYPTION:\n\n");

    for (col = 0; col < NCOL; col += KEY) {
        printf ("%c%c", str[col], pad);
    }
    printf ("\nx");
    for (col = 0; col < NCOL; col += KEY) {
        printf ("%c%c", str[col + 1], pad);
    }

    printf ("\n\n Your new name is now \n\n");

    for (col = 0; col < NCOL; col += KEY) {
        printf ("%c%c", str[col], pad);
    }
    for (col = 0; col < NCOL; col += KEY) {
        printf ("%c%c", str[col + 1], pad);
    }

    printf ("\n\nCAESAR CIPHER ENCRYPTION:\n\n");
    printf (" Your new name is now\n\n");

    for (row = 0; row < NCOL; ++row) {
        char c = str[row];
        c = (char) (c + KEY + 1);
        printf ("%c%c", c, pad);
    }

    printf ("\n");
    printf ("\n");
    printf ("The End\n");

    return 0;
}

Example Use/Output
$ ./bin/railcipher

****Welcome to The Caesar's Palace for Encrypted Names****

 Please enter your name: ALLIGATOR
 You entered: ALLIGATOR

2-RAIL CIPHER ENCRYPTION:

AxLxGxTxRxx
xLxIxAxOxxx

 Your new name is now

AxLxGxTxRxxLxIxAxOxxx

CAESAR CIPHER ENCRYPTION:

 Your new name is now

DxOxOxLxJxDxWxRxUxxxx

The End

note: I make no representations about the correctness of your CAESAR cipher and I'm no expert on rail-ciphers, but the syntax and code corrections must be dealt with before you tweak the ciphers. Look over the changes and let me know if you have any questions.

A: Here are what you need to do to fix your codes:
Step 1 Add a define hashtag and the include string library to the top of your code...
#include <string.h>
#define BUFFER_SIZE 100

Step 2 Replace these following members that you have...
char row, col;
char str[100][100];
char pad = 'x';

...to these ones
int col, size;
char str[BUFFER_SIZE];

Step 3: Right below your scanf, define your size with a strlen. Strlen calculates and returns to you the length of a string. Any string that you input. This is my strlen for your problem. Use it. ;)
size = strlen(str);

Step 4:
From 2-Rail cipher encryption till the last printf function, replace your code to the ones below.
for (col = 0; col < size; col += 2)
    {
        printf("%c", user[col]);
    }

    printf("\n");
    for (col = 0; col < size; col += 2)
    {
        //printf("%c", user[col + 1]);

        if (col + 1 != size)
            printf("%c", user[col + 1]);
        else
            printf("x");

    }

    printf("\n");

    for (col = 0; col < size; col += 2)
    {
        printf("%c", user[col]);
    }
    for (col = 0; col < size; col += 2)
    {
        if (col + 1 != size)
            printf("%c", user[col + 1]);
        else
            printf("x");
    }

In case you need explanation, your issue was simple, you had an extra row in your C-string that the program was not using. Additionally, you needed the strlen and an if function that basically says "if you've reached the end of the character string in an array of more than 100 characters, then print an x. If you did not have that code in the program would either print nothing (as stated in your issue) or print a zero.
But, keep in mind that if you type in a super long C-string name that is more than 100+ characters and you have the x padding at the end, it will cause some memory issue. Just food for thoughts.
But from now, do these steps and your codes should work with the output you wanted. (hopefully it should). This was my ouput.
adeiea
nrdmrx

adeieanrdmrx


text:
Q: Mocking and resolving Autofac dependency in integration test in AspNetCore with TestServer I'm using AspNetCore 2.2
Following (moreless) the docs here:
https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2
I am using Autofac, my Startup class has the following methods:
public void ConfigureServices(IServiceCollection services)
public void ConfigureContainer(ContainerBuilder containerBuilder) //this is where things can be registered directly with autofac and runs after ConfigureServices
public void Configure(...) //the method called by runtime

The way I use Autofac, as recommended by its docs, is by having Program.cs like this
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .ConfigureServices(services => services.AddAutofac())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                var env = builderContext.HostingEnvironment;
                config
                    .AddJsonFile("appsettings.json", false, true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
                    .AddEnvironmentVariables();
            });
}

I am now using TestServer for my test project where I want to use the real Startup class. But I would like to modify one of the dependencies.
I have seen that there is a method available on WebHostBuilder to .ConfigureTestServices(services => {});
so I tried the following:
public abstract class ComponentTestFeature
    : Feature
{
    protected HttpClient HttpClient { get; }

    protected ComponentTestFeature()
    {
        var configuration =
            new ConfigurationBuilder()
                .AddJsonFile("appsettings.Test.json")
                .Build();

        var webHostBuilder =
            new WebHostBuilder()
                .ConfigureServices(services => services.AddAutofac())
                .ConfigureTestServices(services =>
                {
                    services.AddScoped<IEventStoreManager, MockEventStoreManager>();
                })
                .UseConfiguration(configuration)
                .UseStartup<Startup>();

        var server = new TestServer(webHostBuilder);
        HttpClient = server.CreateClient();
        var myService = server.Host.Services.GetRequiredService<IEventStoreManager>();
    }
}

As you can see I want to use a MockEventStoreManager implementation for IEventStoreManager so that this is the implementation that should be resolved by the container. However this is not working as expected and myService resolved is the original implementation, the real one, not the mock one.
Does anybody know how could I achieve what I want?
UPDATE 1:
After more investigation I had to create an issue on github AspNetCore because the extension method is executed before the ConfigureContainer, therefore I cannot really override autofac dependencies nor retrieve autofac container later on.
https://github.com/aspnet/AspNetCore/issues/6522
UPDATE 2:
Just FYI, this is how the Startup.cs looks like. As you can see all the dependencies but mvc are registered in autofac's container.
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

// This is where things can be registered directly with autofac and runs after ConfigureServices, so it will override it
public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterType<EventStoreManager>().As<IEventStoreManager>();
}

and what I want to do is to use MockEventStoreManager implementation for IEventStoreManager in my tests, so I need to override (from my test project) that Autofac's registration in a nice way.

A: Adding to Nkosi's excellent answer, I'd like to mention that ConfigureTestContainer does not work with the generic host recommended over the web host by Microsoft as of .NET Core 3.0. There is however a workaround proposed by Alistair Evans from the Autofac team. Unfortunately, it relies on the deprecated IStartupConfigureContainerFilter that has been removed in .NET 5.0.
This means that currently in .NET 5.0 there is no way to mock dependencies injected by an external DI container in integration tests when using the generic host.
Luckily, David Fowler from the ASP.NET team is looking into the issue.

A: Register the mocked implementation with the container builder for the test using ConfigureTestContainer
//...
.ConfigureServices(services => services.AddAutofac())
.ConfigureTestContainer<ContainerBuilder>(builder => {
    builder.RegisterType<MockEventStoreManager>().As<IEventStoreManager>();
})
//...

This should avoid getting the actual implementation that is added by Startup.ConfigureContainer as

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service:
Reference Default Registrations

ConfigureTestContainer is invoked after the Startup.ConfigureContainer so the last registration with the mock would be the default provider of the service.

A: There are a couple of options:

*

*Have a custom implementation of your dependency in your testserver
project

*Implement and manually register a mocked implementation of your dependency with a nugget like "Moq"


text:
Q: How to check if value is string in lua? Hello guys i please need your help.
I have values, most of them are numbers but some of them are strings.
How can i check if value is string or number?
I already tried this code but when it reach string value i get error " attempt to perform arithmetic on local 'numberValue' (a nil value)"
function Config:IsNumber(value)
    if value ~=nill or value ~=nil then
        local numberValue = tonumber(value)
        if numberValue/numberValue ==1 then
            return true
        else
            return false
        end
    end
end
end
end

A: First of all let's start with errors in your code.

*

*You have 2 ends to many.

*it is nil, not nill. I'm not sure where you're going with that check.

Other issues / things to improve:
numberValue / numberValue == 1 does not make any sense. A number dividided by itself always results in 1. So checking that is pointless.
Also instead of
if something == 1 then
  return true
else
  return false
end

Can simply be replaced by return something == 1. There is no need for a conditional statement here.
To your question:
To check wether a value is a string use type(value) == "string".
To check wether a value can be convertet do a number use tonumber(value). It will either return a number or nil.
So according to your error the conversion to a number failed.
If you don't know for sure that your value can be converted to a number, you should ensure that tonumber succeded befor you do any operations on its return value.
local numberValue = tonumber(value)
if not numberValue then
  print("converting value to a number failed)
  return
end
-- at this point you know numberValue is a number

So if you wanted to write a function that ensures a string represents a number you could do something like this:
function IsNumber(value)
  return tonumber(value) and true or false
end


text:
Q: How to make 3 columns mobile friendly? I was trying to figure it out on my own, but didn't work well for me.
I am using bootstrap and trying to make proper version for mobile users.
Now it looks horrible on mobile devices.
I think problem is with div classes i was trying to change them, but didn't help me that much.
Here is my code:

Unlimited Domains & Subdomains

Ulimited Email Addresses

Unlimited Databases (MySQL)

Unlimited Bandwidth

SSH, sFTP/FTP acess

PHP 5/7, Perl 5, Python, Zend, phpMyAdmin

One Click CMS Install

Cron Job Manager

SSL Certificate

POP3, IMAP, SMTP For E-Mail

Daily Backups

Detailed Logs & Statistics

Protection From Viruses

Advanced DDoS Protection

24/7 Support

Thanks!
P.S How can i easily test pages on mobile devices?

A: When using Bootstrap, the col-xs class means that the column, and whatever it has inside it, will be squished as much as necessary to fit the contents on a mobile phone.  When you have 3 columns side by side on your desktop or lap top monitor, that makes sense, because each of the 3 columns is big enough for you to read it.
If this is the case with your situation (which I think it is), consider changing these col-xs to col-md or even col-lg.  This will cause the columns not to be squished to fit the mobile screen, but instead, they will stack on top of each other so that you see the left-most column first, then scroll down, you see the one in the middle, and then further below, you see the right column.

A: Try this:

columns do not work well on vertical mobile devices. You should favor rows instead.

A: You're using Bootstrap's extra small (xs) columns size. xs will always create columns no matter how small the viewport. Try using sm, md, lg instead, i.e. col-sm-4.
See Bootstrap Grid Options.
You can also provide multiple column classes to the same element for even more control. For example 50% width columns on small mobiles and 33.333% width columns on larger devices, i.e.
.

A: Two things i would like to add, you might wanna replace col-xs-4 with col-sm-4
that way they are not cramped in for a mobile screen view. Secondly your i tag for list items(little green arrow) Make it position absolute , that way when the word wrap occurs it doesnt look odd.
.featuresBody > li i.icofont-simple-right {
  left: 10px;
  position: absolute;
  top: 10px;
}
.featuresBody > li {
  position: relative;
}


text:
Q: Adding Content-Type Headers to Java HTTP echo server I'm playing with HTTPservers and running into an issue. I need to add ContentType headers to the response, but when I do the client gets ERR_EMPTY_RESPONSE.
If I remove:
headers.add("Content-Type", "text/html");

Then the server works fine, but I need to pass the CType headers for my app. What gives? How do I include Content-Type headers?
/*
* EchoServer.java
*
* Accept an HTTP request and echo it back as the HTTP response.
*
* Copyright (c) 2005 Sun Microsystems, Inc
* Copyright (c) 2008 Operational Dynamics Consulting, Pty Ltd
*
* The code in this file is made available to you by its authors under the
* terms of the "GNU General Public Licence, version 2" See the LICENCE file
* for the terms governing usage and redistribution.
*/

/*
* This code is a simple derivation of the example in the package
* documentation for com.sun.net.httpserver, as found in file
* jdk/src/share/classes/com/sun/net/httpserver/package-info.java as shipped
* with the openjdk 1.6 b08 code drop. Used under the terms of the GPLv2.
*/

import static java.net.HttpURLConnection.HTTP_OK;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.List;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpExchange.*;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
* Echo the body of an HTTP request back as the HTTP response. This is merely
 * a simple exercise of the Secret Sun Web Server. As configured, the URL to
* access it is http://localhost:8000/echo.
*
* @author Andrew Cowie
*/
public final class Test {
    public static void main(String[] args) throws IOException {
        final InetSocketAddress addr;
        final HttpServer server;

        addr = new InetSocketAddress(8000);

        server = HttpServer.create(addr, 10);
        server.createContext("/echo", new EchoHandler());
        server.start();
    }
}

class EchoHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
        final InputStream is;
        final OutputStream os;
        StringBuilder buf;
        int b;
        final String request, response;

        buf = new StringBuilder();

    /*
     * Get the request body and decode it. Regardless of what you are
     * actually doing, it is apparently considered correct form to consume
     * all the bytes from the InputStream. If you don't, closing the
     * OutputStream will cause that to occur
     */

        is = t.getRequestBody();

        while ((b = is.read()) != -1) {
            buf.append((char) b);
        }

        is.close();

        if (buf.length() > 0) {
            request = URLDecoder.decode(buf.toString(), "UTF-8");
        } else {
            request = null;
        }

    /*
     * Construct our response:
     */

        buf = new StringBuilder();
        buf.append("<title>HTTP echo server</title>");
        buf.append("

");
        buf.append(t.getRequestMethod() + " " + t.getRequestURI() + " " + t.getProtocol() + "\n");

    /*
     * Process the request headers. This is a bit involved due to the
     * complexity arising from the fact that headers can be repeated.
     */

        Headers headers = t.getRequestHeaders();

        for (String name : headers.keySet()) {
            List<String> values = headers.get(name);

            for (String value : values) {
                buf.append(name + ": " + value + "\n");
            }
        }

    /*
     * If there was an actual body to the request, add it:
     */

        if (request != null) {
            buf.append("\n");
            buf.append(request);
        }

        buf.append("

");
        buf.append("\n");

        response = buf.toString();
        System.out.println(response);

    /*
     * And now send the response. We could have instead done this
     * dynamically, using 0 as the response size (forcing chunked
     * encoding) and writing the bytes of the response directly to the
     * OutputStream, but building the String first allows us to know the
     * exact length so we can send a response with a known size. Better :)
     */

        headers.add("Content-Type", "text/html");
        t.sendResponseHeaders(HTTP_OK, response.length());

        os = t.getResponseBody();

        os.write(response.getBytes());

    /*
     * And we're done!
     */

        os.close();
        t.close();
    }
}

A: You are extracting the headers from the request and changing request headers doesn't make any sense. you will need to modify the response headers. You can do so by the adding the following
t.getResponseHeaders().add("Content-Type", "text/html");


text:
Q: Data modelling concepts Let´s say I have 3 entities. Can I have them all linked to each other "forming a circle" where each one is linked to the other trough a many to many relationship.
Cheers

A: Sometimes this is called "a cycle" in database design, and while it is not forbidden (because as the commenters point out, you must take into account your purpose and business problem), it is considered a red flag for many designers.
Here is a related Stack Overflow question that attempts to point out why this can be a red flag: https://stackoverflow.com/questions/8115748/why-should-i-avoid-loops-when-designing-relationships-for-a-database


text:
Q: Running Ionic App in the Memu emulator not work properly I'm trying to run an Ionic project to the Memu emulator, I have been connected the emulator to the Android studio with this comment
    adb connect localhost:21503

And after running the project with this comment
   ionic cordova run android -l

It runs successfully in the emulator, but the problem is after opening the app in the emulator I got the error below
Application Error

The connection to the server was unsuccessfully.
  (http://localhost:8100)

A: Try running it on an actual android phone and see if it is just an emulator error. If it is an emulator error delete the emulator and re-install it.


text:
Q: How can I securely format a solid-state drive? When selling / throwing away / giving away HDDs I always use DBAN to do a DoD wipe first.
Is this still a valid thing to do on an SSD?
Will it have an adverse effect on the SSD's lifespan?

A: After the fact, but things have changed a lot in the last 10 months or so - a lot of SSD manufacturers are including (or will be soon) a secure erase function in their optional software utilities that will do the single wipe pass for you properly from a controller level.  (I know Intel already has this and it works great.)

A: A DoD wipe with DBAN would be unnecessary ...
SSD Security: Erase Solid State Drives Data
While it is still not common sense to securely erase data on hard drives (read: Securely Erase Files) before computers
or hard drives are sold or given away the matter becomes even more complicated where SSD – Solid State Drives – are concerned. The positive aspect of Solid State Drives is that data cannot be recovered if it is overwritten on the drive which means that only one pass would be needed to erase the data on the SSD. The bad news however is that not the operating system but the controller is specifying where the data is written on the SSD.
This in effect means that all methods of overwriting free space are not sufficient for erasing the data securely on those drives. This also means as well that it is not possible to erase specific files securely on the SSD. Users who want to delete data securely on SSDs have therefor the following options at hand:

*

*Encryption

*Format

*Filling the Drive

Encryption is surely the best method of ensuring that the data on a SSD is secure as it cannot be accessed without decryption. Formatting the drive on the other hand is only reasonable if no data on that drive is needed anymore. It would otherwise require extensive backup and restoration procedures. Filling the drive with data might work as well as it would overwrite anything on the drive as well.
Source

A: I agree with Molly minus the encryption.  Encryption is a good way to protect data, but it doesn't erase it.
If you want to erase the whole SSD, DBAN on a single pass would work.  I would set it to pseudorandom so if anyone looked it would look like it could be encrypted.
If you want to only wipe a file, using a conventional wipe program (one for a hard drive) would only make it save from undelete tools.  I don't know of any data carving tools that are SSD/flash wear leveling aware, but I'm sure if they aren't out there, they will be.  The most effective way to wipe a file from a SSD/flash is to fill all the free space.
All that said, I don't know if all the spare cells in the flash would be overwritten.  (Most flash have spare cell just like hard drive have spare sectors.)
Also, strictly speaking, overwriting (no matter the passes done) is no longer authorized by the DoD to sanitization hard drives.  Also, many software say DoD wipe but do the 3-pass and not the 7-pass.  In addition, I hear from many people talking about hard drive magnetics and the best wipe is a multipass random pattern.  They say having a known pattern would make reconstruction easier.

A: Use one linux command: scrub
For example:
scrub somedrive -p fillff

This command tells the scrub to fill 0xffs to the drive or folder until full. After this it will delete previous filled values. Therefore it is not recoverable.

A: I use the following code:
// fillSSD(.c)
#include <stdio.h>

void main() {
    while(1) {
        printf("-----WIPED DATA\n");
    }
}

and override the SSD using
a) clear all data
b) ./fillSSD >/media/DISKTOWIPE/dummy.txt
after some time the HD is full and I delete dummy.txt


text:
Q: C# WinForms: Cannot increment when query result is null I have a function here that gets the last value of an order_id and increments it by 1 if it's not already 1. Problem is, the initial value is null and I couldn't get it to add by 1.
Code:
private void getOrderId()
    {
        var orders_dt = conn.Select("orders", "MAX(order_id)").GetQueryData();

        if (orders_dt == null || orders_dt.Rows.Count == 0 || orders_dt.Rows[0][0] == null)
        {
            //Should not preemptively insert into the database
            order_no.Text = "1";
        }
        else
        {
            int order_id = orders_dt.Rows[0][0] + 1; //ERROR HERE
            order_no.Text = order_id.ToString();
        }
    }

An error occurs on int order_id = orders_dt.Rows[0][0] + 1;
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Operator '+' cannot be applied to operands of type 'System.DBNull' and 'int''
Any ideas?
Edit: I've already confirmed the query in MySql, it returns null.

A: Your initial check is checking for null instead of DBNull.Value.
private void getOrderId()
{
    var orders_dt = conn.Select("orders", "MAX(order_id)").GetQueryData();

    if (orders_dt == null || orders_dt.Rows.Count == 0 || orders_dt.Rows[0][0] == DBNull.Value)
    {
        //Should not preemptively insert into the database
        order_no.Text = "1";
    }
    else
    {
        int order_id = orders_dt.Rows[0].Field<int>(0) + 1;
        order_no.Text = order_id.ToString();
    }
}

Note:
//I'm using `Field<T>` to ensure correct datatype.  Change `Field<int>` to reflect whatever type it really is.
int order_id = orders_dt.Rows[0].Field<int>(0) + 1;


text:
Q: An equivalent for "Carrying coal to Newcastle" widespread in both AmE and BrE What is the Americans equivalent for the following proverbial sayng which means: "to supply something to a place or person that already has a lot of that particular thing":

*

*Carrying coal to Newcastle.

I know two other sayings, but I have no idea about their prevalence geographically:

*

*Carrying pepper to Malabar.

*Bringing sand to the beach.

Please let me know which one of my mentioned or presumably your new offers work in both BrE/AmE every day speech?

A: Carrying coal[s] to Newcastle is known in the U.S., but at this writing I cannot recall the last time I have actually heard it come out of anyone's mouth, either in real life or in films or television (I have lived almost my entire life in Southern California and the Mid-Atlantic region). I do see it from time to time in writing and in foreign usage. The same goes for bringing owls to Athens, a literary usage that would not surface in many Americans' everyday conversations, but one which people with a strong humanities education would recognize.
The expression may be falling out of use because it is relatively easy to devise a nonce metaphor or simile to express the idea of a superfluous or redundant supply: bringing wood to the forest, bringing sand to the desert, and so on. At this point, I would not even call these snowclones.
There are almost limitless possible variations, making them difficult to search for, but a few examples include

"Bringing this to Havana," says the Cuban doctor to Gnossos, "is like bringing bread to a bakery." — Vincent Canby, "Been Down So Long' on Film," The New York Times, Sept. 16, 1971
Besides, as my friend Rob Duncan told me one time, bringing a date to a wedding is like bringing beer to a keg party. — Kevin Faris, "The Best Man," Ace (Lexington, Ky.), January 10, 2002
In many ways, taking existentialism to China is like bringing salt to the ocean. —Jason Dias, "Better Than Food," Saybrook University blog, March 25, 2013

The place where you are bringing X needn't be an actual location or event; often, it is some hypothetical gathering of people associated with X: a party, a show, a meeting, and so on. In casual conversation, in a small group, you might hear something compared to bringing donuts to a cop convention, say. As you may imagine, however, it is extremely easy to give offense. I would caution against the use of such metaphors by learners altogether.

Similar but different expressions include don't bring sand to the beach and selling  ice to Eskimos.

*

*The first is commonly an admonition against bringing a date to a party with mixed company; there will be other people to meet, and so the date is superfluous or even burdensome.

*The second (sometimes phrased using freezers, fridges, or snow instead of ice) is a way of characterizing someone's (strong) salesmanship or (weak) ethics for selling people something they have no need of. Note further that Eskimo is considered offensive in Canada (but not in the U.S.).

A: "Carrying coal to Newcastle" is understood in America too, although it does sound archaic. The other two sayings may not be understood; at least, I don't recognize them.
(I've usually heard it with just "coal", but "coals" works too.)

A: Many have suggested that this points to a activity in futility whereas it is actually a comment on the lack of necessity. I was born and raised in RI and have been familiar with this phrase all of my life. I believe that those from the East coast (especially New England) would have a greater familiarity. I grew up in a home where coal was delivered through a basement window.
Phrases such as "spitting into the wind" show neither lack of necessity or futility but more an act of ignorance.
"Tilting at windmills" is an expression of futility.

A:
Carrying coals to Newcastle.

Is familiar to me, but although I am a US native, I have read a lot of works of BrE
This that should be understood widely might might include:

*

*Bringing sand to the beach.

*Bringing sand to the Sahara.

*Taking ice to Antarctica

*Importing gold to South Africa.

None of these have the idiomatic status of "coals to Newcastle", but they should get the point across, in any variety of English.


text:
Q: Unable to render icon from font library with actioncolumn and iconCls I have the following in index.html for FontAwesome:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

An item in grid as:
{
    text: 'Add',
    xtype: 'actioncolumn',
    flex: 1,
    align: 'center',
    items: [{
        iconCls: 'icon-circle-up',
        tooltip: 'above this'
    },{
        iconCls: 'icon-circle-down',
        tooltip: 'below this'
    }]
}

And finally the related scss as:
.icon-circle-up {
    font-family: FontAwesome;
    content: "\f0aa";
    display: inline-block;
    vertical-align: middle;
}

.icon-circle-down {
    font-family: FontAwesome;
    content: "\f0ab";
    display: inline-block;
    vertical-align: middle;
}

When the grid is rendered, I see the placeholders for icons and tooltip, but icons are not rendered.
One of the icons has the following as it is rendered:
<img role="button" alt="" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" class="x-action-col-icon x-action-col-0  icon-circle-up" data-qtip="above this">

What's wrong here? Is it unable to get icon from font stylesheet? How can I get the icon?
Please note that other "image" components on the page work fine with 'glyph' using FontAwesome.

A: AFAIK this is not possible because ExtJS renders the action buttons as 'img' tags. If you don't provide an 'icon' parameter the image you see in the html code is an empty gif of 1x1 pixels.
But @qdev found a workaround here:
Font-Awesome ExtJS ActionColumn
Instead of
icon: ...,

you write
glyph: 'xf0aa@FontAwesome',

I just made a fiddle for ExtJS 4.2 for that. Works quite nice: http://jsfiddle.net/mmfs3678/3/

A: I know this question was likely asked for ExtJS 5, but for anyone using ExtJS 6 and above, the issue could be that the fontCls parameter is missing.
In ExtJS 6, iconCls is specified with the following notation:
iconCls: '{fontCls} {iconPrefix}-{iconName}'

So, rather than just fa-home, try specifying x-fa fa-home, as below:
iconCls: 'x-fa fa-home'

https://docs.sencha.com/extjs/6.0.2/guides/core_concepts/font_ext.html


text:
Q: Animating "sliding" in NSOutlineView I've done a fair amount of Googling, but still haven't find any proper solution for animating the expansion of NSOutlineView.  I'm trying to mimic a "sliding" animation when expanding/collapsing rows.  Anyone know a good strategy for attempting this?
Animating this:
}} Folder 1
To expand and look like this:
}} Folder 1
}}}}} Item 1
}}}}} Item 2
}}}}} Item 3

A: Take a look at this project: TLAnimatingOutlineview

A: This is actually very simple, and you don't need third-party libraries. Instead of calling the expandItem: / collapseItem: directly on your NSOutlineView instance, you pass them to the animator proxy object.
NSOutline *outlineView = ...;
id item = ...;
[[outlineView animator] collapseItem:item];

Also note that you can expand/collapse all the cells at once by passing a nil item.
Documentation: NSAnimatablePropertyContainer Protocol Reference