text:
Q: How to lighten a color map is sass I have created a color map as shown below and I am looking to use lighten(color, amount) every button when I hover over them.
the @each part of the code works and brings all of the colors over its the hover section that's not working.
`@each $button, $color in $button-colors{
    .btn#{$button}{
        background-color: $color;
    &:hover{
      background-color: lighten(get-map($button-colors), 15%);
    }
    }
  }`

`$button-colors:(
    '.default':#51ddfc,
    '.error':  #e4757a,
    '.info':   #927bc1,
    '.success':#63cc82,
    '.warning':#fd7856,
);`

Thanks

A: You got the get-map function wrong. First of all it's map-get, and it has 2 parameters $map and $key. Read docs at https://sass-lang.com/documentation/modules/map.
There is no need to use map-get since you are already inside the loop and have access to the $color:
$button-colors: (
    '.default': #51ddfc,
    '.error': #e4757a,
    '.info': #927bc1,
    '.success': #63cc82,
    '.warning': #fd7856
);

@each $button, $color in $button-colors{
  .btn#{$button}{
    background-color: $color;

    &:hover{
      background-color: lighten($color, 15%);
    }
  }
}


text:
Q: if a Facebook user already authorised my app, can I pass it on to my webView? When a user hits the Like button in my webView (even after he/she authorised the native Facebook integration for the app), The webView keeps bringing up the Facebook login form.
This only means the session of the app and the one of the webView are obviously different ones.
Any idea of how to share the session cookies?

redpajama_set_name: RedPajamaStackExchange


