text:
Q: How to drop data above a certain frequency in a histogram/dataset? To make things clearer, I don't want to remove the entire bin from the histogram, I just want to get rid of some of the data so that it is brought below a desired frequency. The line in the image shows the max frequency I would like

For context, I have a dataset containing a number of angles. My question is very similar to the question asked here Remove data above threshold in histogram in terms of the data used but unlike the question in the link, I dont wish to get rid of the data, just reduce it.
Can I do this directly from the histogram or will I need to just delete some of the data in the dataset?
edit (sorry I am new to coding and formatting here):
here is a solution i tried
bns = 30
hist, bins  = np.histogram(dataset['Steering'], bins= bns)
removeddata = []

spb = 700
for j in range(bns):
    rdata = []
    for i in range(len(dataset['Steering'])):
        if dataset['Steering'][i] >= bins[j] and dataset['Steering'][i] <=
        bins[j+1]:
            rdata.append(i)
    rdata = shuffle(rdata)
    rdata = rdata[spb:]
    removeddata.extend(rdata)

print('removed:', len(removeddata))
dataset.drop(dataset.index[removeddata], inplace = True)
print ('remaining:', len(dataset))

center = (bins[:-1] + bins[1:])*0.5
plt.bar(center,hist,width=0.05)
plt.show()

This is somebody else's solution but it seemed to work for them. Even directly copying, it still throws errors. The error I got was "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()", I tried to change 'and' to & and got the error "TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]". Unsure what this exactly refers to but points to the line with the if statement. Checked the dtype of everything and they are all type float64, so unsure of my next step

A: This answer doesn't re-bin or re-center the data, but I believe it generally achieves what you're asking.  Working from the example in the chosen answer of the post you linked, I edit the hist array so that the original input data is not changed as you indicated is your preferred solution:
import numpy as np
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1,2)
ax1.set_title("Some data")
ax2.set_title("Gated data < threshold")

np.random.seed(10)
data = np.random.randn(1000)

num_bins = 23
avg_samples_per_bin = 200

hist, bins = np.histogram(data, num_bins)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) * 0.5
ax1.bar(center, hist, align='center', width=width)

threshold = 80

gated = np.empty([len(hist)], dtype=np.int64)
for i in range(len(hist)):
    if hist[i] > threshold:
        gated[i] = threshold
    else:
        gated[i] = hist[i]

ax2.bar(center, gated, align="center", width=width)

plt.show()

which gives

A: This solution takes into account the clarified requirement that the original input data that exceeds the frequency threshold be dropped.  I left my other answer because it is simpler and different enough that it may be useful to another user.
To clarify, this answer produces a new 1D array of data with fewer elements and then plots a histogram from that new data.  The data are shuffled before the elements are removed (in case the input data were pre-sorted) in order to prevent bias in dropping data from either the low or high side of each bin.
import numpy as np
import matplotlib.pyplot as plt
from random import shuffle

def remove_gated_val_recursive(idx, to_gate_lst, bins_lst, data_lst):
    if to_gate_lst[idx] == 0:
        return(data_lst)
    else:
        bin_min, bin_max = bins_lst[idx], bins_lst[idx + 1]
        for i in range(len(data_lst)):
            if bin_min <= data_lst[i] < bin_max:
                del data_lst[i]
                to_gate_lst[idx] -= 1
                break
        return remove_gated_val_recursive(idx, to_gate_lst, bins_lst, data_lst)

threshold = 80

fig, ax1 = plt.subplots()
ax1.set_title("Some data")

np.random.seed(30)
data = np.random.randn(1000)

num_bins = 23

raw_hist, raw_bins = np.histogram(data, num_bins)

to_gate = []
for i in range(len(raw_hist)):
    if raw_hist[i] > threshold:
        to_gate.append(raw_hist[i] - threshold)
    else:
        to_gate.append(0)

data_lst = list(data)
shuffle(data_lst)

for idx in range(len(raw_hist)):
    remove_gated_val_recursive(idx, to_gate, raw_bins, data_lst)

new_data = np.array(data_lst)
hist, bins = np.histogram(new_data, num_bins)

width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) * 0.5
ax1.bar(center, hist, align='center', width=width)

plt.show()

gives the following histogram, plotted from the new_data array.


text:
Q: I am not able to install Miniconda on MacOS X with Homebrew and .zsh Please help, I tried to install Miniconda on Mac OS X Mojave with:
brew cask install miniconda

then I added export path to .zshrc file (Oh my Zsh):
export PATH="$PATH:$HOME/miniconda3/bin"

But it is not being recognized:
zsh: command not found: conda

I cant find what I am doing wrong

A: I finally had to do a workaround by downloading it directly:
wget https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
bash Miniconda3-latest-MacOSX-x86_64.sh

but I still don't understand why Homebrew is not working

A: After brew cask install miniconda, it was installed to /opt/miniconda3

A: After installing miniconda using homebrew, you will need to run:
/opt/miniconda3/condabin/conda init zsh

For more info see https://discourse.brew.sh/t/why-does-brew-cask-install-miniconda-to-opt-instead-of-usr-local-caskroom/7926

redpajama_set_name: RedPajamaStackExchange


text:
Q: regexp_replace fails in presto but works on regex101 with java8 flavor The following regex works on regex101 (with the Java8 flavor), but doesn't work when running it with regexp_replace in Presto SQL.
Regex:
(?<!timeFrame:\"(?:\d\d?\d?\d?)?)[0-9.\/,]
Test string:
timeFrame:"122 Days" ipAddress:1.1.1.1
Expected outcome:
timeFrame:"122 Days" ipAddress:
You can see it working on regex101 here:
https://regex101.com/r/udpivA/1
According to Presto's documentation, it should be running "the Java pattern syntax".
When running this function in Presto:
regexp_replace(string, '(?<!timeFrame:\"(?:\d\d?\d?\d?)?)[0-9.\/,]', '')
I get this error:
java.sql.SQLException: [Simba][AthenaJDBC](100071) An error has been thrown from the AWS Athena client. INVALID_FUNCTION_ARGUMENT: invalid pattern in look-behind

How can I get this regex to work on Presto?

A: The error message mentions an invalid pattern in the look-behind pattern, which most probably means that presto does not support look-behind patterns that could match strings with varying lengths, and so it would not allow the ? quantifier (nor + or *) in a look-behind pattern.
You can avoid this by actually matching the "timeframe" pattern, and capturing it in a capture group, so that you can reproduce it in the replacement string with $1 -- which practically means that you don't actually delete it. With | you can then add another alternative that also matches digits (but which don't match with the first option). If those are matched, the capture group (around the "timeframe" pattern) is empty, and so $1 represents the empty string, which practically means that those matches are removed:
regexp_replace(string, '(timeFrame:\"\d+)|\d[0-9.\/,]*', '$1')

NB: I have prefixed the [0-9.\/,] pattern with \d as I assume you don't want to remove points and commas when they are not part of a term that starts with a digit.


text:
Q: HTML - tide times - change source url based on user input Why:
My site will have tide times as a small feature (so not the primary feature).
What:
As part of that tide times feature, I want to provide the user a 'drop down' set of options to select a location and the default tide times update with the users selection.
Why it's not working:
After selecting an option, the table disappears. It should not disappear. It should update with the chosen location.
Would love some help/direction on this.  It's been driving me crazy for the past week now.
Long summary:
I'm bolting together the site and I have a tide time widget / html snippet. Only the snippet doesn't come with the option for a user to change the location. I hope to customise the html page to include a drop down list and the selected value replace the src url location. Then the widget updates on the change (not the whole page).
I've been learning lots on here. But I am a novice - so maybe there are basic rules I am breaking.
Would love some help/direction on this. It's been driving me crazy for the past week now.
I've been researching and the code below is what I came up with.
<select onChange="ChangeLocation(value)">
  <option value="-">Select region</option>
  <option value="barry">Barry</option>
  <option value="aldeburgh">Aldeburgh</option>
</select>

A: I have solved this using "postscribe" from https://github.com/krux/postscribe.
I'm using postscribe from the cdn by using it in the

Then, the content of the  tag as following:
<select onChange="ChangeLocation(value)">
    <option value="-">Select region</option>
    <option value="barry">Barry</option>
    <option value="aldeburgh">Aldeburgh</option>
</select>


text:
Q: Rails + Angularjs: How to communicate (delete record from database) with backend? I stuck on this for the whole day.
On http://localhost:3001/posts/, I list all posts I have in the database. I am trying to delete a task with using Angularjs - every loaded record from the database has a link for its deleting:
= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"

Then I have a file /assets/javascript/angular/controller/posts.js that looks like this:
var app = angular.module('AngTestApp', ['ngResource']);

app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
        index:   { method: 'GET', isArray: true, responseType: 'json' },
      show:    { method: 'GET', responseType: 'json' },
      update:  { method: 'PUT', responseType: 'json' }
    });
})

app.controller("PostsCtrl", function($scope, Post) {
  $scope.posts = Post.index();
    $scope.deletePost = function(index) {
        console.log("index: "+index);
        post = $scope.posts[index];
      Post.delete(post);
        $scope.posts.splice(index, 1);
        console.log('aa');
    }
})

When I click the delete link, I receive this error in the JS console:
DELETE http://localhost:3001/posts 404 (Not Found)

and in terminal:
Started DELETE "/posts" for 127.0.0.1 at 2015-10-15 16:23:08 -0700

ActionController::RoutingError (No route matches [DELETE] "/posts"):

The routes look like this:
resources :posts do
  resources :comments
end

The JS code is very chaotic, I tried to modify a tutorial I found on the Internet, but it doesn't work well.
What is wrong in this attempt?
Thank you in advance.

A: You need to pass the ID of the record you're trying to delete as a parameter in the call to Rails. Rails is telling you it can't find the route because you do not have an ID.
Since you do not define the DELETE action in your factory, that is likely why the ID is not getting passed. You could also try explicitly passing the id as a param, like below:
$resource takes a params attribute, so you can modify your factory like so:
app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
      index:   { method: 'GET', isArray: true, responseType: 'json' },
      show:    { method: 'GET', responseType: 'json' },
      update:  { method: 'PUT', responseType: 'json' },
      delete:  { method: 'DELETE', params: '@id', responseType: 'json' }
    });
})

The $resource docs are pretty helpful: https://docs.angularjs.org/api/ngResource/service/$resource


