text:
Q: Action buttons in ASP.NET Core 2.2 razor view Suppose we're redesigning the view below:

The current code is:
@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Url)

            Edit |
            Details |
            Delete

}

Our goal is to remove the Delete view that is linked in each row. Instead we would like to have a delete button that deletes the row upon confirmation without leaving the Index page (reload is fine).
How would one go about implementing such button? And is there any relevant documentation?

A: You can use ajax to issue a delete request so that user can stay during the deletion process. Once the ajax request is successful,you can remove the table row from the UI.
First, add a new attribute to your anchor tag, which you can use for your jQuery selector to wire up the click event.
Delete

Here I added an attribute called ajaxy
Now we will listen to the click event on anchor tags with this ajaxy attribute, stop the normal behavior( navigating to the href attribute value URL) and instead make an ajax call. To do the confirmation, you can use window.confirm API.
@section Scripts
{

}

Assuming your Delete action accepts the Id parameter.
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
   // to do : return something
}

A: If you just want to remove the extra 'delete' view, you can move the delete code from the delete page tot he index page and use a simple html-form. e.g.
<form method="post" asp-page-handler="Delete" class="btn-group-sm" >
    Edit
    Details
    <input type="hidden" asp-for="@item.Id" />
    <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you wish to delete this q-Section?')" />
</form>

Rename the 'OnPost' function to 'OnPostDelete' and it will work. You can do the same for the 'delete' button on the details page.
Regards Ken.


text:
Q: JS Support Ticket - Auto create WP account Maybe you guys know if it's possible to create an account when a new user creates a ticket. At this point there are 2 options.

*

*Let user create a ticket based on e-mail address

*Let user create an account first

It would be nice if people don't need to create an account manually.
So if they fill in all the fields, an account will be created based on their e-mail address and receive login details for future use.

A: wp_create_user is your friend!
It takes a username, password, and email:
wp_create_user( $username, $password, $email );

And here's an example:
$user_id = username_exists( $user_name );
if ( !$user_id and email_exists($user_email) == false ) {
    $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
    $user_id = wp_create_user( $user_name, $random_password, $user_email );
} else {
    $random_password = __('User already exists.  Password inherited.');
}

Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new ticket is created, be it a webhook or an action depending on how tickets are implemented.
You can find more information, including examples here

A: As I understand your case, you should try Catchers Helpdesk plugin
Then your customer send you a ticket, the plugin creates an  user account and front end. The user will be notified by e-mail.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting to local machines through OpenVPN I've now done quite some research on this topic and could not come up with a viable solution so far. There have been many questions, most of them not quite matching my issue, and only few answers. So, I hope to get some help here. Here's the setup:
My local network uses the adress range 10.1.0.0/24 with 10.1.0.1 being the router, and 10.1.0.2 being the machine I'm trying to access from outside the network.
The router runs dd-wrt firmware and is configured to be an OpenVPN server with a vpn address range of 10.2.0.0/24. In the servers configuration, I'm trying to push the route to my local
network via:
push "route 10.1.0.0 255.255.255.0"

I can establish a working OpenVPN connection from my client at work and the route get pushed correctly:
$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         ds9-ds10.gate.u 0.0.0.0         UG    302    0        0 wlan0
10.1.0.0        10.2.0.1        255.255.255.0   UG    0      0        0 tun0
10.2.0.0        *               255.255.255.0   U     0      0        0 tun0
10.20.4.0       *               255.255.254.0   U     0      0        0 wlan0
10.20.4.0       *               255.255.254.0   U     302    0        0 wlan0

I can also ssh into my router or use its web-interface using either its regular ip 10.1.0.1 (which is only possible when pushing the route) or its vpn ip 10.2.0.1.
Ip forwarding is enabled on the router:
# cat /proc/sys/net/ipv4/ip_forward
1

I thought I should now be able to ssh to the other machine (which is configured to accept connections from 10.1.0.0/24 and 10.2.0.0./24 addresses) using its lan ip 10.1.0.2, as all connections to 10.1.0.0/24 should now be routed via the 10.2.0.1, still I can't get a connection.
I cannot see the missing bit in my setup, probably somewhere in the router. Why does my request to connect to 10.1.0.1 (local address range) work but the request for 10.1.0.2 does not reach the machine connected to the router?
EDIT:
I was unaware of the issue @MariusMatutiae pointed out. I've read about needing a static route on a couple of occasions but it was never clear where and what to add, I've to admit that my knowledge about the finer details is quite limited. The clarification in his reply makes perfect sense however. Following his suggestions I have modiefied the routing table on the router to now include
10.2.0.0        10.2.0.1        255.255.255.0   UG    0      0        0 tun2

leading to the following table:
root@DD-WRT:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         188-193-191-254 0.0.0.0         UG    0      0        0 vlan2
10.1.0.0        *               255.255.255.0   U     0      0        0 br0
10.2.0.0        10.2.0.1        255.255.255.0   UG    0      0        0 tun2
10.2.0.0        *               255.255.255.0   U     0      0        0 tun2
127.0.0.0       *               255.0.0.0       U     0      0        0 lo
169.254.0.0     *               255.255.0.0     U     0      0        0 br0
188.193.184.0   *               255.255.248.0   U     0      0        0 vlan2

The FORWARD chain of iptables include the lines
pkts bytes target     prot opt in     out     source               destination
   0     0 ACCEPT     0    --  tun2   *       0.0.0.0/0            0.0.0.0/0
   0     0 ACCEPT     0    --  *      tun2    0.0.0.0/0            0.0.0.0/0

above any DROPs or REJECTs with tun2 being the tun device of the OpenVPN server. Should be okay I think.
The issue, however, still remains unsolved. What's wrong?

A: You think that the statement
 push "route 10.1.0.0 255.255.255.0"

is the end of the story, so far as routing goes, but it is not. All this stement does is make the client aware of the existence of a private LAN, 10.1.0.0/24, behind the VPN server. However, the VPN server itself is not aware of the existence of the VPN network 10.2.0.0/24 because no one instructed it to add a suitable route to its table. This is the reason of your problems: in fact, your client can connect to the members of the LAN, but it never receives a reply because the router does not know how to route back its replies to the VPN client.
The way out of that is either to add this command to the router,
 route add -net 10.2.0.0/24 gw 10.2.0.1

or
 route add -net 10.2.0.0/24 dev tun0

or (after having tested that this is the only problem you have) to add this statement to your server.conf file:
 route 10.2.0.0 255.255.255.0

You need this statement as well as the statement
 push "route 10.1.0.0 255.255.255.0"

You may be surprised that the router does not know the route back to the VPN client, because you are thinking that router and VPN server are the same machine, but this is exactly the explanation why the router does not know what the server is doing: the general case is the one where the two are hosted by two different machines. In this case, you do not wish to alter the routing table of the VPN server, because this would mean that the other pcs on the LAN would not know how to reach the VPN client, and you would have to solve that by changing all the routing tables of all pcs to tell them that the gateway to the VPN is the VPN server, not the router. Instead, what you really wish to do in this case is not to alter the VPN server's routing table, and change instead the router's routing table, so that you do this just once.


text:
Q: Proving the complement of sets Let U be the universe and let A be a subset of U. Then prove:
a. $A$ $\cup$ $A^c$= $U$
b. $A$ $\cap$ $A^c$=$\emptyset$
Proof:
a. Let $x$ $\in$ $A$ $\cup$ $A^c$ $\Rightarrow$ $x$ $\in$ $U$
Then $x$ $\in$ $A$ or $x$ $\in$ $A^c$ $\Rightarrow$ $x$ $\in$ $U$
By definition, the complement of a set $A$ is $A^c$ = $U$ $-$ $A$ where $x$ $\in$ U and $x$ $\notin$ $A$.
It follows that $x$ $\in$ $A$ or $x$ $\in$ U and $x$ $\notin$ $A$ $\Rightarrow$ $x$ $\in$ $U$
Thus it is proven that $x$ $\in$ $U$ and $A$ $\cup$ $A^c$= $U$.
$\blacksquare$
b. Let $x$ $\in$ $A$ $\cap$ $A^c$ $\Rightarrow$ $x$ $\in$ $\emptyset$
Then $x$ $\in$ $A$ and $x$ $\in$ $A^c$ $\Rightarrow$ $x$ $\in$ $\emptyset$
By definition of the complement of A, it follows that $x$ $\notin$ $A$.
The intersection is empty and therefore $x$ $\in$ $\emptyset$.
$\blacksquare$
These are my proofs. If someone could looks over them to see if I missed anything. That'd be greatly appreciated.

A: It seems like you're on the right way, but I think you're confusing different notations or concepts. At the end of (b), you claim $x \in \emptyset$, but $\emptyset$ does not contain any elements.
The definitions of complements, unions ($\cup$) and intersection ($\cap$) give us:
$A^c = \{x: x\notin A\} $
$A \cup B = \{x:x \in A \; or \; x \in B\}$ (both may hold)
$A \cap B = \{x:x \in A \; and \; x \in B \}$.
In (a) you have $A \cup A^c = \{x:x \in A \;\; or \;\; x \in A^c \}$.
If we take any $x \in U$, one of these must hold (by the law of excluded middle). Therefore, $A \cup A^c = U$.
In (b), what you want to do is prove that there are no elements in $A \cap A^C$. Using the definition, you have $A \cap A^c = \{x:x \in A \;\; and \;\; x \in A^c \}$, which does not hold for any $x$ (by the law of non-contradiction). Hence, $A \cap A^c = \emptyset$.


text:
Q: Hosting the PHP API in nginx with a reverse proxy My angularjs application would interact with the REST API using AJAX calls. So I wanted to add a reverse proxy which would allow those calls to work with cross-origin resource sharing(CORS), but they don't make it through.
Here is the API server side configuration:
server {
  listen       80;
  server_name  www.test.com;
  root /data/backend/static/;
  index index.html;
  charset utf-8;

  access_log  /var/log/nginx/backend.access.log  main;

  location / {
    root /data/backend/static/;
    index index.html;
  }

  location /api/ {
    alias /data/backend/api/public/;
    index index.html;
    #try_files $uri $uri/ /api/index.php;
    if (!-f $request_filename)
      rewrite /api/(.*) /api/index.php/$1;
  }

  location ~ \.php($|/) {
    fastcgi_pass   unix:/tmp/php-cgi.sock;
    fastcgi_index  index.php;
    fastcgi_split_path_info ^(.+\.php)(.*)$;
    fastcgi_param   PATH_INFO $fastcgi_path_info;
    #fastcgi_param  SCRIPT_FILENAME  $request_filename;
    fastcgi_param  SCRIPT_FILENAME /data/backend/api/public/index.php;#$fastcgi_script_name;
    include        fastcgi_params;
  }

Here is client side configuration of nginx, according as here:
upstream see_api {
    server    119.119.119.119:80;
}

server {
    listen 80 default_server;

    root /Users/a123/Work/backend_static/src;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        rewrite ^/api/?(.*) /$1 break;

        proxy_pass http://see_api;
        proxy_redirect off;
    }
}

And the result is a 404 error:


text:
Q: SearchView: Keyboard not show button Done android 4.3.
here snippet:
 <android.support.v7.widget.SearchView
        android:id="@+id/searchView"
        style="@style/Widget.AppCompat.SearchView.ActionBar"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginEnd="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginStart="20dp"
        android:background="@drawable/search_view_bg"
        android:imeOptions="actionDone"
        android:maxLines="1"
        android:inputType="text"
        android:theme="@style/SearchViewTheme"
        app:defaultQueryHint="@null"
        app:layout_constraintLeft_toLeftOf="@+id/searchViewContainer"
        app:layout_constraintRight_toRightOf="@+id/searchViewContainer"
        app:layout_constraintTop_toTopOf="@+id/searchViewContainer"
        app:searchHintIcon="@null" />

I want when click on SearchView to show keyboard with Done button. So I set android:imeOptions="actionDone". But it not help:
Here result:

A: Try this
searchview.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchview.setSingleLine(true);

A: The xml for SearchView:
android:imeOptions="actionSearch"
android:inputType="text"

This will show you the search icon.


text:
Q: Using CSS to style my Flex application I'm using flash builder 4.5 to make a website. At the moment I'm trying to work on the layout of my website but I'm facing some problems. First of all my CSS looks like this.
/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

s|Application{
    backgroundColor : #ffffff;
}

mx|LinkButton{
backgroundColor : #000000;
color: #666666;
}

s|Button{
backgroundColor : #666666;
color: #666666;
}

The problem is that neither my buttons nor my linkbuttons obtain the color I have set in the above stylesheet, yet my application backgroundcolor is the color i set it to be in the above css file. So I'm sure the url for my style sheet is correct... this is it:
<fx:Style source="PsyThOn.css"/>

This is what my code looks  like(a fragment)
<mx:LinkButton id="btnHome" width="100" height="30"
                   label="Startpagina" click="goHome(event)"/>
<mx:LinkButton id="btnProfiel" visible="{profielVisible()}" height="30"
                   label="Profiel" click="toonProfiel(event)"/>

Since I'm relatively new to the flex development the problem might be obvious but i can't put my finger on it.
Any help?
Is there maybe another/better way to style a flex application?
Thanks in advance.

A: try using chromeColor
Like this:
s|ActionBar
{
    chromeColor: #229988;
        titleAlign: center;
}

s|ActionBar #titleDisplay
{
    color: #CCCCCC; /* default color is white */
    fontSize: 40;
    fontFamily: "Comic Sans MS";
}


text:
Q: what is the difference in these queries? I was trying to improve on a previously written query . here's that query-
select tq.feature as Feature, tq.Total, pq.Passed
from (
  select feature, count(distinct id) as Total
  from X.results
  where ver = '4.2'
  group by feature
) as tq
LEFT JOIN (
  select feature, count(distinct id) as Passed
  from X.results
  where ver = '4.2' and result = 'pass'
  group by feature
) as pq USING (feature);

This is the query i wrote.But the result seems to be different .Am is missing something here ?
select feature,count(distinct id) as totalcases,
  sum(case when result = 'PASS' then  1 else 0 end) as passed
from X.results
where ver='4.2'
group by feature
order by feature;

I'm a real noob in sql so forgive me if it's something silly ..

A: SELECT feature, count(distinct id) AS Total,
  count(distinct if (result='pass', id, null)) AS passed
FROM X.results
WHERE ver = '4.2'
GROUP BY 1 ORDER BY 1;

This SQL is different from yours, please see the result as below:

A: One way is to group based on both a results and feature and then do another aggregate again on just feature. Something like this.
SELECT
    feature,
    SUM(id_count) totalcases,
    SUM(CASE WHEN result = 'PASS' THEN id_count ELSE 0 END) passed
FROM
(
    SELECT
    feature,
    CASE WHEN result = 'PASS' THEN 'PASS' ELSE 'OTHER' END result,
    COUNT(distinct id) id_count
    FROM x.results
    WHERE ver='4.2'
    GROUP BY feature,CASE WHEN result = 'PASS' THEN 'PASS' ELSE 'OTHER' END
) x
GROUP BY feature
ORDER BY feature


text:
Q: How to Browse ResultSet in thymeleaf? I want to display attributes using thymeleaf from a ResultSet.
for exemple:
I want to show in my views the function's result using thymeleaf.
public ResultSet getIntervenantById(String nomTable, String id,String nomcle) {

        try {
            st = connection.prepareStatement("select * from ? where ? = ?");
            st.setString(1, nomTable);
            st.setString(2, nomcle);
            st.setString(3, id);
            rs = st.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return rs ;
    }

A: See http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html especially http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#model-attributes for your question. You really should start out by learning the basics - Thymeleaf's website provides some good stuff: http://www.thymeleaf.org/documentation.html

A: There are multiple ways to handle this problem.  Here is a quick and dirty one just to display the results.  You can create a List and add it to your model.
Service (MyService):
public static List createList(ResultSet resultSet) throws SQLException {

    ResultSetMetaData metadata = resultSet.getMetaData();
    int numberOfColumns = metadata.getColumnCount();

    List<String> list = new ArrayList<>(numberOfColumns);
    while (resultSet.next()) {
        int i = 1;
        while (i <= numberOfColumns) {
            list.add(resultSet.getString(i++));
        }
    }
    return list;
}

Controller:
@GetMapping("/myPage")
public String getList(Model model) {
   ResultSet resultSet = ...; //however you call this
   model.addAttribute("items", MyService.createList(resultSet); //try block hidden for brevity
   return "myPage";
}

HTML (myPage.html):
<div th:each="item : ${items}">
    <span th:text="${item}">No item</span>
</div>

Another (arguably cleaner) way to do this is to use implement a RowMapper.  I am excerpting some of the code as an example:
public class EmployeeMapper implements RowMapper {
   public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
      Employee employee = new Employee();
      employee.setEmpid(rs.getInt("empid"));
      employee.setName(rs.getString("name"));
      employee.setAge(rs.getInt("age"));
      employee.setSalary(rs.getLong("salary"));
      return employee;
   }
}

Then you may have:
public Employee getEmployee(Integer empid) {
   String SQL = "SELECT * FROM Employee WHERE empid = ?";
   Employee employee = (Employee) jdbcTemplateObject.queryForObject(SQL, new Object[]{empid}, new EmployeeMapper());
    return employee;
}

And you can add these beans to the model and iterate as above.  There is also the BeanPropertyRowMapper for a quick implementation of the RowMapper from Spring.
Though instead of going this route with ResultSets, you may be better off with a JPA implementation and just returning List objects.  It's some more dependencies, but less code for you to maintain in the end.


text:
Q: Container being 'pushed' to centered position of body Good day all.
This is maybe a small thing, but I am unable to find a solution to this.
My #body has the right dimensions to fill up the page, but as soon as I add my .Container class with the same dimensions, it still gets 'pushed' a few pixels.
How do I fully fill up the body with my container?
HTML issue

A: add this to your css
body {
  margin:0;
  padding:0;
}

A: It seems that either your body or your .Container have some extra padding or margin that messes up your layout. Try using a proper CSS Reset to avoid that.

A: From the look of it you haven't reset the default margin on the <body> that browsers apply which is usually 8px.
Try:
body {
    margin: 0;
}

Use a CSS reset to help normalize some of these things across browsers. A popular one is Eric Meyer's Reset CSS.

A: Press F12 on your website and inspect the elements from there. Click on the container and see why it is being pushed. You have one more option you have the opportunity to see directly why it is pushed by clicking with the right button of your mouse in the white space where are the pixels you need to remove and click on inspect element on Chrome. Then you will see in the console what is pushing the container.


text:
Q: Hyper Link Picture Not Working Right I've been trying to work on this code for day's now and it's just not working right even though everything is right. Any help would be fantastic!
FYI : I'm trying to put a hover picture over a over one as a transparent, if you know what I mean!
Full code:

Testing

JSFiddle:  http://jsfiddle.net/za6n3/

A: I noticed in your background image you do not have quotes around your link. I am not sure if this is the problem but if i copy your code into http://www.w3schools.com/css/tryit.asp?filename=trycss_background-image_norepeat and put the link in for your image it works fine.

A: put the background image and the overlay image in the same div

Edit: updated code to add  tag

A: Hello Travis first off lets fix your code.
this is the code i made to fix yours, this is the first file index.php, this file will contain all of your HTML code, none of your CSS.
index.php
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
    <title>...</title>
    <link rel="stylesheet" href="style.css" />

as you can tell we modified your code so that it will properly function, the first thing you can see that is different is the correct HTML structure,
<!DOCTYPE html>

we added this for the simple purpose that any and all HTML document should have this, HTML documents that dont include its default structure usually do not function as they should,
next we add this part of the code,

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
    <title>...</title>
    <link rel="stylesheet" href="style.css" />

we are looking at the meta tags, title tags, and link tag, we have the meta tags with the
attribute http-equiv and inside http-equiv its says content-type and content-language this will tell your web server to tell the browser that you are using this code format for content-type and this is the default language for content-language, next is the title tag which tells the browser to put this as the title of the page e.g. the little title inside each tab, next is the link tag which links our CSS file to our main web page, when coding HTML or CSS it is always proper to put you HTML in one file and your CSS in its own file, it is not improper to put them together but is better practice to make a external stylesheet, only use the inline CSS if absolutely necessary, next we add to the body of our html document

this is were we start to add the elements you see in your web browser, in the HTML language, the only thing outputted to the screen is inside the body, but external sheets or scripts are added in the head, scripts can be in the head or body, but any external link to files needs to be in the head of the document,

the first thing you see different in the body is that there is only display-1 there is no longer 2 display classes, and it is no longer a class but a id, we have also put our img tag in between the a tags, next we add our css file (Read me: the code below is its own file not stored in the index.php)
style.css
html{

}
body{
    background-color:#707070;
}
#body{

}
#body-conainer{

}
#display-1{
    background-image:url('http://www.unwritten-quotes.com/images/bgg.gif');
    background-repeat:no-repeat;
    width:115px;
    height:139px;
    border-radius:20px;
}
.display-border{
    border-radius:20px;
}

the first thing we add to this code is the main structure e.g. what you see above, next we add this code to change the background color
body{
    background-color:#707070;
}

this makes the background color gray, next we add the background image,
#display-1{
    background-image:url('http://www.unwritten-quotes.com/images/bgg.gif');
    background-repeat:no-repeat;
    width:115px;
    height:139px;
    border-radius:20px;
}

this adds the background image and trims the image to fit the border, next we trim the border added within the HTML code

we use this code to trim the border,
.display-border{
    border-radius:20px;
}