text:
Q: MYSQL/PHP Shifting order of objects up or down while maintaining numerical order I have table that holds objects, it looks like this:
CREATE TABLE `post_objects` (
  `id` mediumint(7) NOT NULL AUTO_INCREMENT,
  `post_id` mediumint(7) NOT NULL,
  `object_data` text,
  `object_order` tinyint(1) DEFAULT '0',
  `created` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

The object_order column tracks the numerical order of the objects and is used to sort when the objects are pulled. It maintains 1, 2, 3, 4, ad infinitum depending on how many objects are assigned to a post_id.
The Problem:
From my PHP I want to be able to move objects up or down incrementally by one. For example, move the object with and order of 3 to the 2 position, and have the remaining objects reorder themselves so as to still maintain 1, 2, 3, 4...
What I've Tried:
The current function is not giving me the expected result. Currently if I move the last position down, it is not renumbering correctly.  Here is the latest attempt:
// Shift given object order by one in given direction.
function objectOrderShift ($object_id, $shift_type) {
    $post_id = getParentPostId($object_id);
    $current_object_order_value = getObjectOrderValue($object_id);
    switch ($shift_type) {
        case 'up':
            $new_object_order_value = $current_object_order_value - 1;
            break;
        case 'down':
            $new_object_order_value = $current_object_order_value + 1;
            break;
    }

    // Update new object id to new order value (*THERE WILL BE TWO ENTRIES WITH THE SAME ORDER NUMBER*)
    $sql = "UPDATE post_objects SET object_order = :new_object_order_value WHERE id = :object_id";
    $stmt = db::getInstance()->prepare($sql);
     $stmt->bindParam(':object_id', $object_id, PDO::PARAM_INT);
     $stmt->bindParam(':new_object_order_value', $new_object_order_value, PDO::PARAM_INT);
    $stmt->execute();

    //set starting order value
    $object_order_value = 1;
    // Run select for all objects edit as needed
    $sql = "SELECT id, object_order FROM post_objects WHERE post_id = :post_id ORDER BY object_order ASC";
    $stmt = db::getInstance()->prepare($sql);
     $stmt->bindParam(':post_id', $post_id, PDO::PARAM_INT);
    $stmt->execute();
    $results = $stmt->fetchAll();

    foreach ($results as $row) {
        $flux_object_id = $row['id'];  // holder for other object_id's from SELECT query

        if($flux_object_id == $object_id) {
            // This is the already altered object_id, skip entry and ++ value
            $object_order_value++;
        }
        $sql = "UPDATE post_objects SET object_order = :object_order_value, created = NOW() WHERE id = :flux_object_id";
        $stmt = db::getInstance()->prepare($sql);
         $stmt->bindParam(':flux_object_id', $flux_object_id, PDO::PARAM_INT);
         $stmt->bindParam(':object_order_value', $object_order_value, PDO::PARAM_INT);
        $stmt->execute();
        $object_order_value++;
    }
}

A: You can do it in a single query. And since you're only shifting by a single place, you only need to update 2 rows: the object you're moving, and the row before or after it in object order.
To shift an object down:
UPDATE post_objects AS p1
JOIN post_objects AS p2 ON p1.object_order IN (p2.object_order, p2.object_order - 1)
SET p1.object_order =
    CASE WHEN p1.id = p2.id THEN p1.object_order - 1
         ELSE p1.object_order + 1
    END
WHERE p2.id = :object_id


text:
Q: Creating an object with dynamic properties in C# I'm using linq to load a csv file, but because the csv may have any number of columns, the object that it returns will need dynamic properties, and I can't figure out how to do that.
var data = from row in csvData
       let col = row.Split(',')
       select new
              {
                  Field1 = data[0],
                  Field2 = data[1],
                  Field3 = data[2] // etc, etc
              };

If possible, I'd like to name the properties by the name given in the csv file, rather than field1, field2, etc.
Thanks!

A: What would you do with this afterwards? If you know the names elsewhere and you're using .NET 4, you could use ExpandoObject - populate it by using it as a dictionary, and then access the property names using dynamic typing later. But if it's all dynamic (i.e. you don't know anything statically anywhere), why don't you just use Dictionary<string, string>?

A: You could just do is simply using arrays or even a Dictionary but if you want to do something cool with Dynamic check out Clay
http://weblogs.asp.net/bleroy/archive/2010/08/18/clay-malleable-c-dynamic-objects-part-2.aspx


text:
Q: Search bar: anchor tag enclosed in list item tags not selectable I have a search bar in the style of like a google search bar where it gives suggestions based on the user input as you are typing in the text box. It filters through a bunch of items that are contained in an unordered list and runs myFunction() below to parse through the unordered list and display items. The only problem is that when you click the items that are displayed in the search bar, the link redirection doesn't work and I THINK it's because the onMouseButtonUp event doesn't register over the list item (because when I click down and hold the button down, it makes the item disappear if that makes sense)...thoughts?
<input style="border-radius: 7px 0px 0px 7px; border-right: 0px; resize: none" id="myInput" onkeyup="myFunction()" name="searchedItem" rows="1" class="form-control" form="searchForm" placeholder="What can we help you find?">

{{obj.productName}}


text:
Q: Refresh Fragment view when RecyclerView.Adapter is changed I am following Shrine example application which is implemented in Kotlin part of Google official codelabs for developers. The application and codelab
The last step, We are asked to

Modify your Shrine application to change the product images shown when
a category is selected from the backdrop menu.

In the ProductGridFragment#onCreateView I attached a onClick listener on one button to begin with (list of categories, are buttons).
As a test, I just popped an element from the list firstly used in Adapter.
theList = ProductEntry.initProductEntryList(resources)
adapter = StaggeredProductCardRecyclerViewAdapter( theList )

val featured = view.findViewById(R.id.featured) as Button
// set on-click listener
featured.setOnClickListener {
        theList.pop(1)
        adapter.notifyDataSetChanged()

It is not working. Is there other things to do to refresh the view ? all I see in onCreateView seems to be just for first creation of the fragment, I mean, when onClick is produced, it seems to me sufficient to just modify the list and notify adapter on changes.
Do I have to do any thing with view object ?
Any hints ?
Edit 1:
I assigned a new adapter and it works now, this is very nice; Although I do not feel it is performance efficient, as notify for data changes is not really used as intended
featured.setOnClickListener {
    theList = ProductEntry.initProductEntryList(resources, "featured")
    this.adapter = StaggeredProductCardRecyclerViewAdapter(
            theList )
    view.recycler_view.adapter = this.adapter
    this.adapter.notifyDataSetChanged()
}

A: in Java/Kotlin you always pass by value, not a reference. So when you passed the list to the StaggeredProductCardRecyclerViewAdapter( theList ), you should update the list from Adapter, not the one you passed, so for example:
class StaggeredProductCardRecyclerViewAdapter(private val theList: List) {

    private var listOfItems = theList

    fun removeItem(position: Int) {
        listOfItems = listOfItems.remove(position)
        notifyDatasetChanged()
    }
}

val featured = view.findViewById(R.id.featured) as Button
// set on-click listener
featured.setOnClickListener {
       adapter.removeItem(1)
}

EDIT:
I went to the codebase and you are operating on the immutable list inside the StaggeredProductCardRecyclerViewAdapter. If you want to filter the items on the list based on "featured" for example, you should do this:
class StaggeredProductCardRecyclerViewAdapter(private val initList: List<ProductEntry>?) : RecyclerView.Adapter<StaggeredProductCardViewHolder>() {

    private var productList: List<ProductEntry>? = initList

    override fun getItemViewType(position: Int): Int {
        return position % 3
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StaggeredProductCardViewHolder {
        var layoutId = R.layout.shr_staggered_product_card_first
        if (viewType == 1) {
            layoutId = R.layout.shr_staggered_product_card_second
        } else if (viewType == 2) {
            layoutId = R.layout.shr_staggered_product_card_third
        }

        val layoutView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        return StaggeredProductCardViewHolder(layoutView)
    }

    override fun onBindViewHolder(holder: StaggeredProductCardViewHolder, position: Int) {
        if (productList != null && position < productList.size) {
            val product = productList[position]
            holder.productTitle.text = product.title
            holder.productPrice.text = product.price
            ImageRequester.setImageFromUrl(holder.productImage, product.url)
        }
    }

    override fun getItemCount(): Int {
        return productList?.size ?: 0
    }

    fun replaceList(items: List<ProductEntry>?) {
        productList = items
        notifyDatasetChanged()
    }
}

And in ProductGridFragment:
...
featured.setOnClickListener {
       adapter.replaceList(ProductEntry.initProductEntryList(resources, "featured"))
}

A: If You want to run again onCreateView with out creating a new instance of the fragment you can just use this:
    supportFragmentManager.beginTransaction().detach(yourFragment).commitNow()
    supportFragmentManager.beginTransaction().attach(yourFragment).commitNow()

This will rerender the whole view.
Based on different cases maybe you need to use childFragmentManager
But the right and most efficient solution when adapter data changes is to use         notifyDatasetChanged()


text:
Q: Dynamic routing and lifecycle in react I'm working with dynamic routing in react.
I'm fetching some data from a third-party API. I have my dynamic route to be something like this
<Route path="/:id" component = {item} />
In the item component, I get the value in params.id and use that id to fetch my data in
componentDidUpdate(){ fetchData(this.props.match.params.id);}
The issue I'm having now is that whenever I try to visit another route of the same format /:id from the Item component, the params changes to the new id passed but still retains the old content for the old id. I believe componentDidmount wasn't called since i'm in that same item component. the component wasn't remounted but just updated. What can I do?

A: You have to make the api call in componentDidMount as well as in componentDidUpdate with class component. Once you fetch the data, you have to set it in state of the component to visually see it.
componentDidmount() {
  fetchData(this.props.match.params.id);
}

componentDidUpdate(prevProps, prevState){
  if(prevProps.match.params.id !== this.props.match.params.id) {
    fetchData(this.props.match.params.id);
  }
}

If you rather use react hooks + functional component, this will be simplified for you. You can use useState to maintain data in the state.
import React, { useEffect } from "react";
const YourComponent = props => {
    const { id } = props.match.params;
    // This will run every time id changes.
    useEffect(() => {
        fetchData(id);
    }, [id]);

    return (
        <>
            Your api call
        </>
    );
};


text:
Q: Roll over / Hovering tabs not displaying correctly in IE8 Check this page. On either firefox, chrome, or IE9 / 10 the tabs on the header display uniform and hover correctly. However on IE8 The tabs step down and disappear off of the header. Anyone familiar with this problem?
http://www.seanprovost.com/frah_dev/newclients.php
$(document).ready( function() {
$("#nav1").animate({
    marginTop: "50px"
}, 'slow');
$("#nav2").animate({
    marginTop: "50px"
}, 'slow');
$("#nav3").animate({
    marginTop: "50px"
}, 'slow');
$("#nav4").animate({
    marginTop: "50px"
}, 'slow');
$("#nav5").animate({
    marginTop: "50px"
}, 'slow');

//Animal Care Animation
$("#link_ac").hover( function() {
    $("#nav1").animate({ marginTop: "0px" }, 'slow');
}, function() {
    $("#nav1").animate({ marginTop: "50px" }, 'slow');
});
//Animal Care Rollover
$("#link_ac").hover( function() {
    $("#nav1").css({"background-image" : "url('i/nav_ac_o.png')" });
}, function() {
    $("#nav1").css({"background-image" : "url('i/nav_ac.png')" });
});
//Our Team Animation
$("#link_ot").hover( function() {
    $("#nav2").animate({ marginTop: "0px" }, 'slow');
}, function() {
    $("#nav2").animate({ marginTop: "50px" }, 'slow');
});
//Our Team Rollover
$("#link_ot").hover( function() {
    $("#nav2").css({"background-image" : "url('i/nav_ot_o.png')" });
}, function() {
    $("#nav2").css({"background-image" : "url('i/nav_ot.png')" });
});
//Boarding Animation
$("#link_b").hover( function() {
    $("#nav3").animate({ marginTop: "0px" }, 'slow');
}, function() {
    $("#nav3").animate({ marginTop: "50px" }, 'slow');
});
//Boarding Rollover
$("#link_b").hover( function() {
    $("#nav3").css({"background-image" : "url('i/nav_b_o.png')" });
}, function() {
    $("#nav3").css({"background-image" : "url('i/nav_b.png')" });
});
//New Clients Animation
$("#link_nc").hover( function() {
    $("#nav4").animate({ marginTop: "0px" }, 'slow');
}, function() {
    $("#nav4").animate({ marginTop: "50px" }, 'slow');
});
//New Clients Rollover
$("#link_nc").hover( function() {
    $("#nav4").css({"background-image" : "url('i/nav_nc_o.png')" });
}, function() {
    $("#nav4").css({"background-image" : "url('i/nav_nc.png')" });
});
//Grooming Animation
$("#link_g").hover( function() {
    $("#nav5").animate({ marginTop: "0px" }, 'slow');
}, function() {
    $("#nav5").animate({ marginTop: "50px" }, 'slow');
});
//Grooming Rollover
$("#link_g").hover( function() {
    $("#nav5").css({"background-image" : "url('i/nav_g_o.png')" });
}, function() {
    $("#nav5").css({"background-image" : "url('i/nav_g.png')" });
});

A: Your css for the nav elements needs some work. Use a console to inspect the LI and  <a> tags etc will see that IE is seeing the positioning of them differently due to lack of css structure on the main elements and floats within those elements.
Also validator is showing broken tags in page. Beef up the css on nav, fix broken tags and you should be better off cross browser
EDIT: disable javascript and will see that jQuery is not the culprit

A: instead of using two hover handlers you can combine them, and try stop() method:
   $("#link_ac").hover( function() {
        $("#nav1").stop().animate({ marginTop: "0px" }, 'slow');
        $("#nav1").css({"background-image" : "url('i/nav_ac_o.png')" });
    }, function() {
        $("#nav1").stop().animate({ marginTop: "50px" }, 'slow');
        $("#nav1").css({"background-image" : "url('i/nav_ac.png')" });
    });


text:
Q: Getting error while display html content on page I would like to display my website ads on other websites like google ads but I got error

Uncaught SyntaxError: Unexpected token < in JSON at position 0

I have used the codeigniter frame work and jquery, it is taking content as variable. Are there any possibilities to solve this issue?
This my Script code:
(window.jQuery || document.write("

The PHP:
function demo_ad()
{
    $ad_var = "

";
    return $ad_var;
}

call to the funtion like this demo_ad()


text:
Q: CodeIgniter - Getting id from a freshly inserted database record in the same function I need to insert some details into a database and get the auto_incremented ID of the record that has just been inserted into the database in the same function.
Firstly i use the controller to tell the model to insert all the data using the following:
$this->client->add_new_client();

Then straight after that i need to insert the clients ID, which was automatically generated by the database when the details where added to the database, to another model using:
$this->model->add_new_details($client_id);

Any help would be fantastic.
Cheers

A: You want to go ahead and return $this->db->insert_id(); from the first function.

A: If you have some way to get at the client object, you can probably call its method that returns an ID and get the ID. I'm not sure enough about CI to tell you how.
In PHP generally, call mysql_insert_id() to get the last ID generated on the current database connection. It should return the ID of the client if that's the last INSERT query that ran.


text:
Q: How to pass parameters into onclick function parameters into dynamically created buttons? My javascript reads text from a file and creates button dynamically base on the button creation below. The problem I am facing is it is not able to call the function on click. I've tried removing the parameters to call it and it works however I can't seem to get it to work with passing of parameters. Can someone help me with it?
JS:
function toggleVisibility(type){
    alert(type);
}

Button creation:
var button='<button type="button" class="btn btn-block btn-inverse active" data-toggle="button tooltip" title="Click this to enable/disable viewing of '+this+'" onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';

A: You shouldn't use inline handlers, first of all, and it's easier to create it with jQuery anyways:
var that = this;
var button = $("<button>");
button.addClass("btn btn-block btn-inverse active");
button.attr({
    type: "button",
    "data-toggle": "button tooltip",
    title: "Click this to enable/disable viewing of " + that
});
button.text(word);
button.on("click", function () {
    toggleVisibility(that);
});

(yes, I know you could chain all of the method calls, I just wanted to do it this way)
When you're ready to put this button somewhere, just use $container.append(button);.
Everything depends on what this is or what you want/expect it to be. If you need the parameter passed to toggleVisibility to be the specific button that was just clicked (I'm guessing to toggle its visibility), just pass this (ignore the that). As for setting the title attribute, I'm not sure what you want :)
If you have an HTML structure like:
<div id="container">
    <!-- Buttons go somewhere in here -->
</div>

And you're appending the buttons to that container (or somewhere in that container), it would be more efficient to bind a single click handler to the container with event delegation:
$("#container").on("click", ".special-btn-identifier", function () {
    toggleVisibility(this);
});

Of course, you'd need to add a "special-btn-identifier" class to the buttons, so that this event handler will work (and remove the individual click handlers for each button, as this will cover them). This single event handler only needs to run once, preferably as soon as the #container is ready...like in $(document).ready(function () {});.

A: Replace your following line:
.. onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';

for this one:
.. onclick="toggleVisibility(this)">'+word+'</button>';

as you dont need to escape the this keyword, nor including a different this from the context where you were creating the button text.

A: Register the onClick event on the document instead of in the html when you create the button.
$(document).on('click', 'button.btn-inverse', function() { toggleVisibility(this); return false;});

A: Don't create inline HTML strings, don't use intrusive Javascript.
Though I don't even advise you to create them with vanilla jQuery, you may try with:
var $button = $('<button></button>', {
  'text'        : word
  'type'        : 'button',
  'class'       : 'btn btn-block btn-inverse active',
  'data-toggle' : 'button tooltip',
  ...
  // any other attributes
});

// append the $button anywere

$( someContainer ).append($button);

$( someContainer ).on('click', '.btn', function(event){

  // you can refer to the button with $(this) here

});


text:
Q: Django ORM get maximum value of a field and corresponding other column values I have a DataFrame:
`exp_no`   'time'   'price'

  1       0:00:00     20.0
  1       7 days      45.0
  1       15 days     100.0
  2       0:00:00     20.0
  2       7 days      45.0
  2       15 days     100.0

The corresponding Django model:
class StData(models.Model):
      exp_no = models.ForeignKey(StIndex, on_delete=models.CASCADE)
      time = models.DateTimeField()
      price = models.DecimalField(max_digits=10, decimal_places=2)

I want to make a smaller table which would have exp_no, max_time and corresponding price such that:
 `exp_no`   'time'   'price'

  1       15 days     100.0
  2       15 days     100.0

In pandas, I'd do df.groupby('exp_no')['time', 'price'].max().reset_index()
to get the desired table.
In Django ORM annotation to get the same result(or Queryset) if I do:
qs.values('exp_no').annotate(max_time=Max('time')).order_by()

it gives me exp_no and time, but I want to get the corresponding price as well. I have looked through this answer in SO: Django orm get latest for each group
But not sure how I get the price. Using Django 2.0 with sqlite3.
I appreciate any help.

A: Your question boils down to obtaining the StData object (or the values) for the record with the largest time column. So we do not need an aggregate, but obtain the smallest or largest row with respect to the time column.
Obtaining the StData object with the maximum time
You can just obtain the last() row when you order on 'time', like:
stdata_max_time = qs.order_by('time').last()  # will return a StData
or alternatively:
stdata_max_time = qs.order_by('-time').first()  # will return a StData
In case time is NULLable (not here), you can ensure that you will not retrieve a row with NULL by specifying that when ordering these should be placed as first/last elements respectively:
from django.db.models import F

# two alternatives
stdata_max_time = qs.order_by(F('time', nulls_first=True)).last()
stdata_max_time = qs.order_by(F('-time', nulls_last=True)).first()
This is thus a StData object, and you can thus retrieve all relevant information you want from that object. Since it is a StData object, it will also behave like this (so extra properties, methods, etc. you defined, will work as well).
Obtaining the values with the maximum time
This is completely similar, except that we put a .values(..) call in the query:
stdata_max_time = qs.order_by('time').values('exp_no', 'time', 'price').last()
But unless there are some really good reasons, I would personally prefer to fetch the StData object, since that means "batteries included" (you get all the logic you wrote in the StData class with that object).


text:
Q: Non-uniform Normal force, friction I got problems understanding the Non-uniform normal force. Why is it non-uniform? Because the object would have different densities in different parts, so weight would be greater in some parts? So Normal Force would be aligned with weight, no? Normal force only depends the force applied on the ground, so it depends of the weight of the object, no?
why does the object can tip? It only tips if Normal Force is on the corner of the object or out of it. how come? How can normal force be applied  outside the contact surfaces?
Try to give me some analogy to understand better please.

A: Half of your questions are concerning Newton's law:

Why is it non-uniform? Because the object would have different densities in different parts, so weight would be greater in some parts?

Yes. Think of a car. It is in contact with the ground in four places and pushes down causing four normal forces. If the car is heavily loaded with bagage in the trunk, the back-wheels will carry much more load than the front-wheels. They experience a larger normal force.
Now, think of a bike where you suddenly brake hard with the front-wheel brake. You are slung forward and so is the rest of the bike, and the front wheel, is carrying much more load than the back-wheel  which is almost lifting (which would give zero normal force).
So yes, uneven normal forces are certainly possible and very usual. An uneven density as you mention is one possibility, but other factors as the above examples show can also cause uneven forces on the ground at different points.

So Normal Force would be aligned with weight, no?

What does "aligned" mean? If you mean "normal force will balance weight", then yes it might, but be careful. That is not a law, but just one possible result of Newton's 1st law:
$$\sum F=0$$
If a car is standing on the road, then $$\sum F=n-w=0\quad\Leftrightarrow\quad n=w$$ Normal force balances weight, yes. But if an elephant is pulling in the it with force $F$, then $$\sum F=n+F-w=0\quad\Leftrightarrow\quad n=w-F$$
Normal force and weight is not related any more than any other forces are. It just happens to often be the case that normal force balances weight.

Normal force only depends the force applied on the ground, so it depends of the weight of the object, no?

Normal force can depend on any force that pushes downwards, as just explained. Think of normal force as a holding force. It is the force a road or a table or etc. applies to hold something up - it doesn't matter which forces that are pushing the objects downwards (it can be weight or any other force); but if the objects are pushed downwards, then normal force will try to hold them up.
The other half of your questions are concerning the rotational equivalent of Newton's law:

why does the object can tip?

If an object tips then it rotates about some point. We here have to introduce the rotational version of Newton's 2nd law:
$$\sum \tau=I\alpha$$
$\alpha$ is the rotational (or angular) acceleration, so if the object starts to tip over, then $\alpha$ is becoming non-zero. And when will that happen? As in Newton's 2nd law, when forces are not balanced, an object will accelerate, the likewise in this rotational version of the law, when torques $\tau$ are not balanced, the object will accelerate rotationally.
So, if e.g. in a heigh truck too much heavy load is put in one side then the centre of mass is in this side. If the truck ever tilts a little, then the centre of gravity might pass the point where the normal force on the wheel applies, and then the weight and normal force will help each other to make the truck rotate more and more since they don't balance each other anymore - so $\alpha$ is non-zero.

It only tips if Normal Force is on the corner of the object or out of it. how come?

It's not about the corner specifically, but it's about where the centre-of-mass is location compared to where other forces, like the normal force, is pushing. All torques from all forces must be balanced at every point, otherwise the object will tip.

How can normal force be applied outside the contact surfaces?

It can't (unless you are talking about some "equivalent" or "average" normal force. Normal force is a contact force that appears at contacting surfaces.


text:
Q: StackOverFlow while counting digits I am trying to count the number of digits in a number in Clojure as follows: I get a StackOverflowError even for 2 digit numbers
(defn num-digits [n]
   (if (= 0 n)
   0
   (inc (num-digits (/ n 10)))))
(println (num-digits 93))

But if I replace / with unchecked-divide then it works for at least 93. But neither of the techniques works for:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

First, I would like to know how to perform division the C-style in Clojure. Whenever I do (/ x y) I get a Ratio and not a Integer. What is the way to do it?
Secondly, is there a way API to convert this Number into a vector of digits and call count on it.
Thanks,
Ajay G

A: This is why you're having a problem:
user> (take 10 (iterate #(/ % 10) 10923))

(10923 10923/10 10923/100 10923/1000 10923/10000 10923/100000 10923/1000000 10923/10000000 10923/100000000 10923/1000000000)

This is the fix:
user> (take 10 (iterate #(quot % 10) 10923))

(10923 1092 109 10 1 0 0 0 0 0)

This is the expression you're looking for:
user> (count (take-while #(not (zero? %)) (iterate #(quot % 10) 10923)))
5

This is cheating:
user> (count (str 10923))
5

This is the function you were trying to write (but careful, it will stack overflow for large numbers):
user> (defn num-digits [n]
        (if (= 0 n)
          0
          (inc (num-digits (quot n 10)))))

#'user/num-digits
user> (num-digits 10923)
5

However, it is up to the challenge:
user> (num-digits 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000)

158

This version of that function will not blow stack:
user> (defn num-digits-tail-recursion
        ([n count]
           (if (= 0 n)
             count
             (recur (quot n 10) (inc count))))
        ([n] (num-digits-tail-recursion n 0)))
#'user/num-digits-tail-recursion
user> (num-digits-tail-recursion 10923)
5

All versions are interesting in their own way. Good question!

A: Clojure attempts to "do the right thing" with numeric operations and never lose precision. so when you device say 17/10 the result is the fraction 17/10 (seventeen tenths) not 1. By default no information will be lost in any of the numerical operations. In cases like this you can explicitly throw away the extra precision with (quote x 10) or you can cast the result to an int (int (/ 17 10))
for the second question here's a little hack:
(count (str 257))

A good way to keep from blowing the stack with recursion in Clojure is to use other higher order functions instead of recursion.
(count (take-while pos? (iterate #(quot % 10) 257))))

A: There's no tail-call optimisation in Clojure. You have to use the recur special form.
E.g.:
(defn num-digits [n]
  (loop [n n
         cnt 0]
    (if (= 0 n)
      cnt
      (recur (quot n 10) (inc cnt)))))

But in answer to your second question: yes, and this is how:
(defn num-digits [n] (count (str n)))

A: According to this page, you can perform integer division in Clojure using quot:
(quot n 10)


text:
Q: Crystal report count insterd of sum I am using Crystal report and I want to get the sum of group.
These are my columns with data type.
Customer - String
Item - String
Qty - Decimal
SalesPrice -Decimal
Value -Decimal
This is GroupBy Customer and I want to get the sum of Qty. But output is count of rows.
How can I solve this issue..

A: If this field was a summary (You right clicked on a certain field, then you chose to insert --> Summary) Then you can right click on it, then choose Edit Summary, then instead of Count choose Sum.

A: sometimes Crystal report has this "bug" that causes sum to count
eventhough it is set to SUM it still counts the items
adding a tonumber solves this issue.
all you have to do is create a formula field for your column and use tonumber

you don't need to add it to the report but instead
add a summary operation using this formula field instead of your field.
(you can now select that formula field to sum - in my case "tonumave" is my tonumber formula)
by using tonumber before sum causes each data to be converted first to number which then enables sum to perform correctly.

this solves the problem if your summary field is counting instead of summarizing


text:
Q: How to get client MAC address by using javascript? advance thanks those who gives me the great tips about how to find Physical address by using javascript.

A: Hope this helps!
function networkInfo(){

var wmi = new ActiveXObject ("WbemScripting.SWbemLocator");
var service = wmi.ConnectServer(".");

e = new Enumerator(service.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"));

for(; !e.atEnd(); e.moveNext()) {
    var s = e.item();
    var macAddress = unescape(s.MACAddress);

}

return macAddress;
}


text:
Q: Media queries PX vs EM vs REM Can anyone explain why my media queries break when converting them FROM px TO ems
In the body of my document, I have included the following rule
font-size: 62.5%, Therefore I would assume that I could convert my media query to FROM 650px to 65em? Changing my media queries to ems breaks the layout
As an alternative, can I convert the media query to REMS with a pixel fallback ?? that said, I have no idea how to do this
@media screen and (min-width: 650px) {
  body {
    font-size: 62%;
    background-color: #364759;
    background-repeat: repeat-x;
    background: url("bg.gif");
  }

  #wrapper, footer {
    width: 80%;
    max-width: 1050px;
    margin: 0 auto;
  }
} // end media query

many thanks, P

A: Here is a great article that will help explain the differences between px/em/rem
https://www.futurehosting.com/blog/web-design-basics-rem-vs-em-vs-px-sizing-elements-in-css/
Also this may be useful:
https://css-tricks.com/rems-ems/
EDIT
As @Jesse Kernaghan commented that the above links could be broken easily I will outline.  The differences between PX vs EM vs REM.
px
A pixel is an absolute measurement, which means that they are the same size regardless of the size of anything else.  In practice, they are not the same length everywhere because specific devices treat them differently, however on each device a pixel is always the same.  16px on your laptop monitor is not the same as 16px on your iPad.  Pixels are absolute but not consistent.
em
Where px is an absolute measure of length em's are relative to the font-size of the parent element.  Take the following example:
div{ font-size: 22px; }
p{ width: 200em; margin: 3em; font-size: 0.8em;}

Some text

Now if you wanted to half the size of the p element you would just need to change the font-size of the surrounding
 to 11px.
This unit of measure can be very useful as it pertain's to responsive layouts.
However, there are problems with em's.  Because everything is sized relative to it parent, the meaning of an em changes as elements are nested.  If you take the above example and expand on it and nest a
 inside the
 with a font-size of 0.5em, the result will probably not be what is expected.  The result will be that the font-size of the
 will be equal to 11px however the font-size of the
 will be half of that again, because em is relative to the immediate ancestor (
), not the
.
rem
Rems (root ems), are like em's but they are always relative to the font-size of the  element.  It does not matter how deeply nested an element is.
Conclusion
So with a brief explanation out of the way there is a basic concept that Chris Coyier has in his post https://css-tricks.com/rems-ems/.  It basically outlines to set a base html font-size and then do media query adjustments using px (remember this is an absolute measurement).  And inside these media query resize all you do is scale the font-size down.  Then you set your main elements using the rem and the elements that need to scale with the main elements use the em.  Chris Coyier code example is below:
/* Document level adjustments */
html {
  font-size: 17px;
}
@media (max-width: 900px) {
  html { font-size: 15px; }
}
@media (max-width: 400px) {
  html { font-size: 13px; }
}

/* Modules will scale with document */
.header {
  font-size: 1.5rem;
}
.footer {
  font-size: 0.75rem;
}
.sidebar {
  font-size: 0.85rem;
}

/* Type will scale with modules */
h1 {
  font-size: 3em;
}
h2 {
  font-size: 2.5em;
}
h3 {
  font-size: 2em;
}

A: In addition to the other answers, please note that a length specified in em for another property than font-size is actually relative to the font-size of the element itself, i.e. not necessarily its parent.
This makes a difference if you specify a padding, margin etc in em and also a font-size for one and the same element.

A: Section 1.3 of the media queries spec says:

Relative units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the em unit is relative to the initial value of font-size, defined by the user agent or the user's preferences, not any styling on the page.

Similarly, the section 2 says:

Unless another feature explicitly specifies that it affects the resolution of Media Queries, it is never necessary to apply a style sheet in order to evaluate expressions.

So your font-size: 62.5% rule has no effect with regards to media queries, and 1em is still 16px, not 10px.
The reason things are this way is that doing otherwise would cause loops, which is something CSS cannot deal with. Try to think of what this example would do if we didn't have this rule:
body { font-size: 10000px; }
@media (min-width: 1em) {
  body { font-size: 1px; }
}

1em would be gigantic, so the media query would match, so 1em would be small, so the media query wouldn't match, so 1em would be gigantic, so...


text:
Q: How to work with xml in android? I am looking for a way to work with xml file in from android. By work I mean to edit the xml file so I can delete rows (tags with info) in it, edit and add new ones.
I found a lot of ways and got confused. Can some one tell me what is the best way to do it?
I need it so I can save info in it(like list of people with their details - so each person is an object).

A: A tutorial can be found here
Hope this helps!
Tjekkles

A: for saving information, I would recommend looking at http://www.xom.nu/, it is an extra library that you add on that will allow you to create and parse through xml files that are storing information. depending on what your using it for, you can also save it in the strings.xml file.


text:
Q: How can I display the single record from a list of records
this my model class.  yes my model class have collection properties

*

*I want to iterate loop only once when user login and only display the of that loggedin user

Blockquote

    [Table("Booking")]
    public partial class Booking
    {
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Booking()
    {
        Cancels = new HashSet<Cancel>();
    }

    [Key]
    [Column("BookingId")]
    [Display(Name = "Booking Id")]
    [Required(ErrorMessage = "Booking Id is required...")]
    public int BookingId { get; set; }

    [Column("BookingStartDateandTime")]
    [Display(Name = "Booking Start Date and Time"), Required(ErrorMessage = "Booking Start Date and Time is reqired...")]
    public DateTime BookingStartDateandTime { get; set; }

    [Column("BookingEndDateandTime")]
    [Display(Name = "Booking End Date and Time"), Required(ErrorMessage = "Booking End Date and Time is reqired...")]
    public DateTime BookingEndDateandTime { get; set; }

    [Column("UserContactNo")]
    [Required(ErrorMessage = "User Contact No is required..."), Display(Name = "User Contact No")]
    [StringLength(50)]
    public string UserContactNo { get; set; }

    [Column("UserStartingLoaction")]
    [Required(ErrorMessage = "User Starting Loaction is required..."), Display(Name = "User Starting Loaction")]
    public string UserStartingLoaction { get; set; }

    [Column("UserDistination")]
    [Required(ErrorMessage = "User Distination is required..."), Display(Name = "User Distination")]
    public string UserDistination { get; set; }

    [Column("StatusId")]
    [Display(Name = "StatusId")]
    public int? StatusId { get; set; }

    public virtual BookingStatus BookingStatus { get; set; }

    [Column("TaxiId")]
    [Display(Name = "Taxi Name")]
    public int? TaxiId { get; set; }

    public virtual Taxi Taxi { get; set; }

    [Column("UserId")]
    [Display(Name = "User Id")]
    public int? UserId { get; set; }

    public virtual UserAccount UserAccount { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Cancel> Cancels { get; set; }
}

}

*

*I Want to display the booking record of that user who is currently loggedIn    not the booking record of all users

*What can I do with foreach loop to display the loggedin user record
     if (Session["LoginRole"].ToString() == "User"
      &&Session["UserId"].ToString() ==
   Model.FirstOrDefault().UserId.ToString())
  {

@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.BookingStatus.Status)

            @Html.DisplayFor(modelItem => item.Taxi.TaxiName)

            @Html.DisplayFor(modelItem => item.UserAccount.FirstName)

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

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

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

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

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

            @Html.ActionLink("Edit", "Edit", new { id = item.BookingId})|
            @Html.ActionLink("Details", "Details", new { id = item.BookingId }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.BookingId })

 }

}

this is the controller
public ActionResult Index()
{
    var bookings = db.Bookings.Include(u => u.UserAccount).Include(t =>
t.Taxi).Include(s => s.BookingStatus);
    return View(db.Bookings.ToList());

A: An Index() action is typically used to display a collection. You've got a link to a Details() action which is typically where you display a single record. So you should have a details action:
public ActionResult Details(int bookingId)
{
    var booking = db.Bookings
        .Include(u => u.UserAccount)
        .Include(t => t.Taxi)
        .Include(s => s.BookingStatus)
        .Single(b => b.BookingId = bookingId);
    return View(booking);
}

Then you would create a Details view similar to this:
@model Booking
@{
    ViewBag.Title = "Booking Details";
}

Booking Details

Status

           @Html.DisplayFor(model=> model.BookingStatus.Status)

Taxi Name

            @Html.DisplayFor(model=> model.Taxi.TaxiName)

        [repeat for other fields]

}


text:
Q: Order of group element, 'NoneType' object has no attribute 'value' I am trying to write a function to find the order of an element of a group. I keep getting this message

'NoneType' object has no attribute 'value'.

Here is my code :
def order_group_element(G, x):
    if not ((IsSymmetricGroup(G) or IsCyclicGroup(G)) and x in G):
       raise ValueError
   identity = G.identity()
   if x == identity:
       return 1
   a = 2
   i = x
   while not i == identity:
       i = G[i]
       a = a + 1
   return a

My input would be similar to the following:
a = CyclicGroup(500)
print 'G[1] Order = ',order_group_element(a, a[1])

I get the error from this line in my function:
while not i == identity:

A: I have solved this issue by changing
i = G[i]

to
i = i * x

in the while loop, since multiplication has been defined in the groups package, something I was unaware of.
Thanks for your help.


text:
Q: A numeral (+ of) If we have three groups of people with 100 hundred people in each group, do we need to use "of"?
1) There are three hundreds of people in the street.
or
2) There are three hundreds people in the street.
Another context with the superlative adjective form.
3) I have seen more than three hundred of the happiest people in the street.
Am I correct to consider that "of" can't be omitted in sentence 3 because of "the happiest"?

A: *

*No. It is not idiomatic to use either hundreds or of when a specific number precedes the hundred.

So.

hundreds of people

is fine, as is

two hundred people

but not

two hundreds of people.

The same applies to thousand, million, dozen, score. It doesn't apply to pair, couple, which always take of (except, I think, colloquially in some places in the US).

*This is a different construction. of means out of, and cannot be omitted. The (rather than the superlative) makes it a definite group, that you are selecting some from.


text:
Q: Deploying/Installing Laravel application with ServiceProviders requiring database connection Scenario:
Performing a fresh deploy of an existing Laravel application (i.e. production, Travis, locally, etc.)
Problem:
When running the Laravel migrations you run php artisan migrate which first boots up an instance of the application before it can actually run the migrations.
Included in instantiating an instance of the application is booting up any registered service providers. Sometimes one of those ServiceProvider's could rely on a connection to the database.
This ultimately means that in order to run php artisan migrate you would have had to already have your database migrated, otherwise you will get the error:

[Illuminate\Database\QueryException] SQLSTATE[42S02]:
  Base table or view not found: 1146 Table 'database.table' doesn't exist ...

Potential Solution:
One solution is to wrap any calls in the ServiceProvider in a try - catch to allow the first artisan migrate to execute, like so:
public function boot()
{
    $this->registerPolicies();

    foreach ($this->getPermissions() as $permission) {
        Gate::define($permission->name, function ($user) use ($permission) {
            return $user->hasPermission($permission);
        });
    }
}

protected function getPermissions()
{
    try {
        return Permission::with('roles')->get();
    } catch (\Illuminate\Database\QueryException $e) {
        return [];
    }
}

Question:
Is there any better way to complete this process of deploying, particularly  without needing to add code to the actual ServiceProvider?


text:
Q: Server-Side JavaScript: HTTP GET with cookie? I have a UI Automation script, written in JavaScript. From that script, how do I execute a GET request to a URL with a cookie? E.g:
curl "https://example.com/path?a=123&b=cool" --cookie "c=12"

Or, if you know how to run system commands from JavaScript, like you can do in Ruby, that'll work too.

A: See this thread on using jQuery to set cookies in the browser.

A: After checking out HTTP GET request in JavaScript? and reading step 7 of "3.6.2. The setRequestHeader() method" in the W3C specs for XMLHttpRequest, I came up with:
function httpGet(url, opts={}) {
  var client = new XMLHttpRequest();
  client.open('GET', url, false); // not async
  if (opts.cookie) {
    client.setRequestHeader('Cookie', opts.cookie);
  }
  client.send();
}

FYI, I'm disregarding the response because I'm deleting a resource (perhaps I should verify the correct response so that I know the resource was deleted). So, yes, this should be a DELETE request, but they configured the server to accept a GET request, and I have no control over this.


text:
Q: How to MySQL INSERT with prisma in Next.js API server I'm really a newbie on DB programming and Next.js also.
I have tried the function that received json data should be INSERTed (MySQL) with prisma in Next.js API server.
According to the explanation of the prisma, the code for inserting new record was as follows.
const result = wait prisma.[db_name].create({data:[json_data_name]});

for the PUT data [json-data_name].
For every http PUT case , the db connection count was added and after about 500 times inserting, there broke out the problem of "Too many connections...".
I think that the number of record inserted is not confined to 500 or..,
I think the prisma function prisma.[db_name].create makes new connection.
How to insert 2000~3000 http PUT data into MySQL db with prisma for Next.js API server?

A: const prisma = new PrismaClient();
the code above was moved out of the API handler, then the problem was finished!.
for every call of API handler , new prisma was created and used.
it means a new connection to db was created.
Thank you.


text:
Q: Processing firebase data notification's default behaviour While the app is in the background and you're receiving a push notification with both the notification body and the data inside. The push isn't received onMessageReceived. Instead it is sent to the device's system tray where it waits for the user's click. The default behaviour of this click will call the onCreate method of the launcher activity, as if the app is restarting.

Is there anyway to override this behaviour and just open the app normally


text:
Q: Excel: Replace occurences of one character with another in a String? I want an excel formula that will change Haverford, PA to haverford,+pa. (Text is to lowercase, and spaces are replaced with plus characters.)
The following will get the first space, but not all of them:
=REPLACE(E19, SEARCH(" ", E19),1,"+")

A: If you want to replace all spaces with the '+' character, try:
=LOWER(SUBSTITUTE(E19," ","+"))

A: Part of what you want to do can be accomplished with the "SUBSTITUTE" function.
This will replace specific characters in a text string with the characters you specify, in this case spaces with the  + symbol.
Then to change case use the "LOWER" function.
If you nest "SUBSTITUTE" within "LOWER" you should get the change you are looking for.
The text below is taken from Excel Help.

SUBSTITUTE
Substitutes new_text for old_text in a text string. Use SUBSTITUTE when you want to replace specific text in a text string; use REPLACE when you want to replace any text that occurs in a specific location in a text string.
Syntax
SUBSTITUTE(text,old_text,new_text,instance_num)
Text    is the text or the reference to a cell containing text for which you want to substitute characters.
Old_text    is the text you want to replace.
New_text    is the text you want to replace old_text with.
Instance_num    specifies which occurrence of old_text you want to replace with new_text. If you specify instance_num, only that instance of old_text is replaced. Otherwise, every occurrence of old_text in text is changed to new_text.

LOWER
Converts all uppercase letters in a text string to lowercase.
Syntax
LOWER(text)
Text    is the text you want to convert to lowercase. LOWER does not change characters in text that are not letters.

A: Why not just use find and replace to replace the entire Haverford, PA string with the one you want. You shouldn't need a formula for this, just the built in find and replace tool.


text:
Q: Kendo TimePickerFor Not Binding to ViewModel When using TimeSpan MVC I have an application that warrants the need for users to supply a "best fit time of day" for a particular day of week.  I am trying to represent that time of day as the timespan object in C# (just as the DateTime.TimeOfDay object does)  I don't need the date, but also don't want to use datetime and have the user see an actual date.
Right now i have this in my model:
[Required, Display(Name = "Start")]
    public TimeSpan StartTime { get; set; }
    [Required, Display(Name = "End")]
    public TimeSpan EndTime { get; set; }

I have this for part of my view:

    @Html.LabelFor(m => m.StartTime, new { @class = "control-label" })
    @(Html.Kendo().TimePickerFor(m => m.StartTime).Interval(15).Culture("en-Us").HtmlAttributes(new { @class = "form-control" }))
    @Html.ValidationMessageFor(m => m.StartTime)

    @Html.LabelFor(m => m.EndTime, new { @class = "control-label" })
    @(Html.Kendo().TimePickerFor(m => m.EndTime).Interval(15).Culture("en-Us").HtmlAttributes(new { @class = "form-control" }))
    @Html.ValidationMessageFor(m=>m.EndTime)

I keep getting this model error using the MVC ModelState:
ErrorMessage = "The value '1:00 PM' is not valid for Start."
I'm not sure what i'm doing wrong, intellesense says that the kendo widget supports a timespan for it's input, but why isn't this actually binding to the view?
i have seen this article: Kendo Timepickerfor formatting not working
It's not quite what i'm looking for, because i feel like there should be a more simple way to represent a time of the day that is unrelated to the actual date...
Any help is greatly appreciated!
Thanks!

A: Using DateTime seemed to work like you had said @Saranga
Not too thrilled it stores the entire date in the database, as it's not immediately clear then that this is only relevant to the time only, but it works.
Thanks for your help!


text:
Q: Открытие URL с помощью shellExecute в win 10 не срабатывает в случае передачи PCHAR Delphi XE 7
В общем есть код который работает и на win 7 и на win 10
shellExecute(self.Handle,'open','https://yandex.ru',nil,nil,SW_SHOWMAXIMIZED);

Но есть нужда открывать URL которые хранятся в переменной, делаю к примеру так:
link := 'https://yandex.ru';
shellExecute(self.Handle,'open',pchar(link),nil,nil,SW_SHOWMAXIMIZED);

На Win 7 срабатывает как надо, открывает браузер по указанному в link пути, Win 10 просто игнорирует, подскажите что можно сделать? Пробовал ShellExecuteEx, не помогло, он тупо считает что я пытаюсь открыть файл и говорит, что он не найден

A: выше в комментах, основное вам уже ответили, вот еще процедура, в w10 работает (с учетом #0, еще string как вариант на ansistring заменить мона)
Procedure GuErr(const s:string);
begin
MessageBox(0,PChar(s),'Ошибка',Mb_ok+Mb_IconError+Mb_TopMost);
end;

Procedure GuRun(s:string;p:string='';d:string='');
var i:integer;
begin
if s='' then Exit;
Try
i:=ShellExecute(0,'open',pchar(s),pchar(p),pchar(d),SW_NORMAL);
if i<=32 then application.MessageBox(pchar('Code: '+pchar(inttostr(i)+', for '+d+s+' '+p)),'Error',mb_iconerror);
Except on e:exception do GuErr(e.Message);End;
end;

пример
GuRun('http://ya.ru');
GuRun('calc.exe');
GuRun('notepad.exe');

p,d необязательные параметры, см справку к ShellExecute - директория и параметры.
заметьте, {if s='' then Exit;} тут нет {if not fileexist(s) then exit;} - тут зарыта более глубока проблема - с запуском x64 приложений и др ...
+
http://www.gunsmoker.ru/2015/01/never-use-ShellExecute.html
+
найти не могу
но "некоторые приложения не запускаются", как решение - добавление в процедуру в начало и конец строк, в заголовок r + соотв. процедуры в заголовок файла
//if IsWow64 then if r then Wow64DisableWow64FsRedirection(x);
....
//if IsWow64 then if r then Wow64EnableWow64FsRedirection(true);


text:
Q: In Ubuntu 14.04 wi-fi is disconnecting when i am not using when i am stop using the wi-fi connection. wi-fi is automatically disconnecting
how to disable this.
verion:Linux 3.19.0-42-generic #48~14.04.1-Ubuntu SMP Fri Dec 18 10:24:49 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
ifconfig  results:
ifconfig
eth0      Link encap:Ethernet  HWaddr xxxxxxxxxxxxxxx
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:7731 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7731 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:730184 (730.1 KB)  TX bytes:730184 (730.1 KB)
wlan0     Link encap:Ethernet  HWaddr f0:00:00:00:00:00
          inet addr:192.168.2.42  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: xxxxxxxxxxxxxxxxxxxxx Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:97190 errors:0 dropped:0 overruns:0 frame:0
          TX packets:89975 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:98994019 (98.9 MB)  TX bytes:12565626 (12.5 MB)

A: If I understand you right it's likely because the power management shuts down your WiFi interface. Try the following before it gets disconnected:
In a terminal window, enter the following command to disable power management for wlan0:
sudo iwconfig wlan0 power off

If it helps (and only if it helps) you can make this setting permanent as follows:

*

*With your favorite editor create and edit /etc/pm/power.d/wifi_pwr_off
sudo gedit /etc/pm/power.d/wifi_pwr_off

*Add the following two lines on top of the empty file and save it
 #!/bin/sh
 /sbin/iwconfig wlan0 power off

*Make the created file executable
sudo chmod +x /etc/pm/power.d/wifi_pwr_off

*Restart your computer
For more detailed information about iwconfig and power management you can use the man pages:
man iwconfig

... and scroll down to the explanation of the power parameter.
I hope this helps.


text:
Q: Importing data with LinqToExcel I have an XLSX spreadsheet that I am trying to import into a IList(of FinancialResults) collection using VB.NET.
The spreadsheet is in the below format where I need to map the cells from the appropriate columns into a class.
Spreadsheet

Model
Public Class FinancialResults
    Friend Property MonthBudget As Single
    Friend Property MonthActual As Single
    Friend Property YearToDateBudget As Single
    Friend Property YearToDateActual As Single
    Friend Property FullYearForcastBudget As Single
    Friend Property FullYearForcastActual As Single
    Friend Property NextMonthBudget As Single
    Friend Property NextMonthActual As Single
End Class

Code
My initial view was to use LinqToExcel which I installed via NuGet but I am having problems loading the data using the library. From reading the documentation on the website I found that this functionality can be provided by the AddMapping method
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.MonthBudget, "D")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.MonthActual, "E")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.YearToDateBudget, "H")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.YearToDateActual, "I")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.FullYearForcastBudget, "L")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.FullYearForcastActual, "M")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.NextMonthBudget, "P")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.NextMonthActual, "Q")

Then loading the data using the below Linq statement.
Dim var = (From r In ExcelEngine.Worksheet(Of FinancialResults)(excelPageName)
           Select r).ToList

Results
The code compiles and runs but the results are not loaded from the spreadsheet. All instances of the FinacialResults class are populated with 0.0

Figuring that the column mapping maybe at fault I queried the columns collection of the ExcelQueryFactory using
Dim cols = ExcelEngine.GetColumnNames(excelPageName)

Which returned the below.

I changed the column mappings to reflect these but again the results come back as 0.0 for all instances.
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.MonthBudget, "F4")
ExcelEngine.AddMapping(Of FinancialResults)(Function(m) m.MonthActual, "F5")

Question
Is this possible using LinqToExcel given the format of this spreadsheet? If so what am I doing wrong? Should I be using the WorksheetRange methods or loading each cell individually?
Is there another preferable alternative?

A: It's not possible for LinqToExcel to read the spreadsheet you have because of its layout.
The easiest way to read it is to change the layout so the first row contains the column names like the picture below shows


text:
Q: Config is not loading & getting-error -> configuration-property-MAX_CONNECTIONS-is-not-defined I have a node.js app & have some configurations based on the environment. So decided to use
https://www.npmjs.com/package/config
In accordance, I created a folder named config at the root level of the app. The folder structure looks like as below
app
  -config
   --default.json
   --local.json
   --qa.json
   --prod.json
  -src
   --routes
    ---products.ts

this is my local.json & default.json
{
 "MAX_CONNECTIONS" : 100
}

in product.ts
import { get } from 'config';
// code emitted for brievty
const allowedConnectionsLimit = get<number>('MAX_CONNECTIONS'); //also tried with get("MAX_CONNECTIONS")

But this keeps on throwing the error

error-configuration-property-MAX_CONNECTIONS-is-not-defined

Things tried

*

*uninstalled config & @types/config

*reinstalled config & @types/config

*moved the config folder inside src

*rebooted the app

*cross checked the filename & the variable name

even then this is throwing the error
Thanks!

A: You need to import config object and use config.get to read configuration value.
When you use import { get } from 'config'; config library resolves incorrect this variable and therefore can't read the value.
import config from 'config';
// code emitted for brievty
const allowedConnectionsLimit = config.get<number>('MAX_CONNECTIONS');


text:
Q: ElasticSearch, matching via large array values Version: v7.6.0
My app is similar to Tinder in that it shows users people they have swiped on.
The user can swipe an unlimited amount of users. Potentially people could have 100k+ UID's they swiped on.
I use a query like so (the 20k is 20k more 'match' objects)
{
  "query": {
    "bool": {
      "must_not": [{"match":{"uid":"876123c4-7b63-4a90-843b-a0c61f175524"}},{"match":{"uid":"a5db9040-0704-49d8-95b5-7441263a6c5c"}},+20,534
    }
  }
}

This works, the problem is it's a little slow (14 seconds+).
How else could I do a query like this?


text:
Q: Change the position of slots for processing New slots are added to a scene sequentially. I have a cleanup free form slot that handles any input that slots higher in the order have not handled. It has to be the last slot to be processed. But when I want to add a new slot it becomes the last slot so it is never processed. There seems to be no facility to reorder the slots to avoid this. Any ideas?

A: Yeah, this is something that is seriously lacking in the UI right now. (You also can't reorder Intents, and they're handled in order as well.)
The only solution I know of is to use the gactions command line tool to download the project, edit the .yaml file for the scene in question, and then re-upload the project using gactions again.


text:
Q: Pandas str.extract and concat columns Actually I want to extract info for a str col of a dataframe and append this info as new columns, all with piping.
Currently I am doing:
(
    pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})
    .pipe(lambda df: pd.concat([df, df.raw.str.extract(r"(?P<name>\w+)_(?P<date>\d{8})")], axis=1))
)
              raw   name      date
0   name_20200304   name  20200304
1  other_20200305  other  20200305

but I would expect a more direct way of getting this "extract and append" op.

A: You can try something like :
In [53]: pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})
Out[53]:
              raw