text:
Q: How do I make my javascript function change the color of my text? I'm trying to make a website. And, on my website, on the menu page, I want my menu options to change color depending on which one has been clicked on. For example, when the page loads, it automatically starts on main, so the main button is green. But, when I click vegoption, I want vegoption to turn green and mainoption to turn black. And the same system for the other options.
Please forgive me if I have done things wrong in my javascript. I'm very new to the language. If there are any other improvements I can make, please let me know.
Here is the code:
/* Start Variables */

:root {
  --aa-color: #57C324;
}

/* End Variables */

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'Source Sans Pro', sans-serif;
}

/* Start Navbar */

.navbar-wrapper {
  // background: blue;
  padding: 20px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 5px 10px 8px #888888;
  z-index: 100;
  position: relative;
}

.leftside {
  // background: green;
  width: 50%;
  height: 10px;
}

.rightside {
  width: 50%;
  // background: red;
}

.options {
  // background: yellow;
  text-decoration: none;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.linkhome {
  font-size: 120%;
  text-decoration: none;
  color: black;
  margin-right: 0%;
  margin-left: 2%;
  display: inline-block;
}

.linkmenu {
  font-size: 120%;
  text-decoration: none;
  color: var(--aa-color);
  ;
  margin-right: 0%;
  margin-left: 2%;
  display: inline-block;
}

.linkabout {
  font-size: 120%;
  text-decoration: none;
  color: black;
  margin-right: 0%;
  margin-left: 2%;
  display: inline-block;
}

.linkfood {
  font-size: 120%;
  text-decoration: none;
  color: black;
  margin-right: 0%;
  margin-left: 2%;
  display: inline-block;
}

.linkculture {
  font-size: 120%;
  text-decoration: none;
  color: black;
  margin-right: 0%;
  margin-left: 2%;
  display: inline-block;
}

.linkmenu:hover {
  color: var(--aa-color);
}

.linkabout:hover {
  color: var(--aa-color);
}

.linkfood:hover {
  color: var(--aa-color);
}

.linkculture:hover {
  color: var(--aa-color);
}

/* End Navbar */

/* Start Main */

.injera-menu {
  background-size: cover;
  overflow: hidden;
  width: 100%;
  height: 10%;
  display: block;
}

.ourmenutext {
  position: absolute;
  margin-top: -25%;
  font-size: 400%;
  background: -webkit-linear-gradient(#10CB00, #10CB00, #FFC701, #FF0101, #FF0101);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke: 3px white;
  -webkit-text-stroke: 3px black;
  margin-left: 3%;
}

.menuoptions {
  display: flex;
  width: 100%;
  justify-content: center;
}

.mainoption {
  margin: 2% 5%;
  color: var(--aa-color);
}

.vegoption {
  margin: 2% 5%;
}

.specialoption {
  margin: 2% 5%;
}

.drinksoption {
  margin: 2% 5%;
}

.vegoption:hover {
  color: var(--aa-color)
}

.specialoption:hover {
  color: var(--aa-color)
}

.drinksoption:hover {
  color: var(--aa-color)
}

/* Start Menu */

.menu {
  position: relative;
}

/* Start Main Menu */

.menumain {
  justify-content: center;
  color: var(--aa-color);
  dis
}

.price {
  float: right;
  border: 1px solid var(--aa-color);
  padding: 1% 2%;

}

.dishtitle {
  margin-left: 40%;
  text-decoration: underline;
}

.dishinfo {
  padding: 5% 10%;
  font-size: 150%;
}

.menu-item {
  width: 70%;
  border: 3px solid var(--aa-color);
  padding: 20px;
  margin-left: 15%;
  margin-bottom: 5%;
  box-shadow: 5px 10px 8px #888888;
    justify-content: center;
}

.menuveg {
    width: 100%;
  justify-content: center;
  color: var(--aa-color);
  display: none;
}

.one-pers, .two-pers, .three-pers, .four-pers{
     margin: 4% 40%;
   display: flex;
}

.perstext{
  width: 50%;
  margin-right: 20%;
}

.persprice{
  width: 50%;
  float: left;
}

.menuspecial {
    width: 100%;
  justify-content: center;
  color: var(--aa-color);
  display: none;
}

.dishinfo2 {
  padding: 5% 10%;
  font-size: 150%;
  text-decoration: none;
  text-align: center;
}
/* End Menu */

/* End Main */

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Addis Abeba | Menu</title>
  <link rel="stylesheet" href="/css/menu.css">
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@900&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">

          Home
          Menu
          About Us
          Our Food
          Ethiopian Culture

          Menu

Main

Vegetarian

Special

Drinks

CHF 21.-

Key Wat

          Tender morsels of meat prepared in specially spiced butter, seasoned with onions and green peppers, sprinkled with garlic and ginger.

CHF 23.-

Doro Wat

          Chicken cooked in specially seasoned red sauce and Ethiopian butter.

CHF 23.-

Yebeg Wat

          Morsels of lamb prepared in special herb butter, seasoned with onions and green peppers and sprinkled with garlic and ginger.

CHF 25.-

Kitfo

          Steak tartare, Ethiopian style, seasoned with special hot red pepper and spiced butter

CHF 24.-

Beef Tibs

          Strips of beef sauteed with onion and pepper.

CHF 24.-

Lamb Tibs

          Cubes of lamb fried in buter, onions, green and black peppers.

CHF 17.-

Shiro

          Yellow split peas cooked in special sauce and blended into a puree flavored with spices.

CHF 17.-

Misir

          Cracked lentil cooked in spiced sauce.

CHF 16.-

Gomen

          Assortment  of spicy chopped vegetables cooked in spiced butter, onions and various kinds of exotic peppers.

Vegetarian Tasting Menu

1 Pers

CHF 22.-

2 Pers

CHF 44.-

3 Pers

CHF 66.-

4 Pers

CHF 88.-

Addis Abeba Special

Includes:

          Tibs, Yebuegue Alicha, Doro Woot and choice of Lentils or Vegetables

2 Pers

CHF 52.-

3 Pers

CHF 78.-

4 Pers

CHF 99.-

Tasting Menu

Includes:

          Tibs, Yebuegue Alicha, Doro Woot, Kitfo and choice of Lentils or Vegetables

2 Pers

CHF 60.-

3 Pers

CHF 90.-

4 Pers

CHF 115.-

Any help is greatly appreciated.
Thank you!

A: If you aren't using a framework, I'd still suggest using jQuery, especially because it's very beginner friendly in my opinion.
The latest version of jQuery can be found here.
You can simply link it within your html like this:

With jQuery, you can set events for when a object is clicked.
An example for a click event for one of your classes would be something like this:
$(".vegoption").click(function(){
    // do something when .vegoption is clicked
})

If you want to change its color when clicked, you can simply call .css() to change the background-color like this:
$(".vegoption").click(function(){
    $(this).css("background-color", "green");
})

If you want a certain class to be colored green when landing on the page, you can call the $(document).ready() event which is included with jQuery and calls everything within its function as soon as the page has loaded correctly.
$(document).ready(function(){
    $(".mainoption").css("background-color", "green");
})

In order make sure that only one option is green at once, you can simply change the color of all the other options back to their defaults within these events as well just like explained in the examples above.


text:
Q: inv edit for minecraft 1.19 I want a inv editor for minecraft 1.19 because on my server someone has a  item in there inv that when they join they get kicked for nbt related reason about inv
can anyone help?

A: If you use a server
Method 1 : Server's Console

#

1
Go to your server's console

2
/clear <name>

NOTE: Might not work
Method 2 : Command Block

#

1
Join the server

2
/give @s minecraft:repeating_command_block

3
Right-Click the command block

4
In the command block, enter this command:

/clear <name>

If you use a LAN world
Method 1 : NBT editor
I suggest using Universal Minecraft Editors, here are the steps

*

*Open Univertial Minecraft Editor

*Select "Java Edition"

*Open the world

*Go to "players"

*Find the player

*Double-click the player

*Find the item and delete it

Method 2 : Command Block

#

1
Join the world

2
/give @s minecraft:repeating_command_block

3
Right-Click the command block

4
In the command block, enter this command:

/clear <name>


text:
Q: Update Column in SQLite I am learning Android now....I am trying to use SQLite in my application. I am inserting data in table without hassle with below code
public void addQuote(String qu_text, int qu_author, int qu_web_id, String qu_time, int qu_like, int qu_share) {
            open();
            ContentValues v = new ContentValues();
            v.put(QU_TEXT, qu_text);
            v.put(QU_AUTHOR, qu_author);
            v.put(QU_FAVORITE, "0");
            v.put(QU_WEB_ID, qu_web_id);
            v.put(QU_TIME, qu_time);
            v.put(QU_LIKE, qu_like);
            v.put(QU_SHARE, qu_share);

            database.insert(TABLE_QUOTES, null, v);

        }

Now I want make another function which can update two column in table called qu_like and qu_share. anyone can please suggest me how can I update only two column instead of full table ?

A: You can use this method.
public void updateQuote(long qu_id, int qu_like, int qu_share) {
            open();
            ContentValues v = new ContentValues();
            v.put(QU_LIKE, qu_like);
            v.put(QU_SHARE, qu_share);

            database.update(TABLE_QUOTES, v, "qu_id=" + qu_id, null);

        }

A: you can try something like that
public void updateRecord(String[] title, long id) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    cv.put(QU_LIKE, title[0]);
    cv.put(QU_LIKE,title[1]);

    db.update(DATABASE_TABLE_NAME, cv, "qu_id" + "=" + id, null);

    db.close();
}


text:
Q: Changing JQuery function into AngularJS I am changing a user list/table I made with Razor and JQuery into AngularJS. One of the features of this table was the ability to show/hide additional user details. The table had two sets of tr with the second one being display:none but would slide down/be visible when its above tr was clicked to show details.
Example (Original) Working Example

I tried to apply the code onto my AngularJS but it does not seem to work for some reason (no errors either)
Original Code (skeleton)

            @Html.DisplayFor(modelItem => item.name)
            @Html.DisplayFor(modelItem => item.email)
            // ect...

            @Html.DisplayFor(other stuff)

New AngularJS Code

            {{actors.name}}
            {{actors.email}}
            // ect...

                    {{actors.otherThings}}

JQuery (Original had td[colspan=12] instead of td[colspan=6])

CSS
/* Removes padding from interactive rows */
.table > tbody > tr > td.nopadding {
    padding: 0px;
}

I am still new to AngularJS so maybe I am missing something simple, but I just want to be able to expand show/hide the additional tr. Not sure why it does not work for my Angular code.
AngularJS
var app = angular.module("app", ['ngRoute', 'ngResource']);

app.config(function ($routeProvider) {
    $routeProvider

    .when('/', {
        templateUrl: '/pages/home.html',
        controller: 'HomeController'
    })

    .when('/home', {
        templateUrl: '/pages/home.html',
        controller: 'HomeController'
    })

    .when('/unknown', {
        templateUrl: '/pages/unknown.html',
        controller: 'UnknownController'
    })
      .otherwise({
          templateUrl: '/pages/home.html',
          controller: 'HomeController'
      });
});

app.factory('userService', function ($http) {
    var userService = {};
    userService.getUsers = function () {
        return $http({
            url: '/API/APITest',
            method: "GET"
        })
    }
    return userService;
});

app.controller('HomeController', function ($scope, userService, $resource, $http) {
    $scope.orderByField = 'name';
    $scope.reverseSort = false;
    $scope.ordering = "(ascending)";

    $scope.orderByFieldFunction = function (value) {
        $scope.reverseSort = !$scope.reverseSort;
        $scope.orderByField = value;
        if ($scope.reverseSort === false) {
            $scope.ordering = "(ascending)";
        } else {
            $scope.ordering = "(descending)";
        }
    }
    userService.getUsers().success(function (users) {
        $scope.Users = users;
    });
});

app.controller('UnknownController', function ($scope, userService, $resource, $http) {
    $scope.title = "404 - Does Not Exist";
});

A: You can add the jQuery in a directive like this, if this is what you're after:
Example: http://jsfiddle.net/58mLfw6z/
AngularJS Directive
app.directive('showmore',function() {
    return {
        restrict:'A',
        link: function(scope,element,attr) {
            element.on('click',function() {
              element.next('tr').toggle();
            });
        }
    }
});

// or apply a flag to the model with an ng-click on the tr
$scope.more = function(actor) {
    if (!actor.more) {
        actor.more = true;
    }
    else {
        actor.more = false;
    }
};

HTML

            {{actors.name}}
            {{actors.email}}

                    {{actors.otherThings}}

A: I think OP already has found the answer. This post is just to say that ng-repeat has its own scope, an isolated scope.
In this plnkr, http://jsfiddle.net/aanders50/HB7LU/5497/, which OP posted in the comment

        Name
        Email

            {{actors.name}}
            {{actors.email}}

birthday: {{actors.birthday}}

showDetails are bound to each tbody where ng-repeat is defined. Thus, each table has its own $scope.showDetails


text:
Q: Cypress logs out when using cy.visit() I'm sending multiple API requests and everything works fine, until I try to navigate to the page that was generated during API testing. When I navigate to the page using cy.visit() function I get unauthorized and all subsequent requests are being sent without authorization token, even though I added authorization header to the cy.visit() function.
Any help would be appreciated
    var accessToken
    before(function () {
        cy.request({
            method: 'POST',
            url: 'https://someurl.com/connect/token',
            form: true,
            body: {
                grant_type: 'password',
                username: 'admin',
                password: 'pass',
                client_id: 'client_id',
                client_secret: 'secret'
            }
        }).then((response) => {
            accessToken = response.body.access_token
        })
    })

   //api requests

    it('Navigates to order page', () => {
        cy.visit(`https://someurl.com/orders/${orderId}`, { auth: { bearer: accessToken.replace('Bearer ', '') } })
    })

A: Your code looks like the antipattern example in the Cypress Docs: Core Concepts: Aliases example.  Using as to create an alias, you could do something like:
before(function () {
    cy.request({
        method: 'POST',
        url: 'https://someurl.com/connect/token',
        form: true,
        body: {
            grant_type: 'password',
            username: 'admin',
            password: 'pass',
            client_id: 'client_id',
            client_secret: 'secret'
        }
    }).then((response) => {
        cy.wrap(response.body.access_token).as('accessToken')
    })
})

//api requests

it('Navigates to order page', function() {
  const accessToken = this.accessToken
  cy.visit({
    url: `https://someurl.com/orders/${orderId}`,
    headers: {
      'Authorization': accessToken
    }
  })
})

NOTE: It is necessary to change the closure of the it() block from an arrow function to a regular function because the arrow function uses the lexical scope this, and will not include the alias created in the before() closure.

A: I managed to fix the problem by changing authorization from backed api request to frontend login form and then whitelisting local storage.
I had to add this piece of code
        Cypress.LocalStorage.clear = function (keys, ls, rs) {
            if (keys) {
                return
            }
        }

And now my spec file looks like this:
    before(function () {
        cy.server()
        cy.route('GET', '/api/orders/orders?PageNo=1&Size=20').as('orders')

        cy.LogIn('email', 'pass')

        //wrapping access token from the request after successfull authorization

        cy.wait('@orders').then((request) => {
            cy.wrap(request.requestHeaders.Authorization).as('accessToken')
        })

        //whitelisting local storage

        Cypress.LocalStorage.clear = function (keys, ls, rs) {
            if (keys) {
                return
            }
        }
    })

    it('A',()=>{
      cy.visit('some url') //it works!
    })

Also when restarting the test I was still logged in. To prevent this from happening I added clearing local storage at the very beginning of before() function
        window.localStorage.clear()

https://github.com/cypress-io/cypress/issues/461


text:
Q: Detecting Click Inside IFrame Using Invisible div I went through this post.
Detect Click into Iframe using JavaScript
But still, I see people have done similar stuff. Please tell me how do I do this.
One developer told me:

You could put a transparent DIV on top of the IFRAME. You size that
  DIV to the same size or bigger than the IFRAME. And with a higher
  z-index CSS property.
Then when you click on the IFRAME, the DIV receives the event.
But as the world is not perfect, now you lost the ability to click
  inside the IFRAME.

But I am not so good with div's and looking to learn how to do this.
Thanks
P.S. It is about Cross Domain or Alien Domain Iframing.

A: If I understand what you are asking here:
jsFiddle
// PLACE OVERLAY OVER EACH IFRAME
var W=0, H=0, X=0, Y=0;
$(".iframe").each(function(i,el){
   W = $(el).width();
   H = $(el).height();
   X = $(el).position().left;
   Y = $(el).position().top;
   $(this).after('<div class="overlay" />');
    $(this).next('.overlay').css({
        width: W,
        height: H,
        left: X,
        top: Y
    });
});

// TRACK MOUSE POSITIONS (the overlay will prevent clicks on iframe page)
var mx = 0, my = 0;
$('.overlay').on('mousemove click',function(e){
    mx = e.clientX - $(this).position().left;
    my = e.clientY - $(this).position().top;

    if(e.type==='click'){
        alert('clicked at: X='+mx+' Y='+my)
    }
});

A: I think a transparent div will not work, because it will catch all click events, and not spread it down to the iframe.
So the only workaround I know to track click on iframes is using the blur event.
You can use the iframeTracker jQuery Plugin to do this easily :
jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

A: Check out Jquery's .live method.
It can attach an event handler to a selector now and in the future, such as when content is loaded into  a div.
http://api.jquery.com/live/


text:
Q: Проблема с раздуванием View в RecyclerView во фрагменте Проблема с раздуванием элементов в приложении, вылетает следующее исключение:

Вопрос что я делаю не так?
Адаптер с ViewHolder
  private inner class IconsAdapter(var icons: List<AppIcon>) :
    RecyclerView.Adapter<IconsAdapter.IconHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconsAdapter.IconHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
        return IconHolder(view)
    }

    override fun getItemCount(): Int = icons.size

    override fun onBindViewHolder(iconHolder: IconsAdapter.IconHolder, position: Int) {
        iconHolder.bind(icons[position])
    }

    private inner class IconHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {

        lateinit internal var imageView: ImageView
        lateinit internal var textView: TextView

        fun bind(appIcon: AppIcon) {
            imageView = itemView.findViewById(R.id.icon_id)
            textView = itemView.findViewById(R.id.name_id)

            imageView.setImageDrawable(appIcon.icon)
            textView.text = appIcon.label
            imageView.setOnClickListener(this)
        }

        override fun onClick(view: View?) {
            mCallBackClickListener!!.onButtonPressed(view, adapterPosition)
        }

    }

}

