text:
Q: Running a JPanel Form I am beginner in java. I created a JPanel form in java (NetBeans). then, i defined some actions such as mathematical calculations. When i ran my project, i did not get any error, but i could not see the JPanel form in the running time. because i did not define jform in main class. how can i define JPanel form in main class to show me JPanel form in running time.
public class NewJPanel extends javax.swing.JPanel {

    public NewJPanel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        jLabel1.setText("First Number:");

        jLabel2.setText("Second Number:");

        jLabel3.setText("Result:");

        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Subtract");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Multiply");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Divide");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Clear");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addComponent(jButton1)
                .addGap(45, 45, 45)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addGap(27, 27, 27))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(88, 88, 88)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                            .addComponent(jTextField2)
                            .addComponent(jTextField3)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(120, 120, 120)
                        .addComponent(jButton4)
                        .addGap(45, 45, 45)
                        .addComponent(jButton5)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap(67, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        double num1, num2, result;
        num1 = Double.parseDouble(jTextField1.getText());
        num2 = Double.parseDouble(jTextField2.getText());
        result = num1 + num2;
        jTextField3.setText(String.valueOf(result));
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        double num1, num2, result;
        num1 = Double.parseDouble(jTextField1.getText());
        num2 = Double.parseDouble(jTextField2.getText());
        result = num1 - num2;
        jTextField3.setText(String.valueOf(result));
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        double num1,num2, result;
        num1 = Double.parseDouble(jTextField3.getText());
        num2 = Double.parseDouble(jTextField2.getText());
        result = num1*num2;
        jTextField3.setText(String.valueOf(result));
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        double num1, num2, result;
        num1 = Double.parseDouble(jTextField1.getText());
        num2 = Double.parseDouble(jTextField2.getText());
        result = num1 / num2;

    }

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration
}

A: JPanel is not a runnable class without a top-level container like JFrame and you need a main method. Instead of creating JPanel form, you should have created a JFrame form that has a main method auto-generated for you. It looks like you are using Netbeans GUI Builder. Just open a new JFrame form. And you can just add the JPanel form to the JFrame form.
With NetBeans desing view, you can just drag and drop your JPanel form to you JFrame form, as seen here
Also to explicitly specify the Main class of a project, see here

A: JFrame frameName = new JFrame();
frameName.setVisible(true);

//Now add your JPanel (JPanel yourJPanelName = new JPanel();)
frameName.add(yourJPanelName);

You can work with JFrame.


text:
Q: How can I back up data from MSN 6? I am reinstalling windows for a friend. He has a large number of emails saved on his computer downloaded through MSN6. These emails are not reachable through webmail and he wants to keep them. I assume they're in some kind of database file. Where is this file located, and how can I back it up in a way that it will be accessible by the new version of MSN that I download.
Sorry for the basic questions but I learned how to use computers on Mac OS and linux so I'm not much of a Windows power user.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drag and play hangs up while using PHP Pseudo Streaming script I want to implement pseudo streaming mp4 with PHP to my website so I can authenticate each user for watching videos.
Here is the source code I refered to
http://www.tuxxin.com/php-mp4-streaming/
<?php

$file = 'video360p.mp4';
$fp = @fopen($file, 'rb');

$size   = filesize($file); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte

header('Content-type: video/mp4');
//header("Accept-Ranges: 0-$length");
header("Accept-Ranges: bytes");
if (isset($_SERVER['HTTP_RANGE'])) {

$c_start = $start;
$c_end   = $end;

list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false) {
    header('HTTP/1.1 416 Requested Range Not Satisfiable');
    header("Content-Range: bytes $start-$end/$size");
    exit;
}
if ($range == '-') {
    $c_start = $size - substr($range, 1);
}else{
    $range  = explode('-', $range);
    $c_start = $range[0];
    $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
    header('HTTP/1.1 416 Requested Range Not Satisfiable');
    header("Content-Range: bytes $start-$end/$size");
    exit;
}
$start  = $c_start;
$end    = $c_end;
$length = $end - $start + 1;
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);

$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {

if ($p + $buffer > $end) {
    $buffer = $end - $p + 1;
}
set_time_limit(0);
echo fread($fp, $buffer);
flush();
}

fclose($fp);
exit();
?>

But the problem is when I drag and play an video quickly, The 206 request will hang up. At the same time, all ajax requests to that PHP server will pending, too. I need to restart Apache service, or close and reopen whole browser, or even wait until the request failed and reload the page(wait about 100 minutes).
This problem will only happen when I'm using Chrome and Firefox in Window, I didn't see this issue on Mac.
Chrome Version: 42.0.2311.135 (64-bit) in Mac
                42.0.2311.152m in Windows 7
PHP Version:    PHP 5.5.9-1ubuntu4.7 (cli) (built: Mar 16 2015 20:47:39)
Apache2:        Apache/2.4.7
Thanks


text:
Q: casting an object to char and then "uncasting it back" If you have an object
struct Packet P;

that consists of
struct Packet {
    struct Packet_header header;
    unsigned char data[MAXIMUM_BUFFER_LENGTH];
};

and the header consists of
struct Packet_header {
    unsigned int checksum;
    unsigned int seq;
    unsigned int ack;
    unsigned int data_length;
};

If I try to cast the packet
(unsigned char*) &P

is there anyway I can "uncast" back to get my original packet P?

A: The easy way would be to use reinterpret_cast<Packet>(*(reinterpret_cast<Packet*>(pUC))), where pUC is the unsigned char*.
The correct ways is to have, in Packet_header, a conversion constructor and a cast operator (or cast-like method):
struct Packet_header {
    Packet_header(unsigned char*);  //construct object form unsigned char*
    operator unsigned char*();      //cast it back
    const unsigned char* getUC();   //or get an unsigned char*

    unsigned int checksum;
    unsigned int seq;
    unsigned int ack;
    unsigned int data_length;
};

A: unsigned char *p = (unsigned char*) &P;
Packet *pPacket = (Packet *)p;