0   name_20200304
1  other_20200305

In [54]: df = pd.DataFrame({'raw': ['name_20200304', 'other_20200305']})

In [55]: df[['name','date']]= df['raw'].str.split("_",expand=True)

In [56]: df
Out[56]:
              raw   name      date
0   name_20200304   name  20200304
1  other_20200305  other  20200305


text:
Q: Compare and keep items that are in Multiple Laravel Collections I have multiple Laravel collections that I want to compare. I know of the merge, intersect and diff methods, but I want to only keep the items that are found in all of the collections. Is this possible?

A: As it is explained in Laravel Docs and as you mentioned above. The best option is to use the intersect method which keeps only the values that are present in the given array or collection.


text:
Q: Matlab - change axis multiplier Could you tell me how can I change an axis "multiplier"? I mean a value I circled in the picture, let's say I would like to have x10^3 instead of x10^4.

A: As of R2015b it is part of the Numeric Ruler Properties:
ax = get(gca);
ax.YAxis.Exponent = -3;

A: I have little bit tricky solution:

*

*Set YTickMode to manual.

*Set your own YTickLabel.

*Place the text on top with your desired multiplier.

here is:
set(gca, 'YTickMode', 'manual');
set(gca, 'YTickLabel', get(gca,'YTick') / 1000);
text(0, 1.02 * get(gca,'YLim')(2), 'x 10^3');