Элемент для Recycler View
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/icon_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground"
        app:layout_constraintBottom_toTopOf="@id/name_id"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/name_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="@id/icon_id"
        app:layout_constraintRight_toRightOf="@id/icon_id"
        app:layout_constraintTop_toBottomOf="@id/icon_id" />

</android.support.constraint.ConstraintLayout>

Код фрагмента
class ShowAllAppFragment : Fragment() {

private lateinit var recyclerView: RecyclerView
private lateinit var appIcons: List<AppIcon>
private var mCallBackClickListener: OnShowAppFragmentListener? = null

init {
    Log.i(
        KeysCommonInteractor.KeysField.LOG_TAG,
        "Identificator of class is $this"
    )
}

companion object FragmentsFactory {

    internal val KEY_LIST = javaClass.canonicalName + "Names of applications"

    fun newInstance(listOfApps: List<AppIcon>): ShowAllAppFragment {
        val showAllAppFragment = ShowAllAppFragment()
        val arguments = Bundle()
        Log.i(
            KeysCommonInteractor.KeysField.LOG_TAG,
            "${javaClass.canonicalName} :  newInstance list = $listOfApps"
        )
        arguments.putParcelableArrayList(KEY_LIST, listOfApps as ArrayList<AppIcon>)
        showAllAppFragment.setArguments(arguments)
        return showAllAppFragment
    }
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    var view = inflater.inflate(R.layout.show_all_app, container, false)

    recyclerView = view!!.findViewById(R.id.recycler_view)
    recyclerView.layoutManager = GridLayoutManager(context, 4)
    //  recyclerView.layoutManager = LinearLayoutManager(context)
    updateUI()
    return view
}

private fun updateUI() {

    appIcons = arguments!!.getParcelableArrayList(KEY_LIST)
    Log.d(
        KeysCommonInteractor.KeysField.LOG_TAG,
        "Count of apps in data ${appIcons.size}"
    )
    recyclerView.adapter = IconsAdapter(icons = appIcons)
}

private inner class IconsAdapter(var icons: List<AppIcon>) :
    RecyclerView.Adapter<IconsAdapter.IconHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconsAdapter.IconHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
        return IconHolder(view)
    }

    override fun getItemCount(): Int = icons.size

    override fun onBindViewHolder(iconHolder: IconsAdapter.IconHolder, position: Int) {
        iconHolder.bind(icons[position])
    }

    private inner class IconHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {

        lateinit internal var imageView: ImageView
        lateinit internal var textView: TextView

        fun bind(appIcon: AppIcon) {
            imageView = itemView.findViewById(R.id.icon_id)
            textView = itemView.findViewById(R.id.name_id)

            imageView.setImageDrawable(appIcon.icon)
            textView.text = appIcon.label
            imageView.setOnClickListener(this)
        }

        override fun onClick(view: View?) {
            mCallBackClickListener!!.onButtonPressed(view, adapterPosition)
        }

    }

}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    try {
        mCallBackClickListener = context as OnShowAppFragmentListener?
    } catch (e: ClassCastException) {
        throw ClassCastException(context!!.toString() + " must implement mShowAllAppFragmentListener")
    }

}