and there you have it a fully working copy of what i think you wanted, let me now if this was or was not what you were looking for, i also highly recommend that you learn the HTML and CSS syntax a little better before diving straight in,
here is a good place to start with html and css:
http://www.w3schools.com/
here is a good place to start with php:
http://www.php.net/manual/en/
i hoped this helped you out (=


text:
Q: How to let Laravel know it's AJAX request without jQuery There is a parameter in jQuery $.ajax() function called 'dataType', which i could set to 'json' so Laravel will response json even if validation is failed. So how to get that effect with pure js. I was trying to set header like this:
    xhr.setRequestHeader('Content-Type','application/json');
Here full code:
    var xhr =  new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(this.readyState == 4){
        console.log(this.response);
    }
}
csrf = document.querySelector('meta[name="csrf-
token"]').getAttribute('content');
var formData = new FormData();
formData.append('text','Funy story');

xhr.open('POST','/posttest/',true);
xhr.setRequestHeader('X-CSRF-TOKEN',csrf);
xhr.setRequestHeader('Content-Type','application/json');


text:
Q: Accessing CentOS server from external IP I have been trying to set up a centos 7 server. There is no problem in accessing the server from the same network. But when I try
$ ssh -x user@ipAddressofServer

from an external network, It returns:
ssh: connect to host ipAddressofServer port 22: Connection refused

Can anyone help me with this?

A: You should first make sure OpenSSH server is running and installed on the CentOS server. If it is up and you are trying to connect from outside of the network you might have to portforward the router. You should also make sure that the server has port 22 opened on the firewall by typing "sudo ufw allow 22"


text:
Q: Minimum price selection Situation looks like this:
We have product 'A123' and we have to remember lowest price for it.
Prices for one product comes from random number of shops and there is no way to tell when shop x will send us their price for 'A123'.
So I had SQL table with columns:
product_number
price
shop (from which shop this price comes)

An SQL function for updating product price looks like this (this is SQL pseudo-code, syntax doesn't matter):
function update_product(in_shop, in_product_number, in_price)
    select price, shop into productRow from products where product_number = in_product_number;
    if found then
        if (productRow.price > in_price) or (productRow.price < in_price and productRow.shop = in_shop) then
            update row with new price and new shop
        end if;
    else
       insert new product that we didn't have before
    end if;

the (productRow.price < in_price and productRow.shop = in_shop) condition is to prevent situation like this:
In products table we have
A123 22.5 amazon

then comes info from amazon again:
A123 25 amazon

Thanks to above condition we update price to higher which is correct behavior.
But algorithm fails in this situation: again we have a row in the products table:
A123 22.5 amazon

then comes info from merlin
A123 23 merlin (we don't update because price is higher)

then comes info from amazon
A123 35 amazon

and we update table and now we have:
A123 35 amazon

but this is wrong because merlin earlier has lower price for that product.
Any idea how to avoid this situation?

A: The only way you are going to solve your problem is keep track of the price per shop and then only return the lowest current price.  So for example you would need a table like the one you already have, but when you select out of the table something like:
select min(price)
  from products
  where product_number = :my_product

Personally if it were me, I would keep a time stamp of when you receive the product price updates so you would be able to ascertain when you got the update.

A: To make this work you should maintain a table that contains the following:

*

*Product

*Supplier

*LatestPrice

Then identify the current best supplier by querying that table - you can either do this when requested or when the table is updated either way you simplify the problem at the price of slightly more complex schema and queries
Additional (following comment):
Ok, this is going to mean that you need to store more data - but you don't have a huge amount of choice - the data is required to solve the problem so you either: a) have to update prices from all suppliers concurrently and then choose the best price from that snapshot or b) store the prices as you get them and pick the best price from the data you've got. The former implies a fairly hefty overhead in terms of fetching and processing data whereas the latter is basically a fairly modest storage problem and something any decent databases will cope with easily.

A: Basically, the problem is that you only store the lowest price from 1 vendor. You have to keep records of prices of all vendors, and use a selection query to select the minimum.
For example, If you have:
A123 22.5 Amazon

and you got:
A123 23 Merlin

You have to insert it, even if it is with higher price, because it's a different vendor. So you'll have:
A123 22.5 Amazon
A123 23 Merlin

When you get the new price from Amazon, for example: 25, you just update it. So you'll get:
A123 25 Amazon
A123 23 Merlin

then select the lowest price, Merlin, in this case.


text:
Q: Why, not How: Stata incorrectly identifies var type on large dataset with mixed (string+numeric) values within vars I'm reading in a 5 million observation pipe delimited text file. One column's first 250,000 values are numeric; the remainder are string. The code below has imported the first 250,000 numeric values, declared the variable to be numeric (long), and treated the string values as missing.
import delimited "mixed_types.txt", delimiter("|")
Solution: import all vars as strings and then destring:
import delimited "mixed_types.txt", delimiter("|") stringcols(_all)
destring, replace

My question is, why? The help file for import delimited states, "import delimited will check if the file is delimited by tabs or commas based on the first line of data." Is this rule followed for ascribing var types?

A: That is not expected behavior.
From http://www.stata.com/help.cgi?whatsnew read:

*import delimited has the following fixes:
a.  import delimited, when string data were not present until row
           number 5,000 or higher for a variable in the imported text file,
           incorrectly chose a numeric data type instead of a string data
           type for that variable.  This has been fixed.

You need to update. See help update.
(The same information can be accessed running help whatsnew. The update is for Stata 14.)


text:
Q: Determine error from Logcat - Android Can anyone determine what is going wrong, or give me any clues? I think it is within the current activity (CreateProfileActivity), in this buttonClick method:
public void saveUserClick(View view){
        saveUserDetails();
        insertUserToDB();
        Log.d("yo", "yoyoyo");
        dbHelper.logDataBase();
    }

in particular, this line dbHelper.logDataBase();
Here is that methods declaration:
public void logDataBase(){
        // Getting all clothing items
        Log.d("Get database Items", "Getting all database items");

        List<ClothingItem> allClothingItems = this.getAllClothingItems();
        List<AppUser> allAppUsers = this.getAllAppUsers();
        for (ClothingItem clothingItem : allClothingItems) {
            Log.d("ClothingItem", clothingItem.getIdString());
        }
        for (AppUser appUser : allAppUsers) {
            Log.d("User", appUser.getImagePath());
        }
    }

Here is the Logcat:
12-30 02:39:57.499: D/dalvikvm(277): GC_EXPLICIT freed 5474 objects / 286208 bytes in 138ms
    12-30 02:41:48.227: D/yo(277): yoyoyo
    12-30 02:41:48.227: D/Get database Items(277): Getting all database items
    12-30 02:41:48.227: E/dbHelper(277): SELECT  * FROM ClothingItem
    12-30 02:41:48.247: E/dbHelper(277): SELECT  * FROM AppUser
    12-30 02:41:48.247: D/ClothingItem(277): 1
    12-30 02:41:48.247: D/ClothingItem(277): 2
    12-30 02:41:48.247: D/ClothingItem(277): 3
    12-30 02:41:48.247: D/ClothingItem(277): 4
    12-30 02:41:48.247: D/ClothingItem(277): 5
    12-30 02:41:48.247: D/ClothingItem(277): 6
    12-30 02:41:48.247: D/ClothingItem(277): 7
    12-30 02:41:48.247: D/ClothingItem(277): 8
    12-30 02:41:48.247: D/ClothingItem(277): 9
    12-30 02:41:48.247: D/ClothingItem(277): 10
    12-30 02:41:48.247: D/ClothingItem(277): 11
    12-30 02:41:48.247: D/ClothingItem(277): 12
    12-30 02:41:48.247: D/User(277): content://media/external/images/media/1
    12-30 02:41:48.247: D/User(277): content://media/external/images/media/1
    12-30 02:41:48.247: D/AndroidRuntime(277): Shutting down VM
    12-30 02:41:48.247: W/dalvikvm(277): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
    12-30 02:41:48.267: E/AndroidRuntime(277): FATAL EXCEPTION: main
    12-30 02:41:48.267: E/AndroidRuntime(277): java.lang.IllegalStateException: Could not execute method of the activity
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.view.View$1.onClick(View.java:2072)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.view.View.performClick(View.java:2408)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.view.View$PerformClick.run(View.java:8816)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.os.Handler.handleCallback(Handler.java:587)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.os.Handler.dispatchMessage(Handler.java:92)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.os.Looper.loop(Looper.java:123)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.app.ActivityThread.main(ActivityThread.java:4627)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at java.lang.reflect.Method.invokeNative(Native Method)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at java.lang.reflect.Method.invoke(Method.java:521)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at dalvik.system.NativeStart.main(Native Method)
    12-30 02:41:48.267: E/AndroidRuntime(277): Caused by: java.lang.reflect.InvocationTargetException
    12-30 02:41:48.267: E/AndroidRuntime(277):  at com.btf271.fashionassistant.CreateProfileActivity.saveUserClick(CreateProfileActivity.java:50)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at java.lang.reflect.Method.invokeNative(Native Method)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at java.lang.reflect.Method.invoke(Method.java:521)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.view.View$1.onClick(View.java:2067)
    12-30 02:41:48.267: E/AndroidRuntime(277):  ... 11 more
    12-30 02:41:48.267: E/AndroidRuntime(277): Caused by: java.lang.NullPointerException: println needs a message
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.util.Log.println_native(Native Method)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at android.util.Log.d(Log.java:122)
    12-30 02:41:48.267: E/AndroidRuntime(277):  at com.btf271.dbhelper.dbhelper.logDataBase(dbhelper.java:138)
    12-30 02:41:48.267: E/AndroidRuntime(277):  ... 15 more

The VM appears to shut down after that logDatabase method for some reason. When i comment it out, it doesn't shut down.

A:
Can anyone determine what is going wrong, or give me any clues?

Yes. This first couple of lines tells us that it is in the onClick
 java.lang.IllegalStateException: Could not execute method of the activity
 12-30 02:41:48.267: E/AndroidRuntime(277):  at android.view.View$1.onClick(View.java:2072)

its having trouble finishing that method (possibly due to an infinite loop in my experience).
These lines tell us that you are correct in that it is in the onClick() that you posted
Caused by: java.lang.reflect.InvocationTargetException
12-30 02:41:48.267: E/AndroidRuntime(277):  at
com.btf271.fashionassistant.CreateProfileActivity.
saveUserClick(CreateProfileActivity.java:50)

and this line
Caused by: java.lang.NullPointerException: println needs a message

tells you what the exception is. The next line that references your project
at com.btf271.dbhelper.dbhelper.logDataBase(dbhelper.java:138)

tells you that it is at line 138 of dbhelper.java

A: when you executing following line
dbHelper.logDataBase();

"dbHelper" reference is null. reason may be you didn't initialise it.


text:
Q: Переполнение стека при рекурсии Имеется код:
#include <iostream>
#include <ctime>
#include <limits>

using namespace std;

void generateArray(int *arr, int size);
void showArray(int *arr, int size);
void changeElementsWithRecursion(int *arr, int size, int &i);
void input(int &size);

int main() {
    cout << "Enter the size:" << endl;
    int size = 0;
    while (true) {
        input(size);
        if (size > 0)
            break;
    }
    int i = 0;
    int *arr = new int[size];
    generateArray(arr, size);
    showArray(arr, size);
    changeElementsWithRecursion(arr, size, i);
    cout << "Transformed array:" << endl;
    showArray(arr, size);
    system("pause");
    return 0;
}

void generateArray(int *arr, int size) {
    srand(time(NULL));
    for (int i = 0; i < size; i++)
        arr[i] = rand() % 2;
}

void showArray(int *arr, int size) {
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

void changeElementsWithRecursion(int *arr, int size, int &i) {
    if (i == 0)
        if (arr[1] == 1)
            arr[i] = 0;
    else if (i == size - 1) {
        if (arr[i - 1] == 1)
            arr[i] = 0;
        return;
    }
    else if (arr[i - 1] == 1 || arr[i + 1] == 1)
        arr[i] = 0;
    i++;
    changeElementsWithRecursion(arr, size, i);
}

void input(int &size) {
    while (true) {
        cin >> size;
        if (cin.good())
            break;
        cout << "Wrong input" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

Задача - заменить все элементы массива, граничащие с 1 на 0, при помощи рекурсии. Рассуждал так: если нулевой элемент массива - проверял только следующий элемент, если последний - проверял предыдущий, а в других случаях проверял и следующий и предыдущий. Однако при выполнении выбивает исключение:

Необработанное исключение по адресу 0x003E2509 в Project1.exe:
  0xC00000FD: Stack overflow (параметры: 0x00000001, 0x00C02F9C).

И указывает на строку
void changeElementsWithRecursion(int *arr, int size, int &i) {

В чём проблема?

A:
if (i == 0)
    if (arr[1] == 1)
        arr[i] = 0;
else if (i == size - 1) {

Скобки поставь.
if (i == 0) {
    if (arr[1] == 1)
        arr[i] = 0;
} else if (i == size - 1) {

PS: Отладчик же есть.


text:
Q: How to automatically LeftClick, RightClick and Scroll with C# How do I automatically LeftClick, RightClick and Scroll up or down on my desktop Using C#
I Want the method like so:
public void RightMouseClick(int x, int y) { }
public void LeftMouseClick(int x, int y) { }
public void Scroll(int x, int y, int amount) { }

A: Here's your beautifully written code
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern bool SetCursorPos(int x, int y);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int
    dwExtraInfo);

    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;

    private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
    private const int MOUSEEVENTF_RIGHTUP = 0x0010;

    private const int MOUSEEVENTF_WHEEL = 0x0800;

    private static void Scroll(int Xposition, int Yposition, int amount)
    {
        SetCursorPos(Xposition, Yposition);
        mouse_event(MOUSEEVENTF_WHEEL, Xposition, Yposition, amount, 0);
    }

    private static void LeftMouseClick(int Xposition, int Yposition)
    {
        SetCursorPos(Xposition, Yposition);
        mouse_event(MOUSEEVENTF_LEFTDOWN, Xposition, Yposition, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, Xposition, Yposition, 0, 0);
    }

    private static void RightMouseClick(int Xposition, int Yposition)
    {
        SetCursorPos(Xposition, Yposition);
        mouse_event(MOUSEEVENTF_RIGHTDOWN, Xposition, Yposition, 0, 0);
        mouse_event(MOUSEEVENTF_RIGHTUP, Xposition, Yposition, 0, 0);
    }

bon apetite


text:
Q: @yield and @section problem while loading multiple sections in a single layout I'm new to laravel and I'm learning about blade system.
I want to have a index page with several sections which are defined in different files.
In this case, I have a index.blade.php, and I want to have two sections, one is called "panel" and another section is called "tasks" in my index.blade.php.
The sections are defined and coded in panel.blade.php and create.panel.php.
Also, all the three files are located in "view/todos/" directory.
The code I'm writing is the code below:
index.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    @yield('panel')
    @yield('tasks')
</body>
</html>

For panel.blade.php I have:
@extends('todos.index')

@section('panel')
<!--- Panel Content --->
@endsection

And for create.blade.php I have something like this:
@extends('todos.index')

@section('tasks')
<!--- Task Content --->
@endsection

And finally, in web.php, I have:
Route::get('/todos',function(){
    return view('todos.index');
});

Whenever I try to access the "/todos" address, it just show me a blank page.
I tried several ways by changing the view("todos.index") to view("todos.panel") or view("todos.create"), but it just shows me one of the sections and not the other one.

A: I don't know if I understand you logic well. But seems like you misunderstood how @yield works.
Instead you can use @include like in this part of the documentation : https://laravel.com/docs/7.x/blade#including-subviews
I was thinking of something using the Aliasing Includes subpart a few scroll down from the main part I linked just above.
Tell me if it helped you

A: If someone still need some help with this, let me show how I solved that:
My template
@include('common.header')
    @yield('menu')
    @yield('content')
    @yield('another-stuff')
@include('common.footer')

Extending the template
@extends('common.template')
@section('menu')
    @include('common.menu')
@endsection

@section('content')
    @include('content')
@endsection

@section('another-stuff')
    @include('another-stuff')
@endsection

And the html + php code (menu, content and another-stuff), as you can see, I separated in its own files, making the content management easy. Enjoy! o/


text:
Q: Add select field to media uploader that adds a class to the image I'm looking for a way to add a <select> menu to the media uploader that will have two options: normal image, which will do nothing, and profile image, which will add a CSS class to the image if it is selected.
I have gotten as far as adding the select menu to the uploader, but I don't know how to:

*

*apply a class to the image based on the selected option

*make sure the selected option stays selected

*make sure the selected option can be changed later

This is what I have so far:
function my_profile_image_select( $form_fields, $post ) {
    $form_fields['image-type'] = array(
        'label' => 'Image Type',
        'input' => 'html',
        'helps' => 'Enter "profile-image" to enable profile image caption',
    );

    $profile_image = 'profile-image';
    $normal_image = 'normal-image';
    $form_fields['image-type']['html'] = '<select name="Profile Image Select" id="Profile Image Select">';
    $form_fields['image-type']['html'] .= '<option value="' . $normal_image . '">Normal Image</option>';
    $form_fields['image-type']['html'] .= '<option value="' . $profile_image . '">Profile Image</option>';
    $form_fields['image-type']['html'] .= '</select>';

   return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'my_profile_image_select', 10, 2 );

A: To apply the class you need a custom function to do something with the value of your setting.
To make sure the selected stays selected use the WP selected() function
    $form_fields['image-type']['html'] = "<select name='attachments[{$post->ID}][profile_image_select]'>";
    $form_fields['image-type']['html'] .= '<option '.selected(get_post_meta($post->ID, "_profile_image_select", true), 'default',false).' value="' . $normal_image . '">Normal Image</option>';
    $form_fields['image-type']['html'] .= '<option '.selected(get_post_meta($post->ID, "_profile_image_select", true), 'default',false).' value="' . $profile_image . '">Profile Image</option>';
    $form_fields['image-type']['html'] .= '</select>';


text:
Q: when i choose a video file through JMF, i hear only audio, but video does not work `this is the first class
the jmf video player is put into a panel
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.IOException;
import java.net.URL;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.swing.JPanel;

public class MediaPanel extends JPanel {

public MediaPanel(URL mediaURL) {
    setLayout(new BorderLayout());

    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);

    try {

        Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);

        Component video = mediaPlayer.getVisualComponent();

        Component controls = mediaPlayer.getControlPanelComponent();

        if (video != null) {
            add(video, BorderLayout.CENTER);
        }

        if (controls != null) {
            add(controls, BorderLayout.SOUTH);
        }

        mediaPlayer.start();
    } catch (NoPlayerException noPlayerException) {
        System.err.println("No media Player Found");

    } catch (CannotRealizeException cannotRealizeException) {
        System.err.println("Could not media Player");

    } catch (IOException ioException) {
        System.err.println("Err reading from the source");
    }
}
}

this is the second class that calls the video player in the JPanel to the frame
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class MediaTest {

public static void main(String[] args) {
    JFileChooser filechooser = new JFileChooser();
    int result = filechooser.showOpenDialog(null);

    if (result == JFileChooser.APPROVE_OPTION) {
        URL mediaURL = null;

        try {
            mediaURL = filechooser.getSelectedFile().toURI().toURL();
        } catch (MalformedURLException malformedURLException) {
            System.err.println("Could not create URL for the file");
        }

        if (mediaURL != null) {
            JFrame mediaTest = new JFrame("Media Tester");
            mediaTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            MediaPanel mediaPanel = new MediaPanel(mediaURL);
            mediaTest.add(mediaPanel);
            mediaTest.setSize(300, 300);
            mediaTest.setVisible(true);
        }
    }
}
}

the problem is when I choose a video file, I can only hear the audio, but video does not display/show
please help


text:
Q: How to configue expressjs to serve index.html in production mode? I am trying to deploy my app to my local computer to simulate the deployment process. You call it staging mode or whatever. Tools I used include pm2 and Nginx.
I am able to use my web app when I run my app using pm2 start server.js directly in my project. The client can access the index.html file though a Nginx server. But I think this is not production mode unless I also use --env production.
So I copy all the required files to the dist directory of my project, configured Nginx to serve the static contents, and in my source code, I want to use
app.get('/', function(req, res) {
    res.sendFile('index.html', {root: somePath});
});

to allow the clients to access the index.html file on express server. But I am not sure what to put in somePath? I separate the server side and client side when I deploy my project to the server. For example, my server side is on /usr/path/server but my client side is on /etc/shared/html. If I mess up with the paths I will get a "forbidden" error message from
express when I access index.html.

A: If you want make production-like repeatability during development, then you should implement same functionality with same tools.
Nowadays docker compose is best solution for resolve this issue. As start you should have two container the first with nginx and the second with pm2. Also you should bind/mount volume for static files to nginx.

A: Your code should be like this.
 var path = require('path');
 var virtualDirPath = process.env.virtualDirPath || '';
 var appDir = path.dirname(require.main.filename) + virtualDirPath;

appDir will give the environment directory, from where you can access the html file.
Hope it helps:)


text:
Q: Will LINQ iterate a Stack in LIFO order Will LINQ methods iterate the contents of a Stack (and in my specific case Stack<T>) in LIFO (Last In, First Out) order (ie: the same order one would get popping each element which is the reverse of the order in which they were pushed into the stack). Furthermore, being side-effect free, will it abstain from popping the stack while iterating it?
A simple question, and I would assume Yes & Yes, but one so simple that searching produced great volumes of LINQ and Stack related answers of which none of the innumerable results I browsed specifically answered this case.

A: Yes.
The following experiment show that it does follow the Stack's LIFO order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class DoesLinqIterateAStackInLifo
{
    public static void Main()
    {
        var stack = new Stack<char>();
        stack.Push('s');
        stack.Push('e');
        stack.Push('Y');
        Console.WriteLine(stack.Aggregate(new StringBuilder(), (builder,letter) => builder.Append(letter)));
        Console.WriteLine(string.Join("",stack.ToList()));
        if(stack.Count==3)
        {
            Console.WriteLine("And it will not pop the stack");
        }
    }
}

Output:
Yes
Yes
And it will not pop the stack


text:
Q: StreamPlot symmetry I have a given (quite difficult) electrical field and i want to make a Streamplot.
This are my Functions:
Ey1 := -σ (Log[
  a - x + Sqrt[(-a + x)^2 + (a - y)^2 + (z - d)^2]] +
 Log[-a + x +
   Sqrt[(-a + x)^2 + (a + y)^2 + (z - d)^2]]) + σ (Log[-a -
    x + Sqrt[(a + x)^2 + (a - y)^2 + (z - d)^2]] +
 Log[a + x + Sqrt[(a + x)^2 + (a + y)^2 + (z - d)^2]])

Ey2 := σ (Log[
      a - x + Sqrt[(-a + x)^2 + (a - y)^2 + (z + d)^2]] +
     Log[-a + x +
       Sqrt[(-a + x)^2 + (a + y)^2 + (z + d)^2]]) - σ (Log[-a -
        x + Sqrt[(a + x)^2 + (a - y)^2 + (z + d)^2]] +
     Log[a + x + Sqrt[(a + x)^2 + (a + y)^2 + (z + d)^2]])

Ez1 := σ (ArcTan[((a - x) (-a + y))/((z -
         d) Sqrt[(a - x)^2 + (-a + y)^2 + (z - d)^2])] +
     ArcTan[((a + x) (-a + y))/((z -
         d) Sqrt[(a + x)^2 + (-a + y)^2 + (z -
          d)^2])]) - σ (ArcTan[((a - x) (a + y))/((z -
         d) Sqrt[(a - x)^2 + (a + y)^2 + (z - d)^2])] +
     ArcTan[((a + x) (a + y))/((z -
         d) Sqrt[(a + x)^2 + (a + y)^2 + (z - d)^2])])

Ez2 := -σ (ArcTan[((a - x) (-a + y))/((z +
         d) Sqrt[(a - x)^2 + (-a + y)^2 + (z + d)^2])] +
     ArcTan[((a + x) (-a + y))/((z +
         d) Sqrt[(a + x)^2 + (-a + y)^2 + (z +
          d)^2])]) + σ (ArcTan[((a - x) (a + y))/((z +
         d) Sqrt[(a - x)^2 + (a + y)^2 + (z + d)^2])] +
     ArcTan[((a + x) (a + y))/((z +
         d) Sqrt[(a + x)^2 + (a + y)^2 + (z + d)^2])])

This is my first Plot:
sp3 = Join[Table[{-2.1, y}, {y, -9, 9, 1}],
   Table[{2.1, y}, {y, -9, 9, 1}], Table[{1.34, y}, {y, -9, 9, 1}]];

Show[StreamPlot[{Ez1 + Ez2, Ey1 + Ey2} /. {a -> 10,
    x -> 0, \[Sigma] -> 1, d -> 2}, {z, -15, 15}, {y, -15, 15},
  StreamScale -> Full, StreamStyle -> {Gray, Arrowheads[0.02]},
  StreamPoints -> sp3],
 Graphics[{Black, Thick, Line[{{-2, -10}, {-2, 10}}], Black, Thick,
   Line[{{2, -10}, {2, 10}}]}]]

This is my second Plot:
   sp1 = Join[Table[{-2.1, y}, {y, -9, 9, 1}],Table[{2.1, y}, {y, -9, 9, 1}]];
   sp2 = Table[{-1.9, y}, {y, -9, 9, 1}];

Show[StreamPlot[{Ez1 + Ez2, Ey1 + Ey2} /. {a -> 10,
    x -> 0, \[Sigma] -> 1, d -> 2}, {z, -15, 15}, {y, -15, 15},
  StreamScale -> Full, StreamStyle -> {Gray, Arrowheads[0.02]},
  StreamPoints -> sp1],
 Graphics[{Black, Thick, Line[{{-2, -10}, {-2, 10}}], Black, Thick,
   Line[{{2, -10}, {2, 10}}]}],
 StreamPlot[{Ez1 + Ez2, Ey1 + Ey2} /. {a -> 10, x -> 0, \[Sigma] -> 1,
     d -> 2}, {z, -2, 2}, {y, -10, 10}, StreamScale -> None,
  StreamStyle -> {Gray, Arrowheads[0.02]}, StreamPoints -> sp2]]

As you can see, on the second plot, i have two Streamplots, one for the outside of the plate and one for the inside.
The reason for this is, as you can see in the first Streamplot on the highlighted spots, where i used only one one Streamplot, it seems that close to the plate on the inside, ther are no lines anymore.
On the Second Plot i can place the manual StreamPoints on the inside very close to the Plate (-1.9), so it looks totally symmetric.
On the first Plot i cant place the manual StreamPlots not closer than 1.34, otherwise all lines on the inside vanishs.
Basicly Teh electrical field functions are in both cases the same, its just a second StreamPlot on in use. But with this second StreamPlot i get a total different behavior in the inside of the plates.
Does somebody know why, and is it possilbe to plot it like the second plot, but with only one Streamplot ?
(related topic: How to delete some lines in streamplot)

A: To give an example of what I meant in my comment.
params = {a -> 10, x -> 0, σ -> 1, d -> 2};

ode = {z'[t], y'[t]} == ({Ez1 + Ez2, Ey1 + Ey2} /. {v : y | z :> v[t]} /.
    params);
ics = Show[sp, Graphics[{Red, PointSize@Large,
    Point@Fold[Drop, sp3, {{38}, {20}}]}]];
psol = ParametricNDSolveValue[{ode, {z[0], y[0]} == {a, b},
   WhenEvent[Abs[z[t]] > 15 || Abs[y[t]] > 15, "StopIntegration"],
   WhenEvent[Abs[Abs@z[t] - 2] < 0.01 && Abs[y[t]] < 10, "StopIntegration"]},
  {z, y}, {t, -100, 100}, {a, b},
  Method -> {"ExplicitRungeKutta", "StiffnessTest" -> True},
  MaxSteps -> 10000, MaxStepSize -> 0.1];

sols = psol @@@ sp3; // AbsoluteTiming
(*  {0.402537, Null}  *)

Graphics[{
  Gray, Arrowheads[0.02],
  Arrow[
   Transpose@Through[#["ValuesOnGrid"]] & /@ sols[[1 ;; -1]]
   ],
  {Black, Thick, Line[{{-2, -10}, {-2, 10}}], Black, Thick,
   Line[{{2, -10}, {2, 10}}]}
  },
 PlotRange -> 15, Frame -> True, PlotRangePadding -> Scaled[.02]]


text:
Q: modalpopupextender: button clicked but postback needs to be 'stopped' I have an ASP.NET webforms application in which I want to show a popup only if a user is not logged in. The event that shows the popup is triggered by a button click, the code behind then shows the modal popup if the user is not logged on.
The problem is that the page gets refreshed (posted back), and only then the popup gets shown. What I want to achieve is that the popup show without the page being refreshed.
Any ideas?
Thanks,
Tom

A: 'I want the popup to show without the page being refreshed'
Here's how to make a submit button that only submits when a user is logged in, (by adding client-side validation).  The button will either:
 - provide a popup for a not-logged-in user and do nothing else
or
 - submit/postback for a logged-in user.
  <form ...>
    ...
    <button type="submit" onclick="checkIfUserIsLoggedIn(event);">Submit</button>
    <script type="text/javascript">
    function checkIfUserIsLoggedIn(event) {
        if (userIsNotLoggedIn()) {  //userIsNotLoggedIn() is a js function you'll need to write
            alert("Please log in and re-submit.");
            event.preventDefault();  // prevent submission / postback
            event.stopPropogation(); // prevent submission / postback, probably unnecessary
        }
    }
    </script>
  </form>


text:
Q: Opening a new window with post request in an Asyncronous request I need to send an Async POST request to a page that creates a PDF for me.
I have a PHP page that collects the data, and then sends an async (jQuery) trigger to process the data and convert it to JSON before sending it to another PHP page, always in Async mode.
The problem now is, i'm trying to use window.open to open a local page that creates the actual PDF and returns it to the browser.
Yet, window.open() does nothing, and the debugging console shows no error.
Code that should open the new window:
$_POST['ddt_data'] = $_SESSION['$refinedJSON']; ?>
<script>window.open("ddt_creation.php");</script>
<?php

I tried to open a blank window, nothing changes. The window doesn't open. I have no adblock active.

EDIT 1:
I've changed the code according to the suggestions in the comments below. The new code is now:
$_POST['ddt_data'] = $_SESSION['$refinedJSON'];
echo "BLAM"; ?>
<script>alert(1); window.open("http://192.168.1.220/var/www/html/DDT_creation.php");</script>
<?php

I can see the echo in a return section that i have preparated for Async requests, but the alert box is never shown, and the same applies to the page i'm trying to open.
By checking the response i got from the request, i noticed it had something strange in it. This is the complete response:
BLAM
<script>alert(1); window.open("http://192.168.1.220/var/www/html/DDT_creation.php");</script>

I know JS is working correctly (Using it in other parts of the same file) and i don't understand why the code is not executed immediately and is instead sent with the response.

A: The response of any AJAX request is always treated as text, unless told otherwise in which case the response is treated as the type you choose, for example JSON. This means that any JavaScript code in the response is never executed. You would need to add the code in the response to the page in order for it to get executed, but again, adding JavaScript code to a page by normal  methods like innerHTML wouldn't get the code executed.
Instead, you should place the window.open code in the jQuery AJAX call, or from wherever in the code you have access to the response of the request.
Like so...
$.ajax({
    type: 'GET',
    url: 'http://example.com/',

    success: function(response) {
        window.open('http://192.168.1.220/var/www/html/DDT_creation.php');
    }
});


text:
Q: How exactly do you earn status points? In the Facebook game and mobile app WSOP - World Series of Poker. You can achieve higher status levels (and additional rewards) by gaining over a certain number of status points.
The only thing the game says about these is:

Play & Purchase to earn points and reach the next status!

But what exactly constitutes "playing". Are higher odds better for getting status points? Is it number of hands based or time based or what?


text:
Q: Best sensor for measuring rotation angle? I've come into an existing design that uses a 2D accelerometer chip to measure a board's rotation angle around a shaft.  The board is attached to a motor that drives a gearbox that rotates the shaft, so the motor and board rotate with the shaft.  Deriving the angle and calibration of this device is quite complex, is there a simple part out there that say has a high level serial interface that can just tell me the rotation angle?  Desired accuracy would be < 1 degree.  It's for a solar tracking application so angles are between -85 and 85 degrees, speed of rotation is quite slow.
Thanks if anyone can help,
Fred

A: *

*Rotary encoder

*Optical Encoder

*Discrete hall effects at predefined positions (viable if you only need zonal info - BLDC)

*Linear hall effect sensors either 2off at quadrature & use atan2( via cordic), or 3off at 120deg displacement and use park&clark.

*resolver

I would say for your requirement two optical encoders slightly displaced from one another to increase the angular resolution

A: The simplest way to measure rotation angle and angular velocity is to use Stepper motor. Either it is unipolar or bipolar stepper motor (Bi-polar stepper motor is little difficult from unipolar s/m).
The simplest method:
The Unipolar stepper motor has five wires (Mostly used in 5" Floppy Drive) one for ground and other 4 wires are used to send pulse to the motor for its rotation. If you rotate its shaft by hand in clock wise or anti clock wise direction it generates a pulse on its four (Coil ends) wires with some voltage and current respectively.
The stepper motor which I discussed has 7.5 degrees single step rotation angle. That means when you rotate its shaft to 360 degrees motor generates pulses on its each wires 12 times.
In this way you can easily calculate rotation angle. This is the easiest way and it is also tried by my self.
If you don't know the basics or working of stepper motor.
Here is a good link for you: http://en.wikipedia.org/wiki/Stepper_motor (wikipedia)

A: Effectively your board is isolated from an easy accessible mechanical stationary reference point - which explains why somebody has chosen to use an accelerometer.
From your description - the angle varies in two dimensions in a vertical plane as part of a solar tracker.
So, if you don't mind the mechanical aspect, a "weighted pivoted arm" that always hangs downwards, with a rotation sensor mounted in the plane of rotation, will give you an easy and relatively low cost means of measurement.
The rotary encoder used can be almost any sort -
As simple and cheap as a potentiometer with a weight clamped to the arm,
 Or a gray-coded disk
 Or a magnet fixed to the arm pivoting relative to a GMR or AMR sensor.
 Or an optical sensor
 Or ... .
Due to the relatively low number of cycles a good quality potentiometer could be a good choice, At one whole return cycle per day, 10 years ~= 4000 cycles - low by most pot standards.
`

A: I would say your best bet in terms of your accuracy specification would be to stay with an accelerometer.
You would however be better off by using an accelerometer with a digital interface such as I2C or SPI ( http://www.sparkfun.com/products/9723 ). There are RS232 serial modules available as well ( http://www.sparkfun.com/products/10537 ).
These devices will provide you with digital values with wich you can calculate the angle. As for accuracy, these devices typically come with selectable sensitivy ranges. For the BOSCH BMA180 to which I linked above the settings are as follows: ±1g, 1.5g, 2g, 3g, 4g, 8g and 16g.
Angle calculation is quite easy and is explained in detail here: http://www.instructables.com/id/Accelerometer-Gyro-Tutorial/#step1

$$
R = \sqrt{R_x^2 + R_y^2 + R_z^2}
$$
With Rx, Ry and Rz the G values the device outputs. From there you can calculate the angles Axr, Ayr and Azr:
$$
A_{xr} = arccos(\frac{R_x}{R})
$$
$$
A_{yr} = arccos(\frac{R_y}{R})
$$
$$
A_{zr} = arccos(\frac{R_z}{R})
$$

A: Use an absolute rotary encoder.  If this isn't good for you, explain why.


text:
Q: binary tree in generalized statement I have to implement a Code which accepts a binary tree and shows a generalised Statement: this is my Code
mkBTree xs
    | (m == 0) = Leaf (unwrap xs)
| otherwise = Fork (mkBTree ys) (mkBTree zs)
where m = (length xs) `div` 2
      (ys, zs) = splitAt m xs
              unwrap [x] = x

but the only thing i get is something like:
Data constructor not in scope: Leaf :: a -> t
Data constructor not in scope: Fork :: t -> t -> t

Failed, modules loaded: none.
What is wrong here?

A: I have to implement a Code which accepts a binary tree and shows a generalised Statement: this is my Code                                                                                import Data.Char
       import Data.List
  data mkBTree xs = Leaf xs | Fork (mkBTree xs) xs (mkBTree xs)
  deriving(Eq,Show)

 data mkBTree xs = Leaf xs | Fork xs [mkBTree xs]
   deriving(Eq,Show)

entferneBlaetter :: NBaum a -> NBaum a
entferneBlaetter xs
             | (m == 0) = BBlatt (unwrap xs)
         | otherwise = BKnoten (NBaum ys) (NBaum zs)
         where m = (length xs) `div` 2
                (ys, zs) = splitAt m xs
                    unwrap [x] = x


text:
Q: Why is my function not running? I'm making a page which contains a single circle and a button. Upon pressing the button I want the circle to change to a random color.
Why is my code not running correctly?

$("#button").click(function() {

  $("#thing").css("background-color", function() {

    var color = "#";

    var hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

    while (var i = 0; i < 6; i++) {

      color += hex[Math.floor(Math.random() * 16)];

    }

    alert(color);

    return color;

  });

});

<button id="button">Click to change colour</button>

A: You need to use a for loop here. not a while loop.
for( var i = 0; i < 6; i++) {
     color += hex[Math.floor(Math.random() * 16)];
}

A: You did'nt even made a circle, and you introduced a new syntax for while loop congrats on that
¯_(ツ)_/¯
Well you can have the following code an see what you were doing wrong in there and you do not return anything from click event you set the color rather than returning from there

$("#button").click(function() {

  $("#thing").css("background-color", function() {

    var color = "#";

    var hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
    var i = 0;
    while (i < 6) {

      color += hex[Math.floor(Math.random() * 16)];
      i++
    }
    $(this).css('background-color', color);
    //return color;

  });

});
#thing {
  color: #000;
  width: 100px;
  height: 100px;
  border: 1px solid red;
  border-radius: 50px;
}

<button id="button">Click to change colour</button>

A: A few errors with your code. Hope this helps

$("#button").click(function() {
  $("#thing").css("background-color", function() {
    var color = "#";
    var hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

    for (i = 0; i < 6; i++) {
      color += hex[Math.floor(Math.random() * 16)];
    }

    alert(color);
    return color;
  })
})
#thing {
  width: 20px;
  height: 20px;
  background: #ededed;
  border-radius: 50%;
}

<button id="button">Click to change colour</button>

A: while does not work as you anticipated. The syntax you have would work as for, but not while.
for (let i = 0; i < 6; i++) {
  color += hex[Math.floor(Math.random() * 16)];
}

If you want to use while you can do the following:
let i = 0;
while(i < 6) {
  color += hex[Math.floor(Math.random() * 16)];
  i++;
}

However there is no need for a loop to create a number between 0 and 0x1000000.

/** Creates a color between
 * #000000 and #ffffff inclusive
 */
function createRandomColor() {
  const strHex =
    Math.floor(Math.random() * 0x1000000)
    .toString(16)
    .padStart(6, '0');
  return `#${strHex}`;
}

const $thing = $('#thing');
$('#button').click(() => {
  $thing.css('background-color', createRandomColor());
});
#thing {
  width: 20px;
  height: 20px;
  background: #ededed;
  border-radius: 50%;
}

<button id="button">Click to change colour</button>

I usually write ES6, but String.prototype.padStart is ES2017. If you follow to the doc you can fetch a polyfill.


text:
Q: Como puedo obtener la fecha de hoy desde un string y no el valor completo de este? Tengo una aplication la cual necesito exportar varios valores. En uno de ellos tengo un string que me devuelve una fecha con hora incluida "2/8/2017 10:26:35 AM".
Lo que necesito es extraer esta string pero solamente validando el dia en que se ejecuta el codigo.
Ejemplo:
Si el string tiene "2/8/2017 10:26:35 AM" necesito el valor de "2/8/2017".
He tratado de usar Contains(DateTime.Today) pero no me resulta.
Como puedo lograr esto?
Saludos

A: Si tienes un string así:
string fecha_de_prueba = "2/8/2017 10:26:35 AM";

De la cual solo deseas obtener el día, mes y año, puedes optar por:
Separar el valor del string fecha_de_prueba de la siguiente manera:
string fecha_de_prueba = "2/8/2017 10:26:35 AM";
string fecha_ddmmyyyy = fecha_de_prueba.Split(' ')[0];
// Resultado: 2/8/2017

O, simplificado:
string fecha_de_prueba = "2/8/2017 10:26:35 AM";
fecha_de_prueba = fecha_de_prueba.Split(' ')[0];
// Resultado: 2/8/2017

Para comparar las fechas, puede hacer lo siguiente:
DateTime fecha_actual = DateTime.Today;
// Valor: 08/02/2016 00:00:00

string fecha_de_prueba = "2/8/2017 10:26:35 AM";
DateTime fecha_a_comparar = DateTime.Parse(fecha_de_prueba.Split(' ')[0]);
// Valor: 02/08/2017 00:00:00

// Aquí validas que los días de ambas fechas sean las mismas
// (tal como indicas en tu pregunta).
if (fecha_actual.Day == fecha_a_comparar.Day) {
   // TODO: Ejecutar tu código.
}

A: Si sabes que luego de la fecha siempre viene un espacio en blanco, entonces puedes usar:
string source = "2/8/2017 10:26:35 AM";
var result = source.Split(new Char[] {' '}, 2).First();

A: Trata de la siguiente manera
`string fecha_de_prueba = "2/8/2017 10:26:35 AM";
 string pattern = "M/d/yyyy h:mm:ss tt"
 DateTime date = DateTime.ParseExact(
        fecha_de_prueba,
        pattern,
        CultureInfo.InvariantCulture);
 string newstrDate = date.ToString("M/d/yyyy");

Tambien hay un TryParseExact que valida antes en caso que la fecha pueda no tener el formato

A: Solo por ampliar las respuestas, en mi opinión cuando se trabaja con fechas siempre es mejor utilizar el tipo dedicado a ello,o sea DateTime.
En este caso, lo que yo haría sería comparar la propiedad Date de DateTime, lo que resultaría en algo así:
DateTime dt1 = DateTime.Parse("9/2/2017 10:26:35 AM", CultureInfo.CurrentCulture);
if (DateTime.Now.Date==dt1.Date)
{

}


text:
Q: Implement monkehTweets on Coldfusion Server I've inherited a site running Coldfusion, and I'm trying to get a twitter feed on the site. I've found a tool that seems to do the job, and I've registered my app with Twitter and I have my client and OAuth codes.
The problem is that I'm not familiar enough with Coldfusion to know exactly what code I need to put on the page in question to pull the tweets. This is the library I'm using: https://github.com/coldfumonkeh/monkehTweets
From what I can gather, my code should look something like this:
<cfinvoke
 component = "component_name"
 method="method_name"
 returnvariable="return_variable">
 <cfinvokeargument name="arg1" value="value">
 <cfinvokeargument name="arg2" value="value">
</cfinvoke>

Unfortunately I have no idea what to put in any of those fields. There doesn't seem to be a list anywhere of the arguments OR what you should put in the name, method, and variable fields. All I need is to pull three recent tweets. This probably isn't a standard format for questions on here, but any help from someone who knows Coldfusion would be greatly appreciated. Thanks!

A: I have written a very basic demo to pull out and display information from the authenticated user's timeline.
You need to start with the object instantiation, which it appears you have done: (obviously adding your own OAuth / Twitter details to the init method here)
<cfset objmonkehTweet   =   new monkehTweet.com.coldfumonkeh.monkehTweet(
            consumerKey     =   '',
            consumerSecret      =   '',
            oauthToken      =   '',
            oauthTokenSecret    =   '',
            userAccountName     =   '',
            parseResults        =   true
        ) />

Setting the parseResults value to true will convert the response into a struct or XML object that you can dump in ColdFusion and easily read the values.
Next, make a call to the getUserTimeline() method. If we don't pass any user id or screen name values in to the method call, it will access the timeline for the authenticated user:
<cfset arrStatus = objMonkehTweet.getUserTimeline() />

As no parameters were sent in regarding format, monkehTweet will return the default response as JSON (which, with parseResults set to true, will result in an array of structs).
Now we can start creating the loop. This is very basic, but will help you get up and running.
Define the maximum number of tweets to return:
<cfset totalTweets = 3 />

It's prudent to then check the length of the array (just in case we have less than the desired maximum number of results):
<cfif arrayLen(arrStatus) LT totalTweets>
    <cfset totalTweets = arrayLen(arrStatus) />
</cfif>

Now define a loop, starting at 1 with a maximum of the totalTweet value:
<cfoutput>

<cfloop from="1" to="#totalTweets#" index="tweet">

    <cfset status = objMonkehTweet.entify(arrStatus[tweet]) />

#arrStatus[tweet]['user']['name']#: #status#

</cfloop>

You can now access each specific tweet like so: arrStatus[tweet].
The monkehTweet object contains a helper function called entify which will convert any URLs, user mentions and hashtags into HTML URLs for display. Simply pass in the tweet object and it will return the formatted status for you. You can also reference any object within the response directly, as we have here with the user name value.
To see what is being returned, it's always best to dump out the entire response so that you can see what is available to access and use in your display:
<cfdump var="#arrStatus#" />

I hope that helps get you up and running.


text:
Q: Java DnD : How do I get the drop target component after export is completed? In canImport function, the first parameter defines the target component. However, in exportDone function, the first parameter defines the source component of the Transferable data.
Is it possible to get the drop target component after the data has been transferred via the TransferHandler class without using the mouseRelease listener? If so, how?
Right now, in canImport function, I'm constantly updating a variable which contains the value of target component. It is of course, very inefficient.

A: I guess there really isn't.
BUT The importData function does receive the drop target component like canImport. However, you ALSO need to rewrite how the Transferable data is imported into the drop target. Hence, it isn't executed AFTER export is completed. You can make it look like it does, but you need rewrite a whole load of logic.


text:
Q: getting issues while trying to call api (local host) from real ios device(Mac OS) first, I run the nodeJs server on localhost
then I tried to call API's from my real ios device, but I'm getting issues while connecting with local host

everything in working fine in case of android device and emulator

A: Try binding the backend on 0.0.0.0 if you want to test from a different device, but in the same network. The 0.0.0.0 will listen on all network interfaces where localhost might only listen to your local loopback net device.
You should also point to your network address where the backend is running from your iOS device.

A: You may find this other stack overflow question helpful.
That localhost URL would make the iPhone try to reach out to itself, you need to set that variable to an IP or URL that the iPhone can actually reach out to. You may find it helpful to use a tunnelling service like ngrok which will make an external URL that your server's localhost can be reached at.


text:
Q: Change position of delete button in UITABLE VIEW I am using table view and I am using different cell size, but when I delete the cell, it shows on constant position, not in the middle of the cell. What should I do for custom delete button position?

A: This is really hacky, but I found this snippet of code a while back:
- (void)willTransitionToState:(UITableViewCellStateMask)state {

    [super willTransitionToState:state];

    if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask) {

        for (UIView *subview in self.subviews) {

            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {

                subview.hidden = YES;
                subview.alpha = 0.0;
            }
        }
    }
}

- (void)didTransitionToState:(UITableViewCellStateMask)state {

    [super willTransitionToState:state];

    if (state == UITableViewCellStateShowingDeleteConfirmationMask || state == UITableViewCellStateDefaultMask) {
        for (UIView *subview in self.subviews) {

            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {

                UIView *deleteButtonView = (UIView *)[subview.subviews objectAtIndex:0];
                CGRect f = deleteButtonView.frame;
                f.origin.x -= 20;
                deleteButtonView.frame = f;

                subview.hidden = NO;

                [UIView beginAnimations:@"anim" context:nil];
                subview.alpha = 1.0;
                [UIView commitAnimations];
            }
        }
    }
}

Basically, you are peeling off the subviews until you find the delete button. What I would also suggest is to not show the default delete button and use your own custom delete button.

A: Reload the table in viewWillAppear. It will reload the table after record has been deleted.
[super viewWillAppear:animated];
//  [self.tableView reloadData ];
[tblSimpleTable reloadData];


text:
Q: Solve the Following series I'm trying to solve the following series
$$\sum_{n=1}^\infty \frac{1}{n(3n+1)}$$
More generally, for $k \in \Bbb N$ Im trying to solve
$$\sum_{n=1}^\infty \frac{1}{n(kn+1)}$$
That way I would be able to solve
$$\sum_{n=1}^\infty \frac{1}{n(n+\frac{1}{k})}= k \sum_{n=1}^\infty \frac{1}{n(kn+1)}$$
and by making $k \rightarrow \infty$ I will get a solution for $\sum_{n=1}^\infty \frac{1}{n^2}$ which we know is
$$\sum_{n=1}^\infty \frac{1}{n^2}= \frac{\pi ^2}{6}$$

A: $$
\sum_{n=1}^\infty \frac{1}{n(kn+1)} = \gamma + \psi\left(1+\frac{1}{k}\right)
$$
with digamma function $\psi(x)$ and Euler-Mascheroni constant $\gamma$.
$$
\sum_{n=1}^\infty \frac{1}{n(3n+1)} = 3 - \frac{\pi}{2 \sqrt{3}} - \frac{3}{2}\log(3)
$$


text:
Q: Creating an importable webpack library into Vite I've stumbled upon an issue with a library that I'm trying to integrate into my project. I've decided to fork it to provide the internal components as exports of the library.
For the consuming project I'm using Vite, while the forked project uses webpack.
I've read a bit about library creation in webpack here
https://webpack.js.org/guides/author-libraries/
I've also create a minimal example via vite.
This is my import statement in a vite react app:
import "webpack-numbers";

This works correctly from the webpack docs:
<html>
<head>
    <meta charset="UTF-8">
    <script src="./dist/webpack-numbers.js"></script>
    <script>
        console.log(webpackNumbers.wordToNum('Five'));
        console.log(window.webpackNumbers.wordToNum('Five'));
    </script>
</head>
<body>

</body>
</html>

The webpack config
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'webpack-numbers.js',
        globalObject: 'this',
        library: {
            name: 'webpackNumbers',
            type: 'umd',

        },
    },
};

I'm getting the following error:
Uncaught TypeError: n is undefined
    <anonymous> http://localhost:5174/@fs/home/blewandowski/repositories/personal/webpack-numbers/dist/webpack-numbers.js?t=1672834535153:2
    <anonymous> http://localhost:5174/@fs/home/blewandowski/repositories/personal/webpack-numbers/dist/webpack-numbers.js?t=1672834535153:2

How does one go about consuming these exports in a vite react app?


text:
Q: The "(optional)" marker in cppreference.com documentation Last week, I had a discussion with a colleague in understanding the documentation of C++ features on cppreference.com. We had a look at the documentation of the parameter packs, in particular the meaning of the (optional) marker:

(Another example can be found here.)
I thought it means that this part of the syntax is optional. Meaning I can omit this part in the syntax, but it is always required to be supported by the compiler to comply with the C++ standard. But he stated that it means that it is optional in the standard and that a compiler does not need to support this feature to comply to the standard. Which is it? Both of these explanations make sense to me.
I couldn't find any kind of explanation on the cppreference web site. I also tried to google it but always landed at std::optional...

A: While I found a page that lists all of the marks, I was unable to find a page that specifies what the marks are intended to mean. Still, I might ask your colleague to take a look at some other pages, with the goal of the colleague abandoning the idea that "optional" means "optional to support". (This is not a definitive argument, but many would find it persuasive.) I found two good examples at Function declaration.

*

*Function declaration:
noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional)
Focus on cv (short for "const-volatile"), which is marked "optional" and which is "only allowed in non-static member function declarations". Your colleague's interpretation of this marker would mean that compilers do not have to support const member functions, as the const keyword is "optional".

*Function definition, the first option for function-body:
ctor-initializer(optional) compound-statement
The "optional" part here is the member initializer list (only allowed in constructors). Is your colleague ready to claim that a compiler need not support member initializer lists?
Sometimes one should look at the familiar to understand annotations.

A: The opt / (optional) suffix means the symbol is optional [for the C++ programmer to use; not the compiler to support]
As this question has been tagged language-lawyer, and as general when we look for a definite reference, let's move away from CppReference and into the standard.
Where CppReference uses the (optional) subscript, the standard uses opt; e.g. as in [temp.param]/1:

The syntax for template-parameters is:

*

*template-parameter:

*

*type-parameter

*parameter-declaration

*type-parameter:

*

*type-parameter-key ...opt identifieropt

*[... and so on]

[syntax]/1 describe the syntax notation [emphasis mine]:

In the syntax notation used in this document, syntactic categories are
indicated by italic type, and literal words and characters in constant
width type. Alternatives are listed on separate lines except in a few
cases where a long set of alternatives is marked by the phrase "one
of". If the text of an alternative is too long to fit on a line, the
text is continued on subsequent lines indented from the first one.
An optional terminal or non-terminal symbol is indicated by the subscript "opt", so

*

*{ expressionopt }

indicates an optional expression enclosed in braces.

Thus, you are correct, and your colleague is wrong. Particularly for your example of template parameter packs (which we introduce by the optional ... after typename) the identifier that follows after typename..., which names the pack (or the template parameter, if ... is omitted), is optional.

But he stated that it means that it is optional in the standard and that a compiler does not need to support this feature to comply to the standard.

The ridiculousness of this claim becomes even more clear if we annotate the "optional permutations" of a class template with a single type template parameter:
template<typename>
      // ^^^^^^^^ type-parameter
      // (omitting optional '...' and 'identifier')
struct S;

template<typename T>
      // ^^^^^^^^^^ type-parameter
      // (omitting optional '...')
struct S;

template<typename...>
      // ^^^^^^^^^^^ type-parameter
      // (omitting optional 'identifier')
struct S;

template<typename... Ts>
      // ^^^^^^^^^^^^^^ type-parameter
struct S;

If the claim above was true, only the first of these four would need to be supported by a compliant implementation (based solely on grammar, in this contrived example), which would mean a compiler vendor could offer a compliant implementation where we could never name neither template (type) parameters nor function parameters.

A: It means that particular token is optional. For instance both these declarations work:
template <class... Args>
void foo();

template <class...>
void bar();


text:
Q: "It will turn into water" vs "it turns into water"
Possible Duplicate:
Scientific article style: present or future

Which sentence is correct between these two:

*

*If you heat ice, it will turn into water.

*If you heat ice, it turns into water.

A: Both are grammatically correct.  One can use the present for a future action, especially when it is a general (not specific) or frequentive one.  Notice the difference in sense between these two contrasting examples:

*

*If you heat up this ice cube, it will melt into water.

*Whenever you heat ice, it turns into water.

The first is about a particular piece of ice, the second about ice in general.

A: Both are grammatical. The second is the normal way of stating something that is always the case. The first is an example of what is sometimes known as the First Conditional, which predicts a likely result if the condition in the if-clause is met.
The nature of the statement in this particular case means that you can use either construction without fear of being misunderstood.
However, that is not always so. There's a difference between If you run, you catch the train and If you run, you will catch the train. The first can be true at any time, but the second would be used in a particular situation in which someone you knew actually needed to catch a train.


text:
Q: How to decrease db attribute value over time with Rails? I'm creating a credit-based application, where the user puts credit in his account and the credit decreases over time based on user's active services.
For example:

*

*User deposits U$ 30 in his account

*User accquires a service that costs U$ 60/month

*His credits will decrease over time, so in the second day of use, user's credit will be U$ 28 (U$ 30 - U$ 2 from the accquired service)

*User will be able to see his current balance any time

I realize that I can use cron jobs to decrease the account balance, but it's gonna make a lot of requests to database and I am sure there must be better ways to do that.
How can I do it?

A: One way to achieve this is using a column and a callback e.g.
You will need to add a column say last_deducted_on as date then in the show action of account_balance you can have a before_action like
before_action :deduct_amount_if_applicable, only: :show

private

def deduct_amount_if_applicable
  if current_user.deduction_applicable?
    amt = (Date.today - account.last_deducted_on).to_i * amount_to_be_deducted
    account.update_attribute(:total, (account.total - amt))
    # update column with today's date
  end
end

Although it will work, I suggest to use scheduler as it is a scheduled job and needs to be done every day, there are ways to reduce queries e.g. using update_all, etc. depending on use case but still the better option. In case if you have transaction history and you show date of transaction, above method will piss of user if he will open his account days later and suddenly huge amount is deducted.


text:
Q: How to calculate sides and degrees of triangle So I understand that we can derive the degrees from a triangle with
$$TAN^{-1}\left(\frac{AB}{CB}\right)= A^o (degree)$$
But this only applies on a Right Triangle.
In the next example I want to get value of $DF$ and all of the degrees in the triangle.

I can't seem to go any further, but I have done other Right Triangles loads of times.
This is what I have:
Split E so that we have 2 new smaller triangles, where EF and G (G is 90 degrees from E. Then DEG is on E:
$$140^0 - 90^0 = 50^0$$
And we know DE and EF.
But from here it seems i'm lost.

A: For DF you can use cosine law:
$$
\text{DF}²= \text{ED}² +  \text{EF}² - 2\cdot\text{ED}\cdot\text{EF}\cdot\cos\text{DÊF}
\\
\text{DF}²= 3² +  4² - 2\cdot3\cdot4\cdot\cos140^o
$$
For the angles you can use sine law:
$$
\frac{\text{DF}}{\sin140^o}=\frac{\text{ED}}{\sin\text{E}\hat{\text{F}}\text{D}}=\frac{\text{EF}}{\sin\text{E}\hat{\text{D}}\text{F}}
$$


text:
Q: How can I get arcpy.TraceGeometricNetwork_management results? I have geometric network and try to launch Python script with tracing
gdb = "C:/Users/my_user/Documents/ArcGIS/gn/gn.gdb"
gdb += "/gn/"
geometric_net = gdb + "gn_Net"
flags = gdb + "flags"
result_name = "gn_Net2"

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

result = arcpy.TraceGeometricNetwork_management(geometric_net,
                                       result_name,
                                       flags,
                                       'FIND_CONNECTED'
                                       )

gl = arcpy.mapping.Layer(result_name)
arcpy.mapping.AddLayer(df, gl, "BOTTOM")

This script do nothing (as I see in ArcMap) - no new group layer in ArcMap, no new layers/feature classes/other instances in current geodatabase.
result variable have some value after last row execution, but I can't determine its type - debugger says thatresult.__class__ returns <class 'arcpy.arcobjects.arcobjects.Result'>, and result returns {geoprocessing server result object} gn_Net2
From documentation I presumed that result is group layer that I must to add to map. But I can't find Arcpy method which can add group layer to map - only layer adding to map or existing group layer (arcpy.mapping.AddLayer).
What really arcpy.TraceGeometricNetwork_management returns? Did I understood correctly that it's group layer? And it's ready for add to ArcMap via arcpy.mapping.AddLayer method?
If no, where is tracing result? How can I see it? What is the arcpy.TraceGeometricNetwork_management result?
Edits: I added

*

*ArcMap document (mxd) and data frame (df) getting

*Group layer adding

to script.
I launches my script from ArcMap via toolbox-script object.
Result of my changes is:
Group layer adds to ArcMap document, but without found path (no new layer, selectiong or highlighting). Only geometry network and its layers was added.
When I run geometry tracing manually with same conditions (Utility Network Analyst - Solve), found way highlights at map.


text:
Q: Overflow: hidden isn't working consistently I am working on some buttons. I want to have a rollover state and I have this in an image in a div with overflow:hidden to hide the state that's not active. It works sometimes but sometimes it looks like this:

The weirdest part is that when I try to use the Chrome Web Inspector it fixes itself! And nothing looks weird in the HTML/CSS.

I'm super confused as to why it isn't consistently either broken or working.
Here's the HTML:

    Friend

And the relevant CSS:
.hunting_card_button {
    width: 65px;
    overflow: hidden;
    display: inline-block;
    text-align: center;
    margin: 0 2px 0 2px;
}
.hunting_card_icon {
    position: relative;
    right: 0;
}
.hunting_card_icon:hover {
    right: 65px;
    cursor: pointer;
}

A: The solution was to change one of its containers to a div from a span.


text:
Q: ndk-debug crashed suddenly. gdb.setup: Permission denied I was debugging my natives libraries with the ndk-gdb and
suddenly it does not works!.. when I try launch it  through Cygwin I
get this:

cp: missing destination file operand after `/cygdrive/c/User/admin/
  workspace/threadTest/obj/local/armeabi/gdb.setup'
Try `cp --help' for more information.
  /cygdrive/c/android-ndk-r5b/ndk-gdb: line 576: /cygdrive/c/User/admin/
  workspace/threadTest/obj/local/armeabi/gdb.setup: Permission denied
/cygdrive/c/android-ndk-r5b/ndk-gdb: line 577: /cygdrive/c/User/admin/
  workspace/threadTest/obj/local/armeabi/gdb.setup: Permission denied

P.D: device-> Samsung GT-P1000, debugging on windows, same problem in the emulator
Any idea?
Thaks!

A:
cp: missing destination file operand after `/cygdrive/c/User/admin/ workspace/threadTest/obj/local/armeabi/gdb.setup'

This error message is by the following line in ndk-gdb script.
cp -f $GDBSETUP_INIT $GDBSETUP

$GDBSETUP_INIT is empty, it comes from
GDBSETUP_INIT=`get_build_var_for_abi NDK_APP_GDBSETUP $COMPAT_ABI`

And then, get_build_var_for_abi is
get_build_var_for_abi ()
{
    if [ -z "$GNUMAKE" ] ; then
        GNUMAKE=make
    fi
    $GNUMAKE --no-print-dir -f $ANDROID_NDK_ROOT/build/core/build-local.mk -C $PROJECT DUMP_$1 APP_ABI=$2
}

Thus, make doesn't work correctly, I guess. Have you installed GNU make with cygwin setup?


text:
Q: Kivy Desktop App for Serial Data communication in fastest possible way I build the basic app using RecycleView to show the SerialPort incoming messages on Windows 10. Things are working fine except that CPU usage rises to more than 60% and Power Usage  is "Very High". Also, I could not find way to update the GUI on other than MainThread. Here are the required code snippets:
            RecycleView:
                id:rv
                do_scroll_x: False
                smooth_scroll_end:10
                do_scroll_y: True
                bar_color: 105/255,105/255,105/255, 1
                bar_inactive_color: 105/255,105/255,105/255, 1
                bar_width:15
                scroll_type:['bars', 'content']
                viewclass: 'Label'
                color: '#000000'
                RecycleBoxLayout:
                    default_size: None, dp(56)
                    default_size_hint: 1, None
                    size_hint_y: None
                    height: self.minimum_height
                    orientation: 'vertical'
                    color: '#000000'

and the function which runs every 2 milliseconds to read bytes from the port:
@mainthread
def read_data(self, *args):
    if(self.serial_port.in_waiting > 0):
        serialString = self.serial_port.read_all()
        self.data_list.append(serialString.decode('utf-8', 'replace'))
        self.ids.rv.data = [{'text': str(x)} for x in self.data_list]

Above code give more than CPU and power issues. And If I replace RecycleView in .kv file with just a single label to show single incoming string (not append it), the CPU and power usage drops dramatically to almost 1%. Please guide me a way to show all the incoming messages on main GUI in appending mode so that user can scroll up and down to see all the messages. Is there any lighter view than Label?
I mean following works excellently without any CPU or high power usage:
self.ids.lbl.text = serialString.decode('utf-8', 'replace')
But doing following makes high CPU usage and Power consumption:
self.ids.lbl.text += serialString.decode('utf-8', 'replace')
Note += in second line.

A: You are regenerating your whole data list every time, this is going to be more and more costly as the list grow in size, instead, you should try to append only (like you do for data_list, and only regenerate rv.data from data_list when really needed, this should improve improve cpu usage when the messages starts to pile up.
this example might be helpful https://gist.github.com/tshirtman/41e533d077567762b3bd981f718f3cd6


text:
Q: catching on-click event of dynamically allocated id element.find('#id1').on('click', function(){ ... does not work.
I am looking for code to do the ABOVE.
/* The below text/code is my problem in deeper context.*/
I can do the same with $('#id1').on('click', function(){ ...  problem is i'm using ng-repeat to dynamically allocate id to element
.set(ng-repeat='item in items').my-directive
  button(id='id{{$index}}') press me

so interestingly
element.find('#id1') works but $('#id1').on('click', .... does not work.
The following is some of my-direcitive code
$('button').on('click', function() { alert('hi');} // works

$('#id0').on('click', function() { alert('hi);} // does NOT work

more over
$('button').on('click', function() {

  element.find('#id1').css('width', 1000); // Also Works

}

It which means using 'element' you can refer to $scope of ng-repeat where as you can't with jQuery ie
using simple $('#id1') of jQuery.

A: For dynamically allocate id :
$('#YourWrapperID').on('click','#id1' , function(){
    alert('test');
});

A: I think you're looking for the .click function.
$( "#id1" ).click(function() {

Take a read here:
http://api.jquery.com/click/


text:
Q: Gson to json returning all the elements of subclass also I have a situation where the gson is returning the child object elements also when i tried to make a json string from parent object. how to eliminate the same.
Here is the code i am having.
Class Image {
    private int imageID;
    private String imageName;

    // Getters and setters
}

Class ImageDetails extends Image {
    private String imageType;
    private byte[] imageData;
    //Getters and setters
}

Class Test {
    // Setting the image Object, and the imageDetails.

    // calling the gson for json string
    String jsonString = GsonString.UserFeed(ImageObject)

    // This jsonString has all the elements from the ImageDetails Object also which i do not want.
}

Class GsonString {

    public static String UserFeed(Object feedData) {
        String feeds = null;
        Gson gson = new Gson();
        feeds = gson.toJson(feedData);
        return feeds;
    }
}

A: You only have to specify the class you want to serialize, using  toJson(Object src,Type typeOfSrc)
A simple example:
class Bob {
    private String bobName = "Bob";
}

class Pete extends Bob {
    private String peteName = "Bob";
}

public static void main(String[] args) {

    Object o = new Pete();
    System.out.println(new Gson().toJson(o));
    System.out.println(new Gson().toJson(o, Bob.class));

}

Output:
{"peteName":"Bob","bobName":"Bob"}
{"bobName":"Bob"}