A: Yes, theoretically you can do that.
Since both Packet* and unsigned char* are pointer to data types, there is no information loss happening (if one of them is a function pointer then it's possible that information could be lost).
Few things to note:

*

*Avoid such typecasting in first place

*It's better to typecast to/from void* for genericness; at while casting to void* you don't have to use typecasting

*Use reinterpret_cast<> to show the reader that something 'dirty' is
happening


text:
Q: Compress videos with ffmpeg in PHP I want to reduce the size of a MP4 video.
I call ffmpeg command via PHP with this command:
ffmpeg -i $convertUrl -c:v libx264 -crf 28 $convertUrlTmp 2>&1
But it does not reduce enough the video dimension (31 mb --> 23 mb).
How can I compress more?

A: You can experiment with the x265 or vpx instead of x264.
You can also try to reduce the bitrate.

... -b:v $bitrate -bufsize $bitrate ...


text:
Q: Run fetchmail at login under MacOSX I'm using MacOSX and I'm trying to migrate to mutt and fetchmail because Mail.app started giving me several issues.
My configuration sits on~/.fetchmailrcand I launch the daemon issuing fetchmail -d 600. I tried to write a launchd file to handle the task at login, but doesn't work, here's the plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>org.atma.fetchmail</string>
        <key>ProgramArguments</key>
        <array>
      <string>/opt/local/bin/fetchmail</string>
      <string>-f /Users/atma/.fetchmailrc</string>
      <string>-d 600</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
    <key>UserName</key>
  <string>atma</string>
    </dict>
</plist>

I think the problem is the user env variables. Tried using a wrapper bust still nothing. I have another plist provided by MacPorts which ignites a global configuration file located in /opt/local/etc/.fetchmailrc. But I'm afraid that using a global configuration might mess my current setup.
Any way I can adjust he above plist to run successfully?
regards

A: Try splitting the ProgamArguments furter down. AFAIK there has to be NO unescaped whitespace inside the single Strings.


text:
Q: Architect makes custom mini-planets in orbit I'm actually trying to find the anthology this short story was part of, but this is the only story I can recall from it. It was written in the 1950s or early 60s.
An up and coming architect is hired by a wealthy patron to make a retro home with flush toilets and such. No one else would take the job because they didn't make this gear any more, but he solves the various problems using several inventive methods.
This gets him in trouble with the union, who revokes his license. He sets up shop building mini-planets in orbit using white dwarf matter. The one I remember was a water-covered planet with little desert islands, built at the request of a famous sailor.
He has cornered the market on the material so the union is left high and dry, but he suggests they can get more from Sirius if they are willing to make the trip.

A: Your synopsis is similar to Jack Vance's "I'll Build Your dream Castle".  Astounding Science Fiction September 1947.
The Protagonist finds a superior way to build cheaper and thus reduces the charge to the client.  His boss thought he should have saved money for the firm and charged the client the same amount and fires him. the firm starts losing big jobs for wealthy clients and someone investigates and learns what he protagonist is doing with the white dwarf star matter.  The Protagonist has filed claims on all the white dwarf star matter asteroids so they would have to go to Sirius to get more.
Apparently there are other versions of the story (1, 2) and you might have read one of those.

Note: In 1962, Vance revised this story to create "Dream Castle", which is longer and with significantly revised wording. It is not clear if this story ever appeared in print prior to Vance Integral Edition in 2005. Vance later revised this story again for Lost Moons published by Underwood-Miller in 1982. Again, the wording was modified from earlier versions, although less significantly than the change between this story and "Dream Castle".


text:
Q: Inserting javascript in web page Hy, First i have a question, how to insert javascript into webpage that already have a script tag
For example:
in the web page, there is javascript code
function win(){
alert("your score is 500"); }

i want to insert alert("Winner!"); above alert("your score is 500");
so the code will look like in the web page:
function win(){
alert("Winner!");
alert("your score is 500"); }

i have tried with this code
WebBrowser1.Document.Body.AppendChild(WebBrowser1.Document.CreateElement("script"))
WebBrowser1.Document.InvokeScript("win", New [Object]() {"(function() { alert('Winner!'); alert('your score is 500');})()"})

but it is not working,
coul you help me? thank you

A: Why create new script tag and append to head element when it already exists ?
You may try :
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("script");
IHTMLScriptElement element = (IHTMLScriptElement)elems[0];
element.text = "function win() { alert('Winner!');alert('your score is 500');}";
webBrowser1.Document.InvokeScript("win");

Caution : haven't actually tested the code, hope this helps !


text:
Q: Filtrar datas utilizando WP_query e Post meta no Wordpress estou desenvolvendo uma categoria de eventos em meu template utilizando o post padrão, neste post adicionei dois campos (Metabox) para data inicial e data final do evento. Já no WP_query eu preciso exibir os eventos que possuam a data inicial menor que a data atual, e a data de finalização menor.
Utilizando WP_query ou get_post_meta, ou qualquer outra função... Como posso fazer isso?

A: No caso isso depende da forma que você salva a data... Eu recomendo usar o formato:
YmdHis

Desta forma pode fazer uma consulta bem simples comprando números apenas:
'meta_query' => array(
    array(
        'key' => 'seu_meta_key',
        'value' => array( 'data_atual', 'data_termino' ),
        'compare' => 'BETWEEN',
        'type' => 'NUMERIC'
    )
);

Também pode tentar usar o type como DATE, mas para fazer isso também vai ter que usar um formato de data como falei.
Para mais detalhes consulte documentação do uso do meta_query em WP_Query.


text:
Q: how can I get backref relation in in async sqlalchemy? I have one Model:
class Tag(BaseModel):
    __tablename__ = 'tags'
    __table_args__ = {'mysql_engine': 'InnoDB', 'comment':''}

    name = Column(VARCHAR(16), nullable=False, comment="标签名称", unique=True)
    leader = Column(VARCHAR(16), ForeignKey('tags.name', ondelete='CASCADE'), comment="上级标签名称")
    parent = relationship('Tag', remote_side=[name], foreign_keys=leader, backref=backref('children'))

and when I query parent, It's worked very well :
res = await session.execute(select(Tag).where(Tag.name == 'aaa').options(selectinload(Tag.parent)))
                for item in res.scalars():
                    print(item.name)
                    print(item.parent.name)

aaa
bbb

but when I want use backref relation to get children, It's raise error:
res = await session.execute(select(Tag).where(Tag.name == 'aaa').options(selectinload(Tag.parent)))
                for item in res.scalars():
                    print(item.name)
                    print(item.parent.name)
                    print(item.children.name)

sqlalchemy.exc.StatementError: (sqlalchemy.exc.MissingGreenlet) greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place?

what should I do ?


text:
Q: EntityManager injected by Spring but null on first use I am just working on a basic webapp that implements spring + hibernate entitymanager
I set up my dao and context exactly as described by this post:
http://blog.springsource.com/2006/08/07/using-jpa-in-spring-without-referencing-spring/
And created a test for it as shown here:
http://lstierneyltd.com/blog/development/examples/unit-testing-spring-apps-with-runwithspringjunit4classrunner-class/
For some reason when I try to access the entitymanager for creating a query, its null.
However from setting a breakpoint inside the setter method for the entitymanager I can see that Spring is injecting it correctly, and the field is being initialized.
Any clue as to why the entitymanager might be getting nullified after the setter has returned ?
Edit:
The dao code where I am setting the breakpoint:
public class ProductDaoImpl implements ProductDao {

private EntityManager entityManager;

@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
    this. entityManager = entityManager;
}

public Collection loadProductsByCategory(String category) {
    return entityManager.createQuery("from Product p where p.category = :category")
        .setParameter("category", category).getResultList();
}
}

A: The <tx:annotation-driven/> that I presume you do have, tells Spring to put transactional advice on any class or method that has an @Transactional annotation on it.
Transactions should be defined on the Service/Business layer, hence your ProductDaoImpl is usually called from within a service, which will have @Transactional. e.g.
pubic class ProductService {

    @Resource(...)   // inject it the way you like e.g. @Autowired / Setter / Constructor injection, etc..
    ProductDao yourProductDao;

    @Transactional
    public List<Product> findCarProducts {
        yourProductDao.loadProductsByCategory( "car" );
    }
}

(alternatively, you can use an XML based transaction configuration)
Now the actual call to your DAO will be within a transaction => which is very important for entityManager / Hibernate Session. Otherwise you'll see all the usual errors: e.g. entityManager is null, entityManager is closed, etc..
In case you'd like to test a DAO in solo, you have to make sure that your test case is wrapped within a transaction via @TransactionConfiguration. For example, if your transaction manager bean is defined as:
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

Your DAO test would include this bean name:
@ContextConfiguration
@TransactionConfiguration(transactionManager="txManager", defaultRollback=false)
public class ProductDaoTransactionalTests {
    // your use cases here..
}

You can read more about transactional tests in Spring Documentation


text:
Q: Cmake : include FindPackageHandleStandardArgs.cmake In many cmake find modules, we find INCLUDE("${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake")
I would like to do the same thing but from the CMakeLists of my project.
The problem is that ${CMAKE_CURRENT_LIST_DIR} is pointing to the directory of my project... And FindPackageHandleStandardArgs.cmake is in /usr/share/cmake-2.8/Modules/.
Is there a CMake variable that is pointing to the cmake module directory ?
If not, how to do that in my CMakeLists (I want that to be portable and not to be "hardcoded") ?
Thank you very much.

A: If a module file is specified, the include command will search the CMake module directory automatically. Just use:
include(FindPackageHandleStandardArgs)

A: If you've changed the CMAKE_MODULE_PATH variable (which is usually the case when creating a custom Find*.cmake), you can do:

include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs)


text:
Q: getting child category's parent name with a single query in mysql I have a mysql table named "category". the basic structure looks like this-
------     --------     ------
cat_id     cat_name     parent
------     --------     ------
1          test1        NULL
2          test2        NULL
3          test3        2
4          test4        1
5          test5        3