interface OnShowAppFragmentListener {
    fun onButtonPressed(view: View?, position: Int)
}

}

A: У Вас проблема конкретно в ImageView , если быть точнее то вы пытаетесь передать в него векторную картинку через старые атрубит android:src="@drawable/ic_launcher_foreground"
По этому у вас собственно и краш.
Векторы передавать в ImageView нужно через новый атрибут
app:srcCompat="@drawable/ic_launcher_foreground"

так же в gradle вашего проекта добавьте в секцию defaultConfig поддержку векторов
 defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }

Кроме того ic_launcher_foreground лежит в ресурсах для api 24+ то есть так же обратите внимание на тот девайс с которого запускаете.
а если быть еще проще, скормите ей обычную пнг.


text:
Q: Bootstrap 3 Datepicker doesn't show calendar I've included the following in my page:
In the

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Bottom of

Then I used jQuery to turn my form's input field into the datepicker:

        <input type='text' class="form-control" />

The input field got styled like a date picker(field with a calendar icon at the end), but when I click anywhere on that field or the icon the calendar doesn't show up.
I've re-read the Installation tutorial but I don't see anything missing.

A: Replace

By

You should get TypeError: $(...).datetimepicker is not a function in the browser console.
Because you include only datepicker not datetimepicker.
Live Demo

A: Add datetimepicker1 To  <input type='text' class="form-control" id="datetimepicker1" />
and $('#datetimepicker1').datepicker(); not $('#datetimepicker1').datetimepicker();
Wokring here :
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

        <input type='text' class="form-control" id="datetimepicker1" />

A: if you opened the browser console,you would have seen an exception error in the console,like bootstrap JS requires jquery or so

this should work


text:
Q: Group by two columns with case query in SQL Server I'm trying to retrieve drivers data with Total Accepted and Total Ignored ride requests for the current date.
Based on the Drivers and DriverReceivedRequests tables, I get the total count but the twists is I have duplicate rows that reside on the DriverReceivedRequest table against the driverId and the rideId. So there has to be group by clause on both the driverId and RideId, having the driver getting multiple requests for the current date, but also receiving twice or thrice request for the same ride as well.
This is the table structure for DriverReceivedRequests:
Id          DriverId       RideId         ReceivedStatusId     DateTime
------------------------------------------------------------------------
0014d26b    93665f55      fef6fb96            NULL              04:55.6
00175c65    6e62a94e      cb214a84            NULL              09:32.1
0017c22b    ec9e1297      4b47dc8a          4211357D            10:28:5
0014d26b    6e62a94e      fef6fb96            NULL              04:56.8

This is the query I have tried:
select
    d.Id, d.FirstName, d.LastName,
    Sum(case when drrs.Number = 1 then 1 else 0 end) as TotalAccepted,
    Sum(case when drrs.Number = 2 or drr.ReceivedStatusId  is null then 1 else 0 end) as TotalRejected
from
    dbo.[DriverReceivedRequests] drr
inner join
    dbo.[Drivers] d on drr.DriverId = d.Id
left join
    dbo.[DriverReceivedRequestsStatus] drrs on drr.ReceivedStatusId = drrs.Id
where
    Day(drr.Datetime) = Day(getdate())
    and month(drr.DateTime) = Month(getdate())
group by
    d.FirstName, d.LastName, d.Id

In the above query if I group by with RideId as well, it generates duplicate names of drivers as well with incorrect data. I've also applied partition by clause with DriverId but not the correct result
This also generates the same result
WITH cte AS
(
    SELECT
        d.Id,
        d.FirstName, d.LastName,
        TotalAccepted = SUM (CASE WHEN drrs.Number = 1 THEN 1 ELSE 0 END) OVER (PARTITION BY drr.DriverId),
        TotalRejected = SUM (CASE WHEN drrs.Number = 2 OR drr.ReceivedStatusId IS NULL THEN 1 ELSE 0 END)
                OVER (PARTITION BY drr.DriverId),
        rn = ROW_NUMBER() OVER(PARTITION BY drr.DriverId
                               ORDER BY drr.DateTime DESC)
    FROM
        DriverReceivedRequests drr
    INNER JOIN
        dbo.[Drivers] d ON drr.DriverId = d.Id
    LEFT JOIN
        dbo.[DriverReceivedRequestsStatus] drrs ON drr.ReceivedStatusId = drrs.Id
    WHERE
        DAY (drr.Datetime) = DAY (GETDATE())
        AND MONTH (drr.DateTime) = MONTH (GETDATE())
)
SELECT
    Id,
    FirstName, LastName,
    TotalAccepted, TotalRejected
FROM
    cte
WHERE
    rn = 1

My question is how can I group by individual driver data in terms of incoming ride requests?
Note: the driver receives same ride request multiple times


text:
Q: Math notation for the $x$ that minimizes $f(x)$ while keeping $f(x)$ above $t$. I want to say: The $x$ that minimizes $f(x)$ while keeping $f(x)$ above $t$.
I know I can write "the $x$ that minimizes $f(x)$" like this: $x = \arg\min_x f(x)$.
How would I complete that to say "while keeping $f(x)$ above $t$"?

A: $\newcommand{amin}{\operatorname*{argmin}}$The best suggestion was made by lhf in the comments:
$$\amin_{\substack{x \\ f(x) > t}} f(x).$$
You could alternatively use the inverse image notation, i.e.
$$f^{-1}(t, \infty) := \{x : f(x) \in (t, \infty)\} = \{x : f(x) > t\}$$
to write
$$\amin_{x \in f^{-1}(t, \infty)} f(x).$$


text:
Q: Combine multiple columns of pandas data frame to one column I've a dataframe df as follows such that it's the number of columns vary time to time:
  Column 1     Column 2
0        A        E
1        B        F
2        C        G
3        D        H

I need to combine the columns into one such that it looks like as given below:
        column 3
0         A,E
1         B,F
2         C,G
3         D,H

For rows to combine into one the following is the code. I need something like that which will not specify the column names.
df = df.stack().to_frame().T
df.columns = ['{}_{}'.format(*c) for c in df.columns]

A: In [52]: df.Column1 += ',' + df.pop('Column2')

In [53]: df
Out[53]:
  Column1
0     A,E
1     B,F
2     C,G
3     D,H

or
In [56]: df['Column3'] = df.pop('Column1') + ',' + df.pop('Column2')

In [57]: df
Out[57]:
  Column3
0     A,E
1     B,F
2     C,G
3     D,H

UPDATE:
In [77]: df
Out[77]:
  Column1 Column2 Column3
0       A       E       I
1       B       F       J
2       C       G       K
3       D       H       L

In [78]: res = pd.DataFrame({'ColX': df.add(',').sum(axis=1).str.rstrip(',')}, df.index)

In [79]: res
Out[79]:
    ColX
0  A,E,I
1  B,F,J
2  C,G,K
3  D,H,L

A: Here's one with .join -
pd.DataFrame({'Out':[",".join(i) for i in df.values]})

Sample run -
In [375]: df
Out[375]:
  Column1 Column2 Column3
0       A       E       I
1       B       F       J
2       C       G       K
3       D       H       L

In [376]: pd.DataFrame({'Out':[",".join(i) for i in df.values]})
Out[376]:
     Out
0  A,E,I
1  B,F,J
2  C,G,K
3  D,H,L


text:
Q: CSS max-width: 100% for IE 6 with expression? I have this css:
.container img {
    max-width: 100% !important;
    height: auto;
 }

Now I need this working for IE 6.
I know you can do:
 width: expression(this.width > xxx ? xx : true);

but xxx needs to be a number, not a percentage I believe.
I'm doing max-width: 100% so that the width of the image will not exceed the width of the .container
Any ideas?
Thanks.

A: Without having tested it, I guess you need to compare the elements (client) width to its parent's. Something like:
width: expression(this.clientWidth > this.parentNode.clientWidth ? this.parentNode.clientWidth + "px" : this.clientWidth + "px");


text:
Q: How to Create Variable Padding When I view my website on a smartphone, some of my menu items are flowing off the page. As a result, I want to give these menu items variable padding widths. For example, my padding-left and padding-right are currently set to 25px. This works fine on larger screen such as tablets and computers, but it is too high a number when viewing on a smartphone.
I want to make it so that I can set the padding to 25px when viewed on a screen over, say 768px wide, but at only 15px when viewed on a screen less than 768px wide. Even better would be if the padding would slowly decrease from 25px to 15px as the browser size gets smaller.
How would I go about doing this?

A: CSS media queries:
/* normal screen CSS */
@media screen and (max-width: 767px) {
  /* small screen override CSS */
}


text:
Q: Server Error in '/' Application. The resource cannot be found. (ASP.NET mvc 2 + built in web server) I'm trying to make a MVC 2 web application for a small portal.
I started with the template in VS 2010 and made several other .aspx pages (for views)
Index.aspx (was a part of the template) opens like he should open, but when I click on a link to acces another aspx page (that I added to the template) he show me this:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Views/AccountPages/Aanvragen.aspx
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
When I set Aanvragen.aspx as startup page, he show me the same message.
I use a built in server (VS2010).
Of course, I checked if the url is correct and it is. So that is certaintly not the problem
Anyone that could help me ?
Thanks a lot

A: You should not be requesting view pages directly at all; the web.config that comes with ASP.NET MVC blocks direct requests for all views in the /views directory, for one thing.
You can link to regular web forms pages elsewhere in your site, such as in the root directory, but that's really not how MVC is meant to be used. You may want to seek out a tutorial on ASP.NET MVC, as it seems you aren't familiar with how to use it. Check out the http://www.asp.net/mvc web site.