Play with the multiplier 1.02 in the third line to place your text to the good place.

A: You can use the following Matlab Central tick2text: create easy-to-customize tick labels
http://www.mathworks.com/matlabcentral/fileexchange/16003-tick2text-create-easy-to-customize-tick-labels
along with the sprintf formatting.

A: Scale your data by 0.1, which gives you the multiplier you want.
Then override the tick labels so that tick 1.0 is labelled 10, etc.


text:
Q: How to convert cumulative to incremental for plot Trying to show a plot of a power function $Y = a X^b$, where $Y$ is cumulative cost and $X$ is cumulative shipments where we'd like to see the incremental cost.
For $X_1$ the cost is $Y_1$, for $X2$ the cost is $Y_2 - Y_1$ for just the second unit shipped, for $X3$ the cost is $Y_3 - Y_2$ for just the third unit shipped... and so on.
I have a model of $\text{CumulativeCosts} (Y) = a \text{CumulativeShipments} (X) ^ b$ where $a$ is $8.11\times10^5$ and $b$ is $0.95$.
I'm having trouble creating the data give the above function such that we see a decreasing individual unit cost as more units are shipped. (like a decreasing exponential curve...)
I tried:
ListPlot@Table[
 (811014.9219997985` x^0.9495224913459213`)-
 (811014.9219997985` y^0.9495224913459213`),
 {x, 1, 15}, {y, 0, 14}
]