now i want all the category data with parent category name (not only id) in a single query. is that possible? i could do it by using a second query (getting child's parent name) in a while loop and merging data as a whole. but is it possible to do this with a single query?

A: Join the table with itself, using the parent column to link to the cat_id of the parent.
SELECT c1.cat_id as childID, c1.cat_name ChildName, c2.cat_name as ParentName
from category c1
LEFT OUTER JOIN category c2
ON c1.parent = c2.cat_id

*

*Be careful: since some elements have no parents (NULL), I put a LEFT
OUTER JOIN so those rows are displayed as well. If you don't want
that, use a JOIN instead of LEFT OUTER JOIN.

*You can also show the lines, but display something else (empty or a
text or ...) instead of the NULL by using COALESCE.

*You can consider the result as one (big) new table, so you can add WHERE clauses as you usually do, for example filtering on the parent name: WHERE c2.cat_name = 'test2'

A: Select p.cat_id, p.cat_name, c.cat_id, c.cat_name, c.parent
From category Left Join category On p.cat_id = c.parent
Where p.cat_name = 'name'

A: SELECT c1.category_name AS category, c2. category_name AS sub_category
FROM (
SELECT *
FROM  category
) AS c1
INNER JOIN (
SELECT *
FROM  category
) AS c2 ON c1.category_id = c2.category_id


text:
Q: Is the subset of a set and its negation equivalent to the empty set? ie. is $\subseteq A \cap \bar A$ equivalent to $\emptyset$ ?
Just thinking about it logically, this seems to make sense to me, but I couldn't find any similar questions when I searched so I'm still unsure. I apologize if this is a poor question but I'm a beginner when it comes to set theory.

A: If the question is whether  the following assertion holds:

Given a set $A$, a set $B$ satisfies the condition $B\subset A\cap A^\complement$ if and only if $B=\emptyset$.

Then, yes, that is true.

A: Your question essentially asks whether the statement $$B\subseteq A\cap \bar A$$ implies $$B=\Phi $$
The answer is yes because the empty set is a subset of every set and nothing belongs to both the set and its complement.


text:
Q: not able to rename all directories in a given path using filepath.Walk() in go This is my visit function,
func visit(path string, f os.FileInfo, err error) error {
    if !f.IsDir() {
        return nil
    }
    str := path
    if str == config.Path {
        return nil
    }
    if str == config.LatestPath {
        return nil
    }
    dir := str
    dir = strings.TrimPrefix(str, filepath.Dir("C:\\Users\\Mark\\Desktop\\testfolder\\"))
    slashes := strings.Count(dir, "\\")
    if slashes < config.PrevSlashes {
        x := len(config.Slashes) - 1
        for x > slashes {
            config.Slashes[x] = 0
            x--
        }
    }
    config.Slashes[slashes]++
    config.PrevSlashes = slashes
    prename := ""
    for k, v := range config.Slashes {
        if k != 0 {
            if k <= slashes {
                prename += strconv.Itoa(v) + "."
            }
        }
    }
    fmt.Println(config.Slashes)
    myRegex := `(\\(?P<number>[\d\.]*))  \w`
    for i := 0; i < slashes-1; i++ {
        myRegex += `(\\(?P<number` + strconv.Itoa(i) + `>[\d\.]*))  \w*`
    }
    re := regexp.MustCompile(myRegex)
    for i, match := range re.FindAllString(dir, -1) {
        return nil
        fmt.Println(i, match)
    }
    Cdir := filepath.Dir(path)
    newpath := fmt.Sprintf("%s\\%s  %s", Cdir, prename, f.Name())
    config.LatestPath = path
    os.Rename(path, newpath)
    return nil
}

the folder structure looks like this
testfolder\a\aa\aaa,
testfolder\a\aa\aab,
testfolder\a\aa\aac,
testfolder\a\ab\aaa

The problem that i have is filepath,Walk() does not see the changed directory names.
it first renames testfolder\a\aa\aaa to testfolder\1. a\aa\aaa and then it tries to rename testfolder\a\aa\aaa to testfolder\a\1. aa\aaa but i want it to rename testfolder\1. a\aa\aaa to testfolder\1. a\1.1. aa\aaa
the end result should look like
\testfolder\1. a\1.1. aa\1.1.1. aaa
\testfolder\1. a\1.1. aa\1.1.2. aab
\testfolder\1. a\1.1. aa\1.1.3. aac
\testfolder\1. a\1.2. ab\1.2.1. aaa
\testfolder\1. a\1.2. ab\1.2.2. aab
\testfolder\2. b\2.1. aa\2.1.1. aaa
\testfolder\2. b\2.1. aa\2.2.2. aab

simply said i want to name a directory "x. name" and the folders in it "x.x. name" where x is a number
EDIT 1 : i worked around the problem by calculating the path names and putting those in an array and then renaming the directories after the filepath.Walk() function has finished
func visit(path string, f os.FileInfo, err error) (error) {
if err != nil {
    log.Fatal(err)
}
if !f.IsDir() {
    return nil
}
str := path
if str == config.Path {
    return nil
}
dir := str
dir = strings.TrimPrefix(str, filepath.Dir("C:\\Users\\Mark\\Desktop\\testfolder\\"))
slashes := strings.Count(dir, "\\")
if slashes < config.PrevSlashes {
    x := len(config.Slashes) - 1
    for x > slashes {
        config.Slashes[x] = 0
        x--
    }
}
config.Slashes[slashes]++
config.PrevSlashes = slashes
prename := ""
for k, v := range config.Slashes {
    if k != 0 {
        if k <= slashes {
            prename += strconv.Itoa(v) + "."
        }
    }
}
myRegex := `(\\(?P<number>[\d\.]*))  \w`
for i := 0; i < slashes-1; i++ {
    myRegex += `(\\(?P<number` + strconv.Itoa(i) + `>[\d\.]*))  \w*`
}
re := regexp.MustCompile(myRegex)
for i, match := range re.FindAllString(dir, -1) {
    config.Dirpaths[slashes] = fmt.Sprintf("%s", f.Name())
    return nil
    fmt.Println(i, match)
}
config.Dirpaths[slashes] = fmt.Sprintf("%s  %s", prename, f.Name())
prenameOld := ""
for k, v := range config.Dirpaths {
    if k != 0 {
        if v != "" {
            if k == slashes {
                break
            }
            prenameOld += v + "\\"
        }
    }
}
oldname := strings.TrimRight(config.Path+prenameOld+f.Name(), "\\")
newName := strings.TrimRight(config.Path+prenameOld+config.Dirpaths[slashes], "\\")
if len(config.OldNames) != config.MaxDir {
    config.OldNames = append(config.OldNames, oldname)
    config.NewNames = append(config.NewNames, newName)
}
return nil
}

A: If you look at the source for filepath.Walk, you'll see that it does the following:

*

*get sorted listed of names for the current directory

*for each name:

*

*call your callback function

*call walk(name)
With your given directories, the first call inside testfolder will be for testfolder/a since testfolder/1 does not yet exist.
No matter what you do, Walk will not reread testfolder/, so it will never see the new 1. a subdirectory.
Renaming dirs/files during Walk is a great way to get the wrong behavior.
Instead, I would recommend you list files in the directories yourself and do your own recursion.
Something along the lines of:

*

*pick next dir to process (by default, testfolder)

*read current subdirectories/files of dir using File.ReadDirNames

*for each entry:

*

*rename as needed

*add new name to list of directories to process

This uses iteration. Alternatively, you can recurse on the new name (this is where filepath.Walk fails you as it doesn't know about the new name).


text:
Q: Circular icons act as squares I'm creating a card in bootstrap with some social media icons (Font-awesome). For some reason all my icons are treated as boxes and have a black outline around them. My hover shadows also wrap around the square rather than the icon itself.
Why does this happen and how can I fix it?

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

A: The box border is being generated by they type="button" parameter in your anchors, which has a defined -webkit-appearance: button; in bootstrap's stylesheet.  So remove that type="button" parameter, or style it as desired.
As for the shadows, if you want them to keep the shape of the icon instead of being boxed, you should either use text-shadow or filter: drop-shadow instead of box-shadow


text:
Q: Google Cloud Messaging in dart I'm trying to connect to the Google Cloud Messaging with this code in dart
  senderIds.add("api-project-testid");
  chrome.gcm.register(senderIds).then(registerCallback);

but I have this error:

Exception: Uncaught Error: Profile was not signed in.

I think that the error arises from the fact that chromium is not connected with any account. Does anyone know how to fix it?

A: Ok... The version Dartium used in DartEditor is 39.0.2171.0  To use chrome.gcm.register (senderIds) without user logged must have at least version 40. You have to import the package in an updated version of chrome.
I hope it can help someone otherwise I can delete.


text:
Q: I can't activate my code in certain discord channels I'm making a Discord bot which deletes excessive Capital letters automatically. There are some channels where I don't want to use that feature. There is some error in my code. I can't activate commands in those safe channels. But I can activate commands in rest of the channels.
This is my code. The rest of my code(commands) doesn't activate in all channels where Anti-capitalization is allowed.
Is there a way by which I can activate rest of my code in those channels where Anti-capitalization is allowed.
#on_message event
@bot.event
async def on_message(message):

  #Removes Excessive Capitalization
  if Anticapitalize is True:

    if message.channel.id in allowAnticaptalize :
      return

    if len(message.content) > 10:

      find_upper = re.findall('[A-Z]', message.content)
      x = len(message.content)
      y = len(find_upper)
      z = (y/x)*100
      if z > 80:

        embed = discord.Embed(title = f"**__AUTO MODERATION__**", description="Please don't write in excessive capital letters!", color = 0xff0000)
        await message.delete()
        await message.channel.send(message.author.mention,embed=embed, delete_after=15)

  await bot.process_commands(message)

A: I suppose if message.channel.id in allowAnticaptalize: return blocks your commands. You should consider putting await bot.process_commands(message) before that.


text:
Q: Beagleboard Black all GPIOs are activated by a single GPIO Earlier I was having a problem with BeagleBoard Black Rev C , which I discussed in the question below.
GPIO.HIGH,LOW doesn't up LED Beagleboard
I've found the real problem. Whenever I turn any single GPIO pin (say , P8_3) , all the other GPIO pins under P8 also becomes HIGH at the same time, that's why I was having problem lighting up an LED by taking both +ve and -ve from two GPIOs from P8. Same goes for P9. In stead if I take one GPIO from P9 and make it HIGH and another from P8 and make it LOW , the LED is lighting up properly(also I checked using Multimeter and its showing potential differences properly). But the problem arises as all the other GPIOs of P9 are HIGH and all of P8 are LOW.
I want to change individual GPIOs HIGH or LOW whenever I wish. What can be the possible problem? Do I need to update the image? But I don't think that would be the reason of this problem.
EDIT: Posting the python code.
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_3", GPIO.OUT)
GPIO.setup("P8_5", GPIO.OUT)

while True:
   GPIO.output("P8_3", GPIO.HIGH)
   GPIO.output("P8_5", GPIO.LOW)


text:
Q: Application Development in JRuby I'm trying to create a windows desktop application in jruby but I have no idea what I'm doing. So far I've installed jruby 1.7.3 and JetBrains RubyMine. I created a new project and then a new file called window.rb but I have no sense of how to structure this program or how to go about this the right way.
Can someone point me to the right jruby tutorial for desktop graphics application development? I've tried this but it fails to talk about the programming design structure and just jumps into the code.

A: The Swing UI library is pretty complicated to dive into off the bat since you need to understand the Java event model and layouts etc.
I suggest the first thing you do is read through some of the early links here:
http://docs.oracle.com/javase/tutorial/uiswing/
Another potential set of documentation is this
http://www.javabeginner.com/java-swing/java-swing-tutorial
Ultimately, googling for 'Java Swing Tutorial' should return lots of information.
Then, you need to layer JRuby on top of that, which will be additional complexity.
With regards to structure, typically Swing applications encourage you to follow a MVC structure.  The UI object is really an amalgamation of the view and controller since the view (a table or panel) is encapsulated in the controller logic (event handlers in the buttons, scrollbars etc).
Were I to approach this I'd definitely separate the representation of your data into a model class ( you could event use an ActiveRecord object to do this ) and a UI class, based on JDialog or JFrame.
So folders would be:
/myapp
/myapp/ui
/myapp/model
/myapp/util

etc.  /ui would hold UI-related components, /model would contain models, /util would contain anything shared or not strictly related to either UI or models.


text:
Q: Refresh display of transparent user control I've written a user control for that supports transparent background (among other things).
However, I've found a problem that when the background is transparent, and you change the text of the user control, the previous text is still displayed on the screen, under the new text, making it impossible to read.
I've been googling for half a day now, finding all sort of suggestions that didn't work in my case, most of them involving painting the parent control onto a bitmap and draw that bitmap on my control's surface.
However, in my case the parent control is also transparent so I've tried to go up to the form's level like suggested here but i was getting an InvalidArgumentException,
I've tried invalidating the parent control like suggested here but no luck either.
my code is basically this (truncated to the bare minimum):
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x20;
        return cp;
    }
}