text:
Q: Sensitivity Analysis: Which resource should I buy more? Let an LP of the form:
$\max \ 2x_1+2x_2+x_3$
$s.t. \ x_1+2x_2+x_3 \leq 4 =b_1$
$\ \ \ \ \ \ \ \ 2x_1+x_2+x_3\leq3 =b_2$
$\ \ \ \ \ \ \ \ x_1,x_2\geq0$
And let the final tableau be:

being $x_4$ and $x_5$ the slack variables.
Question: Which action is more profitable? Buying more resources of $b_1$ or $b_2$? And how much should I buy?

A: Suppose we increase resounces $b_i$ by $\delta e_i$, the profit would change by $$\delta c_B'B^{-1}e_i=\delta \begin{pmatrix} 2 & 2\end{pmatrix}B^{-1}e_i$$
For the first resource, $B^{-1}e_1=\begin{pmatrix} \frac23 \\ -\frac13 \end{pmatrix}$ and for the second resources $B^{-1}e_2=\begin{pmatrix} -\frac13 \\ \frac23 \end{pmatrix}$, hence they are equally profitable.
Suppose we increase resources of $b_i$, the basis remains the same if
$$x_B+\delta B^{-1}e_i \geq 0$$
For resource $1$, we have  $$\begin{pmatrix} \frac53 \\ \frac23 \end{pmatrix}+\delta \begin{pmatrix} \frac23 \\ -\frac13 \end{pmatrix} \geq \begin{pmatrix} 0 \\ 0 \end{pmatrix}$$
Hence if $\delta \leq 2$, the basis remains the same. (remark: However, if $\delta > 2$, we will have to continue with dual simplex.)
We can repeat the same thing for resource $b_2$.


text:
Q: How to subtract two text box values and display in another text box using Javascript I want to fins the range between two number entered in a textbox and display it in another text box.
I am using the event onBlur.
Initially i got NaN in the result textbox.
Later I used ParseInt now no value is getting displayed.
My code :

HTML CODE :

                    MSISDN Start Range  <input class="form-control"
                        type="text" name="startmsisdn"
                        placeholder="MSISDN Starting Range" required>

                    MSISDN End Range  <input class="form-control"
                        type="text" name="endmsisdn" placeholder="MSISDN Ending Range"
                        required>

                    IMSI Start Range  <input class="form-control"
                        type="text" name="startimsi" placeholder="IMSI Starting Range"
                        required>

                    IMSI End Range  <input class="form-control"
                        type="text" name="endimsi" placeholder="IMSI Ending Range"
                        required onblur="countRows()">

                    No of rows  <input class="form-control"
                        type="text" name="rows"  id="rows"
                        required>

A: Add default value for empty field
Try to get element by id for input field;
like this
Html
div class="col-md-4">
IMSI Start Range
<input class="form-control"
   type="text" id="startimsi" name="startimsi" placeholder="IMSI Starting Range"
   required>

   IMSI End Range
   <input class="form-control"
      type="text" id="endimsi" name="endimsi" placeholder="IMSI Ending Range"
      required onblur="countRows()">

Javascript
var startMsisdn=parseInt(document.getElementById("startmsisdn").value) || 0;
var endMsisdn=parseInt(document.getElementById("endmsisdn").value) || 0;

A: You have two issues here. parseInt may return NaN, so any value you add to it will also always return NaN. The second issue is there is no getElementByName method (singular). It's getElementsByName which returns an array-like object:
function countRows(){

    var rows=document.getElementById("rows");
    var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
    var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
    rows.value=endMsisdn-startMsisdn;

}

You may notice that I added an extra parameter to your parseInt too. This is to force non-ES5 compliant browsers to parse as decimal - they may default to using octal for parsing which will result in unexpected results if a zero-prefixed value is entered.
Working Example

function countRows(){
    var rows=document.getElementById("rows");
    var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
    var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
    rows.value=endMsisdn-startMsisdn;
}

    MSISDN Start Range
    <input class="form-control" type="text" name="startmsisdn" placeholder="MSISDN Starting Range" required>

    MSISDN End Range
    <input class="form-control" type="text" name="endmsisdn" placeholder="MSISDN Ending Range" required>

        IMSI Start Range
        <input class="form-control" type="text" name="startimsi" placeholder="IMSI Starting Range" required>

        IMSI End Range
        <input class="form-control" type="text" name="endimsi" placeholder="IMSI Ending Range" required onblur="countRows()">

        No of rows
        <input class="form-control" type="text" name="rows" id="rows" required>

A: try this by replacing  NaN with 0 ..
function countRows(){
    var rows = document.getElementById("rows");
    var startMsisdn=document.getElementById("startmsisdn").value;
    if(startMsisdn =='' ){ startMsisdn =0;}
    var endMsisdn=document.getElementById("endmsisdn").value;
    if(endMsisdn =='' ){ endMsisdn =0;}
    rows.value= parseInt(endMsisdn) - parseInt(startMsisdn);
}

HERE is the FIDDLE

A: Add These line of code in script its will work fine.
function countRows() {

            var rows = document.getElementById("rows");
            var startMsisdn = parseInt(document.getElementsByName("startmsisdn")[0].value);
            var endMsisdn = parseInt(document.getElementsByName("endmsisdn")[0].value);
            rows.value = endMsisdn - startMsisdn;

        }


text:
Q: How can I prevent Android from auto locking while activity (application) is in focus? I'm new to android development. How can I prevent Android from locking while my application is in focus? When my application is out of focus I want to ensure than the android os will have its default behavior.

A: use

WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON

you can do this using

Activity.getWindow().addFlags().

A: private PowerManager mPowerManager;
private WakeLock mWakeLock;

Write this in OnCreate

 // Get an instance of the PowerManager
    mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);

    // Create a bright wake lock
    mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK|
            PowerManager.ACQUIRE_CAUSES_WAKEUP, getClass()
            .getName());

Write this in onResume

    mWakeLock.acquire();

write this in onPause

    mWakeLock.release();


text:
Q: Out-GridView with Passthru for powershell 2? Powershell v3 added the -Passthru switch to the Out-GridView cmdlet that allows user to select items that are returned back to the pipeline.
I'm looking for a similar solution for Powershell v2 (Dotnet 3.5/4.0). I need the option to pipe in some values, allow user to filter and choose multiple values, and return the selected items to the pipeline.
Is there a way run the new Out-GridView throught dotnet? or maybe someone created a code for something similar?

A: I've got this, FWIW:
Select -Item
Not a real grid view, but it works for V2, and in remoting sessions where GridView isn't an option.


text:
Q: "Id returned 1 exit status" error c++ I'm writing this fairly simple code but suddenly I start getting this "Id returned 1 exit status error". The most recent change I made to this code was adding all the "endl"s in the display function. I have no idea what to do, please help
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

void getOrder(double&spools, double&stock, double&charge);
void displayOrder(double spools, double stock, double charge);

int main()
{
    double spools;
    double stock;
    double charge;
    getOrder(spools, stock, charge);
    displayOrder(spools, stock, charge);
    system("pause");//come back to these v2v lines
    return 0;
}

void getOrder(double&spools, double&stock, double&charge)
{
    charge= 0;
    char extra;
    double extraCharge;
    cout<<"How many spools were ordered?:";
    cin>>spools;
    while(spools<1){
        cout<<"Entry must be greater than 1...: ";
        cin>> spools;
    }
    cout<<"How many spools are in stock?:";
    cin>>stock;
    while(stock<0){
        cout<<"Entry must be greater than 0...: ";
        cin>> stock;
    }
    cout<<"Are there any special shipping and handling chsrges?(y for yes, n for no):";
    cin>>extra;
    if(extra=='y'|| extra=='Y'){
        cout<<"Enter the special charge amount:$";
        cin>>extraCharge;
        while(extraCharge<0){
        cout<<"Entry must be greater than 0... :";
        cin>> extraCharge;
        }
    }

    charge=extraCharge;
//no returns needed because reference variables
}

void displayOrder(double spools, double stock, double charge=10)
{
    double backOrder=spools-stock;
    double spoolsOrdered;
    double subTotal=spools*100;
    double shipping;
    double total=subTotal+charge;
    double ready=stock-spools;

    //spools ready to ship from current stock
    cout<<"There are"<<ready<<"spools ready to be shipped."<<endl;
    //if statement for BACKORDERRRrr
    if(spools>stock)
    {
        backOrder=spools-stock;
        cout<<"There are"<<ready<<"spools ready to be shipped."<<endl;
        cout<<"There are"<<backOrder<<"spools on back order."<<endl;
        cout<<"Subtotal: $"<<subTotal<<endl;
        cout<<"Shipping & Handling charge:$"<<charge<<endl;
        cout<<"The total fee for this transaction is:$"<<total<<endl;

    }
    else
    {
        cout<<"There are"<<ready<<"spools ready to be shipped."<<endl;
        cout<<"Subtotal: $"<<subTotal<<endl;
        cout<<"Shipping & Handling charge:$"<<charge<<endl;
        cout<<"The total fee for this transaction is:$"<<total<<endl;
    }
}

A: I just tried your code on Dev C++ and it runs perfectly fine.
A probable reason for this error is that the .exe file from the previous run is still ON somewhere. Close it and try again.


text:
Q: change a list of dictionaries to feature vector and target in scikit I have a list of dictionaries that contains features and the classification label.  I read from a CSV. How can I split it into a numpy array as required by the scikit for a classification task.
Code so far
from sklearn.feature_extraction import DictVectorizer
          rowdicts =[{'feature1': 4, 'feature2':2,'target':"yes","feature3":0},{'feature1': 3, 'feature2': 2,'target':"no","feature3":1}]

    vec1 = DictVectorizer(sparse=False)
    X = vec1.fit_transform(rowdicts)

What could be a good way to remove the target labels from the above vectorizer for a classification task?

A: You can figure out which columns mean what using get_feature_names:
print(vec1.get_feature_names())

output:
['feature1', 'feature2', 'feature3', 'target=no', 'target=yes']

Now that we know that we can just drop the target=no column:
X = numpy.delete(X, 3, axis=1)


text:
Q: access local repository file instead of tfs file We have a development server that is running TFS 2010, it is working fine however we have a bit of issue:
when person X take the latest and build the app , it get checkout abc.csproj application and due to that another person can't take the latest and it shows the error message as.

Here I'm looking for, whenever we modify any changes locally (pages) it should not get checked out & lock by TFS, only in their local repository it changes.
any suggestion would be appreciated.

A: There are two places you may need to change TFS to allow multiple check-outs.

