text:
Q: Installing R packages in Colab I'm trying to install fPortfolio using install.packages("fPortfolio") on a Google Colab notebook. And I know there are some limitations.
Warning message in install.packages("fPortfolio"):
"installation of package 'gsl' had non-zero exit status"
Warning message in install.packages("fPortfolio"):
"installation of package 'Rglpk' had non-zero exit status"
Warning message in install.packages("fPortfolio"):
"installation of package 'energy' had non-zero exit status"
Warning message in install.packages("fPortfolio"):
"installation of package 'fAssets' had non-zero exit status"
Warning message in install.packages("fPortfolio"):
"installation of package 'fPortfolio' had non-zero exit status"

So  I need apt-get some libraries. But I don't know which ones. Does anyone have any ideas?


text:
Q: Can't handle specific status code error in Retrofit with Rxjava while using a base extension fuction for handilng Exception I want to call an API function of my server. I implement that using Retrofit and Rxjava and make a base exception handler method 'toSingle()'. API call is successful. but the problem is when the server sends a response with status code 406, the message did not show. Instead, it shows null value
BaseResponse.kt
open class BaseResponse(
    @SerializedName("status") val status: Int = 0,
    @SerializedName("message") val message: String? = null
)

LoginResponse.kt
data class TutorLoginResponse (
    @SerializedName("data") val data: TutorLoginCredential
) : BaseResponse()

Extension.kt
fun <T: BaseResponse> Single<Response<T>>.toSingle(): Single<T> {
    return map {
        if(it.isSuccessful) {
            it.body()
        } else {
            if (it.code() == 406) {
                throw Exception(it.body()?.message)  // Can't get this message from BaseResponse Class. Show null
            } else {
                throw Exception("Something went wrong")
            }
        }
    }
}

LoginService.kt
@POST("signin/tutor")
fun tutorLogin(
    @Body loginBody: LoginBody
): Single<Response<TutorLoginResponse>>

LoginViewModel.kt
fun tutorLogin(email: String, password: String) {
        compositeDisposable += authenticationService.tutorLogin(email, password)
            .toSingle()
            .doOnSubscribe { }
            .doAfterTerminate { }
            .performOnBackgroundOutputOnMain()
            .subscribe({

            }, {
                handleException(it)
            })
}

fun handleException(throwable: Throwable) {
    when(throwable) {
        is IOException -> toastMessage.value = Event("No Internet Connection")
        else -> toastMessage.value = Event(throwable.message.toString())
    }
}