protected override void OnPaintBackground(PaintEventArgs e)
{
    if(this.BackColor != Color.Transparent)
    {
        base.OnPaintBackground(e);
    }
}

A: I keep learning again and again that simply explaining the problem to someone else often helps you solve it.
So, After combining a few answers from all my searches,
mainly this one about invalidating a specified rectangle of the parent,
and this one about getting the location of the control on the form,
I came up with this:
// Make the Text property browsable again, call Refresh when changed.
[Browsable(true),
 DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text
{
    get { return _Text; }
    set
    {
        if(_Text != value)
        {
            this.Refresh();
            _Text = value;
        }
    }
}

// Override Refresh to invalidate the relevant part of the parent form
public override void Refresh()
{
    Form form = this.FindForm();
    // only for transparent controls that has text and no background image
    if (this.BackColor == Color.Transparent &&
        !string.IsNullOrEmpty(this.Text) &&
        (this.Gradient.BackColor2==Color.Transparent || !this.Gradient.IsGradient) &&
        this.BackgroundImage == null &&
        form != null)
    {
        Point locationOnForm = form.PointToClient(
                                   this.Parent.PointToScreen(this.Location)
                               );
        // Invalidate the rectangle of the form that's behind the current control
        form.Invalidate(new Rectangle(locationOnForm, this.Size));
    }
    base.Invalidate();
}

I will still have to deal with parent controls between the current control and the form, but for now this is good enough for me.

A: I think we are close on this one.
Firstly, you cannot suppress OnPaintBackground like that and expect the rest of winforms to run as expected, this means nothing gets painted to that region at all, so we have left GDI+ or windows or presumably some other construct to "fill in the blanks". The controls on your form that are opaque may want to call your UserControl to get it's background, so we have to paint something...
So we always call base.OnPaintBackground, but if the background is Transparent, then we need to invalidate the entire surface of the control to be repainted.
    public Glass()
    {
        InitializeComponent();
        this.SetStyle(ControlStyles.Opaque, true);
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;
            return cp;
        }
    }

    private bool rePaintState = false;
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        base.OnPaintBackground(e);
        if (this.BackColor == Color.Transparent)
        {
            // we want to invalidate and force it to re-paint but just once
            if (rePaintState)
            {
                rePaintState = false;
            }
            else
            {
                rePaintState = true;
                this.Invalidate();
            }
        }
    }

This is still not complete, but saved most of the flickering I was experiencing when controls above and below the UserControl had textboxes with values refreshing on a timer.

I know its not a huge help, but WPF is really good for these types of UX issues ^-^


text:
Q: I'm writing a spider base on scrapy ,I get into trouble about how to modify the scrapy.Request.formdata format, the key is dynamic password_name = select.xpath('//form/div/input[@type="password"]/@name').extract()[0].encode('utf-8')
yield Request(action_url,
    meta = {'cookiejar' : response.meta['cookiejar']},
    headers = self.headers,
    formdata = {
        'mobile': 'xxxxx',
        password_name:'xxxxx', #password_name,there is wrong
        'code': self.code,
        'remember': remember,
        'backURL': backURL,
        'backTitle': backTitle,
        'tryCount': tryCount,
        'capId': capId,
        'vk': vk,
        'submit': submit
    },
    method = "POST",
    callback = self.mainInfo
)

password_name is a variable and is different via every request,how can I deal with it in the formdata

*

*I tried str(password_name) replace it, but failed

*I also tried dict type to replace the {...} , also failed

*how can I do with this problem??


text:
Q: How to access the cURL executable with Python subprocess module I am trying to access the curl executable on my computer using a subprocess call, but when I do so, I get the following error:
WindowsError: [Error 2] The system cannot find the file specified
my code looks as follows
path = 'C:\\Users\\Username\\AppData\\Local\\Continuum\\Anaconda2\\Library\\bin\\curl.exe
subprocess.call([path])
I know the path is correct, is there a reason that my script is balking at this?
As you can see, I am running the Anaconda2 Python Interpreter, not the standard one from Python.org

A: Take a step back and do some sanity checks. Here are some steps to try.

*

*Copy the path in your script, and paste it into the file explorer (remove the escape characters) and verify that the path is indeed correct.

*Verify that you have proper permissions to the path
* Copy the executable (curl.exe) to a same location your python script is at, this eliminates the need to specify a path (sanity check)
import subprocess
path = 'curl.exe'
subprocess.call([path])
If this works, you can then move it your expected path and verify


text:
Q: MySQL error on can't open named pipe with python and flask The error code is:
mysql.connector.errors.DatabaseError: 2017 (HY000): Can't open named pipe to host: . pipe: MySQL (2)
I can see no reason for this error in MySQL Workbench settings.
db.py:
import mysql.connector

import click
from flask import current_app, g
from flask.cli import with_appcontext
from .schema import instructions

def get_db():
    if 'db' not in g:
        g.db = mysql.connector.connect(
            host=current_app.config['DATABASE_HOST'],
            user=current_app.config['DATABASE_USER'],
            password=current_app.config['DATABASE_PASSWORD'],
            database=current_app.config['DATABASE']
        )
        g.c = g.db.cursor(dictionary=True)
    return g.db, g.c

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

def init_db():
    db, c = get_db()

    for i in instructions:
        c.execute(i)

    db.commit()

@click.command('init-db')
@with_appcontext
def init_db_command():
    init_db()
    click.echo('Base de datos inicializada')

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