*

*In Visual Studio, use the "Team" menu, then "Team Project Settings", then "Source Control..." and ensure "Enable multiple check-out" is checked.

*In Visual Studio, use the "Team" menu, then "Team Project Collection Settings", then "Source Control..." and ensure that if "csproj" is listed there, it has "File Merging" set to "Enabled".


text:
Q: How to correctly compute direct kinematics for a delta robot? I'm trying to put together a simple simulation for a delta robot and I'd like to use forward kinematics (direct kinematics) to compute the end effector's position in space by passing 3 angles.
I've started with the Trossen Robotics Forum Delta Robot Tutorial and I can understand most of the math, but not all. I'm lost at the last part in forward kinematics, when trying to compute the point where the 3 sphere's intersect. I've looked at spherical coordinates in general but couldn't work out the two angles used to find to rotate towards (to E(x,y,z)). I see they're solving the equation of a sphere, but that's where I get lost.

A delta robot is a parallel robot (meaning the base and the end effector(head) always stay parallel). The base and end effector are equilateral triangles and the legs are (typically) placed at the middle of the triangle's sides.
The side of the base of the delta robot is marked f.
The side of the effector of the delta robot is marked e.
The upper part of the leg is marked rf and the lower side re.
The origin(O) is at the centre of the base triangle.
The servo motors are at the middle of the base triangle's sides (F1,F2,F3).
The joints are marked J1,J2,J3. The lower legs join the end effector at points E1,E2,E3
and E is the centre of the end effector triangle.
I can easily compute points F1,F2,F3 and J1,J2,J3.
It's E1,E2,E3 I'm having issues with. From the explanations,
I understand that point J1 gets translate inwards a bit (by half the end effector's median)
to J1' and it becomes the centre of a sphere with radius re (lower leg length).
Doing this for all joints will result in 3 spheres intersecting in the same place: E(x,y,z). By solving the sphere equation we find E(x,y,z).
There is also a formula explained:

but this is where I get lost. My math skills aren't great.
Could someone please explain those in a simpler manner,
for the less math savvy of us ?
I've also used the sample code provided which (if you have a WebGL enabled
browser) you can run here. Click and drag to rotate the scene. To control the three angles use q/Q, w/W,e/E to decrease/increase angles.
Full code listing:
//Rhino measurements in cm
final float e = 21;//end effector side
final float f = 60.33;//base side
final float rf = 67.5;//upper leg length - radius of upper sphere
final float re = 95;//lower leg length - redius of lower sphere (with offset will join in E(x,y,z))

final float sqrt3 = sqrt(3.0);
final float sin120 = sqrt3/2.0;
final float cos120 = -0.5;
final float tan60 = sqrt3;
final float sin30 = 0.5;
final float tan30 = 1/sqrt3;
final float a120 = TWO_PI/3;
final float a60 = TWO_PI/6;

//bounds
final float minX = -200;
final float maxX = 200;
final float minY = -200;
final float maxY = 200;
final float minZ = -200;
final float maxZ = -10;
final float maxT = 54;
final float minT = -21;

float xp = 0;
float yp = 0;
float zp =-45;
float t1 = 0;//theta
float t2 = 0;
float t3 = 0;

float prevX;
float prevY;
float prevZ;
float prevT1;
float prevT2;
float prevT3;

boolean validPosition;
//cheap arcball
PVector offset,cameraRotation = new PVector(),cameraTargetRotation = new PVector();

void setup() {
  size(900,600,P3D);
}

void draw() {
  background(192);
  pushMatrix();
  translate(width * .5,height * .5,300);
  //rotateY(map(mouseX,0,width,-PI,PI));

  if (mousePressed && (mouseX > 300)){
    cameraTargetRotation.x += -float(mouseY-pmouseY);
    cameraTargetRotation.y +=  float(mouseX-pmouseX);
  }
  rotateX(radians(cameraRotation.x -= (cameraRotation.x - cameraTargetRotation.x) * .35));
  rotateY(radians(cameraRotation.y -= (cameraRotation.y - cameraTargetRotation.y) * .35));

  stroke(0);
  et(f,color(255));
  drawPoint(new PVector(),2,color(255,0,255));
  float[] t = new float[]{t1,t2,t3};
  for(int i = 0 ; i < 3; i++){
    float a = HALF_PI+(radians(120)*i);
    float r1 = f / 1.25 * tan(radians(30));
    float r2 = e / 1.25 * tan(radians(30));
    PVector F = new PVector(cos(a) * r1,sin(a) * r1,0);
    PVector E = new PVector(cos(a) * r2,sin(a) * r2,0);
    E.add(xp,yp,zp);
    //J = F * rxMat
    PMatrix3D m = new PMatrix3D();
    m.translate(F.x,F.y,F.z);
    m.rotateZ(a);
    m.rotateY(radians(t[i]));
    m.translate(rf,0,0);

    PVector J = new PVector();
    m.mult(new PVector(),J);
    line(F.x,F.y,F.z,J.x,J.y,J.z);
    line(E.x,E.y,E.z,J.x,J.y,J.z);
    drawPoint(F,2,color(255,0,0));
    drawPoint(J,2,color(255,255,0));
    drawPoint(E,2,color(0,255,0));
    //println(dist(F.x,F.y,F.z,J.x,J.y,J.z)+"\t"+rf);
    println(dist(E.x,E.y,E.z,J.x,J.y,J.z)+"\t"+re);//length should not change
  }
  pushMatrix();
    translate(xp,yp,zp);
    drawPoint(new PVector(),2,color(0,255,255));
    et(e,color(255));
    popMatrix();
  popMatrix();
}
void drawPoint(PVector p,float s,color c){
  pushMatrix();
    translate(p.x,p.y,p.z);
    fill(c);
    box(s);
  popMatrix();
}
void et(float r,color c){//draw equilateral triangle, r is radius ( median), c is colour
  pushMatrix();
  rotateZ(-HALF_PI);
  fill(c);
  beginShape();
  for(int i = 0 ; i < 3; i++)
    vertex(cos(a120*i) * r,sin(a120*i) * r,0);
  endShape(CLOSE);
  popMatrix();
}
void keyPressed(){
  float amt = 3;
  if(key == 'q') t1 -= amt;
  if(key == 'Q') t1 += amt;
  if(key == 'w') t2 -= amt;
  if(key == 'W') t2 += amt;
  if(key == 'e') t3 -= amt;
  if(key == 'E') t3 += amt;
  t1 = constrain(t1,minT,maxT);
  t2 = constrain(t2,minT,maxT);
  t3 = constrain(t3,minT,maxT);
  dk();
}

void ik() {
  if (xp < minX) { xp = minX; }
  if (xp > maxX) { xp = maxX; }
  if (yp < minX) { yp = minX; }
  if (yp > maxX) { yp = maxX; }
  if (zp < minZ) { zp = minZ; }
  if (zp > maxZ) { zp = maxZ; }

  validPosition = true;
  //set the first angle
  float theta1 = rotateYZ(xp, yp, zp);
  if (theta1 != 999) {
    float theta2 = rotateYZ(xp*cos120 + yp*sin120, yp*cos120-xp*sin120, zp);  // rotate coords to +120 deg
    if (theta2 != 999) {
      float theta3 = rotateYZ(xp*cos120 - yp*sin120, yp*cos120+xp*sin120, zp);  // rotate coords to -120 deg
      if (theta3 != 999) {
        //we succeeded - point exists
        if (theta1 <= maxT && theta2 <= maxT && theta3 <= maxT && theta1 >= minT && theta2 >= minT && theta3 >= minT ) { //bounds check
          t1 = theta1;
          t2 = theta2;
          t3 = theta3;
        } else {
          validPosition = false;
        }

      } else {
        validPosition = false;
      }
    } else {
      validPosition = false;
    }
  } else {
    validPosition = false;
  }

  //uh oh, we failed, revert to our last known good positions
  if ( !validPosition ) {
    xp = prevX;
    yp = prevY;
    zp = prevZ;
  }

}

void dk() {
  validPosition = true;

  float t = (f-e)*tan30/2;
  float dtr = PI/(float)180.0;

  float theta1 = dtr*t1;
  float theta2 = dtr*t2;
  float theta3 = dtr*t3;

  float y1 = -(t + rf*cos(theta1));
  float z1 = -rf*sin(theta1);

  float y2 = (t + rf*cos(theta2))*sin30;
  float x2 = y2*tan60;
  float z2 = -rf*sin(theta2);

  float y3 = (t + rf*cos(theta3))*sin30;
  float x3 = -y3*tan60;
  float z3 = -rf*sin(theta3);

  float dnm = (y2-y1)*x3-(y3-y1)*x2;

  float w1 = y1*y1 + z1*z1;
  float w2 = x2*x2 + y2*y2 + z2*z2;
  float w3 = x3*x3 + y3*y3 + z3*z3;

  // x = (a1*z + b1)/dnm
  float a1 = (z2-z1)*(y3-y1)-(z3-z1)*(y2-y1);
  float b1 = -((w2-w1)*(y3-y1)-(w3-w1)*(y2-y1))/2.0;

  // y = (a2*z + b2)/dnm;
  float a2 = -(z2-z1)*x3+(z3-z1)*x2;
  float b2 = ((w2-w1)*x3 - (w3-w1)*x2)/2.0;

  // a*z^2 + b*z + c = 0
  float a = a1*a1 + a2*a2 + dnm*dnm;
  float b = 2*(a1*b1 + a2*(b2-y1*dnm) - z1*dnm*dnm);
  float c = (b2-y1*dnm)*(b2-y1*dnm) + b1*b1 + dnm*dnm*(z1*z1 - re*re);

  // discriminant
  float d = b*b - (float)4.0*a*c;
  if (d < 0) { validPosition = false; }

  zp = -(float)0.5*(b+sqrt(d))/a;
  xp = (a1*zp + b1)/dnm;
  yp = (a2*zp + b2)/dnm;

  if (xp >= minX && xp <= maxX&& yp >= minX && yp <= maxX && zp >= minZ & zp <= maxZ) {  //bounds check
  } else {
    validPosition = false;
  }

  if ( !validPosition ) {
    xp = prevX;
    yp = prevY;
    zp = prevZ;
    t1 = prevT1;
    t2 = prevT2;
    t3 = prevT3;
  }

}

void  storePrev() {
  prevX = xp;
  prevY = yp;
  prevZ = zp;
  prevT1 = t1;
  prevT2 = t2;
  prevT3 = t3;
}