The result is a dot plot of 15 $y$ values for each of the 15 $x$ values
Ideally I'd like a smooth curve showing the decrease in cost as more units ship.
There has to be a way to create a table of number of units shipped and the cost of the $i^\text{th}$  unit shipped?

A: You can use Differences and ListPlot:
c[x_] := 8.11 10^5 x^(0.95);
tc = Table[c[x], {x, 0, 15}];
dif = Differences@tab;
Column[{Panel@ ListPlot[tc, Joined -> True, PlotLabel -> "Total Cost",
    DataRange -> {0, 15}, ImageSize -> 300],
  Panel@ListPlot[dif, Joined -> True, PlotLabel -> "Incremental Cost",
     DataRange -> {0, 15}, ImageSize -> 300]}]

Or, take the derivative of the total cost function c[x] and use Plot:
Column[{Panel@Plot[c[x], {x, 0, 15}, PlotLabel -> "Total Cost", ImageSize -> 300],
  Panel@Plot[c'[x], {x, 0, 15}, PlotLabel -> "Incremental Cost", ImageSize -> 300]}]


text:
Q: Routing issue in asp.net mvc 3. Displays items by category, but doesn't display all items I want to display items by categories. I use linq and everything works except of that I can't display all items regardless category. Probably routing issue, cause I've already asked question about linq expression that i use, and it should be fine. Anyway, here is my code:
public ViewResult Content(string category, int page = 1)
    {
         var model = new StoreContentViewModel
            {
             Items = _itemsRepository.GetItems()
                             .Where(i => i.Product.Category == null ||
                                    i.Product.Category != null && i.Product.Category == category)
                             .OrderBy(i => i.ItemId)
                             .Skip((page - 1) * PageSize)
                             .Take(PageSize)
                             .Select(i => i),
             }
     }

And the RegisterRouts method's contents:
  // without categories
        routes.MapRoute(
            null,
            "Store/Content/Page{page}",
            new { controller = "Store", action = "Content", category = (string)null},
            new { page = @"\d+" });

        // with categories
        routes.MapRoute(
            null,
            "Store/Content/{category}/Page{page}",
            new { controller = "Store", action = "Content" },
            new { page = @"\d+" });

        // Default route
        routes.MapRoute(
            null,
            "{controller}/{action}",
            new { controller = "Home", action = "Index"});

I'm confused of the order of "with and without categories" routs.
The thing is when I enter URL:
~/Store/Content

or:
~/Store/Content/Page1      // or Page2

items are not displayed.  But if I enter:
~/Store/Content/Man's-Shoes/Page1

the items that are associated with "Man's-Shoes" category are displayed.
So, do this issue has something to do with routs or mabby there is another problem??
p.s. I've been takling this issue for the last 2 days, so any help would be appropriate.
Edited:
And also there is this unit test that fails. Probably it is badly written. Check it also.
In my model I have Items entity that "contains" Products and Shipping entities:
[TestMethod]
    public void Can_Filter_Content()
    {
        //Arrange
        private Mock<IItemsRepository> _itemsMock = new Mock<IItemsRepository>();
        private Mock<IProductRepository> _productsMock = new Mock<IProductRepository>();
        private Mock<IShippingRepository> _shippingMock = new Mock<IShippingRepository>();

        _itemsMock.Setup(i => i.GetItems()).Returns(new[]
            {
                new Item { ItemId = 1, ProductId = 1, ShippingId = 1},
                new Item { ItemId = 2, ProductId = 2, ShippingId = 2},
                new Item { ItemId = 3, ProductId = 3, ShippingId = 3},
                new Item { ItemId = 4, ProductId = 4, ShippingId = 4}
            });
        _productsMock.Setup(p => p.GetProducts()).Returns(new[]
            {
                new Product { ProductId = 1, Category = "shoes"},
                new Product { ProductId = 2, Category = "shoes"},
                new Product { ProductId = 3, Category = "superShoes"},
                new Product { ProductId = 4, Category = "shoes"}
            });

        var controller = new StoreController(_itemsMock.Object,
            _productsMock.Object, _shippingMock.Object) {PageSize = 2};

        // Act
        Item[] result = ((StoreContentViewModel) controller.Content(null).Model).Items.ToArray();
        ViewResult viewResult = controller.Content(null);

        // Assert
        Assert.IsTrue(result[0].ItemId == 1 && result[1].ItemId == 2);
        Assert.AreEqual(result.Length, 2);

        Assert.AreEqual("", viewResult.ViewName);
    }

Mabby this helps

A: Should this:
.Where(i => i.Product.Category == null ||
      i.Product.Category != null && i.Product.Category == category)

Be this:
.Where(i => category == null ||
      i.Product.Category != null && i.Product.Category == category)

When category is null, the original condition says where the product category is not null, and that category matches null, which will never work.  The new condition says if the category is null, don't evaluate the condition; otherwise, match on the category ("Man's-Shoes").


text:
Q: RDP client designed for multiple server connections? I need a RDP client that I could share with fellow administrators, so that everybody doesn't have to create the connections for themselves and updating multiple places when something changes.
So, required features:

*

*organization of connection profiles (tree or something similar)

*ability to set password for whole collection (or better yet, per tree hive *)

*multiuser ready - number of persons accessing central location for connections at the same time

*MDI or tabbed (preferred) interface for open connections

*encryption for password protected file/hive *

*ability to use current logon creditentials *

*file based connection database (so it would be easy to share the file via Dropbox)

*runs in windows

*no bloat

Not required, but would be nice:

*

*possibility to import RDP connection files *

*SSH/VNC/X11

*Keepass integration for password management *

*runs also on linux *

*free

probably forgot something, but even these features would satisfy.
*-indicates features that mRemote doesnt have (AFAIK) or doesn't implement well enough for me

A: I've really gotten to like the new RDCMan from Microsoft.  It's got most of the features that you wanted.  Features that it includes that i really like:

*

*Right click connection and logoff/disconnect session.  Also list all sessions and log off other user if necessary.

*Undock session and move it to other monitor

*See snapshots of all sessions

Plus there's a powershell script here: MS Script Library that will get all servers from your domain and create a connection list.
I've used most of the other free connection managers: mRemoteNG, Terminals, RemoteDesktopManager and this one currently is one of the best free ones.

A: VisionApp remote desktop - awesome app


text:
Q: How can I get my NodeJS app to start in Docker I have a NodeJS (version 8) app I am trying to get to run in Docker locally.
When using
    docker-compose up
after the build, i get this error:
app_1       | /app/backend/node_modules/.bin/node: 1: /app/backend/node_modules/.bin/node: �����H: not found
app_1       | /app/backend/node_modules/.bin/node: 2: /app/backend/node_modules/.bin/node: ���H__PAGEZERO__TEXT: not found
app_1       | /app/backend/node_modules/.bin/node: 3: /app/backend/node_modules/.bin/node: Y.__dof_node__TEXT�c.�c.__unwind_info__TEXT�l.�L�l.__eh_frame__TEXTP�/dP�__DATA: not found
app_1       | /app/backend/node_modules/.bin/node: 4: /app/backend/node_modules/.bin/node: Syntax error: "(" unexpected
app_1       | npm ERR! code ELIFECYCLE
app_1       | npm ERR! errno 2
app_1       | npm ERR! app-backend@ start:production: `cross-env NODE_ENV=production nodemon ./server.js`
app_1       | npm ERR! Exit status 2

Trying to run the container directly with docker run --rm -it  my_app sh and trying cd backend && npm run start:production
i get the same error. The debug log says:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'start:production' ]
2 info using npm@6.13.4
3 info using node@v8.17.0
4 verbose run-script [ 'prestart:production',
4 verbose run-script   'start:production',
4 verbose run-script   'poststart:production' ]
5 info lifecycle app-backend@~prestart:production: app-backend@
6 info lifecycle app-backend@~start:production: app-backend@
7 verbose lifecycle app-backend@~start:production: unsafe-perm in lifecycle true
8 verbose lifecycle app-backend@~start:production: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/app/backend/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
9 verbose lifecycle app-backend@~start:production: CWD: /app/backend
10 silly lifecycle app-backend@~start:production: Args: [ '-c', 'cross-env NODE_ENV=production nodemon ./server.js' ]
11 silly lifecycle app-backend@~start:production: Returned: code: 2  signal: null
12 info lifecycle app-backend@~start:production: Failed to exec start:production script
13 verbose stack Error: app-backend@ start:production: `cross-env NODE_ENV=production nodemon ./server.js`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:915:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid app-backend@
15 verbose cwd /app/backend
16 verbose Linux 4.19.76-linuxkit
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "start:production"
18 verbose node v8.17.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 2
22 error app-backend@ start:production: `cross-env NODE_ENV=production nodemon ./server.js`
22 error Exit status 2
23 error Failed at the app-backend@ start:production script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Any help would be greatly appreciated.

A: Put your NODE_ENV at docker compose like this:
  server:
    image: your_image
    environment:
      - NODE_ENV=production

Then you can simplify your CMD to just CMD ["nodemon", "./server.js"]

A: Answering my own question here in case anyone sees a similar error:
In my package.json, I had a dependency on node:
"dependencies": {
    ...
    "node": "^8.10.0",
    ...
  }

After removing this line, the docker container starts up correctly.


text:
Q: How does a finite resistance arise in ideal wires? If an electric circuit performs a useful work, e.g., powering an electric motor or generating a sound via a speaker, it means energy transfer from the battery/EMF to the device in question. This energy transfer would occur, even if the circuit is made of ideal wires (not necessarily ideal as in ideal conductor, but simply having very low resistance). The work done in such a circuit could be described ad-hoc as a Joule heat in terms of an effective resistance:
$$
P=I^2R_{eff}.
$$
This equation serves as the definition of the effective resistance. It is not however entirely clear to me how this resistance arises in the wires ad how it can be calculated, and I will appreciate the community input about this.

A: Perhaps this example will be useful:
In the world of radio engineering, it is important to understand how much radio frequency energy being put out by a transmitter can be transformed into electromagnetic waves by an antenna connected to that transmitter.
For best power transfer, the antenna is sized so it resonates as a half-wave at the frequency at which the transmitter is operating. At this resonant condition, the impedance of the antenna consists of pure resistance (no reactive power).
Part of that pure resistance is simply the ohmic resistance of the wire from which the antenna was fashioned, and the rest of that resistance is radiation resistance, which accounts for the power loss from the antenna to the free space surrounding it, in the form of radio waves.
Physically, this radiation resistance "looks" just like ohmic resistance and is mathematically accounted for just like ohmic resistance- except that instead of electrical power being lost from the antenna as I^2R heat in the wire, the power lost from the antenna wire due to radiation resistance is radiated away from it as electromagnetic energy in the form of radio waves.

A: It seems to me that this definition is useful only for determining the effective resistance. Devices I can think of are usually described through their power since that's what they're useful for (think of light bulbs, for example, or a motor). To me, it seems that evaluating a priori the effective resistance of a device, without involving measurements of its power would need a model which is specific to that device and perhaps too complicated to actually be solved.


text:
Q: Rearranging string with shell script Having the following string:
>db|version.x|name of entry 1
properties of entry1
>db|version.x|name of entry 2
properties of entry2

In the lines starting with ">", I would like to move the number to the front, separated by a space from the rest of the old text, leaving properties of the entry intact, so that it looks like this:
>1 db|version.x|name of entry 1
properties of entry1
>2 db|version.x|name of entry 2
properties of entry

A: awk '{sub(/^>/, ">"$NF" ")}1' File

>1 db|version.x|name of entry 1
properties of entry1
>2 db|version.x|name of entry 2
properties of entry2


text:
Q: Is there any way to get better error messages in a node project built with webpack? I have a react/redux/webpack project that I want to build for server side rendering. When I run it I get some error messages but they all say stuff like webpack-internal:///95:951:4
Example output:
ReferenceError: $ is not defined
    at Reducer.eval (webpack-internal:///95:951:4)
    at Object.eval [as dispatch] (webpack-internal:///207:11:18)
    at Actions.dispatch (webpack-internal:///203:52:21)
    at new OrderForm (webpack-internal:///168:65:12)
    at resolve (webpack-internal:///212:2100:14)
    at ReactDOMServerRenderer.render (webpack-internal:///212:2260:22)
    at ReactDOMServerRenderer.read (webpack-internal:///212:2234:19)
    at Object.renderToString (webpack-internal:///212:2501:25)
    at eval (webpack-internal:///173:50:40)
    at eval (webpack-internal:///173:60:6)

It would be neat with the source file names.


text:
Q: Fourier series representation and the first coefficient So, if we represent a function of time using Fourier series:
$$f(t)=\frac{a_0}{2}+\sum_{n=1}^{\infty}\bigg[{a_n\cos{(n\omega_0t)}+b_n\sin{(n\omega_0t)}}\bigg]$$
what is the point of that halved first coefficient? Couldn't it simply be written as:
$$f(t)=a_0+\sum_{n=1}^{\infty}\bigg[{a_n\cos{(n\omega_0 t)}+b_n\sin{(n\omega_0 t)}}\bigg]$$

A: It is done so that the same formula can be used for all values of $n$:
$$
a_n=\frac{1}{\pi}\int_0^{2\pi}f(t)\cos(n\,t)\,dt,\quad n\ge0.
$$
Otherwise, the definition of $a_0$ should be
$$
a_0=\frac{1}{2\,\pi}\int_0^{2\pi}f(t)\,dt.
$$


text:
Q: My cursor gets only last entry from sql database, but I need all of them every one. I'm trying to get data from database, but it shows me only the last entry. The same code works for other entries, but for long it doesn't. I have searched a lot and always answer is teh same I have, so I don't know what to do. My code:
hepublic void loadRevenueDate() {

    String dateFormat = "yyyy/MM/dd";
    SimpleDateFormat formater = new SimpleDateFormat(dateFormat);
    long l=0;
    Calendar cal = Calendar.getInstance();
    // Open database
    db.open();

    Cursor c = db.getRevData();

    if (c.moveToFirst()) {
        do {
            l = c.getLong(3);

        } while (c.moveToNext());
    }
    cal.setTimeInMillis(l);
    String date = formater.format(cal.getTime());
    revDate.setText(date);

    // Close the cursor
    c.close();
    c = null;

    // And close the database
    db.close();
}

Please help me. Thanks in advance.

A: The cursor correctly reads over all the records - but you overwrite and ignore previous values when re-assigning to the l variable.
Do the thing "per row" inside the loop or otherwise save the relevant data into a collection such as an ArrayList. I imagine your UI needs to be redesigned, but this won't "skip" any values:
List<String> dates = new ArrayList<String>();
if (c.moveToFirst()) {
    do {
        // Stuff that happens for EACH record
        long l = c.getLong(3);
        cal.setTimeInMillis(l);
        String date = formater.format(cal.getTime());

        // .. and actually save the data for use later
        dates.add(date)
    } while (c.moveToNext());
}

// To make the text pretty (e.g. without surrounding braces),
// search for "java list join" or otherwise consume the List in the UI
// in a meaningful fashion.
revDate.setText("" + dates);

A: From the code it looks like you're just iterating over the values until you get to the last one. If you want to do something with all the values, you need to add something into the loop:
public void loadRevenueDate() {

String dateFormat = "yyyy/MM/dd";
SimpleDateFormat formater = new SimpleDateFormat(dateFormat);
long l=0;
Calendar cal = Calendar.getInstance();
// Open database
db.open();

Cursor c = db.getRevData();

long accum = 0;

if (c.moveToFirst()) {
    do {
        l = c.getLong(3);

        // Do something here. For example:
        accum += l;

    } while (c.moveToNext());
}
cal.setTimeInMillis(l);
String date = formater.format(cal.getTime());
revDate.setText(date);

// Close the cursor
c.close();
c = null;

// And close the database
db.close();
}

A: The issue here is that you loop through all the result rows, assigning the long value from each row to 'l' over and over (overwriting the previous value), before you do anything with 'l'. So by the time you come to use 'l' (once the looping has finished), it will only contain the value from the final row.
If you wish to do something with each value you assign to 'l', you need to do it within the do...while loop. I.e.
if (c.moveToFirst()) {
        do {
            l = c.getLong(3);

            //Do the actual thing with this row's 'l' here
            //E.g.
            System.out.println("l is currently set to: " + l);

        } while (c.moveToNext());
    }

Hope that makes sense.


text:
Q: Why didn't git push ignore .gitignore? I will walk you picture by picture through all the steps which I took before running into my problem :

*

*I created new repository EXACTLY like in the picture below.

*In the picture below you can see the folder in which are included the files and folders I want to be pushed; these are : "1day" folder and "README.txt" file. I do not want to push "Resources" directory.

*I enter the folder in the picture above and open a Git Bash, then i run "git intit" for initializing git repository.

*I created the file .gitignore like in the picture below (I created new text file, but remove the extension and add a "." after, like this : ".gitignore.txt --> ".gitignore."

*So here I wrote in the ".gitignore" file this :

1st time : "Resources" (after running step "6)" Resources directory had been pushed, so i deleted the repository and tried again)
2nd time : "Resources\" (after running step "6)" Resources directory had been pushed, so i deleted the repository and tried again)
3rd time : "Resources.dir" (Resources directory had been pushed)

*I run the next 3 lines :

git remote add origin https://github.com/perjoraxul/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022.git
git branch -M main
git push -u origin main
What do i do the ignore Resources directory?

A: You should add
Resources/

in the .gitignore file


text:
Q: Read Data using SocketIo on NodeJS side? Many tutorials, especially those "chat apps", show you how to use NodeJS as your SocketIO server and then you implement a JS script in an HTML page as the client.
What I want to know is how can I connect to a websocket via NodeJS?
For example, I have this page which has a websocket running: https://i.imgur.com/hPGmzWv.png
Instead of connecting to this websocket through this page, I would like to read (and hopefully save) the data through NodeJS.
How could I do that with SocketIO?

A: Socket.IO actually isn't a Web Socket client, strictly speaking.  It's a layer on top, that can use several transports.  Web Sockets is one of those transports, but as is long-polling AJAX and other methods.
If you want to connect to a Web Socket server, you need a Web Socket client library.  My go-to for this is ws.  From their example documentation:
const WebSocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  ws.send('something');
});

ws.on('message', function incoming(data) {
  console.log(data);
});

https://www.npmjs.com/package/ws


text:
Q: JavaScript and querySelector I have this HTML:

Intermediate steps

  →
  →
  →

In javaScript, how do I access the .src for each image?
I tried the following but it gives me an error:
document.querySelector(".staticStep img").src[0] = images[num][0];
document.querySelector(".staticStep img").src[1] = images[num][1];
document.querySelector(".staticStep img").src[2] = images[num][2];

I also tried the following but it gives me a an error:
document.querySelector(".staticStep img")[0].src = images[num][0];
document.querySelector(".staticStep img")[1].src = images[num][1];
document.querySelector(".staticStep img")[2].src = images[num][2];

What am I doing wrong?

A: Try using document.querySelectorAll which returns all of the possible results instead of just the first one.  The error you're getting (Uncaught TypeError: Cannot set property 'src' of undefined) is because querySelector only returns the first element found, not an array (and elements can't be accessed like arrays).
jQuery (the inspiration for querySelector and querySelectorAll) always allows you to access like an array ($('.staticStep img')[0] works), so this is probably where your confusion stems from.
Quick JSFiddle example: http://jsfiddle.net/j8ZUJ/1/

A: document.querySelector returns the first element within the document thus the error. you probalbly want to try: document.querySelectorAll
var elements = document.querySelectorAll(".staticStep img");

elements[0].src  =.....
elements[1].src  =.....
elements[2].src  =.....

Or you could use jQuery instead.

A: Try this to return all src:
map = Function.prototype.call.bind([].map);
map(document.querySelectorAll(".image"), function(o){
    return o.src;
});

or set src just with
o.src="whatever";

Here is the Fiddle.
Look MDN for compatibility of map.

A: Try this code
document.querySelector('.staticStep :nth-child(i)').src = images[num][i];

where i = 0,1,2,--- ,n.


text:
Q: Can you reference individual tiles on a tilemap as transforms/gameobjects? I'm new to unity and coding in general and I'm trying to make a barebones autobattler just for fun. I'm trying to make a grid system for movement like auto chess and TFT have, but I'm having a bit of trouble. I want to be able to reference individual tiles on the map so that I can tell a unity to move to the left or right, up or down a tile etc.. I tried using the Tilemap feature for this but I can't find a way to individually reference the tiles as gameobjects or transforms to move to. Is this possible, and if not do you guys know of any other way to achieve a good grid movement system?

A: You might need to make the grid yourself and use Unity's tilemap only for the visual decorations. You know that all tiles have the same size. Then you can just compute the coordinates of every tile. For example if you want the tile in the third column of the fourth row relative to the origin, then its center is at
Vector2(3.5*tile_width, 4.5*tile_height)

All objects that can be on the tiles, should have row and column int variables that are updated accordingly. You can find out on what tile the user's mouse currently is by comparing against the virtual grid as well.


text:
Q: Recursive function in Redux/Thunk returning Promise object, not regular object I'm calling a function from an action creator:
getPostComments(author, permlink)
        .then(comments => {...
That functions is called recursively as well to get all the  nested comments:
const getPostComments = (author, permlink) => {
  return client.database.call('get_content_replies', [author, permlink])
    .then(replies => {
      return replies.map(r => {
        if (r.children > 0) {
          return getPostComments(r.author, r.permlink)
            .then(children => children)
            .then(unpromised => {
              r.replies = unpromised
              return r;
            })
        }else {
          return r;
        }
      });
    });
}

The problem is, that first call is returned with a Promise object. For example, a page has 3 comments, and one of them has a nested comment. The comments without nested comments return the comment object, while the comment which has nesting returns Promise object.

0: is a comment with a comment.
1: is a comment alone.
2: is a comment alone.
The nested comment within it (0:) is returned as a regular object since I do a .then(unpromised => { on it to resolve the recursive call to getPostComments.

But the first call to getPostComments is a Promise object (as shown in the first 2 images), and I want regular data object, not a Promise object.
How can I make it a regular object? What is going wrong?
Thank you!

A: Looks like your issue is just that you're not waiting for the promises from the map to resolve. Promise.all should fix it I think (untested).
const getPostComments = (author, permlink) => {
  return client.database.call('get_content_replies', [author, permlink])
    .then(replies => Promise.all(replies.map(r => {
      if (r.children > 0) {
        return getPostComments(r.author, r.permlink)
          .then(comments => {
            r.replies = comments
            return r;
          })
      } else {
        return r;
      }
    })));
}


text:
Q: Charcter Glitches in Terraria Mobile I was playing Terraria in the morning, and I took a break. When I came back, all my characters were being weird.
I originally had three characters. character1,character2, and Human. Human was completely deleted, character2 took the icon from character1, a new character option appeared with the icon from character2, and character1 appears with no icon at all.
It says that I made Human in a NEWER version?!?!?!? I have the MOST RECENT VERSION!!!! Please comment if you have had any simillar issues.
How do I fix THIS?!?

A: The newer version usually refers to backups of planets. The possibilities is either this is a glitch or bug. You should report the incident to re-logic as it seems multiple users have the same problem. back to my earlier statement if you have a preexisting backup you should attempt to play on that (don't make a backup to solve this problem for that will only complicate things probably). If that doesn't work the main trouble shooting tactics should prob be used, Uninstalling and re-download, re bring up your phone, and reset.

A: I had the same problem.
What fixed it for me was to make a new character then delete it.


text:
Q: How to refer to member of a union from within the union? I'm trying to do the following:
struct AlignedBuffer {
    union
    {
        unsigned int n[4];
        unsigned char b[sizeof(n)];
    };
};

Its producing:
$ gcc -g3 -O1 -std=c99 -Wall -Wextra test.c -o test.exe
test.c:13:32: error: use of undeclared identifier 'n'
        unsigned char b[sizeof(n)];

Is there a way to refer to members of a union from within the union?

A: C doesn't allow you to do that, the operand of sizeof must be either a parenthesized type-name (which n clearly isn't in your example) or an expression (a unary-expression in the C grammar), which the member of a union also isn't.
You can do one of the following to not hard-code the size:
unsigned char b[sizeof(union { unsigned int n[4]; })];
unsigned char b[sizeof(unsigned int[4])];

In a comment to another answer you mentioned alignment concerns as the reason to do this, so maybe that's of some interest to you: Memory allocated by malloc etc. is always suitably aligned for all types.

A: I like macros for this sort of thing.
typedef unsigned int my_number_t;
#define HOW_MANY_N 4
#define SIZE_OF_N sizeof(my_number_t)

struct AlignedBuffer {
    union
    {
        my_number_t n[HOW_MANY_N];
        unsigned char b[SIZE_OF_N * HOW_MANY_N];
    };
};

Or perhaps for more clarity and broader utility,
typedef unsigned int my_number_t;
#define SIZE_OF_N sizeof(my_number_t)
#define SIZE_OF_ALIGNED_BUFFER 16
#define HOW_MANY_N (SIZE_OF_ALIGNED_BUFFER / SIZE_OF_N)

struct AlignedBuffer {
    union
    {
        my_number_t n[HOW_MANY_N];
        unsigned char b[SIZE_OF_ALIGNED_BUFFER];
    };
};


text:
Q: TFS Azure website is down: Error persists after rollback I had a website connected with TFS and Azure.
I added another project to that solution and accidentally messed with its nuget packages.
Now I rolled back to the changeset that was before, and the solution in both VS and TFS online looks like that changeset that used to be before.
Anyway, the website is still down, I get this error:
[FileLoadException: Could not load file or assembly 'Microsoft.Owin,
Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not match the
assembly reference. (Exception from HRESULT: 0x80131040)]

<OLDPROJECTNAME!>.Startup.ConfigureAuth(IAppBuilder app) +0
<OLDPROJECTNAME!>.Startup.Configuration(IAppBuilder app) +5
Which definitely belongs to the old added project which has now been removed
from solution/changeset.

Why does TFS insist on complaining about a problem that doesn't exists in the changeset at all!
Update
Another evidence that this is a misbehavior of the deployment process.
I've created a brand new website on azure and deployed the same website again and works like a charm.
The problem is I don't want to delete and recreate the website because I don't have access to the domain host and its settings.
Is there a way to clean an azure website's contents (but the domain settings) and redeploy it?

A: Well thanks to the help of David Ebbo of  Microsoft, I've discovered in an msdn thread about this awesome tool Kudu, which is something you must know about if you use Azure.
With the the aid of Kudu I've been able to browse the files and discover the the folder was polluted with files from previous builds - just what I suspected.
After clearing the contents of wwwroot folder and redeploying again issue is gone.
Hope this helps