init.py (the init is into a "__ __":
import os

from flask import Flask

def create_app():
    app = Flask(__name__)

    app.config.from_mapping(
        SECRET_KEY='mikey',
        DATABASE_HOST=os.environ.get('FLASK_DATABASE_HOST'),
        DATABASE_PASSWORD=os.environ.get('FLASK_DATABASE_PASSWORD'),
        DATABASE_USER=os.environ.get('FLASK_DATABASE_USER'),
        DATABASE=os.environ.get('FLASK_DATABASE'),
    )

    from . import db

    db.init_app(app)

    @app.route('/hola')
    def hola():
        return 'Happy Pig'

    return app

Schema.py:
instructions = [
    'SET FOREIGN_KEY_CHECKS=0;',
    'DROP TABLE IF EXIST todo;',
    'DROP TABLE IF EXIST user;',
    'SET FOREIGN_KEY_CHECKS=1:',
    """
        CREATE TABLE user (
            id INT PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(50) UNIQUE NOT NULL,
            password VARCHAR(100) NOT NULL
        )
    """,
    """
        CREATE TABLE todo(
            id INT PRIMARY KEY AUTO_INCREMENT,
            created_by INT NOT NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            description TEXT NOT NULL,
            completed BOOLEAN NOT NULL,
            FOREIGN KEY (created_by) REFERENCES user (id)
        );
    """
]


text:
Q: How do you group an R dataframe by time interval and column value? I have a dataset that is a list of the times that events happen at specific facilities:
> head(facility_events);
facility_id          event_time
1   20248 2018-01-01 00:00:01
2   12445 2018-01-01 00:00:04
3   20248 2018-01-01 00:00:08
4   17567 2018-01-01 00:00:47
5   17567 2018-01-01 00:03:50
6   10459 2018-01-01 00:04:01

I would like to generate a dataframe with an aggregate sum by grouping the data by facility and also grouping the events into 3 minute intervals.  Output would look something like this:
count facility interval
2      20248   0
1      12445   0
1      17567   0
1      17567   1
1      10459   1

How do you accomplish this in R?

A: You can use tidyverse with lubridate for this:
df <- data.frame(facility_id = c(20248, 12445, 20248, 17567, 17567, 10459),
                 event_time = as.POSIXct(c("2018-01-01 00:00:01", "2018-01-01 00:00:04", "2018-01-01 00:00:08", "2018-01-01 00:00:47", "2018-01-01 00:03:50", "2018-01-01 00:04:01")))

library(tidyverse)

df %>%
    mutate(interval = lubridate::minute(event_time) %/% 3) %>%
    group_by(facility_id, interval) %>%
    summarise(count = n())

# A tibble: 5 x 3
# Groups: facility_id [?]
  facility_id interval count
        <dbl>    <int> <int>
1       10459        1     1
2       12445        0     1
3       17567        0     1
4       17567        1     1
5       20248        0     2

A: Here is a solution with data.table. Same logic:

*

*Creates group of interval

*summarise (count) by this group

This is a one-liner with data.table concise syntax.
df <- data.frame(facility_id = c(20248, 12445, 20248, 17567, 17567, 10459),
                 event_time = as.POSIXct(c("2018-01-01 00:00:01", "2018-01-01 00:00:04", "2018-01-01 00:00:08", "2018-01-01 00:00:47", "2018-01-01 00:03:50", "2018-01-01 00:04:01")))

library(data.table)

setDT(df)
df[, .(count = .N), by = .(facility_id, interval= minute(event_time) %/% 3)]
#>    facility_id interval count
#> 1:       20248        0     2
#> 2:       12445        0     1
#> 3:       17567        0     1
#> 4:       17567        1     1
#> 5:       10459        1     1

Created on 2018-01-14 by the reprex package (v0.1.1.9000).


text:
Q: Find mapping between ASCII values in C I'm stuck at this problem. I want to take in a char as input (ex: a) and return h. And b would return p. c would x. I am to use the ASCII table to figure out the bitwise mapping between the characters. Any help would be appreciated. The question says "For the two suggested input texts, use the table of ASCII codes to identify the bitwise mapping between input and outputs." So I need to look at the ASCII table binary representation of the values and find a pattern that is common in all of them
So in short:
input : abcdefghijklmnopqrstuvwxyz
output: hpxaiqybjrzcksf{dlt|emu}gfnv

This is the skeleton of the code:
#include <stdio.h>

int main(void)
{
    int inChar, outChar;

    while((inChar = getchar())!=EOF)
    {
        //your code here

        //last statement in while loop
        putchar(outChar);
    }
    return 0;
}

A: Working with that skeleton, if you can only put code inside the loop, then just compute the character looking at the string every single time. This is very slow but gets the job done, there really is no other good way if you cannot put code outside the loop.
There you go:
#include <stdio.h>

int main(void)
{
    int inChar, outChar;

    while((inChar = getchar())!=EOF)
    {
        char *in  = "abcdefghijklmnopqrstuvwxyz";
        char *out = "hpxaiqybjrzcksf{dlt|emu}gfnv";
        char *match;

        match = strchr(in, inChar);

        if (match == NULL)
            outChar = '?'; // Some default char in case nothing matches.
        else
            outChar = out[match - in];

        putchar(outChar);
    }
    return 0;
}

Here's a link to strchr() documentation in case you are not familiar with the function.

Old answer, efficient way of solving the problem.
Just use a simple array as a map for the characters:
int main(void) {
    // Empty map (all '\0' characters).
    char map[256] = {0};

    // Original characters:
    char *in_chars  = "abcdefghijklmnopqrstuvwxyz";

    // Corresponding translated characters:
    char *out_chars = "hpxaiqybjrzcksf{dlt|emu}gfnv";

    int i;

    // Assign each character from in_chars the corresponding one
    // from out_chars by adding it to the map.
    for (i = 0; in_chars[i] != '\0' && out_chars[i] != '\0'; i++) {
        char from = in_chars[i];
        char to = out_chars[i];
        map[from] = to;
    }

    while (1) {
        // Get one character from standard input:
        int c = getchar();

        // Break the loop in case of error or end of input:
        if (c == EOF)
            break;

        // Convert the input character to the corresponding output
        // character according to the map, and output it:
        putchar(map[c]);
    }

    return 0;
}

Characters that don't appear in in_chars will be replaced with \0. You can do an initial memset() to set the default value to something else if you want.
Also, the two strings you provided are of different lengths, you might want to check that.

A:  #include <stdio.h>
 #include <math.h>

 bool IsBitSet(int b, int pos)
 {
      return (b & (1 << pos)) != 0;
 }

 int SetBit(int value, int bitToSet)
 {
     return value | (int)pow(2, bitToSet);
 }

 int ClearBit(int value, int bitToClear)
 {
     return (value & ~((int)pow(2, bitToClear)));
 }

int main(void)
{
      unsigned char inChar= 0, outChar=0;
      while ((inChar = getchar()) != EOF)
{
// Your bitwise code appears here…
char isFirstBitset = IsBitSet(inChar, 0);
char isSecondBitset = IsBitSet(inChar, 1);
char isFourthBitset = IsBitSet(inChar, 3);
char isFifthBitset = IsBitSet(inChar, 4);

// If first bit is set
if (isFirstBitset)
{
    inChar = SetBit(inChar, 3);
    if (!isFourthBitset)
        inChar = ClearBit(inChar, 0);
}

// If 2nd bit is set
if (isSecondBitset)
{
    inChar = SetBit(inChar, 4);
    if (!isFifthBitset)
        inChar = ClearBit(inChar, 1);
}

// if 4th bit is set
if (isFourthBitset)
{
    inChar = SetBit(inChar, 0);
    if (!isFirstBitset)
        inChar = ClearBit(inChar, 3);
}

// if 5th bit is set
if (isFifthBitset)
{
    inChar = SetBit(inChar, 1);
    if (!isSecondBitset)
        inChar = ClearBit(inChar, 4);
}

outChar = inChar;
putchar(outChar);
 }
 return 0;
   }


text:
Q: Finding the direction of an induced current, swinging pendulum
The conductor shown in #1 is held still in position #2. The switch s1 is now open, and the switch s2 is now closed, see #1. There is no current going through the conductor as its held still. Then, the conductor is released and an electric current is induced. Find the direction of this current:
1 As the conductor swings towards the lowest point.
2 As the conductor makes its way up to the right after having passed the lowest point.
Since the flux is reduced when the conductor makes its way down the lowest point (angle between area vector and b field goes towards 90 degrees), the flux is reduced. Therefore i think there must be induced a magnetic field going in the same direction as the field in #2, and the force on the conductor must be opposite of the direction of the velocity (Lenz's law) i.e to the left, and therefore the current should be going into the plane of the paper. Because the flux is reduced after the conductor has passed the lowest point and swings up to the right, my idea is that it should be the excact opposite (current going out of the plane of the paper). However this is not correct apparently.
It's a bit of a complex problem, so if you need additonal details or explanations please let me know.

A:
. . . and the force on the conductor must be opposite of the direction
  of the velocity (Lenz's law) i.e to the left, and therefore the
  current should be going into the plane of the paper.

Q So when the conductor has passed the vertical which way is the conductor moving and so which way should the opposition to motion be?
A The same as before, to the left, and so the induced current must be in the same direction as before.
Before the conductor reached the vertical position the induced current produce a clockwise magnetic field around the bottom conductor thus trying to increase the (downward) magnetic flux through the loop to try and counteract the decreasing magnetic flux due to the external magnetic field..
On the other side of the vertical the direction of the induced current and hence the induced magnetic field is the same but note that now that induced magnetic field and hence the flux is upwards through the loop and it is trying to reduce the increase in magnetic flux through the loop due to the external magnetic field.
Update as a result of a comment
The external magnetic field always points downwards.

The magnetic field due to the induced current has a downward component through the loop when the loop is left of vertical (left picture) and an upward component through the loop when the loop is right of vertical (right picture).


text:
Q: How to let IBM BlueSocket run on a GUI application and support multi connections Recently, I found a pure swift socket server and client called IBM BlueSocket.
It is suitable for me that it does server-cleint communication.
It has a pretty simple sample. but I encountered some problems.
1. How to run it on a GUI application's run loop?
2. How to run it and support multi connections?

A: For what it's worth, I present the world's simplest chat client.
import Foundation
import Socket

// Very simplified chat client for BlueSocket - no UI, it just connects to the echo server,
// exchanges a couple of messages and then disconnects.
// You can run two instances of Xcode on your Mac, with the BlueSocketEchoServer running in one and
// this program running in the other. It has been tested running in the iPhone simulator, i.e.,
// under iOS, without problems.
// License: Public domain.
public class BlueSocketChatClient {

   public func runClient() {

      do {
         let chatSocket = try Socket.create(family: .inet6)

         try chatSocket.connect(to: "127.0.0.1", port: 1337)

         print("Connected to: \(chatSocket.remoteHostname) on port \(chatSocket.remotePort)")

         try readFromServer(chatSocket)

         try chatSocket.write(from: "Hello to you too!")

         try readFromServer(chatSocket)

         try chatSocket.write(from: "Bye now!\n")
         try chatSocket.write(from: "QUIT")

         sleep(1)  // Be nice to the server
         chatSocket.close()
      }
      catch {
         guard let socketError = error as? Socket.Error else {
            print("Unexpected error ...")
            return
         }
         print("Error reported:\n \(socketError.description)")
      }
   }

   // This is very simple-minded. It blocks until there is input, and it then assumes that all the
   // relevant input has been read in one go.
   func readFromServer(_ chatSocket : Socket) throws {
      var readData = Data(capacity: chatSocket.readBufferSize)
      let bytesRead = try chatSocket.read(into: &readData)
      guard bytesRead > 0 else {
         print("Zero bytes read.")
         return
      }
      guard let response = String(data: readData, encoding: .utf8) else {
         print("Error decoding response ...")
         return
      }
      print(response)
   }
}

Bill Abt: If you can use this in any way you're welcome to it.

A: The sample has been recently updated and illustrates use of the GCD based Dispatch API to do multi-threading and supporting multiple connections. It also should give you a idea on how to run it on the main queue (which'll work for either a GUI or server application).


text:
Q: How to replace all occurrences of a character in string? What is the effective way to replace all occurrences of a character with another character in std::string?

A: std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.
#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

A: If you're looking to replace more than a single character, and are dealing only with std::string, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.
while(sHaystack.find(sNeedle) != std::string::npos) {
  sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}

A: Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.
In cases where:

*

*the replacing and the to-replaced string have different lengths,

*there are many occurences of the to-replaced string within the source string and

*the source string is large,

the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over.
(I do not know the boost solution, maybe it is OK from that perspective)
This one walks along all occurrences in the source string and builds the new string piece by piece once:
void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
    std::string newString;
    newString.reserve(source.length());  // avoids a few memory allocations

    std::string::size_type lastPos = 0;
    std::string::size_type findPos;

    while(std::string::npos != (findPos = source.find(from, lastPos)))
    {
        newString.append(source, lastPos, findPos - lastPos);
        newString += to;
        lastPos = findPos + from.length();
    }

    // Care for the rest after last occurrence
    newString += source.substr(lastPos);

    source.swap(newString);
}

A: As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.
Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

A: What about Abseil StrReplaceAll?  From the header file:
// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
//                                                {"&", "&"},
//                                                {"<", "<"},
//                                                {">", ">"},
//                                                {"\"", """},
//                                                {"'", "'"}});

A: #include <iostream>
#include <string>
using namespace std;
// Replace function..
string replace(string word, string target, string replacement){
    int len, loop=0;
    string nword="", let;
    len=word.length();
    len--;
    while(loop<=len){
        let=word.substr(loop, 1);
        if(let==target){
            nword=nword+replacement;
        }else{
            nword=nword+let;
        }
        loop++;
    }
    return nword;

}
//Main..
int main() {
  string word;
  cout<<"Enter Word: ";
  cin>>word;
  cout<<replace(word, "x", "y")<<endl;
  return 0;
}

A: Old School :-)
std::string str = "H:/recursos/audio/youtube/libre/falta/";

for (int i = 0; i < str.size(); i++) {
    if (str[i] == '/') {
        str[i] = '\\';
    }
}

std::cout << str;

Result:

H:\recursos\audio\youtube\libre\falta\

A: A simple find and replace for a single character would go something like:
s.replace(s.find("x"), 1, "y")
To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

A: The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

Usage:
std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

Outputs:

Number_Of_Beans
XXjXugtXty
hhjhugthty

EDIT:
The above can be implemented in a more suitable way, in case performance is of your concern, by returning nothing (void) and performing the changes "in-place"; that is, by directly modifying the string argument str, passed by reference instead of by value. This would avoid an extra costly copy of the original string by overwriting it.
Code :
static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

A: I thought I'd toss in the boost solution as well:
#include <boost/algorithm/string/replace.hpp>

// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");

// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");

A: For completeness, here's how to do it with std::regex.
#include <regex>
#include <string>

int main()
{
    const std::string s = "example string";
    const std::string r = std::regex_replace(s, std::regex("x"), "y");
}

A: For simple situations this works pretty well without using any other library then std::string (which is already in use).
Replace all occurences of character a with character b in some_string:
for (size_t i = 0; i < some_string.size(); ++i) {
    if (some_string[i] == 'a') {
        some_string.replace(i, 1, "b");
    }
}

If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://stackoverflow.com/a/29752943/3622300

A: here's a solution i rolled, in a maximal DRI spirit.
it will search sNeedle in sHaystack and replace it by sReplace,
nTimes if non 0, else all the sNeedle occurences.
it will not search again in the replaced text.
std::string str_replace(
    std::string sHaystack, std::string sNeedle, std::string sReplace,
    size_t nTimes=0)
{
    size_t found = 0, pos = 0, c = 0;
    size_t len = sNeedle.size();
    size_t replen = sReplace.size();
    std::string input(sHaystack);

    do {
        found = input.find(sNeedle, pos);
        if (found == std::string::npos) {
            break;
        }
        input.replace(found, len, sReplace);
        pos = found + replen;
        ++c;
    } while(!nTimes || c < nTimes);

    return input;
}

A: I think I'd use std::replace_if()
A simple character-replacer (requested by OP) can be written by using standard library functions.
For an in-place version:
#include <string>
#include <algorithm>

void replace_char(std::string& in,
                  std::string::value_type srch,
                  std::string::value_type repl)
{
    std::replace_if(std::begin(in), std::end(in),
                    [&srch](std::string::value_type v) { return v==srch; },
                    repl);
    return;
}

and an overload that returns a copy if the input is a const string:
std::string replace_char(std::string const& in,
                         std::string::value_type srch,
                         std::string::value_type repl)
{
    std::string result{ in };
    replace_char(result, srch, repl);
    return result;
}

A: This works! I used something similar to this for a bookstore app, where the inventory was stored in a CSV (like a .dat file). But in the case of a single char, meaning the replacer is only a single char, e.g.'|', it must be in double quotes "|" in order not to throw an invalid conversion const char.
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int count = 0;  // for the number of occurences.
    // final hold variable of corrected word up to the npos=j
    string holdWord = "";
    // a temp var in order to replace 0 to new npos
    string holdTemp = "";
    // a csv for a an entry in a book store
    string holdLetter = "Big Java 7th Ed,Horstman,978-1118431115,99.85";

    // j = npos
    for (int j = 0; j < holdLetter.length(); j++) {

        if (holdLetter[j] == ',') {

            if ( count == 0 )
            {
                holdWord = holdLetter.replace(j, 1, " | ");
            }
            else {

                string holdTemp1 = holdLetter.replace(j, 1, " | ");

                // since replacement is three positions in length,
                // must replace new replacement's 0 to npos-3, with
                // the 0 to npos - 3 of the old replacement
                holdTemp = holdTemp1.replace(0, j-3, holdWord, 0, j-3);

                holdWord = "";

                holdWord = holdTemp;

            }
            holdTemp = "";
            count++;
        }
    }
    cout << holdWord << endl;
    return 0;
}