float rotateYZ(float x0, float y0, float z0) {
  float y1 = -0.5 * 0.57735 * f; // f/2 * tg 30
  y0 -= 0.5 * 0.57735    * e;    // shift center to edge
  // z = a + b*y
  float a = (x0*x0 + y0*y0 + z0*z0 +rf*rf - re*re - y1*y1)/(2*z0);
  float b = (y1-y0)/z0;
  // discriminant
  float d = -(a+b*y1)*(a+b*y1)+rf*(b*b*rf+rf);
  if (d < 0) return 999; // non-existing point
  float yj = (y1 - a*b - sqrt(d))/(b*b + 1); // choosing outer point
  float zj = a + b*yj;
  return 180.0*atan(-zj/(y1 - yj))/PI + ((yj>y1)?180.0:0.0);
}

The problem is, when visualizing, the lower part changes length (as you can see in the printed message0 and it shouldn't, which further adds to my confusion.
I've used the supplied C code in Java/Processing, but the programming language is least important.
[Edit by spektre]
I just had to add this picture (for didactic reasons).

*

*the lined nonsense is not the best way for grasping the kinematics abilities

*as I understand the base with the motors is on this image on the upper triangle plane

*and the tool is on the bottom triangle plane

A: I would do it as follows (algebraic representation of graphic solution):

*

*compute F1,F2,F3;

*solve system
// spheres from Ji to Ei ... parallelograms (use lower Z half sphere)
(x1-J1.x)^2 + (y1-J1.y)^2 +(z1-J1.z)^2 = re^2
(x2-J2.x)^2 + (y2-J2.y)^2 +(z2-J2.z)^2 = re^2
(x3-J3.x)^2 + (y3-J3.y)^2 +(z3-J3.z)^2 = re^2
// Ei lies on the sphere
E1=(x1,y1,z1)
E2=(x2,y2,z2)
E3=(x3,y3,z3)
// Ei is parallel to Fi ... coordinate system must be adjusted
// so base triangles are parallel with XY-plane
z1=z2
z1=z3
z2=z3
// distance between any Ei Ej must be always q
// else it is invalid position (kinematics get stuck or even damage)
|E1-E2|=q
|E1-E3|=q
|E2-E3|=q
// midpoint is just average of Ei
E=(E1+E2+E3)/3

*

*where q is the joint distance |Ei-E| which is constant

[Notes]
Do not solve it manually

*

*use derive or something to obtain algebraic solution

*and use only valid solution

*its quadratic system so there will be most likely more solutions so you have to check for the correct one

Just a silly question why don't you solve inverse kinematics

*

*it is most likely what you need (if you just don't do a visualization only)

*and also is a bit simpler in this case

Also when you use just direct kinematics

*

*I am not entirely convinced that you should drive all 3 joints

*most likely drive just 2 of them

*and compute the 3.th so the kinematics stay in valid position

[Edit1]
There is one simplification that just appear to me:

*

*Ti = translate Ji towards the Z axis by q (parallel to XY plane)

*now if you just need to find intersection of 3 spheres from Ti

*

*this point is E

*so Ei is now simple translation of E (inverse from the Ji translation)
PS. I hope you know how to compute angles when you have all the points ...


text:
Q: How do I make a "definition" template as shown? Recently I started taking notes in LaTeX and wanted to know how I could make a reproducible "definition" template as shown below.
As shown in the images the sizes of the orange line vary depending on the amount of text. What would be the best reproducible method to do this?

A: Something like this?

\documentclass{article}
\usepackage{amsthm}
\usepackage[skins]{tcolorbox}

\newtcolorbox{myframe}{
enhanced,
sharp corners=all,
colback=white,
colframe=orange,
toprule=0pt,
bottomrule=0pt,
leftrule=1.5pt,
rightrule=0pt,
overlay={\draw[orange,line width=1.5pt] (frame.south west) -- ++(1cm,0pt);}
}

\theoremstyle{definition}
\newtheorem{definition}{Definition}

\begin{document}

\begin{myframe}
\begin{definition}
Definition
\end{definition}
\begin{enumerate}
\item a
\item b
\item c
\end{enumerate}
\end{myframe}

\end{document}


text:
Q: Baud Rate Clock VHDL -- floating point exception error and/or style issues I am trying to build a generic baud rate generator process for a uart transmitter.
The transmitter works fine if I ignore the baud rate divider and pass in the clk signal in the sensitivity list. But I get errors (describe in code comments) if I try to implement the divider. I tried two different methods and both either gave an error, or did not have the expected output. Yes, the exact code posted will not work since I assign fbaud twice, I comment one out to test.
Perhaps I don't understand how the baud generator is supposed to work. From my understanding, the fpga clock runs at 50mHz which is to fast for the rs232 communication. So we need to wait a certain number of clock cycles before we can transmit our character.
In this case, we have a variable baud so we divide the stock clock by the baud generator to get the number of clock cycles we need to wait before sending our 'tick' signal to the transmit state machine.
The baud divider is set in the test bench to x"000008".

-- Universal Asynch Receiver Transmitter
---------------------
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity eds_uart is
   generic (width : positive := 16);
   port ( clk,reset: in std_logic ;
     din_wen: in std_logic; -- state machine sets value thus buffer needed
     brd : in std_logic_vector(23 downto 0); -- buad rate dividor
     din : in std_logic_vector(7 downto 0); -- input value
     txd: out std_logic; -- sent data bit
     tx_busy : buffer std_logic -- sent data bit active
     );
end entity eds_uart;

architecture behaviour of eds_uart is
    type state_type is (idle_s, wait_s, transmit_s);  -- three possible states of uat
    signal current_s: state_type;
    signal tick: std_logic := '0'; -- baud rate clock
    signal count: integer := 0; -- count number of characters sent
    signal shift: std_logic_vector(9 downto 0); -- intermediate vector to be shifted
    signal fbaud: integer := 0;
    signal fbaud_counter: integer := 0;

begin
   --- process that is causing the issue.
   process(clk, brd) begin
      fbaud <= (50000000)/to_integer(signed(brd)); -- 50,000,000 is the default clock Hz
      ------ error message  ------
      --# ** Warning: NUMERIC_STD.TO_INTEGER: metavalue detected, returning 0
      -- # Time: 0 ns  Iteration: 0  Instance: /eds_uart_tb/inst_uart
      -- # ** Fatal: (SIGFPE) Floating point exception.
      --#    Time: 0 ns  Iteration: 0  Process: /eds_uart_tb/inst_uart/line__29 File:

      fbaud <= 50000;
      --- error ---
      -- this command simply does not work, it compiles and runs though
      -- I don't get any transitions in my output wave
      -- I don't think it is entering the transmit stage based on a clock signal

      if (rising_edge(clk)) then
         if (fbaud_counter = fbaud) then -- tick when proper number of counts have appeared
             tick <= '1';
         elsif (fbaud_counter < fbaud) then
             tick <= '0';
             fbaud_counter <= fbaud_counter + 1;
         end if;
      end if;
   end process;

   process(tick, reset, din) begin
       if (reset = '1') then
           current_s <= idle_s; -- default state
           count <= 0; -- reset character counter
           txd <= '1';
           tx_busy <= '0';
       elsif (current_s = idle_s and din_wen = '1') then -- transition when write enable is high
           current_s <= wait_s; -- transition
           tx_busy <= '1';
           shift <= '1' & din & '0'; -- init shift value
       end if;
       if(rising_edge(tick)) then
          if (current_s = wait_s) then -- transition on clock signal
               current_s <= transmit_s;
          elsif (current_s = transmit_s) then -- transition on clock signal
               if (count < 9) then
                   txd <= shift(0); -- output value
                   shift <= '0' & shift(9 downto 1); -- shift to next value
                   count <= count + 1; -- increment counter
                   current_s <= transmit_s; -- dont change state
               elsif (count = 9) then
                   txd <= shift(0); -- send last element
                   count <= 0;
                   tx_busy <= '0'; -- reset busy signal
                   current_s <= idle_s; -- start process again
              end if;
          end if;
      end if;
   end process;
end architecture behaviour ;

A: There are a few potential problems with this code, but what seems to be causing your failure is that you're declaring fbaud_counter as an integer but with no range limit specified, and more critically, you're not clearing it when it reached your fbaud count value. Since you never reset the value after the count is reached, it will continue counting through all 2^32 values before it wraps around and matches fbaud again. A range limit is probably a good idea anyway, but either way, if you don't reset it, your baud rate will not be correct. For instance:
if (rising_edge(clk)) then
  if (fbaud_counter = fbaud - 1) then
    tick <= '1';
    fbaud_counter <= 0;
  else
    tick <= '0';
    fbaud_counter <= fbaud_counter + 1;
  end if;
end if;

Note that there's really no need for an elsif condition there, as there really isn't a condition where you don't otherwise want to set tick to '0' or increment your count. Note that I'm also counting to fbaud - 1 - If you start at 0, counting all the way to fbaud may put your rate off very slightly.
edit
I simulated the above with the changes I recommended to the process, and I got a response on txd (as well as a steady tick). Are you sure you're simulating long enough? Assuming your clock is set up to be 50 MHz as your code indicates it should be, setting brd to x"000008" will give you an incredibly slow tick rate (8 Hz, oddly enough). I reduced the numerator to 5000 just to speed things up a bit.
I also realize I didn't cover your floating point exception (thanks for pointing that out).
The warning is a hint as to the error. "metavalue detected, returning 0". The warning indicates to_integer is trying to convert a value that it can't resolve to a 1 or 0 (e.g. 'X', or another such std_logic value), and of course you can't divide by 0. This is most likely an initialization problem (note that your fatal error says Time: 0 ns  Iteration: 0). In your testbench, how is brd driven initially? Can you give it a default value? If not, you will need to guard against this condition some other way.

A: When you simulate it it sounds like your brd input is not initialized, so the Us are turning into 0s and you are dividing by zero - hence the exception.
Also, this will synthesise to something very big, resource-wise:
fbaud <= (50000000)/to_integer(signed(brd));

You are asking for this to be calculated every clock cycle, which is a big ask from the hardware.
The usual method is to accept a terminal count (your fbaud) as the input and let the controlling software  figure out what the value should be. Or calculate it at compile time as a constant, depending on how flexible you need to be.


text:
Q: Adding Calendar and Time to Forms Introduction

Hello. I am a newbie to PHP programming. I have know the basics and now I am into developing a web application from it. I trying to implement the following functionality(It's a ASP.NET calendar),

Explanation

In the Date of Birth option, when the user clicks the calendar icon shown, the following calendar shows up and the user can select the date from it.
What have I done?

Sorry, but my knowledge for now is nothing more than this,
<input name="todo" type="text" />

<input name="time" type="button" />

My Requirements

I need the same functionality for my web application for time and date.
I would be very thankful for the help. Thanks in advance.

A: Sorry, I had to answer my question myself as I found out the answer. Its implemented here.
However, I am not marking my answer as selected answer. I await for better answers as time functionality is still needed by me. Thankyou.


text:
Q: UNIX System commands for iPhone to control services I am looking for SpringBoard commands to control jailbroken iPhone programmatically, but theres hardly any information out there, or its pretty well hidden!  I would like to be able to talk to the ComCenter programmatically. Now I know this is not approved by Apple, but I dont care, I dont follow rules  ;-)
Anyone know of a good reference source for jailbroken commands for SpringBoard or ComCenter on 3.1.2 iPhone?
This is an example of what I am looking for:
NSString *cmd = (@"killall SpringBoard");
ssystem([cmd UTF8String]);

Which restarts SpringBoard

A: system("process unload /com.service.name");


text:
Q: Continuously update marker when location changed on Android I'm trying to implement an simple navigation app using Google maps. Initially I developed a code for marking two Geo points on map and showing route between them.
Now I am trying to move the first marker towards second marker (destination) based on users location.
For this I used LocationListener and implemented code in onLocationChanged.
The problem is onLocationChanged is not getting fired and marker is not moving based on user location.
Here is my code.
MapActivity.java
public class MapActivity extends FragmentActivity implements OnMapClickListener, LocationListener{

private GoogleMap gMap;
private ArrayList<LatLng> markersArray; //Marker points ArrayList
private ArrayList<Marker> markers;
private MarkerOptions options; //Marker options
String distance="";
String duration="";
private TextView travelDetails;
private ProgressDialog pDialog;
private double lattitude=0.0;
private double longitude=0.0;
Marker mMarker;
String bestAvailableProvider;
private LocationManager mLocationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    //Loading Google Maps
    try{
        loadMapView();
        markersArray=new ArrayList<LatLng>();
        markers=new ArrayList<Marker>();
        gMap.setOnMapClickListener(this);
        gMap.setMyLocationEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        travelDetails=(TextView) findViewById(R.id.lbl_traveldetails);
        pDialog=new ProgressDialog(MapActivity.this);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * This method loads map
 *
 */

private void loadMapView(){

    if (gMap==null) {
        gMap=((SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map_fragment)).getMap();
    }

    mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    // Specify Location Provider criteria
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setSpeedRequired(false);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);

}

/*
 * catches onclick event of map
 * @see com.google.android.gms.maps.GoogleMap.OnMapClickListener#onMapClick(com.google.android.gms.maps.model.LatLng)
 */

@Override
public void onMapClick(LatLng point) {

    //Clearing markers in map

    if (markersArray.size()>1) {
        markersArray.clear();
        gMap.clear();

    }

    //Adding  marker to array
    markersArray.add(point);

    //marking point on Map
    addMarkerOnMap(point);

    //Drawing route when two markers are placed

    if(markersArray.size() >= 2){
        LatLng origin = markersArray.get(0);
        LatLng dest = markersArray.get(1);

        String url = getDirectionsUrl(origin, dest);

        DownloadTask downloadTask = new DownloadTask();

        downloadTask.execute(url);
    }

}

/*
 * This method places markers on map
 */

private void addMarkerOnMap(LatLng point){

    //Marking points on map
    options=new MarkerOptions();
    options.position(point);

    //Setting marker icons

    if (markersArray.size()==1) {

        //Source marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    }else if(markersArray.size()==2){

        //Destination marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    }

    //adding marker point to map
    try{
        Marker mMarker=gMap.addMarker(options);

        markers.add(mMarker);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * Getting direction url between two points
 *
 */

private String getDirectionsUrl(LatLng origin,LatLng dest){

    // Origin of route
    String str_origin = "origin="+origin.latitude+","+origin.longitude;

    // Destination of route
    String str_dest = "destination="+dest.latitude+","+dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin+"&"+str_dest+"&"+sensor;

    // Output format
    String output = "json";

    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

    return url;
}

/*
 * passing the direction url
 *
 */

private class DownloadTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.show();
        pDialog.setMessage("Loading route...");
        pDialog.setCancelable(false);
    }

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/*
 * downloading from url
 *
 */

private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJsonParser parser = new DirectionsJsonParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        //  MarkerOptions markerOptions = new MarkerOptions();

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                if(j==0){    // Get distance from the list
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = (String)point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(5);
            lineOptions.color(Color.BLUE);
        }

        // Drawing polyline in the Google Map for the i-th route
        try{
            gMap.addPolyline(lineOptions);
            travelDetails.setText("Distance:"+distance+"Duration:"+duration);
            pDialog.dismiss();
        }catch (Exception e) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Toast.makeText(getApplicationContext(), "No Road route found.", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    loadMapView();
}

@Override
protected void onPause() {
    super.onPause();
    mLocationManager.removeUpdates(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.map, menu);
    return true;
}

/*
 * (non-Javadoc)
 * @see com.google.android.gms.maps.LocationSource.OnLocationChangedListener#onLocationChanged(android.location.Location)
 */

@Override
public void onLocationChanged(Location location) {
    Log.e("loca", ""+location.getLatitude());

    try {

        if(markersArray.size()>0){

            lattitude=location.getLatitude();
            longitude=location.getLongitude();

            LatLng mLatLng=new LatLng(lattitude, longitude);
            Marker newMarker=markers.get(0);
            newMarker.setPosition(mLatLng);
            gMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

}

DirectionsJsonParser.java
public class DirectionsJsonParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    JSONObject jDistance = null;
    JSONObject jDuration = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                /** Getting distance from the json data */
                jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                HashMap<String, String> hmDistance = new HashMap<String, String>();
                hmDistance.put("distance", jDistance.getString("text"));

                /** Getting duration from the json data */
                jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                HashMap<String, String> hmDuration = new HashMap<String, String>();
                hmDuration.put("duration", jDuration.getString("text"));

                /** Adding distance object to the path */
                path.add(hmDistance);

                /** Adding duration object to the path */
                path.add(hmDuration);

                /** Getting poly points */
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);

                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                        hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                /** Adding poly points */
                routes.add(path);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return poly;
}

}

A: I think you have not used location provider ,  use googleapiclient
and read about this topic , it allows you to show your current position on map when location  changed, that provides you your current locations.
Hint
Implements GoogleApiClient.ConnectionCallbacks , GoogleApiClient.OnConnectionFailedListener
in your activity then you can easily do that.


text:
Q: missing mutex lock error i have a variable accessed via mutex lock in multiple threads.
when i run coverity static analysis on it, it gives the following error:-
MISSING_LOCK (Accessing variable"g_atag"(g_atag) requires the osag_mutex.mutex lock.) [coverity]
Code snippet:
unsigned long g_atag = 0;
pthread_mutex_t g_atag_lock = PTHREAD_MUTEX_INITIALIZER;

void get_atag(unsigned long *atag)
{
    int ret = -1;

    ret = pthread_mutex_lock(&g_atag_lock);
    if (0 != ret) {
        return;
    }

    if (g_atag < 10000) {
        g_atag++;
    } else {
        g_atag = 0;
    }

    *atag = g_atag;

    pthread_mutex_unlock(&g_atag_lock);
}

Does any one sees any problem in this? i have added the locks then why is it saying the locks are missing?


text:
Q: Basic Authentication not working even for correct credentials in IIS 7 I am currently having a issue in basic authentication for a WCF service deployed on IIS.
When I browse the service i get a pop up window from the browser to give my credentials.Even if i am giving correct credentials , still i am getting the pop up again and again. Is it possible that the user id with which i am logging in is locked or something ?, because i was able to log in (several times) without problem earlier today.I also deliberately tried to login with wrong credentials which may have caused some problem i guess.
Any expert suggestion on this issue ? Thank You.


text:
Q: C# 2D array of doubles and strings I am trying to get quite a large SQL query into an array in C#. However, the values from the query are made up of doubles and strings. How do I account for that? Because, using the below method (just putting everything in as a string) does not work in my worksheet, as the numbers are formatted as text.
String sql = "SELECT Ticker, Cusip, Shares, value, Price, " +....

string[,] data = new string[5000, 10]; //multi-dimentional array

string connectionString = Database.ConnectionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql, connection))
    {

        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            String ticker = (string)reader["ActTicker"];
            String cusip = (string)reader["Cusip9"];
            double shares = (double)reader["shares"];
            double price = (double)reader["price"];
            double value = (double)reader["value"];

            data[row, 0] = ticker;
            data[row, 1] = "=iferror(bdp(\"" + cusip + " cusip\", \"GICS_SECTOR_NAME\"),0)";
            data[row, 2] = "=iferror(bdp(\"" + cusip + " cusip\", \"SECURITY_TYP\"),0)";
            data[row, 3] = "=iferror(bdp(\"" + cusip + " cusip\", \"CUR_MKT_CAP\"),0)";
            data[row, 4] = "=iferror(bdp(\"" + cusip + " cusip\", \"VOLUME_AVG_10D\"),0)";
            data[row, 5] = shares.ToString();
            data[row, 6] = value.ToString();
            data[row, 7] = price.ToString();
            data[row, 8] = "=iferror(bdp(\"" + cusip + " cusip\", \"last price\"),0)";
        }
    }
}

A: You can use a DataTable, or if you want something a bit more lightweight and strongly typed then create your own custom data structure.
public struct MyCustomData
{
    String ticker;
    String cusip;
    double shares;
    double price;
    double value;
}

The make an array out of that
MyCustomData[] data = new MyCustomData[5000];
.
.
.
data[row].ticker = ticker;
data[row].cusip = "=iferror(bdp(\"" + cusip + " cusip\", \"GICS_SECTOR_NAME\"),0)";
.
.
.

A:     public SqlConnection myConnection = new SqlConnection("");

    public DataTable Select(string sTSQL)
    {
        DataTable dt = new DataTable();
        try
        {
            myConnection.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand(sTSQL,  myConnection);
            myReader = myCommand.ExecuteReader();

            dt.Load(myReader);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            dt = null;
        }
        finally
        {
            try
            {
                myConnection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        return dt;
    }