A: Finally I solved the problem. The code is given bellow
Extension.kt
fun <T> Single<Response<T>>.toSingle(): Single<T> {
    return map {
        if(it.isSuccessful) {
            it.body()
        } else {
            if (it.code() == 406) {
                val error = Gson().fromJson(it.errorBody()?.charStream(), BaseResponse::class.java)
                throw Exception(error.message)
            } else {
                throw Exception("Something went wrong")
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android compare time I am getting day and time in this format dd.MM. HH:mm from server. I want to get current city day and time irrespective of where I am staying in the same format and check if its less than than 20 mins. How do I do this?

A: I have used this code to get difference in min.
It require date with year also.
public static int getDifferenceTimeInMin(String startDate, String endDate)
{

        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat(getString(R.string.common_dateTime_format));

        Date date2 = null;
        Date date1 = null;
        try {
            date1 = simpleDateFormat.parse(startDate);
            date2 = simpleDateFormat.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //milliseconds
        long different = date1.getTime() - date2.getTime();

        //System.out.println("startDate : " + startDate);
        //System.out.println("endDate : "+ endDate);
        System.out.println("different : " + different);

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        System.out.printf(
                "%d days, %d hours, %d minutes, %d seconds%n",
                elapsedDays,
                elapsedHours, elapsedMinutes, elapsedSeconds);

       // int Hours = Integer.parseInt(String.valueOf(elapsedHours));

        return  Integer.parseInt(String.valueOf(elapsedMinutes));

}

Hope it will help...


text:
Q: Mobile navigation dropdown not lining up I am making my website responsive and when I move to mobile version my navigation bar changes but now I am struggling with the dropdown within the navigation. I want the dropdown when I hover on it to appear on the left side of the vertical menu "Tours" dropdown.
Mobile Nav version hovering on the dropdown

// JavaScript Document
/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */
function myFunction(){
document.getElementsByClassName("Menu")
[0].classList.toggle("responsive");
}
/*hide all list items, except for the first one ("Home").
Show the list item that contains the link to
open and close the topnav (li.icon) */
.Menu li:not(:first-child)
{
display:none;
border-bottom:none;
}

.Menu li.icon
{
float:right;
display:inline-block;
}

/* The "responsive" class is added to the Menu with JavaScript
when the user clicks on the icon. This class makes the Menu look good
on small screens */
.Menu.responsive
{
position:relative;
}

.Menu.responsive li.icon
{
position:absolute;
right:0;
top:-4px;
border:none;
}

.Menu.responsive ul li.icon a
{
border-bottom:none;
}

.Menu.responsive li
{
float:none;
display:inline;

}

.Menu.responsive li a
{
display:block;
text-align:left;
background-color:#161616;
border-bottom:solid 1px #FFFFFF;
}

/* The container
 - needed to position the dropdown content */
.dropdown
{
position:relative;
display:inline-block;
}

/*Dropdown arrow for link items*/
.caret
{
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-menu
{
position:absolute;
visibility:hidden;
min-width: 100px;
background-color: #161616;
opacity:0;
-webkit-transition:opacity 0.4s ease-in-out;
-moz-transition:opacity 0.4s ease-in-out;
transition:opacity 0.4s ease-in-out;
}

/* links inside the dropdown*/
.dropdown-menu a
{
color: white;
padding: 12px 16px;
text-decoration: none;
display: block;
border-top:solid 1px #FFFFFF;
margin-top:0px;

}

/* Change color of dropdown links on hover */
.dropdown-menu a:hover
{
color: #755378;

}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-menu
{
visibility:visible;
right: auto;
left: 0;
opacity:1;

}

Home

About Us

        Tours

Tours

Day Tours

Contact Us

☰

I added the Javascript for external purposes not actually needed this is just to make the menu responsive.
The Css is from my CssResponsive stylesheet for mobile version.


text:
Q: please tell me correct way to use usb_modeswitch in ubuntu saucy I have one mobile router "hw0-2e".
(https://www.nttdocomo.co.jp/product/data/hw02e/index.html )(japanese only)
I want to use this by usb connection as my pc is desktop and no wifi.
I know this one can connect with windows pc by usb connection.
but if I connect it with Ubuntu, my pc cannot identify it as usb modem,my pc identifies it as CD.
So I think ,if I install usb_modeswitch to ubuntu, I will use it.
then,I installed it to Ubuntu saucy,
and I searched vendorID=12d1 ,productID=1506
and read
http://www.draisberghof.de/usb_modeswitch/bb/viewtopic.php?t=708
and tried a lot of things.
but I cannot use "hw0-2e" as router.
please tell me correct way to use usb_modeswitch in Ubuntu saucy.


text:
Q: How to declare a multidimensional array in jquery I want to store details where the number of columns of array are fixed and number of rows are unknown.
I want to assign each column a key by extracting text from the div of a specific page and then assign the value to it.
This is my code
var data1=[[]];
var val=0;
$('.education_box.eb1 .inner_box').each(function(){
    $('.education_box.eb1 .inner_box ul li').each(function(){
        var key= $(this).children('strong').text();
        var value= $(this).children('em').text();
        data1[key][val]= value;
    });
    val++;
});
console.log(data1);

Please let me know how to declare the 2D array in line 1 as each time it gives the error: Cannot set property '0' of undefined

A: You can use:
var data1= [];
for (var i=0;i<$('.education_box.eb1 .inner_box ul li').length;i++) {
   data1[i] = [];
}

then use:
 data1[key][val]= value;

A: Try this:
Declare array using Array class

var data=[];

data[0]=new Array(10,2);;
data[1]=new Array("val1","val2");
data[2]=new Array(true,false);

console.log(data);


text:
Q: I am using Alfresco 5.0.d Community Edition and mysql as database. I am creating user through Admin Tools -> Users -> Create User I am using Alfresco 5.0.d Community Edition and mysql as database. I am creating user through Admin Tools -> Users -> Create User. But when I am trying to invite these users, they are not searchable. They are also not searchable in People section but they are searchable in Admin Tools -> Users.
No error is coming in server logs.
I have even deleted previous indexing and created new indexing many times.
Any help would be appreciated.
Thanks

A: You can try by changing a property in alfresco-global.propeties file
### Solr indexing ###
index.subsystem.name=solr4

to
### Solr indexing ###
index.subsystem.name=solr

This issue is related with indexing.


text:
Q: Remove the background color in Windows Photo Viewer for Win7 aero glass theme I use Black Glass Enhanced (curiouso9.deviantart.com/art/Black-Glass-Enhanced-v0-5-156752713) with my black Windows 7 theme. Unfortunately, Windows Photo Viewer does not have any transparency like all my other specified programs. When Windows Photo Viewer executes, it runs as dllhost.exe, which is already on the list of programs to make transparent within Black Glass Enhanced. So I'm not sure why it isn't "glassifying" properly.
The first screenshot is Windows Photo Viewer; and the second is Windows 7 Gif Viewer (www.sevenforums.com/music-pictures-video/97830-windows-7-gif-viewer-works-perfectly.html), which is just Windows XP Photo Viewer transferred to Win7. Windows 7 Gif Viewer executes within rundll32.exe, which is also included in the list on Black Glass Enhanced. And as you can see, it is properly glassy.

I tried this method (superuser.com/questions/719867/how-to-change-the-background-color-in-windows-photo-viewer) to change the Photo Viewer background color manually, but changing it had no effect on transparency. Is there a DWORD value that can achieve this? Or remove the background block entirely and make it look like the Windows XP Photo Viewer?
P.S. Sorry for the long links, it wouldn't let me post hyperlinks.


text:
Q: Trying to send a post request with PHP from swift I'm trying to send a user's input (done through a UISearchBar) to my PHP file to search through a database of store names. However, it seems like my $_POST variable $searchWord is empty.
My swift code:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
    return
}
searchBar.resignFirstResponder()
doSearch(searchWord: searchBar.text!, searchbar: searchBar )

}
func doSearch(searchWord: String, searchbar: UISearchBar){

mysearchBar = searchbar

mysearchBar.resignFirstResponder()

let myURL = NSURL(string: "http://localhost:8080/searchStore.php")

var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

print("name=\(searchWord)")

let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    DispatchQueue.main.async() {

        if error != nil{
            self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
            return
        }
        do{
            var _: Error?
            //STOPPED HERE AS OF NOW
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            self.results.removeAll(keepingCapacity: false)
            self.tableView.reloadData()

            if let parseJSON = json{
                print("json")
                if let stores = parseJSON["stores"] as? [AnyObject]{
                    print("stores")

                    for storeOjb in stores{
                        let name = (storeOjb["name"] as! String)
                        self.results.append(name)
                    }

                    self.tableView.reloadData()

                }else if(parseJSON["message"] != nil){
                    print("message")

                    let errorMessage = parseJSON["message"] as? String
                    if(errorMessage != nil){
                        self.displayAlertMessage(userMessage: errorMessage!)

                    }
                }
            }
        } catch {
            print(error)
        }
    }

}

task.resume()
}

func displayAlertMessage(userMessage: String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}

My php file
<?php
require("Conn.php");
require("MySQLDao.php");

$returnValue = array();

if(empty($_POST["name"])){
    $returnValue["message"]= "Missing required field";
    echo json_encode($returnValue);
    return;
}

$searchWord =htmlentities($_POST["name"]);

$dao = new MySQLDao(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass,
Conn::$dbname);
$dao->openConnection();

$storeNames = $dao->searchStore($name);
$dao->closeConnection();

$returnValue["stores"]=$storeNames;
echo json_encode($returnValue);
?>

class MySQLDao
    {
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
    $this->dbhost = $dbhost;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpassword;
    $this->dbname = $dbname;
}

public function openConnection() {
    $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass,
$this->dbname);
    if (mysqli_connect_errno())
        throw new Exception("Could not establish connection with database");
    $this->conn->set_charset("utf8");
}

public function closeConnection() {
    if ($this->conn != null)
        $this->conn->close();
}

public function searchStore($name){
    $returnValue =  array();
    $sql  = "SELECT * FROM stores s WHERE s.name LIKE ? ";
    $statement = $this->conn->prepare($sql);
    if(!$statement)
    throw new Exception($statement->error);
    $name = '%' .$name. "%";
    $result->bind_param("s", $name);
    $result->execute();
    $result = $statement->get_result();

while($myrow = $result->fetch_object())
{
    $returnValue[] = $myrow;
}

return $returnValue;
}

}
?>

And Conn.php included MySQL connection details.
PostString in the swift code displays the users input correctly (I was able to figure it out by using breakpoints). However, whenever I search anything I would get an alert message saying that "Missing required field" indicating that my $_POST variable $searchWord is empty. Does anyone know how to solve this issue?

A: The PHP $_POST array is only populated when the the request content type is of x-www-form-urlencoded.
If you are POSTing application/json from your Swift application, then you will need to parse the request body from the php input stream: php://input or you can use the STDIN constant.
However, it looks to me like you are actually intending to send x-www-form-urlencoded data, so change your content type appropriately.


text:
Q: Windows 10 laptab leave music on during sleep So I have a fully featured windows 10 laptop to tablet convertible. I use it mostly as a tablet so I was looking for  a way to get it working like most tablets do , so like if you press the power button the screen blacks out and any music running remains playing in the background. Right now pressing the start button makes it go into sleep which makes it play no music.

A: it seems you would like to make the screen turn off (instead of windows default "sleep") on power button press action. To do so, go to
Control Panel\Hardware and Sound\Power Options
click on "Edit Plan Settings" next to your currently selected plan
next click on "Change advanced power settings"
A new window should pop up - find the "Power buttons and lid" position and click it. Next reveal "Power button" list and change both positions from "sleep" to "Turn off display". Accept by clicking "OK"
@Edit - a screenshot of what it looks like on my Win 10 laptop


text:
Q: Is any jQuery version compliant to Promise/A specifications? After going through several articles I have come to know that promise implementation is there in jQuery. But I am not sure whether any version of jQuery is Promise/A compliant or not.

A: Update 2015: jQuery 3.0 is Promises/A+ compatible. See this issue on GitHub so 3.0 beta is 3.0 compatible and when 3.0 is out it will also be compatible. Until then - the below still applies.
All jQuery versions (up to 3.0) feature a broken promise implementation
They don't allow error handling well, and they don't mix and match with other implementations well.
However, since version 1.8 .then exists, which means you can kind of use the jQuery implementation as promises. This is an attempt to fix this bug and become more Promises/A compliant. There is an effort to improve interoperability, which is what the promises specification is all about anyway, the target of that effort is 2.2 and 1.12.
This means that from 2.2 onward, jQuery promises will be able to interop with other promise libraries, assimilate thenables like any promise library should, and behave less incorrectly according to the spec.
For all practical uses, you should consider another implementation.
There exist a lot of good promise implementation out there. Bluebird for example is fast ( much faster than jQuery promises), has a low memory footprint, has amazing stack traces and debugging support and interops seamlessly with jQuery promises and assimilates them.


text:
Q: How to read data where there variables with different lengths in R? I have a data set stored in a txt file. The variable x and y have different lengths. Therefore I could not manage to read them in R. Here is how my data looks like
x     y    z
1     2    3.2
1.5  1.6   2.5
3    0.8   3.1
2.5        2.4
2.6        2.2

I tried this, but did not work as I desired. Any idea why?
data <- read.table(data.txt,header=T,fill=T)

Here is how it looks
 x     y    z
1     2    3.2
1.5  1.6   2.5
3    0.8   3.1
2.5  2.4
2.6  2.2

A: Questions that say "did not work" are often too vague to answer. I tried your problem and got a result rather than an error, so you now need to clarify in what manner it is not "working" for your needs:
txt <- "x     y
1     2
1.5  1.6
3    0.8
2.5
2.6"
data <- read.table(text=txt,header=T,fill=T)
data
#------
    x   y
1 1.0 2.0
2 1.5 1.6
3 3.0 0.8
4 2.5  NA
5 2.6  NA

For the edited question:
If that is from an Excel file then you should use "\t" as the sep= argument. If it is a fixed-width file format than you should use read.fwf as the read function.

A: You could try the readr package with function read_table
data <- read_table("data.txt")

> data
    x   y   z
1 1.0 2.0 3.2
2 1.5 1.6 2.5
3 3.0 0.8 3.1
4 2.5  NA 2.4
5 2.6  NA 2.2

> dim(data)
[1] 5 3

A: You may use the parameter fill=TRUE and then you could replace NA by zero
a <-read.table(header = TRUE, fill= TRUE, file= "./data/data.txt")
a[is.na(a)] <- 0

the result:
    x   y
1 1.0 2.0
2 1.5 1.6
3 3.0 0.8
4 2.5 0.0
5 2.6 0.0


text:
Q: Retrieving Input Values from a Text Box I need to make a box so that when the user enters a value of one through 6, it rolls that many dice. I'm a complete beginner to javascript and any help would be greatly appreciated.
Here's my function:
function NumberValue() {
        for (i = 0; i <['randNumber']; i++){
            var numberRoll = Math.floor(Math.random() * 6) + 1;
            var userNumber = '../images/die' + numberRoll + '.gif';
            myNewTag = ""
            document.getElementById('dieDivRandom').innerHTML += myNewTag;

And here is my body element:

Why don't you pick please?

<input type="text" id="randNumber" size=20 value="Enter 1 through 6">

<input type="button" value="Click to Roll" onclick="NumberValue();">

The function needs to allow a user to submit the number one, two, three, four, five, or six, and that many images need to display on the screen. The images a relocated in my images folder, so relative links will work just fine. That's actually what I need to use. Thank you.

A: Replace:
for (i = 0; i <['randNumber']; i++){

With:
for (i = 0; i <document.getElementById('randNumber').value; i++) {

The <input /> tag can be accessed by using either of the following:

*

*document.getElementById('inputId').value;

*document.formName.inputName.value

Finally, your code becomes:
function NumberValue() {
    for (i = 0; i < document.getElementById('inputId').value; i++) {
        var numberRoll = Math.floor(Math.random() * 6) + 1;
        var userNumber = '../images/die' + numberRoll + '.gif';
        myNewTag = ""
        document.getElementById('dieDivRandom').innerHTML += myNewTag;
    }
}

A: Use this   to read values from textbox
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;

        for (i = 0; i <ranNum ; i++){

        }

}

EDIT:
If you want to validate the Entered number
add this block of code
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
        if(ranNum < 1 || ranNum > 6) {
           alert("Please enter number from 1 to 6 only");
           return false;
          }

        for (i = 0; i <ranNum ; i++){

        }

        return true;

}


text:
Q: Checking if a website doesn't permit iframe embed I am writing a simple lightbox-like plugin for my app, and I need to embed an iframe that is linked to an arbitrary page. The problem is, many web sites (for example, facebook, nytimes, and even stackoverflow) will check to see if is being embedded within a frame and if so, will refresh the page with itself as the parent page. This is a known issue, and I don't think there's anything that can be done about this. However, I would like the ability to know before hand if a site supports embed or not. If it doesn't, I'd like to open the page in a new tab/window instead of using an iframe.
Is there a trick that allows me to check this in javascript?
Maybe there is a server-side script that can check links to see if they permit an iframe embed?
I am developing a browser extension, so there is an opportunity to do something very creative. My extension is loaded on every page, so I'm thinking there's a way to pass a parameter in the iframe url that can be picked up by the extension if it destroys the iframe. Then I can add the domain to a list of sites that don't support iframe embed. This may work since extensions aren't loaded within iframes. I will work on this, but in the meantime....
Clarification:
I am willing to accept that there's no way to "bust" the "frame buster," i.e. I know that I can't display a page in an iframe that doesn't want to be in one. But I'd like for my app to fail gracefully, which means opening the link in a new window if iframe embed is not supported. Ideally, I'd like to check iframe embed support at runtime (javascript), but I can see a potential server-side solution using a proxy like suggested in the comments above. Hopefully, I can build a database of sites that don't allow iframe embed.

A: Probably pretty late but what you need to do is make a request, likely from your server and look for the x-frame-options header. If it's there at all you can just open a new tab because if it is there is is one of the following:  DENY, SAMEORIGIN, ALLOW-FROM. In any of these cases it's likely that you don't have access to open it in an iframe.

A: Check x-frame-options header by using following code
$url = "http://stackoverflow.com";
$header = get_headers($url, 1);
echo $header["X-Frame-Options"];

If return value DENY, SAMEORIGIN or ALLOW-FROM then you can't use iframe with that url.

A: This subject has been discussed forever on the web with a particularly interesting (failed) attempt here:
Frame Buster Buster ... buster code needed
The bottom line is that even if you are able to construct a proxy that parses the contents of the page that you want in your iframe and removes the offending code before it is served to the iframe you may still come under "cease and desist" from the site if they get to hear about you doing it.
If you don't want your development to be widely available, you could probably get away with it. If you want your development to become popular, forget about it, and build a less underhand way of dealing with it.
Or develop it for mobile only... ;)
UPDATE: OK following on from your comment here's a bit of taster:
in javascript capture the click on the link
$("a").click(function(e){

    preventDefault(e); // make sure the click doesn't happen

    // call a server side script using ajax and pass the URL this.href
    // return either a true or false; true = iframe breakout
    // set the target attribute of the link to "_blank" for new window (if true)
    // set the target attribute of the link to "yourframename" for iframe (if false)
    // only now load the page in the new window or iframe
});

server side in PHP
$d = file_get_contents($url); // $url is the url your sent from the browser
// now parse $d to find .top .parent etc... in the <head></head> block
// return true or false


text:
Q: Logstash Netflow Module listening, but not reading packets Logstash 6.2.4 with the netflow module
Elasticsearch Version: 6.2.4
Ubuntu 16.04 LTS
I have an issue where logstash is listening on the correct port, but does not seem to be collecting
the netflow data and passing it to elasticsearch.
The routers in our network are sending their netflow data to Server A and nfcap is listening on port
9995 so trying to run logstash with the netflow module on Server A results in an address in use
error. So, I am using iptables to duplicate the packets and forwarding them to a different server, Server B, like this.
iptables -t mangle -A PREROUTING -p udp --dport 9995 -j TEE --gateway <Server B ip address>

Checking with tcpdump, I can see the duplicated packets being received by Server B, with Server A's IP address.
Output is below, but for security reasons I've redacted the IP addresses.
tcpdump -i eno1 -n dst port 9995
12:49:49.130772 IP <Router 1 ip address>.10005 > <Server A ip address>.9995: UDP, length 1392
12:49:49.131067 IP <Router 1 ip address>.10005 > <Server A ip address>.9995: UDP, length 1392
12:49:49.133504 IP <Router 1 ip address>.10005 > <Server A ip address>.9995: UDP, length 1392
12:49:49.133527 IP <Router 1 ip address>.10005 > <Server A ip address>.9995: UDP, length 1392
12:49:49.133533 IP <Router 1 ip address>.10005 > <Server A ip address>.9995: UDP, length 1260
12:49:49.391871 IP <Router 2 ip address>.62500 > <Server A ip address>.9995: UDP, length 1452
12:49:49.391894 IP <Router 2 ip address>.62500 > <Server A ip address>.9995: UDP, length 1368

So, I know that Server B is receiving the packets on port 9995.
Checking with netstat also shows this.
netstat -an | grep 9995
udp        0      0 0.0.0.0:9995            0.0.0.0:*

logstash.yml is as follows
node.name: server-b
path.data: /var/lib/logstash
http.host: "0.0.0.0"

modules:
  - name: netflow
    var.input.udp.port: 9995 # Inbound connections
    var.elasticsearch.hosts: "<ip address>:9200"
    var.kibana.host: "<ip address>:5601"

path.logs: /var/log/logstash

Checking /var/log/logstash/logstash-plain.log, the only warning I see is about the version of elasticsearch being greater than version 6 so type won't be used to
determine the document type.
[2018-07-06T12:58:13,771][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"6.2.4"}
[2018-07-06T12:58:13,817][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2018-07-06T12:58:17,599][INFO ][logstash.pipeline        ] Starting pipeline {:pipeline_id=>"module-netflow", "pipeline.workers"=>4, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50}
[2018-07-06T12:58:17,733][INFO ][logstash.outputs.elasticsearch] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://<ip address>:9200/]}}
[2018-07-06T12:58:17,734][INFO ][logstash.outputs.elasticsearch] Running health check to see if an Elasticsearch connection is working {:healthcheck_url=>http://<ip address>:9200/, :path=>"/"}
[2018-07-06T12:58:17,784][WARN ][logstash.outputs.elasticsearch] Restored connection to ES instance {:url=>"http://<ip address>:9200/"}
[2018-07-06T12:58:17,810][INFO ][logstash.outputs.elasticsearch] ES Output version determined {:es_version=>6}
[2018-07-06T12:58:17,810][WARN ][logstash.outputs.elasticsearch] Detected a 6.x and above cluster: the `type` event field won't be used to determine the document _type {:es_version=>6}
[2018-07-06T12:58:17,811][INFO ][logstash.outputs.elasticsearch] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//<ip address>:9200"]}
[2018-07-06T12:58:18,088][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-City.mmdb"}
[2018-07-06T12:58:18,101][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-ASN.mmdb"}
[2018-07-06T12:58:18,102][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-City.mmdb"}
[2018-07-06T12:58:18,103][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-ASN.mmdb"}
[2018-07-06T12:58:18,103][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-City.mmdb"}
[2018-07-06T12:58:18,103][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-ASN.mmdb"}
[2018-07-06T12:58:18,104][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-City.mmdb"}
[2018-07-06T12:58:18,104][INFO ][logstash.filters.geoip   ] Using geoip database {:path=>"/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-filter-geoip-5.0.3-java/vendor/GeoLite2-ASN.mmdb"}
[2018-07-06T12:58:18,120][INFO ][logstash.inputs.udp      ] Starting UDP listener {:address=>"0.0.0.0:9995"}
[2018-07-06T12:58:18,126][INFO ][logstash.pipeline        ] Pipeline started successfully {:pipeline_id=>"module-netflow", :thread=>"#<Thread:0x16700849@/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:247 sleep>"}
[2018-07-06T12:58:18,131][INFO ][logstash.inputs.udp      ] UDP listener started {:address=>"0.0.0.0:9995", :receive_buffer_bytes=>"212992", :queue_size=>"2000"}
[2018-07-06T12:58:18,135][INFO ][logstash.agent           ] Pipelines running {:count=>1, :pipelines=>["module-netflow"]}

ElasticSearch is running and is receiving data from packetbeat and filebeat, there is nothing in  /var/log/elasticsearch/elasticsearch.log to sugguest any error with elasticsearch.
However, elasticsearch does not have an index pattern for netflow. Kibana on the other hand, does.
So, logstash on Server B is listening on 0.0.0.0:9995, port 9995 is open and receiving packets from Server A, but logstash is not recognizing these packets.
My assumption is that Server B is ignoring them because the destination IP address is that of Server A. Does that sound right? If so, is there away round this?
Is there a better way to forward the duplicated packets from Server A to Server B and have logstash read them?
Unfortunately, adding another netflow exporter destination to the router configs is not possible.

A: I'll answer my own question.
Server B was indeed ignoring the netflow data because it did not recognise the IP address.
I added server A's ip address as a loopback interface and it works as expected.
That's probably not the best solution and one to avoid in a production environment, but for testing purposes it should be fine.


text:
Q: How to calculate the AUC of a graph in R? I have a dataframe (gdata) with x (as "r") and y (as "km") coordinates of a function.
When I plot it like this:
    plot(x = gdata$r, y = gdata$km, type = "l")

I get the graph of the function:

Now I want to calculate the area under the curve from x = 0 to x = 0.6. When I look for appropriate packages I only find something like calculation AUC of a ROC curve. But is there a way just to calculate the AUC of a normal function?

A: The area under the curve (AUC) of a given set of data points can be archived using numeric integration:
Let data be your data frame containing x and y values. You can get the area under the curve from lower x0=0 to upper x1=0.6 by integrating the function, which is linearly approximating your data.
This is a numeric approximation and not exact, because we do not have an infinite number of data points: For y=sqrt(x) we will get 0.3033 instead of true value of 0.3098. For 200 rows in data we'll get even better with auc=0.3096.
library(tidyverse)

data <-
  tibble(
  x = seq(0, 2, length.out = 20)
) %>%
  mutate(y = sqrt(x))
data
#> # A tibble: 20 × 2
#>        x     y
#>    <dbl> <dbl>
#>  1 0     0
#>  2 0.105 0.324
#>  3 0.211 0.459
#>  4 0.316 0.562
#>  5 0.421 0.649
#>  6 0.526 0.725
#>  7 0.632 0.795
#>  8 0.737 0.858
#>  9 0.842 0.918
#> 10 0.947 0.973
#> 11 1.05  1.03
#> 12 1.16  1.08
#> 13 1.26  1.12
#> 14 1.37  1.17
#> 15 1.47  1.21
#> 16 1.58  1.26
#> 17 1.68  1.30
#> 18 1.79  1.34
#> 19 1.89  1.38
#> 20 2     1.41

qplot(x, y, data = data)

integrate(approxfun(data$x, data$y), 0, 0.6)
#> 0.3033307 with absolute error < 8.8e-05

Created on 2021-10-03 by the reprex package (v2.0.1)
The absolute error returned by integrate is corerect, iff the real world between every two data points is a perfect linear interpolation, as we assumed.

A: I used the package MESS to solve the problem:
# Toy example
library(MESS)
x <- seq(0,3, by=0.1)
y <- x^2
auc(x,y, from = 0.1, to = 2, type = "spline")

The analytical result is:
7999/3000
Which is approximately 2.666333333333333
The R script offered gives: 2.66632 using the spline approximation and 2.6695 using the linear approximation.


text:
Q: How to interactively shows data from store I'm new to Vue. I'm trying to interactively shows data from store - my input should be automatically showed in summary.vue.
What's I have done so far:
summary.vue
<template>

        {{ summaryInfo }}

</template>

store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
      input1: '',
    },
  mutations: {
    upateState(state, value) {
      this.state.input1= value;
    }
  }
});

input.vue
<template>

    <el-input placeholder="Please input" v-model="input1"></el-input>

</template>

What am I missing?
Console log shows that state is updating correctly, but this changes are not visible in template.

A: Ok, my problem was with summary.vue.
Correct component should looks like this:
<template>

        {{ summaryInfo }}

</template>


text:
Q: How can I simplify my function and make it more pythonic? I have written a Python function for some post processing in my text recognition algorithm. It works fine, but it seems to be kind of lengthy and has many if-else-conditions. I am looking for a way to simplify my code:
def postProcessing(new_s): #new_s is a list
  import string

  new_s=removeFrontLetters(new_s) #This function has to be called first

  if all(ch in string.digits for ch in new_s[:4]): #checking if first 4 elements are digits.

    if all(ch in string.ascii_letters for ch in new_s[4:5]): #checking if the [4] and [5] are letters

      if len(new_s)>=7:
        if new_s[6]=='C':

          new_s=new_s[:7] #if length>=7 and the [6] =='C' the reversed of the first 7 elements has to be returned.
          new_s=list(reversed(new_s))
          return(new_s)

        else:
          new_s=new_s[:6] #if length>=7 but the [6] =!'C' the reversed of the first 6 elements has to be returned.
          new_s=list(reversed(new_s))

          return(new_s)

      else:
        new_s=list(reversed(new_s)) #if length<7, the reversed of the given list has to be returned.
        return(new_s)
    else:
      print('not valid') #if the [4] and [5] are not letters, it is not valid
  else:
    print('not valid') #if the [:4] are not digits, it is not valid

This seems very beginner-level and lengthy. I am a beginner, but I am trying to improve my function. Do you have suggestions?

A: You can invert your if statements and use early returns to reduce the indentation of your code.
def postProcessing(new_s):  # new_s is a list
    import string

    new_s = removeFrontLetters(new_s)  # This function has to be called first

    if not all(ch in string.digits for ch in new_s[:4]):  # checking if first 4 elements are digits.
        raise ValueError("First four elements must be digits")

    if not all(ch in string.ascii_letters for ch in new_s[4:5]):  # checking if the [4] and [5] are letters
        raise ValueError("First elements 4 and 5 must be digits")

    if len(new_s) <= 7:
        new_s = list(reversed(new_s))  # if length<7, the reversed of the given list has to be returned.
        return (new_s)

    if new_s[6] == 'C':

        new_s = new_s[
                :7]  # if length>=7 and the [6] =='C' the reversed of the first 7 elements has to be returned.
        new_s = list(reversed(new_s))
        return (new_s)

    new_s = new_s[:6]  # if length>=7 but the [6] =!'C' the reversed of the first 6 elements has to be returned.
    new_s = list(reversed(new_s))
    return (new_s)

A: It's quite neat you ask 'the world' for advise.  Did you know there's a dedicated stackexchange site for this?  https://codereview.stackexchange.com/.
Unless you insist writing Python code for this, it seems that you need a regular expression here.
So some tips:

*

*use regex for pattern matching

*use variables to express what an expression means

*use exceptions instead of an 'invalid value' string

*separate the 'parsing' from the processing to keep functions small and focused

*use doctest to document and test small functions

def post_process(new_s):
    """
    reverse a string (with a twist)

    what follows is a doctest.  You can run it with
    $ python -m doctest my_python_file.py

    >>> post_process('1234abCdef')
    'Cba4321'
    >>> post_process('1234abdef')
    'ba4321'
    """

    cmds = {
      'C': cmd_c,
      '': cmd_none
    }

    command, content = command_and_content(new_s)
    process = cmds[command]
    return process(content)

def cmd_c(content):
  return 'C' + "".join(reversed(content))
def cmd_none(content):
  return "".join(reversed(content))

The command_and_content function replaces the parsing logic:
def command_and_content(new_s):
    # get help on https://regex101.com/ to find the
    # regular expression for four digits and two letters
    digits_then_ascii = re.compile(r"(\d{4}[a-z]{2})(C?)(.*)")
    if match := digits_then_ascii.match(new_s):
      content = match.group(1)
      command = match.group(2)
      return command, content

    # pylint will ask you to not use an else clause after a return
    # Also, Python advises exceptions for notifying erroneous input
    raise ValueError(new_s)

A: From the context you provided, I assume that all this processing can happen in-place (i.e. without the need to allocate additional memory). The benefit of lists is that they are mutable, so you can actually do all your operations in-place.
This adheres to the style conventions (PEP 8) and uses correct type annotations (PEP 484):
from string import digits, ascii_letters

def remove_front_letters(new_s: list[str]) -> None:
    ...
    raise NotImplementedError

def post_processing(new_s: list[str]) -> None:
    remove_front_letters(new_s)
    if any(ch not in digits for ch in new_s[:4]):
        raise ValueError("The first 4 characters must be digits")
    if any(ch not in ascii_letters for ch in new_s[4:6]):
        raise ValueError("The 5th and 6th characters must be letters")
    if len(new_s) >= 7:
        if new_s[6] == 'C':
            del new_s[7:]
        else:
            del new_s[6:]
    new_s.reverse()

If you do want a new list, you can just call this function with a .copy() of your input list.
References: list methods; del statement
PS: If you use Python version 3.8 or lower, instead of list[str] you'll need to use typing.List[str].
Also someone mentioned the possibility of replacing the iteration via all() (or any()) with a "".join(...).isdigit() for example. While this is certainly also correct and technically less code, I am not sure it is necessarily more readable. More importantly it creates a new string in the process, which I don't think is necessary.
By the way, you could even reduce that conditional deletion of list elements to a one liner like this:
...
    if len(new_s) >= 7:
        del new_s[7 if new_s[6] == 'C' else 6:]
    new_s.reverse()

But I would argue that this is worse because it is less readable. Personal preference I guess.


text:
Q: PHP imagettfbbox gives different result when i'm trying to find text length and sum of char length I have a string with font and i need to find it's width, and then width of each char in this string, I'm using GD lib imagettfbbox for this, but it always gives me different result in the end.
$text="some random text";
$info=imagettfbbox(18,0,'/var/www/html/ARIAL.TTF',$text);
$text_width=$info[2]-$info[0];

$text_width_by_chars=0;
for($i=0;$i<strlen($text); $i++){
    $char=$text[$i];
    $info=imagettfbbox(18,0,'/var/www/html/ARIAL.TTF',$char);
    $char_width=$info[2]-$info[0];
    $text_width_by_chars+=$char_width;
}
echo $text_width.' '.$text_width_by_chars;

It happens to all fonts doesnt metter if $info[0] posetive or negative or 0, the differance is always around strlen($text) but not exactly, i've tried to find out if i can mutiply char width to some multiplier but it doesn't work, it's always around 0.91.
Why does it happen? And how can i prevent this so in the end $text_width and $text_width_by_chars become equal?


text:
Q: T versus Mann-Whitney U test I am working on an online learning problem, in which I need to detect whether two independent samples (possibly of different sizes) come from the same underlying distribution. Let us call the samples $S_{1}$ and $S_{2}$, such that $100 \leq |S_{1}|, |S_{2}| \leq 1000$ and both can come from any kind of distributions (i.e., I can make no assumptions on their shape or form).
After going over multiple online resources, I found out that there exist two main tests that can serve my goal:

*

*paired T test: with the assumption that $|S_{1}| = |S_{2}|$ and that both samples come from normal distribution.

*Mann-Whitney U test: with no assumptions on the samples' sizes and that both need to come from normal distributions.
Which of the two tests should I use, and what is the accuracy of Mann-Whitney U test if both samples come from normal distributions**(question 1)? Is there a rule of thumb on which test one should pick based on sample size **(question 2)?

A: Please note, that the non-paired t-test as well as the U-test both tell you, whether $S_1$ or $S_2$ leads to systematically larger or smaller values. They will not detect different distributions, as long if not one produces larger or smaller values.
t.test(rnorm(100), runif(100, -1, +1))

In R this will perform a t-test comparing values from a standard normal distribution with values from a uniform distribution between -1 and +1 and there is no significant result. The same is true for the U test.
As there are no assumptions about the underlying distribution, I would tend towards a U-test, but the t-test is quite robust against deviation from normality when you compare large numbers (and yours are large in this respect). It will however eventually loose it's advantages with respect to statistical power in non-normally distributed data.
So you are basically free to choose between both tests with only a slight and subjective tendency towards the nonparametric test.
As you have independent data, you do not want a paired t-test.


text:
Q: URL query clearing php code problem This is the code that im using for clear any queries in my url..
<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  $pageURL = substr( $pageURL, 0, strrpos( $pageURL, "?"));
 }
 return $pageURL;
}
?>

this clears

www.mydomian.com/myurl.html?*****

result is

www.mydomian.com/myurl.html

Its done....but the thing it when its come with normal URL

www.mydomian.com/myurl.html

The result is EMPLTY,NO RESULT !
BUT i want as it is..
no change..

www.mydomian.com/myurl.html

i want the result normall url as it is...
Thank You!

A: strrpos returns FALSE if the search string wasn't found.
$pageURL = strrpos( $pageURL, "?") !== FALSE ?
   substr( $pageURL, 0, strrpos( $pageURL, "?")) : $pageURL;

or
if (FALSE != ($pos = strrpos( $pageURL, "?")))
   $pageURL = substr( $pageURL, 0, $pos);


text:
Q: how to control trackwheel sensitivity in Blackberry trackwheelRoll( int amount, int status, int time)

Is there a way to control the trackwheel sensitivity from this method?
Thanks.

A: If you're trying to lower it, you can set a lastMoveTime flag in your class. After that, in your trackwheelRoll() method you can compare the time to that and see if you should move. For example:
protected boolean trackwheelRoll(int amount, int status, int time) {
    if(time - lastMoveTime > someTimeThatYouDetermine) {
        lastMoveTime = time;
        return super.trackwheelRoll(amount, status, time);
    }
    return false;
}

You'll set someTimeThatYouDetermine to control how much lower the sensitivity is. What this does is essentially discard some of the motion so it feels slower to the user.
Alternatively, if you want to increase sensitivity, you can simply multiply amount by some number.


text:
Q: Changing value of input while being in an echo I wanted to change the value of several  elements by clicking the row of one of my list elements
my inputs
<legend> current Song </legend>

            Id
            <input type = "text"
                   id = "currentId"
                   value = ""/>

        //like 12 more of them with the same format as these

            Paragraphs
            <textarea id="currentParagraph"
                      rows="10"
                      cols="80"></textarea>

my code for the table atm:

            Number
            Name
            Category

            <?php
            for($i = 0;$i<sizeof($editor->lieder);$i++)
            {
              echo "
";

              echo "".$editor->lieder[$i]['number']."	";
              echo "".$editor->lieder[$i]['name']."	";
              echo "".$editor->lieder[$i]['category']."	";
              echo "
";
            }
            ?>

I'm not sure how to set the inputs from inside the if because already some layers into it but it's the only way I think of to realise my idea


text:
Q: html templates in AngularJS modules Is there a way to include html templates in AngularJS modules without putting them as strings into js code into the templateCache?

A: The way we've accomplished this is to write our html templates as standalone html files, then use a grunt task to crunch them into strings (handles all the escaping etc) and inject them into the template cache. best of both worlds, as the developers can work on individual HTML files all under source control, but we drastically reduce roundtrips to the server to pull the templates down to the app at runtime. (At the cost of up-front loading)

A: If you want to include one html in another, you can use ng-include directive of angularjs.
I have used this like below:
<div ng-include src = "'partials/myModule/myHtml.html'"></div>


text:
Q: Meteor Semantic-UI-React: focusing components I am building an app with Meteor, React and Semantic-UI. I am new in these frameworks/libraries.
After reading the docs, I still don't understand how to set the focus on a component, because some say you can't do it yet, others say that you can but their example doesn't work for me.
In the below example the options are defined as constants and imported from another document, and the changeHospital & changeActivity functions just set the state of the hospital and activity with the data.value from the options:
          <Form.Field
            label='Hospital'
            control={Select}
            fluid
            search
            value={this.state.hospital}
            placeholder='Select hospital'
            options={hospitals}
            onChange={this.changeHospital}
          />

          <Form.Field
            label='Activity'
            control={Select}
            search
            fluid
            value={this.state.app}
            placeholder='Select activity'
            options={apps}
            onChange={this.changeActivity}
          />

What do I want?
After submitting the first field I want to change the focus on the next field automatically without pressing the tab key or selecting it with the mouse cursor.
Later edit
If you can understand more than me you can read the docs for the semantic-ui-react component at: https://github.com/Semantic-Org/Semantic-UI-React/blob/master/src/modules/Dropdown/Dropdown.js
They say:
/** A dropdown can receive focus. */
tabIndex: PropTypes.oneOfType([
  PropTypes.number,
  PropTypes.string,
]),

A: Disclaimer: I don't know semantic-ui-react, but I do know react, so this is a guess based on how you would solve it with a normal react input.
// Add ref to the field you want to focus
<Form.Field
    ref="activityField"
    label="Activity"
    control={Select}
    search
    fluid
    value={this.state.app}
    placeholder="Select activity"
    options={apps}
    onChange={this.changeActivity}
/>

// Update function from previous input
changeHospital() {
    ... // do what you already do, then change focus
    this.refs.activityField.focus()
}

Calling .focus() on a react input focuses it, but it's possible that Form.Field does not handle .focus() and in that case it won't work.


text:
Q: Running code at noon in Golang Is it possible to execute code at a noon everyday? The program is handling user input the rest of its run time but needs to run a function at noon to output some text. What is the most effective way to do this?

A: So you need Interval Timer to run one function at noon  everyday, you may use:
timer.AfterFunc()  or time.Tick() or time.Sleep() or time.Ticker
first when program starts calculate time interval for start up time till first next noon and use some wait (e.g. time.Sleep or ...) then use   24 * time.Hour interval for the next interval.
sample code using time.Sleep:
package main

import "fmt"
import "time"

func noonTask() {
    fmt.Println(time.Now())
    fmt.Println("do some job.")
}
func initNoon() {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    d := n.Sub(t)
    if d < 0 {
        n = n.Add(24 * time.Hour)
        d = n.Sub(t)
    }
    for {
        time.Sleep(d)
        d = 24 * time.Hour
        noonTask()
    }
}
func main() {
    initNoon()
}

and you may change main to this (or any thing you need):
func main() {
    go initNoon()

    // do normal task here:
    for {
        fmt.Println("do normal task here")
        time.Sleep(1 * time.Minute)
    }
}

using timer.AfterFunc:
package main

import (
    "fmt"
    "sync"
    "time"
)

func noonTask() {
    fmt.Println(time.Now())
    fmt.Println("do some job.")
    timer.AfterFunc(duration(), noonTask)
}
func main() {
    timer.AfterFunc(duration(), noonTask)
    wg.Add(1)
    // do normal task here
    wg.Wait()
}

func duration() time.Duration {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    if t.After(n) {
        n = n.Add(24 * time.Hour)
    }
    d := n.Sub(t)
    return d
}

var wg sync.WaitGroup

using time.Ticker:
package main

import (
    "fmt"
    "sync"
    "time"
)

var ticker *time.Ticker = nil

func noonTask() {
    if ticker == nil {
        ticker = time.NewTicker(24 * time.Hour)
    }
    for {
        fmt.Println(time.Now())
        fmt.Println("do some job.")
        <-ticker.C
    }
}
func main() {
    timer.AfterFunc(duration(), noonTask)
    wg.Add(1)
    // do normal task here
    wg.Wait()
}

func duration() time.Duration {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    if t.After(n) {
        n = n.Add(24 * time.Hour)
    }
    d := n.Sub(t)
    return d
}

var wg sync.WaitGroup

and see:
https://github.com/jasonlvhit/gocron
Golang - How to execute function at specific times
Golang: Implementing a cron / executing tasks at a specific time


text:
Q: PHP em tempo real Me deparei com uma situação que pra mim é complexa.
Como fazer a atualização de um conteúdo em uma página HTML sem precisar atualizar a página, sempre que o banco de dados for alterado, os dados são modificados sem dar refresh neles. Apenas aparece os novos dados.
Procurei por Ajax, mas alguns amigos disseram que ele sobrecarrega o servidor quando tem muitos usuários.
PHP long Polling, até cheio perto de implementar ele, mas não ficou da forma como queria. É como se fosse a aba de comentários do Facebook, quando um novo comentário é enviado, ele só aparece na página, sem atualizar o conteúdo ou a página. Não quero códigos feitos. Quero respostas de métodos pra fazer isso, os prós e contras, alguém por aí já usou ou usa isso? Pode usar como comparação do que preciso, as funcionalidades em tempo real desse site mesmo. Stack Overflow.


text:
Q: Grunt SCSS - Not reloading I am trying to achieve a smooth workflow.
my problem:
My JS modifications are shown and minified and the live reload works fine. When I make changes to my SCSS files they do not run under the run command:
grunt

or the grunt plugin:
grunt watch

It only works when I invoke:
grunt sass

This was the output from the 'grunt sass' console window:
Macintosh:grunt-test Neil$ grunt sass
Running "sass:dist" (sass) task
File "css/global.css" created.

Done, without errors.

Notes:
When I run 'grunt watch' on a sass file I have noticed that grunt runs the minification on the javascript for no reason. Surely this be invoked when that file or one of its dependencies is effected?
Gruntfile.js Contents:
module.exports = function(grunt) {

// 1. All configuration goes here
grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    watch: {
        options: {
            files: ['css/*.css'],
            livereload: true
        },

        css: {
            files: ['css/*.scss'],
            tasks: ['sass'],
            options: {
                spawn: false,
            }
        },

        scripts: {
            files: ['js/*.js', 'scss/*.scss'],
            tasks: ['concat', 'uglify'],
            options: {
                spawn: false,
            }
        }
    },

    sass: {
        dist: {
            options: {
                style: 'compressed'
            },

            expand: true,
            cwd: 'scss/',
            src: ['*.scss'],
            dest: 'css/',
            ext: '.css'
        }
    },

    concat: {
        // 2. Configuration for concatinating files goes here.

        dist: {
            src: [
                'js/libs/*.js', // All JS in the libs folder
                'js/global.js'  // This specific file
            ],
            dest: 'js/build/production.js',
        }
    },

    uglify: {
        build: {
            src: 'js/build/production.js',
            dest: 'js/build/production.min.js'
        }
    },

    imagemin: {
        dynamic: {
            files: [{
                expand: true,
                cwd: 'images-lossy/',
                src: ['**/*.{png,jpg,gif}'],
                dest: 'images/'
            }]
        },

        png: {
            options: {
                optimizationLevel: 7
            }
        },

        jpg: {
            options: {
                progressive: true
            }
        }
    }
});

// 3. Where we tell Grunt we plan to use this plug-in.

// CONCATENATION PLUGIN
grunt.loadNpmTasks('grunt-contrib-concat');
// MINIFY PLUGIN
grunt.loadNpmTasks('grunt-contrib-uglify');
// IMG CRUSH PLUGIN
grunt.loadNpmTasks('grunt-contrib-imagemin');
// GRUNT WATCH PLUGIN
grunt.loadNpmTasks('grunt-contrib-watch');
// SASS LIBARY PLUGIN
grunt.loadNpmTasks('grunt-contrib-sass');

// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default', ['sass','concat', 'uglify', 'imagemin', 'watch']);

};

I hope the above information helps. I have previously used Codekit, and it a really great app. I want to move to grunt but maybe my configuration file is incorrect I am close.
Any help would be greatly appreciated.

*

*Neil

A: It looks like both of your issues occur within the watch configuration.
First, the reason the SASS task isn't working during watch is due to the files entry pointing to the wrong location. Your current files entry points to the "css" folder, but it should point to the "scss" folder, according to what you've specified in the actual "sass" task. In other words, your entry should be: files: ['scss/*.scss'].
css: {
  files: ['scss/*.scss'],
  tasks: ['sass'],
  options: {
    spawn: false,
  }
}

Second, the JavaScript minification occurs during the watch whenever a SASS file changes because you have it listed here:
scripts: {
  files: ['js/*.js', 'scss/*.scss'], // <-- scss is covered here
  tasks: ['concat', 'uglify'],
  options: {
    spawn: false,
  }
}

Change it to files: ['js/*.js'], instead to have the watch task kick in for JavaScript files only.
Once you address those issues, if things are slightly working you might want to expand the patterns so that it covers all files in the subdirectories for your JavaScript, CSS, SASS, etc. For example, js/*.js includes all .js files under the js folder, while js/**/*.js covers the js folder and its subfolders. You can read more under the GruntJS "globbing patterns" documentation.
EDIT: here's how the updated watch should look like...
watch: {
    options: {
        livereload: true
    },

    // css is really for Sass
    css: {
        files: ['scss/*.scss'],
        tasks: ['sass'],
        options: {
            spawn: false,
        }
    },
    // scripts will detect js changes
    scripts: {
        files: ['js/**/*.js'],
        tasks: ['jshint', 'concat', 'uglify'],
        options: {
            spawn: false,
        }
    }
},

As mentioned, your individual tasks might need to use the ** pattern similar to what I've done with the "scripts" entry above: js/**/*.js


text:
Q: Add a new column in table with a sequence - Oracle I have a table that has 60 million rows of data. I would like to introduce a new column say "id" for the table that is an auto incremented sequence.
For example:
CREATE TABLE Persons (
    LastName varchar(255),
    FirstName varchar(255)
);

INSERT INTO Persons VALUES ('abc', 'def');
INSERT INTO Persons VALUES ('abcd', 'ghi');

CREATE SEQUENCE "PERSON_SEQUENCE" START WITH 1 INCREMENT BY 1;

ALTER TABLE PERSONS ADD (PERSONID NUMBER);

UPDATE persons SET personid = PERSON_SEQUENCE.NEXTVAL;

In the above sql statements, I am able to create a sequence then alter the table and update it.
Since the amount of data I need to update is large.. I would like to perform this with as much low cost as possible.
I am trying to do so something like this:
ALTER TABLE PERSONS ADD (PERSONID NUMBER DEFAULT(PERSON_SEQUENCE.NEXTVAL));

but the above does not work. Oracle throws me the below error:

Error starting at line :
1 in command - ALTER TABLE PERSONS ADD (PERSONID NUMBER
  DEFAULT(PERSON_SEQUENCE.NEXTVAL)) Error report -
ORA-00984: column not allowed here
  00984. 00000 -  "column not allowed here"
  *Cause:
  *Action:

However this works:
ALTER TABLE PERSONS ADD (PERSONID NUMBER DEFAULT(0));

Could some one help me with how I can achieve to alter a table (create a new column) and populate the column with a seq id both in a single sql. Thank you!

A: For a table with 60 million rows, I would not do an add column + insert, but create the table new:
RENAME persons TO persons_old;

CREATE TABLE Persons (
  personid   number,
  LastName   varchar(255),
  FirstName  varchar(255)
);

INSERT INTO persons (personid, lastname, firstname)
SELECT person_sequence.nextval, lastname, firstname
  FROM persons_old;

DROP TABLE persons_old;

If this is still taking too long, speak to your DBA about ALTER TABLE NOLOGGING and INSERT /*+ APPEND */ and PARALLEL DML.
EDIT: Ah, yes, for 60 million you could even increase the cache size of the sequence for the initial assignment:
ALTER SEQUENCE PERSON_SEQUENCE CACHE 1000;

A: This worked for me:
alter table PERSONS add (PERSON_ID number default PERSON_SEQ.nextval);


text:
Q: "subst" where indices to be equated also use subst I'm stuck on the following. I have the derivation of a pi calculus transition that takes place in some context Γ, plus a proof that Γ ≡ Γ′. I would like to coerce the derivation into a transition in Γ′, using subst. The details of the setting are mostly unimportant, as usual.
module Temp where
   open import Data.Nat as Nat using (_+_) renaming (ℕ to Cxt)
   open import Function
   open import Relation.Binary.PropositionalEquality

   data _⟿ (Γ : Cxt) : Set where
      bound : Γ ⟿
      nonBound : Γ ⟿

   target : ∀ {Γ} → Γ ⟿ → Cxt
   target {Γ} bound = Γ + 1
   target {Γ} nonBound = Γ

   data Proc (Γ : Cxt) : Set where
   data _—[_]→_ {Γ} : Proc Γ → (a : Γ ⟿) → Proc (target a) → Set where

   -- Use a proof that Γ ≡ Γ′ to coerce a transition in Γ to one in Γ'.
   coerce : ∀ {Γ Γ′} {P : Proc Γ} {a R} → P —[ a ]→ R → (q : Γ ≡ Γ′) →
               subst Proc q P —[ subst _⟿ q a ]→ subst (Proc ∘ target) {!!} R
   coerce E refl = {!!}

It's easy enough to coerce both the source P of the transition, and the action a which appears as a label on the transition. The problem is the target R of the transition, whose type depends on a. In the coerced transition, I use subst to coerce a from Γ ⟿ to Γ' ⟿. Naively, I would like to then also use subst to change the type of R from Proc (target a) to Proc (target (subst _⟿ q a) by showing that the Proc indices are equal. However, by its very nature subst _⟿ q a has a distinct type from a, so I'm unsure how to do this. Maybe I need to use the proof of Γ ≡ Γ′ again or somehow "undo" the inner subst to unify the types.
Is what I'm trying to do reasonable? If so, how do I coerce R given the heterogeneity?

A: Generally, when you want to compare two things of different types (that can become equal given suitable reduction), you would want to use heterogeneous equality.
The proof that subst doesn't actually change the value cannot be done with usual (propositional) equality, because a and subst P q a have different types. However, once you know that q = refl, you can reduce those expressions enough so that their types now match. This can be expressed using heterogeneous equality:
data _≅_ {ℓ} {A : Set ℓ} (x : A) : {B : Set ℓ} → B → Set ℓ where
   refl : x ≅ x

This allows you to even express the fact that a ≅ subst P q a. When you then pattern match on q, the goal reduces to simple a ≅ a, which can then be proven by reflexivity:
≡-subst-removable : ∀ {a p} {A : Set a}
                    (P : A → Set p) {x y} (eq : x ≡ y) z →
                    P.subst P eq z ≅ z
≡-subst-removable P refl z = refl

So, the first instinct is to change the last subst to heterogeneous subst (from Relation.Binary.HeterogeneousEquality) and use the proof ≡-subst-removable. This almost works; the problem is that this subst cannot capture the change from a : Γ ⟿ to Γ′ ⟿.
As far as I know, the standard library doesn't provide any alternate substs that capture this interaction. The simple solution is to write the combinator ourselves:
subst′ : ∀ {Γ Γ′} {a} (q : Γ ≡ Γ′) (R : Proc (target a)) →
         Proc (target (subst _⟿ q a))
subst′ refl R = R

As you noted in the comments, this can be further generalized. However, unless you expect to do a lot of proofs of this kind, this generalization is not very useful since the problem is fairly rare and for the simpler cases, heterogeneous equality usually does the work.


text:
Q: Understanding functions with variable scoping For this code :
A <- 100; B <- 20

f1 <- function(a) {
  B <- 100
  f2 <- function(b) {
    A <<- 200
    B <<- 1000
  }
  f2(a)
}

f1(B)
cat(A)
cat(B)

The following is the output :
> cat(A)
200
> cat(B)
20

Here is my understanding of above code :
The function f1 is invoked with parameter B that has value 20. Within f1 a local variable B is created ( B <- 100 ), f1.B does not have an effect on the variable B
initialiazed outside function call f1 as f1.B is locally scoped to the function f1. A new function f2 is created within f1 that accepts a single argument b.
Within f1 the function f2 is invoked passing as paramter a to f2. f2 does not makes use of its argument b. f2 modifies A using the global operator <-- and sets it to 200. This
why cat(A) outputs 200.
My understanding is incorrect as B is set to 20 when I expect 1000 ? As A is set to 200 in f2 using <-- . d should same not also occur for B ?

A:
The function f1 is invoked with parameter B that has value 20.

No, I don't think so. It is invoked with a parameter a that has the same value as the B in the global environment. B is not directly involved in this point.
You then assign a 100 to a different B, which you call f1.B in your post. (Note that, following the previous statement, that B is created here, not overwritten.)
Then when using the <<- operator, it traverses up in scope, going from f2 (where no B exists) to f1, where it finds this "f1.B" and assigns a 1000.
Similarly, when using the <<- on A, it traverses up. It finds no A in either f2 or f1, but does in the global environment and assigns it there.
You then print to old original B, which has never been altered.
From the help:

<<- and ->> (...) cause a search to be made through parent environments for an existing definition of the variable being
  assigned. If such a variable is found (and its binding is not locked)
  then its value is redefined, otherwise assignment takes place in the
  global environment.

So for B, "such a variable is found", while for A "assignment takes place in the global environment."
Conclusion: <<- is confusing, and often better to be avoided.


text:
Q: Importing android projects that do not have android manifest file I am currently busy in designing a custom view for my major project. I ran through custom view tutorial provided at developer.android.com . I downloaded the associated sharable project because it gets easy to handle and understand the mechanism of the application when source code is in front of you. To my surprise, the project only contains two folders, src and res and there was no android-manifest file. I tried normal import method, import from existing code and createing new project from exsting android code, no luck with any of the methods. Here the link for the project.
Can somebody please explain to me how I can get it working ?

A:
Can somebody please explain to me how I can get it working ?

Create an empty Android project. Copy in the res/ and src/ from the ZIP file. Modify the manifest to point to the activity class that you copied from the ZIP file.

A: Create a new empty android project. Copy all resources and source files to your project folder.
http://developer.android.com/guide/topics/manifest/manifest-intro.html.
Goto AndroidManifest.xml define activities and permissions accordingly.
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="package name"
  android:versionCode="1"
  android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="packagename.MainActivity"//your mainactivity
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
       <activity
        android:name="packagename.SecondActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="packagename.SecondActivity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>


text:
Q: Java 8 Stream distinct is not working This is what i am doing:
List scores = Stream.concat(oldEntries.stream(), newEntries.stream())
                    .sorted()
                    .distinct()
                    .limit(maxSize)
                    .collect(Collectors.toList());

I am expecting a sorted list without any duplicates, but some times there is duplicate in the list.
I have override the hashCode and equals method, I have also observed that these methods are returning the correct value every time. Can any one see what is wrong with my stream?
This is my equals() and hashCode() They are auto generated by IDEA :
..
private int userId;
private int levelId;
private int score;

@Override
public boolean equals(Object o) {

    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Score score = (Score) o;

    if (userId != score.userId) return false;
    return levelId == score.levelId;

}

@Override
public int hashCode() {
    int result = userId;
    result = 31 * result + levelId;
    return result;
}

public int compareTo(Score other) {

    if (other == null) {
        return 1;
    } else {
        return Integer.compare(other.score, this.score);
    }
}

 ..

A: It is a bug.
The documentation of Stream.distinct() simply says:

Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream.
For ordered streams, the selection of distinct elements is stable (for
duplicated elements, the element appearing first in the encounter
order is preserved.) For unordered streams, no stability guarantees
are made.

There is no requirement that for ordered streams the equal objects should come right after each other (consecutively). However the implementation seems to assume they do. What the documentation means is that the first occurrence of user 2, level 3 should be preserved and the second occurrence discarded.
According to the Java bug database the bug exists up to Java 13 and remains unresolved.
Links

*

*Documentation of Stream.distinct()

*JDK-8223933 Stream.distinct() sometimes allows duplicates when the stream is sorted in the JDK Bug System.

A: Your stream is first ordered according to compareTo, i.e. using score.
It's then "distinctified" using equals(), i.e. using userId and levelId. According to the javadoc:

For ordered streams, the selection of distinct elements is stable (for
  duplicated elements, the element appearing first in the encounter
  order is preserved.)  For unordered streams, no stability guarantees
  are made.

Example:
score 1, user 2, level 3
score 3, user 2, level 3
score 1, user 3, level 1

After sorting...
score 1, user 2, level 3
score 1, user 3, level 1
score 3, user 2, level 3

Distinct now does nothing, because the elements are not equal according to user/level. This can result in "duplicate" elements, because you're ordering the stream based on one thing, but determining equality by an entirely different thing.


text:
Q: How to return querySelectorAll for IDs starting with a number JavaScript function querySelectorAll() fails on Chrome when the IDs begin with a number.
For example, querySelectorAll("#A5") succeeds, but querySelectorAll("#5A") returns
Error:

"Uncaught DOMException: Failed to execute 'querySelectorAll' on
'Element': '#5A' is not a valid selector."

I understand that an ID starting with a number is valid in HTML5 so I wondered if anyone knows of another way to query for it.
I tried querySelectorAll("#5A") and expected the query to include the element with an id set to "5A"
I realise I can just use "document.getElementById()" to find one element, but I want to include it in a multi-element query in the DOM.


text:
Q: Rolling my own Require Forward
It has come to my attention that this problem was a "Function Scoping - Not Block Scoping" answer, the difference being for ... in opposed to for ... i<n ... i++ The solution could be wrapping the for(var p in ...) { with a function to give them their own scope (much like was done with Array.prototype.forEach). Thank you for your help.
Problem
I'm rolling my own tiny Require.js solution as opposed to the actual Require.js library (no I haven't taken a look at their source).
My callback function never seems to be executed, but I can't figure out why. It's probably a simple logical error, but you know how it goes when you stare at your own code for too long. (Everything looks logically sound)
Usage
Used as follows:
require(["LibraryA", "LibraryB", "LibraryC"], function() {
    //code which requires libraries a-c here
});

Code
var require = (function() {
    var scriptsLoaded = [];
    return function(paths, callback) {
        var pathsDoneLoading = {};
        for(var i = 0; i < paths.length; i++) {
            pathsDoneLoading[paths[i]] = false;
        }
        for(var p in pathsDoneLoading) {
            for(var i = 0; i < scriptsLoaded.length; i++) {
                if(p === scriptsLoaded[i]) {
                    pathsDoneLoading[p] = true;
                }
            }
        }
        for(var p in pathsDoneLoading) {
            if(pathsDoneLoading[p] === false) {
                var script = document.createElement("script");
                script.src = p + ".js";
                script.onload = function() {
                    scriptsLoaded.push(p);
                    pathsDoneLoading[p] = true;
                    for(var p in pathsDoneLoading) {
                        if(pathsDoneLoading[p] !== true) {
                            return;
                        }
                    }
                    callback();
                };
                document.documentElement.appendChild(script);
            }
        }
    }
})();

Plunker
https://plnkr.co/edit/OFWTUpmV3sIJAjhGhcLO

A: It's the old for loop variable catching problem.
During your loop where it's iterating through what paths are loading (for (var p in pathsDoneLoading) {) the p is being bound to the function inside. The problem is that p changes and persists after the loop has complete so every single function is adding the last key in the pathsDoneLoading object to the scriptsLoaded array (and setting the matching value in pathsDoneLoading to true).
An example of the problem:

var obj = { a: 1, b: 2, c: 3 };
var funcs = [];
for (var key in obj) {
  funcs.push(function() {
    return key; // Remember, `key` is bound to the function, not the block
  });
}

funcs.forEach(function(f) {
  document.querySelector('pre').innerText += f() + '\n';
});

To fix this, you can wrap it in an IIFE to create a new binding per p value.
for (var p in pathsDoneLoading) {
  (function(p) {
    if (pathsDoneLoading[p] === false) { // or `if (!pathsDoneLoading[p])`
    ...
  })(p);
}

That way every time you generate an onload handler, they have a unique binding to the intended path.
Our previous example fixed with this solution:

var obj = { a: 1, b: 2, c: 3 };
var funcs = [];
for (var key in obj) {
  (function(key) {
    funcs.push(function() {
      return key; // Remember, `key` is bound to the function, not the block
    });
  })(key);
}

funcs.forEach(function(f) {
  document.querySelector('pre').innerText += f() + '\n';
});

A: Simply put, you'll need capture the for loop iterator because it's a moving target and by the time onload fires, it will have changed.
    var require = (function() {
    var scriptsLoaded = [];
    return function(paths, callback) {
        var pathsDoneLoading = {};
        for(var i = 0; i < paths.length; i++) {
            pathsDoneLoading[paths[i]] = false;
        }
        for(var p in pathsDoneLoading) {
            for(var i = 0; i < scriptsLoaded.length; i++) {
                if(p === scriptsLoaded[i]) {
                    pathsDoneLoading[p] = true;
                }
            }
        }
        for(var p in pathsDoneLoading) {
            if(pathsDoneLoading[p] === false) {
                var script = document.createElement("script");
                script.src = p + ".js";

                // Wrapping in a closure
                script.onload = (function(Vp) {
                    scriptsLoaded.push(Vp);
                    pathsDoneLoading[Vp] = true;
                    for(var prop in pathsDoneLoading) {
                        if(pathsDoneLoading[prop] !== true) {
                            return;
                        }
                    }
                    callback();

                // Execute the closure function and send in your
                // var(s) as argument(s) to capture it's current state
                }(p));
                document.documentElement.appendChild(script);
            }
        }
    }
})();


text:
Q: mod_rewrite $_GET I have a FrontController expecting two $_GET params:
controller
action

A typical call to the site would look like this:

http://foo.bar/index.php?controller=start&action=register

What I want to do is to allow the user to visit this site by the following url:

http://foo.bar/start/register

What I've tried:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.+)/(.+)$ index.php?controller=$1&action=$2 [L,QSA]
</IfModule>

Since this gives me 404 Errors it doesn't seem to work.
mod_rewrite itself is enabled on the server.

A: The .htaccess you posted works for me:
// GET /cont1/action1

print_r($_GET);

/* output
Array
(
    [controller] => cont1
    [action] => action1
)
*/

You might want to try an absolute path to index.php rather than a relative one.
Regardless, that regex will result in:
// GET /cont1/action1/arg1

print_r($_GET);

/* output
Array
(
    [controller] => cont1/action1
    [action] => arg1
)
*/

You'd be better off doing:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>

And having your index.php split up the $_GET['url'] into controller, action, args, etc...

A: There are 2 parts to getting this working. If you are working with PHP and Apache, rewrite engine must be available on your server.
In your user folder put a file named .htaccess with these contents:
 RewriteEngine on
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule . index.php [L]

Then your index.php you can use the REQUEST_URI server variable to see what was requested:
<?php
$path = ltrim($_SERVER['REQUEST_URI'], '/');
echo $path;
?>

If someone requested /start/register, then assuming all the above code is in the html root, the $path variable would contain start/register.
I'd use the explode function on $path using the / as a separator and pull the first element as register.
The rewrite code has the benefit of working with filenames and directory names.


text:
Q: Can't use google custom font via expo in other part of app I'm loading a google custom font with expo in my App.js file as such:
;

import {
  useFonts,
  Poppins_300Light,
  Poppins_400Regular,
  Poppins_400Regular_Italic
} from "@expo-google-fonts/poppins";

export default function App() {
  const [auth, setAuth] = useState(false);

  const [loading, setLoading] = useState(true);
  let [fontsLoaded] = useFonts({
    "Poppins-Light": Poppins_300Light,
    "Poppins-Regular": Poppins_400Regular,
    "Poppins-Regular-Italic": Poppins_400Regular_Italic,

  });

  useEffect(() => {
    (async () => {
      // Check if user is logged in
      const token = await getKey("access_token");
      if (token) {
        setAuth(true);
      }
    })();
    setLoading(false);
  }, []);

  if (loading || !fontsLoaded) {
    return <AppLoading />;
  }

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Camera"

      >
        {!auth ? (
          <>
            <Stack.Screen
              name="Analytics"
              component={Analytics}

            />
            <Stack.Screen
              name="Settings"
              component={Settings}

            />

          </>
        ) : (
          <>
            <Stack.Screen
              name="Login"
              component={Login}

            />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Now, when I try to use font-family: Poppins-Light in my Login.js file, I get the error Unrecognized font family "Poppins-Light"
Not sure what's going on. I think there may be something wrong with the way I'm loading, and, further, how I am importing the fonts into my Login file.
I'm also using styled components so I'm not sure if that has any effect.
Here is my package JSON
"dependencies": {
    "@expo-google-fonts/inter": "^0.1.0",
    "@expo-google-fonts/poppins": "^0.1.0",
    "@react-native-community/masked-view": "0.1.10",
    "@react-navigation/bottom-tabs": "^5.11.8",
    "@react-navigation/native": "^5.9.3",
    "@react-navigation/stack": "^5.14.3",
    "expo": "~40.0.1",
    "expo-app-loading": "^1.0.1",
    "expo-camera": "~9.1.0",
    "expo-constants": "~9.3.3",
    "expo-font": "~8.4.0",
    "expo-haptics": "~8.4.0",
    "expo-jwt": "^1.4.0",
    "expo-linear-gradient": "~8.4.0",
    "expo-secure-store": "~9.3.0",
    "expo-sqlite": "~8.5.0",
    "expo-status-bar": "~1.0.3",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
    "react-native-dotenv": "^2.5.3",
    "react-native-gesture-handler": "~1.8.0",
    "react-native-global-props": "^1.1.5",
    "react-native-reanimated": "~1.13.0",
    "react-native-safe-area-context": "3.1.9",
    "react-native-screens": "~2.15.2",
    "react-native-svg": "^12.1.0",
    "react-native-svg-transformer": "^0.14.3",
    "react-native-unimodules": "^0.12.0",
    "react-native-web": "~0.13.12",
    "react-swipeable-views-native": "^0.13.2",
    "styled-components": "^5.2.1"
  },

This is how I'm using it in my Channels.js file

 <HeaderTitle style={{ fontFamily: "Poppins-Light" }}>
          Channels
        </HeaderTitle>

Here is the error when I try to access the page:

Any idea what I'm doing wrong?
Your help would be massively appreciated.

A: Take look here, snack. Follow the pattern.
If the problem still occurs then please, give a little more code snippet with file structure then we can pinpoint your problem.

A: You need first install, as all google fonts are available there
expo-google-fonts
As in your case you are using Poppins
So
expo install @expo-google-fonts/poppins expo-font

You can replace Poppins with your custom fonts
You can get it from
https://directory.vercel.app/ => All Google Fonts Expo Package Name
import React, { useState, useEffect } from 'react';

import { Text, View } from 'react-native';
import AppLoading from 'expo-app-loading';
import {useFonts, Poppins_500Medium} from '@expo-google-fonts/poppins'

export default () => {
  let [fontsLoaded] = useFonts({
    Poppins_500Medium,
  });

  if (!fontsLoaded) {
    return <AppLoading />;
  } else {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>

        <Text style={{ fontFamily: 'Poppins_500Medium' }}>
          Your text goes here
        </Text>

      </View>
    );
  }
};

You can refer this from https://github.com/expo/google-fonts


text:
Q: Отказано в доступе из под рута Установил FTP-сервер pure-ftpd.
Хочу настроить.
Конфига у сервера нет.
Настройки он воспринимает так: в каталоге /etc/pure-ftpd/conf
находятся файлы, каждый из которых отвечает за один параметр.
Чтоб настроить что-то нужно создать файл с определённым именем и в нём написать "yes" или "no".
Пытаюсь сделать это:
sudo echo no > /etc/pure-ftpd/conf/someparam
На что мне отвечают:
An error occurred while redirecting file '/etc/pure-ftpd/conf/someparam'
open: Permission denied
Как у root'а может отсутствовать доступ?

A:
sudo echo no > /etc/pure-ftpd/conf/someparam

от имени привилегированного пользователя выполняется процесс, запущенный командой echo no.
а манипуляции с перенаправленным потоком stdout осуществляет уже текущий процесс оболочки, который, судя по всему, не имеет прав на запись в указанный файл.

можно пойти двумя путями:

*

*именно запись в файл осуществлять от имени привилегированного пользователя, например, так:
$ echo no | sudo tee /etc/pure-ftpd/conf/someparam

*выполнять от имени этого пользователя оба действия, совместив их в одну команду, передаваемую shell-у, например, так:
$ sudo sh -c 'echo no > /etc/pure-ftpd/conf/someparam'


text:
Q: Cannot convert null or undefined to object when using hasOwnProperty I am trying to use hasOwnProperty in a more elegant way.
I have this code here, which works fine:
var obj = {
    a: 2,
    b: 7,
    bamboo: 22
};

var keys = Object.keys(obj).filter(key => obj.hasOwnProperty(key));

// keys: [ "a", "b", "bamboo" ]

However when I try to pass obj.hasOwnProperty as shorthand (which should work), it doesn't behave how I expect.
var keys = Object.keys(obj).filter(obj.hasOwnProperty);

// Uncaught TypeError: Cannot convert undefined or null to object
//     at hasOwnProperty (<anonymous>)

To ensure that the parameter is passed to hasOwnProperty correctly, I have set up this test case:
var testFilter = (key) => {
    console.log(key);
    return true;
};

Object.keys(x).filter(testFilter);

a, b and bamboo are all logged to the console, so I know that it is passing the parameters correctly.
Why does the behaviour not work correctly for hasOwnProperty?

A: object.hasOwnProperty takes the object as its this value. When you do direct calls, this is implicitly provided by looking at what object the method is called on, but with indirect calls, you have to specify this manually:

var obj = { foo: 3 };
var func = obj.hasOwnProperty;

console.log(func('foo')); // TypeError: Cannot convert undefined or null to object

One of the easiest way to do this is with function.bind, like this:

var obj = { foo: 3 };
var func = obj.hasOwnProperty.bind(obj); // bind `this` of function to `obj`
console.log(func('foo')); // = true

A: For a correct callback, you need to bind the object to hasOwnProperty and then use the returned function.

var obj = {
        a: 2,
        b: 7,
        bamboo: 22
    },
    keys = Object.keys(obj).filter({}.hasOwnProperty.bind(obj));

console.log(keys);


text:
Q: Encryption Key Management Software and Transparent Data Encryption MySQL For PCI compliance, is there any recommended Encryption Key Management Software? Open source preferable, but commercial is ok too. Is there a tool or software that provides both?

A: ezNCrypt looks like it may be useful, it promises TDE for MySql
You could also consider using MS SQL 2008 to store the card data, then look into Extensible Key Management. There are a few EKM providers out there, such as Thales.  Using a 3rd party EKM would be easy (probably zero development time), but very costly (think $50k). With an EKM module you can then use Transparent Data Encryption
If you only want key management, without the transparent data encryption, then StrongKey is probably your best price/performance option. You'd need to spend some development time to integrate with it.
If you want to take the time and develop your own solution, then I can offer some help in the answer here
Good luck!

A: MyDiamo is freeware for non-profit personal use, and commercial for another use.
You can encrypt datas in MySQL.
MyDiamo has developed under Engine-Level Encryption.
It provides "transparent" installation and encryption.
Thank you.

A: I'm not going to pretend to answer the main question, but I would have thought that if the encryption is transparent, then that likely wouldn't address the usual concerns re PCI compliance.  That is to say, the encryption of things like credit card data being highly opaque from the point of view of your application is the whole point of the exercise.


text:
Q: Имя выбранного файла из html в php Есть html с кнопкой выбора файла:
   <!DOCTYPE html>

     <meta charset="UTF-8">
     <title>Поле загрузки файлов, которое мы заслужили</title>
     <link rel="stylesheet" href="style.css">

     <form id="upload-container" method="POST" action="index.php">

               <input id="file-input" type="file" name="file" multiple>

     </form>
     <form action="index.php" method="POST">
        <input name="submit" type="submit" value="Выполнить" />
   </form>

И есть PHP в который нужно получить имя файла :
    <?php
if (isset($_POST['submit']){
    $_FILES['userfile']['name']

include('выбор.html');
include ('наша.php');
echo '
';
$kml = new SimpleXMLElement($xmlstr);
foreach ($kml->Document->Folder->Placemark as $Placemark) {

        echo $Placemark->MultiGeometry->Polygon->outerBoundaryIs->LinearRing->coordinates, PHP_EOL;

    foreach ( $Placemark->ExtendedData->SchemaData as $SchemaData ) {
        foreach ( $SchemaData as $SimpleData ) {
            $name = $SimpleData->attributes()->name;
            if ( $name == 'TITLE' || $name == 'DESCRIPTIO' || $name == 'SHAPE_Area') {
                echo '
';
                echo $SimpleData . PHP_EOL;
                echo '
';
            }
        }
    }
}
}
?>

Как мне в PHP через POST получить имя выбранного файла?

A: Пропущена круглая скобка в условии.
Найди:
if (isset($_POST['submit']){

Замени на:
if (isset($_POST['submit'])){

A:
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="my_file[]" multiple>
        <input type="submit" value="Upload">
    </form>
    <?php
        if (isset($_FILES['my_file'])) {
            $myFile = $_FILES['my_file'];
            $fileCount = count($myFile["name"]);

            for ($i = 0; $i < $fileCount; $i++) {
                ?>

File #<?= $i+1 ?>:

                        Name: <?= $myFile["name"][$i] ?>

                        Temporary file: <?= $myFile["tmp_name"][$i] ?>

                        Type: <?= $myFile["type"][$i] ?>

                        Size: <?= $myFile["size"][$i] ?>

                        Error: <?= $myFile["error"][$i] ?>

                <?php
            }
        }
    ?>


text:
Q: Will USB 2.0 degrade through connectors? In my design I have a national instruments chassis (cDAQ 9132) inside of a closed rack fixture. I want to be able to access the usb port on the NI chassis from a front panel on the external of the rack. My thoughts were to just connect a male-to-male usb cable from the NI chassis into the front panel via a panel mount usb connector.
My question is, will the usb extender and connector cause signal degradation? The total length would only be a few feet, much less then the 5 meter maximum.

A: From my experience, USB extender cables work, with caveats.

*

*Power

A device I have draws 460mA out of the allowed 500mA. It will only work with good quality cables (ie, with enough copper in them), no extenders, and only some ports on the PC (those on the mobo, not those on the front, which go through more cables). Contact and wire resistance matters...
Less power-hungry devices will cause less problems.

*

*Data

USB Bulk mode retransmits packets when an error is detected.
If your device uses bulk mode, a little more bit errors will reduce throughput (slightly). If there are enough bit errors to make enumeration fail, though, it won't work at all.
I have used extenders with high speed devices without problems.
When you think about it, the USB connectors on the front of your PC go through an extender cable... and they're connected to the mobo with 0.1" headers, which I honestly doubt respect the USB impedance spec...
Why not try? I'm pretty sure it will work, as long as all connectors are USB certified.

A: You are essentially asking if you can use a USB 2.0 extender cable in your setup. The answer is "it depends".
First, formally the USB specifications disallow cable extenders, for the reason that every extra cable imperfection (two extra connectors and two cable fan-outs at solder joints inside cable molds) usually degrade the high-speed signals beyond acceptable. Quality of extenders, however, vary greatly, so your mileage can vary.
Then, it depends whether you/your users/customers are going to plug USB devices with extra long 5-m cables. Then your extra extender will likely kill the USB functionality in high-speed mode. You will have flaky behavior, with unpleasant experience, data corruption, etc. Contrary to the belief in USB data recovery mechanism, it works only in a narrow region of degraded signals. If the channel gets degraded a bit deeper (due contact wear, contamination, different mechanical tension), the channel will just drop off, reconnect back, and cause a lot of troubles.
However, if you plan to use only LS/FS USB devices (mice/keyboards/sound) the extender will be fine.
The hopes that USB port will fall-back into FS mode are also unfounded. The reason is that the FS-HS negotiations are coming at a relatively low signal speed (~20kHz) where the signal degradation is negligible, so the initial connection will be always negotiated as "HS mode", and the link will always start in HS at 480 Mbps. Then the channel will see massive transfer errors, and host will try to recover the port by resetting/re-enumerating it, and process will fall into the same loop.