// result:
Big Java 7th Ed | Horstman | 978-1118431115 | 99.85

Uncustomarily I am using CentOS currently, so my compiler version is below . The C++ version (g++), C++98 default:
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

A: This is not the only method missing from the standard library, it was intended be low level.
This use case and many other are covered by general libraries such as:

*

*POCO

*Abseil

*Boost

*QtCore
QtCore & QString has my preference: it supports UTF8 and uses less templates, which means understandable errors and faster compilation. It uses the "q" prefix which makes namespaces unnecessary and simplifies headers.
Boost often generates hideous error messages and slow compile time.
POCO seems to be a reasonable compromise.

A: How about replace any character string with any character string using only good-old C string functions?
char original[256]="First Line\nNext Line\n", dest[256]="";
char* replace_this = "\n"; // this is now a single character but could be any string
char* with_this = "\r\n"; // this is 2 characters but could be of any length

/* get the first token */
char* token = strtok(original, replace_this);

/* walk through other tokens */
while (token != NULL) {
    strcat(dest, token);
    strcat(dest, with_this);
    token = strtok(NULL, replace_this);
}

dest should now have what we are looking for.


text:
Q: Microsoft technology similar to Java EE servlets? I have a java application which runs under Tomcat.  Fairly simple architecture - users invoke a servlet through HTTP which then puts a request onto an in memory queue.  A consumer thread which was started as a ServletListener and is running continuously polls the queue and processes the requests which includes calling some stored procs and sending some data over socket connections to backend systems.
I may need to port the code over to C#.  What I am trying to figure out is what is the equivalent technology in Microsoft land which will allow me to architect the same system.  The porting of the code from Java to C# will be trivial, but what I can't seem to find is an application server technology from MS which will allow me to drop in my code and then declaratively specify that I want a new "servlet" for each HTTP call, and that I need to run a "daemon" thread in the same process, etc...
Any advice?  I am not very familiar with the MS landscape...

A: See what-are-the-correspondent-of-servlet-and-applet-in-net. The accepted answer says:

In .Net, HTTP handlers (.ashx) are probably the closest thing to a servlet.

A: I'm betting it's System.Net.HttpListener:
http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
But I'm not a .NET guy yet, either.

A: If you're unfamiliar with the Microsoft environment then don't expect to learn things quickly, since running a web site/service is far more complex than most people think. That is, if you want to run a secure environment.
First of all, I do wonder why you're moving to C# and IIS. Apache runs perfectly on Windows too, and it wouldn't surprise me if you can get everything running in the same way on a Windows system.
But if you do want to move towards C# and Windows development, start by reading some technical books first! O'Reilly has some excellent books about C# and .NET, including titles like "Learning WCF", "Programming Entity Framework" and "Programming ASP.NET 3.5" which should provide enough information for moving to .NET.
However, it will be different from what you're used to. The design patterns are similar, the names and techniques do differ though.
I'm not a Java guy, though. So I don't know what it is you want to do here...Looking at your comment and desires, it seems that what you're building is a messagequeue system, where requests are sent to a queue on the server, waiting to be resolved. Windows has some good build-in functionality for that, although it might not be exactly what you're looking for. Still, the principle would be simple: the web interface will add requests to the queue and a Windows service (not a WEB service) will query the message queue for new requests to process these. It makes porting your code from Java to C# a lot less trivial, though!

About the equivalent of servlets in ASP.NET, I think gimel is partly right. An HTTP handler will allow you to generate any kind of response, including non-html pages. I've used them in the past to return data in XML or Excel format to the user. I've also used them to generate dynamic images with additional watermark. But a data service (.svc) might also be a good alternative. (I use one as a RESTful service around an Entity model.) Or just a regular web service(.asmx) could be as practical.
.NET and Java aren't easy to compare at this level. Each has a lot of it's own techniques to handle things. I'd almost think the equivalent of servlets is ASP.NET itself, not a subpart.

A: The vendor, who will make standardized, transactional, container based .NET server with all Java EE concepts like Servlets, MDBs and resource connectors working with less than 1 million config files will win.


text:
Q: Flickr photo search API with space in search string I am trying to find a way to search photos using text parameter but with a space in the search string.
I want to search for 'Zera zera' which is scientific name of a butterfly and I want the search to be precisely both the words with a space between them rather than just a word Zera which could return me 1000s of photographs with people having zera as part of their names.
Is there any way to do this in Flickr API?

A: Instead of querying for "Zera zera" query for "Zera zera species" and see the results.


text:
Q: How to add new contentType in postman I want to send a POST which requires -ContentType 'application/json-patch+json'.
I have tried this

and when I check the code snippet generated by postman
$headers.Add("ContentType", "application/json-patch+json")
...
$response = Invoke-RestMethod 'https://dev.azure.com/myOrg/myProject/_apis/wit/workitems/$task?api-version=6.0' -Method 'POST' -Headers $headers -Body $body

This invoke-restmethod is missing -ContentType 'application/json-patch+json' and will return 400 Bad Request
If I add it manually it will work.
#$headers.Add("ContentType", "application/json-patch+json")
...
$response = Invoke-RestMethod 'https://dev.azure.com/myOrg/myProject/_apis/wit/workitems/$task?api-version=6.0' -Method 'POST' -Headers $headers -Body $body -ContentType 'application/json-patch+json'

How do I add this in postman?

A: You should add on Headers section (Postman) the below:
Content-Type --> application/json

Attaching also a guide for REST api triggering on Azure DevOps through POSTman
https://blog.geralexgr.com/cloud/trigger-azure-devops-build-pipelines-using-rest-api


text:
Q: Calculate and Display % Discount for price classes Javascript I am looking for help with javascript. We are trying to calculate and display the difference in percentage between a price before discount and a price after discount. The relevant classes are .from_price and .for_price. The prices look like this 160,00 and 130,00.
So we were trying with this code, but is doesn't work:
var price = (Math.round($(".from_price").html())).toString();
var sale = (Math.round($(".for_price").html())).toString();
var korting = (Math.round(((sale - price)/price)*100)).toString();
$("#discount").html("You receive" + korting + "%" + " " + "discount");
}

Thanks so much for your help!

A: This is because you're using string values to get your discount value. You can transform 160,00 to 160 using parseFloat()

function getDiscount() {
  var price = parseFloat($(".from_price").html());
  var sale = parseFloat($(".for_price").html());
  console.log(price);
  console.log(sale);
  var korting = (Math.round(((sale - price)/price)*100));
  $("#discount").html("You receive" + korting + "%" + " " + "discount");
}

160,00

130,00

<button type="button" onclick="getDiscount()">get discount</button>

A: Don't use classnames as element selectors (what if your document contains multiple elements with class .from_price?). Don't depend on innerHTML for your (numeric) values. Using data-attributes for the pricing values gives you full control over it. I'd suggest to use css and a data-attribute to display the discount percentage. Finally, you don't really need jQuery for it.
Here's a simple (html in dutch) snippet to play with

(() => {
  const price = +document.querySelector("[data-fromprice]").dataset.fromprice;
  const sale = +document.querySelector("[data-forprice]").dataset.forprice;
  const discountPercentage = ((1-(sale/price)) * 100).toFixed(0);
  document.querySelector("[data-discount]").dataset.discount = discountPercentage;
})();
[data-discount]:before {
  content: attr(data-discount)'%';
  color: red;
  font-weight: bold;
}

Van €160,00

Voor €130,00!

Uw korting:

A: Here is an example:

var price = +((Math.round($(".from_price").html())).toString());
var sale =  +((Math.round($(".for_price").html())).toString());
var korting = (Math.round(((sale - price)/price)*100)).toString();

$("#discount").html("You receive "+ korting + " %discount");

console.log(typeof sale);

100

50

Your problem was that you trying to do calculations with strings this doesn't work like you expect. Therefore, I coerced your strings into numbers with the + sign and parentheses. Here is an example:

const el = document.getElementById('test').innerHTML;

console.log(el);
console.log(typeof el);

const sumString = el + el;

console.log(sumString); // the string 10 gets added to another string of 10 and thus forms 1010

const sumNr = parseFloat(el) +  +(el);  // now the strings are coered to numbers, both parseFloat and  +(yourvar) coerce strings to nubmers.
console.log(sumNr);

10

A: <!Doctype html>

    <input id="price">Price

    <input id="discount">%

    <button onclick="getPrice()">
Get total
</button>

    <input readonly id="total">

</html


text:
Q: Thoroughly understand the concepts and formulas in Linear Algebra In linear algebra(I'm the beginner so far), I feel the concepts and ideas are based on on another, like layer by layer, and there are many relations among the properties.
For example, Matrix Multiplication, AB is essentially the composition of Linear Transformation($A(Bx)=(AB)x$ to manually define AB) , and Linear Transformation is also from Matrix Equation($Ax=b, T(x)=b=Ax$),and Matrix Equation is also from Vector Equation($x_1a_1+...+x_na_n=b$ equivalent to $Ax=b$),and finally Vector Equation is the basic System of Linear Equations.
so Vector Equation could be intuitively understood as Linear System,Matrix Equation is just another formation。 Linear Transformation is fine too,but when it comes to Matrix Algebra, like Inverse Matrix and its properties, it seems very hard to be intuitively understood through the basic System of Linear Equations. It'll be only fine when I admit the manually definition the matrix multiplication from composition of linear transformation. Because as the process moves on, it's more and more like everything is constructed layer by layer, and more and more complicated as it's very hard to try to understand it from the very basic layer (e.g. linear system) intuitively.
I'm not sure whether it's the normal situation, because there are also intersected properties among many 'layers'. Therefore the whole 'knowledge structure' is not very clear in my brain.
And, when I think of the the basic Quadratic Formula in elementary algebra, , its meaning is just to solve the quadratic equation with one variable, and then it is proved from completing square of $ax^2+bx+c=0$ to find general formation of $x$. But it is still impossible to 'understand thoroughly' from the original equation like how the relation among each variable and coefficient. So when I need to use it, I just refer to the book or prove it myself (assume if I forget)
So will it the same thing as learning the Linear Algebra, like the determinant of matrix,  $\det A = \sum_{j=1}^{n}(-1)^{1+j}a_{1j}\det A_{1j}$. Is it okay that what I need to do is only to know two things,

*

*What it really is.

*How to prove it.
(When I use it, just refer to book or prove it, however, prove the determinant takes a little long time). Because this formula ($\det A$) is already impossible to be thoroughly understood from the very basic 'layer' like system of linear equations or even vector equation. I only know, Firstly its meaning is to determine whether a matrix is invertible (because invertible matrix must has $n\times n$ size and has pivot position in each row and no zeros in diagonal entries.), Secondly it's proved from $n\times n$ matrix row reduced to echelon form, then the right-bottom corner must be nonzero, the above formula is just the brief formation of the item in right-bottom corner.
I know this two things,could I say I'm already understand it ?  Because even though I know 1.what is really is and 2.how to prove it, but I'm still not able to remember it when use it.

A: I think you're on the right track when you say you want to get a better intuitive understanding of what's going on.
Let's start with a geometric interpretation for the determinant of a matrix:
Given an $n$-by-$n$ square matrix $A$ consisting of column vectors $v_1,v_2,\dots,v_n$, the volume of the parallelotope spanned the $n$ vectors is the absolute value of the determinant, $|\det(A)|$.
Now think of the matrix $A$ as a linear map from the $n$-dimenesional real vector space $\mathbb R^n$ to $\mathbb R^n$ given by $v \mapsto Av$ for $v \in \mathbb R^n$.  Consider the unit cube $[0,1]^n=[0,1]\times\dots\times[0,1]$ in $\mathbb R^n$.  The image of the unit cube under that linear map $v \mapsto Av$ will just be the parallelotope spanned by the $v_1,v_2,\dots,v_n$ which were the column vectors of $A$.  Note that if $\det(A)=0$, then the volume will be zero.
This can tell us something intuitive about the invertibility of the linear map given by $A$.  Think about what the image of the entire space $\mathbb R^n$ is under the map given by $A$ (what's also called the "range" of the map).  It will either be all of $\mathbb R^n$, or some proper subspace of $\mathbb R^n$.  Observe that the map given by $A$ is invertible if and only if the range of the map is all of $\mathbb R^n$.  Indeed, if the range were not all of $\mathbb R^n$, then the map has "squashed" $\mathbb R^n$ into some subspace of smaller dimension, so you'll have a many-to-1 map rather than 1-1, so it won't be invertible.
What does this have to do with the determinant?  If $\det(A)=0$, then the volume of the image of the unit cube is zero, so the unit cube must have been "squashed" by the map into a subspace of smaller dimension.  You can then extrapolate this reasoning to see that if $\det(A)=0$, then the image of the whole space $\mathbb R^n$ will also be "squashed" into a proper subspace, so the map won't be invertible.  Conversely, if $\det(A)\neq0$, then the volume of the image of the unit cube is greater than zero, and some thought might convince you that then the image of the whole space $\mathbb R^n$ in be all of $\mathbb R^n$, so that map will be invertible.
Thus, to summarize our intuitive argument:
matrix $A$ is invertible $\Leftrightarrow$ map on given $\mathbb R^n$ by $A$ is invertible $\Leftrightarrow$ image of the map is all of $\mathbb R^n$ $\Leftrightarrow$ the volume of the image of the unit cube is $>0$ $\Leftrightarrow$ $\det(A) \neq 0$.
The next step to understanding the determinant is to think about what "signed volume" should mean, what kind of properties it should have, and then work backwards from those properties to get the usual formulas for the determinant.  A great discussion of this in in Chapter 5 of Peter Lax's Linear Algebra and its Applications.

A: À la Sheldon Axler, determinants are a horrible way of teaching linear algebra. I agree with him as well but sometimes determinants are convenient. They way you should learn linear algebra and matrices (at least to me) is to imagine a matrix as being some kind of linear map between two vector spaces of finite dimension (If you do not know what a vector space is, or for that matter the dimension of a vector space you can look at wikipedia).
What you need to know is this: A matrix being square is a necessary but not sufficient condition for a matrix to be invertible. Why? Well firstly I should say that the dimensions of a matrix determine the dimensions of the vector spaces in question. For example, if $T : V \rightarrow W$, where $V$ and $W$ are of finite dimension $n$ and $m$ respectively then your matrix is going to be of size $m \times n$ (Think about it in terms of how you multiply matrices with column vectors).
Prove the following: Every linear map between two finite dimensional vector spaces can be represented by a matrix.
Now perhaps in your class they have done row reduction, reducing a matrix into row-reduced-echelon form. Then perhaps you would have been told of the formula:
Number of columns in a matrix = number of pivot columns + number of columns with free variables.
This can be restated as follows: If $T$ is a linear map from $V \rightarrow W$, then dim $V = $ dim null $T$ + dim im $T$.
With this formula alone, prove that if either the dimensions of the two spaces $V$ and $W$ in question are not equal, the map is either not injective or not surjective. If you don't know what these mean, you can look at the wikipedia link here. For example, it dim $V > $dim $W$, then by the formula I stated above,
$\begin{eqnarray*} \text{dim null} T &=& \text{dim} V - \text{dim im} T \\
&>& \text{dim} W - \text{dim im} T \\
&\geq& 0. \quad \quad (\text{Why?})
\end{eqnarray*}$
So there is not only the trivial solution to the equation $Ax = 0$, where is the matrix represented by the linear map $T$, which is equivalent to saying that the map is not injective. A similar result can be proven for the case when dim $W > $ dim $V$. This relates back to what I said on a matrix being square being a necessary but not sufficient condition for it to be invertible.
So prove that a matrix is invertible iff it is surjective and injective. In fact proving that the following 3 statements are equivalent would be of great help to your understanding:
Let $V$ and $W$ be finite dimensional vector spaces.
$\textbf{1.}$ There exists an invertible linear map from $V$ to $W$, call this $T$.
$\textbf{2.}$ The dimension of $V$ is equal to the dimension of $W$.
$\textbf{3.}$ The map $T$ is surjective and injective.
So really, all the properties of whether a linear system has a unique solution or not reduces to checking the dimensions of the null space, image, etc.
To give you an idea how to see connections:
Consider the linear system $Ax = 0$. This is equivalent to finding the null space of the linear map represented by the matrix $A$, which is equivalent to asking if the columns of $A$ are linearly independent (What does it mean to multiply a matrix by a vector?)
In three dimensions at least, three vectors being linearly independent is the same as saying that the parallepiped formed by the three vectors is not squashed, which is the same as saying that the determinant of $A$ is non-zero.
After a while, some connections will be seen and your eyes will light up!
I hope that helped!
$\textbf{Edit:}$. To answer your question on why the right most element last row of a matrix in reduced-row echelon form must be non-zero to have at least one solution, think about it in terms of dimensions.


text:
Q: PDOException::("SQLSTATE[HY000] [2002] Connection refused" in laravel I have successfully installed Laravel and it running in a http://127.0.0.1:8000/. when I run the php artisan migrate it gives me the following error.
PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=plantshop", "root", "", []) /Projects/blog/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
I can able to access my php myadmin using http://192.168.64.2 port but not by http://127.0.0.1:8000/ and one more thing is I have a lamp/htdocs/abc directory if I go to this link the page is not displaying and it says
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
I have tried changing the port number and directly pointed unix_socket to php myadmin but none of its working. what is wrong with my configuration? I am using a mac, could anyone help me out?
my .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=plantshop
DB_USERNAME=root
DB_PASSWORD=

Databse.php
'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,

            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

A: You're searching for the database at the address 127.0.0.1, but you most likely configured it to use address 192.168.64.2. In your .env, you need to direct DB_HOST to your actual DB server, in this case, 192.168.64.2.

A: In your case MySQL server is not running. Please restart the MySQL server, The issue will resolve.
if you are using an ubuntu server then run the below command.
sudo /etc/init.d/mysql start


text:
Q: Is possible to manage computing power on Google Earth Engine? I'm new to Google Earth Engine and I can't modify or choose the computing power like the Compute Engine service on Google Cloud Platform.
It's this possible! Thanks!

A: Generally, no. Earth Engine is a shared service — your computation runs on the same machines as everyone else's.
Your main choice is between whether you use the interactive API with things like print, evaluate, interactive maps, etc. or whether you use exports which can run for much longer times and with more resources. But your first step should always be to ensure that your code is written to run efficiently and makes use of Earth Engine's strengths.


text:
Q: Android AlertDialog with AutoCompleteTextView and soft input I have a simple Xamarin.Android application that just displays an alert dialog with an AutoCompleteTextView
    protected override void OnCreate(Bundle savedInstanceState) {
        base.OnCreate(savedInstanceState);
        var arr = new string[] { "Test", "Other Item", "Test 2", "Item Test" };

        AutoCompleteTextView tv = new AutoCompleteTextView(this);
        tv.Threshold = 2;
        tv.Adapter = new ArrayAdapter(this, Resource.Layout.support_simple_spinner_dropdown_item, arr);

        Android.App.AlertDialog.Builder d = new Android.App.AlertDialog.Builder(this);
        d.SetView(tv);
        d.Create().Show();
    }

When it opens everytihing is fine...

However when I start to type in and the autocomplete dropdown appears, the view gets shifted down as if the soft input was closed...

And now the fun part, changing the package name from
com.companyname.test_app to
com.companyname.test_app_1
fixes it...

What is causing this and how to fix it?
E1: Rewrote the code into Kotlin and deployed it. Android studio warned me that an app with the same pacakage name exists, do I want to uninstall? -> Yes. Launches but the same problem occurs.
E2: From the discussion below. I tried:

*

*Explicitly setting the soft input mode as an attribute.

*Explicitly setting the soft input mode in the Manifest.

*Setting in on the dialog .Window property

*On the .Window property of the Activity

*On dialog .Window as Support.V7.App.AlertDialog
E3: Running the same code in android emulator works... but that was expected.
E4: Tried CCleaner to remove all Mono runtimes and other packages that are added by Xamarin. Did not work.
E5: Tried FragmentDialog, did not do a thing...
E6: So I decided to reinvent the wheel...
EditText + PopupWindow but the popup window was rendering above the soft input method, for that I found that setting
popupWindow.InputMethodMode = InputMethod.Needed;
is causing it! A breakthough. Now why is this persistent in a package?


text:
Q: How to know the height the space left on a browser by the menus, bookmarks and tabs? I want make a page (HTML + CSS) that fits all the space left on the browser without horizontal and vertical scrollbars.
Now you are readind this question on a web browser and, probably, you can see horizontal scrollbar. I want to use this space without using horizontal and vertical scrollbars.

A: I think you are looking for window.innerWidth and window.innerHeight and its friends.
Check out this great table on quirksmode.org for an overview on which variables are supported by which browser.
Edit: Pure CSS
In CSS you have width: 100% and height: 100%. If those work for your scenario, use them. To avoid scroll bars, you can use overflow: hidden on the body, but be very careful because this prevents scrolling completely. It depends on what you want to do.