text:
Q: Observe livedata inside a for loop I want to update a list in my activity that depends on the data of another list. Both the data list are being observed from the activity from the my viewmodel. After I get the data from my firstlist I need to run a for loop on this list to get the required ids and get the data for the second list.
But keeping the livedata observer in the for loop is causing a lot of problems. The for loop runs as expected but the livedata observer is getting called almost double the amount of the for loop. This happens only the first time when the list in being brought from the api. When I do the same operation a second time where the list is cached and is being brought from the database, the problem does not occur. Below is the source code for the problem,
for (int i = 0; i < firstList.size(); i++) {

    final String uId = firstList.get(i).item.uid;
    final long id = firstList.get(i).item.id;
    viewModel.initAnotherItemRepository(uId, id);
    viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
        @Override
        public void onChanged(Resource<List<SecondItem>> listResource) {
            if (listResource.data != null) {
                secondItemList.addAll(listResource.data);
                if (count == firstList.size() - 1) {
                    //Do something

                }
                count = count + 1;
            }
            if (listResource.state == Resource.STATE_FAILURE) {
                showLoadingSpinner(false);
            }
        }
    }

    );
}

A: Try to observe SecondItem outside the for loop. It gets data whenever update
viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
    @Override
    public void onChanged(Resource<List<SecondItem>> listResource) {
        if (listResource.data != null) {
            secondItemList.addAll(listResource.data);
            if (count == firstList.size() - 1) {
                //Do something

            }
            count = count + 1;
        }
        if (listResource.state == Resource.STATE_FAILURE) {
            showLoadingSpinner(false);
        }
    }
}

);

for (int i = 0; i < firstList.size(); i++) {

    final String uId = firstList.get(i).item.uid;
    final long id = firstList.get(i).item.id;
    viewModel.initAnotherItemRepository(uId, id);
}


text:
Q: Google Colab. Show time until next reset does someone know if it is possible to show the time when the colab will reset the environment. I am currently using it for deep learning and I would like to know when the 12h of runtime is over without starting a timer myself.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: ListView add more items in Metro apps? I have a metro application in which I have a Listview and service data contains above 100 items. Initially when am loading listview in my page it has to display only 8 items plus 1 more-related item and later if i click on a more-item it needs add another 9 items to my page and totally it has to show 17 items in my page and need to display more item also like that flow continues.What should I get to get my scenario.Can anyone help me.Below I tried to give u my scenario.
Thank you.

A: Take a look to this article: http://www.silverlightplayground.org/post/2012/06/10/Metro-Incrementally-load-GridView-and-ListView-with-ISupportIncrementalLoading.aspx.

A: There are a couple of solutions -- all depending on the work that you want to undertake. Also, I would suggest that you don't have a "More" button if you can help it -- it's not the best user interaction. Option 2 is going to give you the best experience.
Option 1
Use WinJS.Binding.List as your data source -- using this you can manipulate it like a JavaScript Array (e.g. push, pop etc). As you add & remove items from the list, the list view will react to those changes.
Full details are here.
Option 2
Create a VirtualDataSource derivation that is intimately aware of the ways in which you can request your data, and can offer up a consistent interface to the ListView. This enables your UI to be completely flexible to it's layout, and request enough data to satisfy the available space, while virtualizing the UI elements (better memory/performance), and the data (ensuring only the data needed by the user is requested.
Full worked example here.


text:
Q: How to search for In-App transaction in Huawei AppGallery I have published my app in Huawei AppGallery.
Users make purchases (In-App), I can only see the number of purchases the next day.
But I can't verify the user's purchase in any way, but only believe them.
In Google Play, I can enter the email or GPA number of the purchase and check when it was made and if the transaction was successful.
In Huawei AppGallery, I did not find this anywhere. Can you please tell me where can I find this option?
After all, it is the most important option for developers, I do not believe that it does not exist. I also need to know about the purchase this day, not the next day.

A: In the developer console, you could download the report as shown below

To track real-time transaction results, you could add "viewing the purchase history" in your app. Once this history is successfully obtained, you could either pass it to your server or save it in the app.
Alternatively, you could confirm the purchase by verifying the purchase token (from InAppPurchaseData) to confirm the purchase as well.

A: According to your description, you can go to Developer Center > My Report > Payment Report.
You can search for all subscriptions under your app by keywords such as the app ID, time, and order status.
https://developer.huawei.com/consumer/en/console#/myReport/payment


text:
Q: Acrobat Combo Box return the Item Selected not the export Value Is there a better way to get the Select Text of a ComboBox  and not the export value?
Here's what i found so far.
//  combobox Return the export value
var expValue = this.getField("Dropdown1").value;

//  combobox return the Selection by Indice
var i = this.getField("ItemType1").currentValueIndices;
console.println(this.getField("ItemType1").getItemAt(i,false));

Just try to find a simpler way of doing this.
This is not event triggered code so 'change' property, and 'changeEX' property will not Work.

A: What you have is how it's done. You could create a document-level function to make it a bit easier.

A: Thank you for your reply
I would've created a Doc Level Function for this, if I had to return the selection more then once. So here's how I believe it would be done.
function ReturnSelection(fieldName){
    // Check that Field is ComboBox or List Box
    var fldField = this.getField(fieldName);

    if(fldField != null && (fldField.type === "combobox" || fldField.type === "listbox")){
        //  combobox return the Selection by Indice
        var i = fldField.currentValueIndices;
        return fldField.getItemAt(i,false);

    }else{
        return "";
    }
 }

not tested.
and to return multi Selections
function ReturnSelection(fieldName){
    // Check that Field is ComboBox or List Box
    var fldField = this.getField(fieldName);
    if(fldField != null && (fldField.type === "combobox" || fldField.type === "listbox")){
        //  combobox return the Selection by Indice
        var i = fldField.currentValueIndices;
        if(typeof i == "number"){
            return fldField.getItemAt(i,false);
        }else{ // Deal With Multi Selections
            var arr = [];
            for(var a = 0; a < i.lenght){
                arr.push(fldField.getItemAt(i[a],false));
            }
            return arr;
        }
    }else{ // Not a Combo or list box
        return "";
    }
 }

A: That looks good. I would suggest handling the case of the getField method returning null, which will happen if you specify a field that doesn't exist and in certain other circumstances.


text:
Q: JSON string deserialisation into C# object I have the following result from an API call - what would be the best C# object structure to be able to deserialise the JSON string into the C# object?
The issue I have is that the JSON object are actually the name of the brand rather than
 "data":{"brands":{"brand":{"name:"Amazon"...etc

the api is returning:
"data":{"brands":{"amazon":{"name:"Amazon",....

Which makes it difficult to create a brands--> brand hierarchy
See below for entire JSON string:
{
       "status":"success",
       "code":"1254",
       "message":"Hello",
       "data":{
          "brands":{
             "amazon":{
                "slug":"amazon",
                "name":"Amazon UK"
             },
             "boots":{
                "slug":"boots",
                "name":"boots UK"
             }
          }
       }
}

A: The following structure should be fine, I guess
public class RootObject
{
    public string status { get; set; }
    public string code { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}

public class Data
{
    public Dictionary<string, Brand> brands { get; set; }
}
public class Brand
{
    public string slug { get; set; }
    public string name { get; set; }
}

And use ii like
var result = JsonConvert.DeserializeObject<RootObject>(yourJsonString);


text:
Q: std::bad_function_call when calling std::swap in visual studio I am trying to port my code from linux to windows. However with Visual Studio my code crashes with the following error:

Microsoft C++ exception: std::bad_function_call at memory location

This is my code:
#include <functional>

class Foo {
public:
    Foo(int) : m_deleter{ []() {} } {}
    Foo(const Foo &) = delete;
    Foo(Foo &&) = default;
    Foo & operator=(const Foo &) = delete;
    Foo & operator=(Foo &&) = default;
    ~Foo()
    {
        m_deleter();
    }
private:
    std::function<void()> m_deleter;
};

int main() {
    Foo foo(1);
    Foo bar(2);
    std::swap(foo, bar);
}

It crashes when I use std::swap. In linux it worked flawlessly.
Weirdly enough, when I try to compile it online via GCC it doesn't work either. What am I doing wrong and why does at work at home with Clang (3.5).
EDIT: It turns out it crashes with Visual Studio 2015 and GCC 4.9.2, but not with Clang 3.5.

A: Introduction
The reason for the behavior is quite simple; m_deleter is unconditionally invoked in the destructor of Foo, even in circumstances when it isn't callable.
The straight forward implementation of std::swap creates a temporary to hold the intermediate result of one of the two operands, this temporary will not have a callable m_deleter.
What is std::bad_function_call?
std::bad_function_call will be thrown if you try to call a std::function which doesn't have a valid target to invoke.

Elaboration
We can reduce your testcase to the following, more explicit, snippet:
 1 #include <functional>
 2 #include <utility>

 3 struct A {
 4   A ()
 5     : _cb {[]{}}
 6   { }
 7
 8   A (A&& src)
 9     : _cb (std::move (src._cb))
10   { }
11
12   A& operator= (A&& src)
13   {
14     _cb = std::move (src._cb);
15     return *this;
16   }
17
18
19   ~A () {
20     _cb ();
21   }
22
23   std::function<void()> _cb;
24 };

25 void swap (A& lhs, A& rhs) {
26   A temporary = std::move (lhs);
27           lhs = std::move (rhs);
28           rhs = std::move (temporary);
29 }

30 int main() {
31   A x, y;
32   swap (x, y);
33 }

The Problem
When leaving swap temporary will be destroyed, which in turn will try to invoke _cb - the problem is that temporary._cb has been moved-from on line 14; it is no longer callable and an exception is thrown.
The Solution
~A::A () {
  if (_cb) // check if callable
    _cb ();
}

A: A temporary object is used in std::swap(). When swap() returns, the temporary object's m_deleter is empty. When the temporary destructs, the m_deleter(); throws std::bad_function_call as m_deleter has no target.
The std::swap on my machine (gcc4.9.1, ubuntu) is like the following:
template<typename _Tp>
  inline void
  swap(_Tp& __a, _Tp& __b)
  noexcept(__and_<is_nothrow_move_constructible<_Tp>,
           is_nothrow_move_assignable<_Tp>>::value)
  {
    _Tp __tmp = std::move(__a);
    __a = std::move(__b);
    __b = std::move(__tmp);
  }

After swap, __tmp (of type Foo) holds a std::function<void()> object m_deleter with no target. The exception is thrown when it destructs and the destructor calls m_deleter();

A: You can reproduce your problem even with Visual C++ 2013, which does not support defaulted move constructors and assignment operators; the same behaviour occurs with self-written functions:
#include <functional>

class Foo {
public:
    Foo(int) : m_deleter{ []() {} } {}
    Foo(const Foo &) = delete;
    Foo(Foo &&src) : m_deleter(std::move(src.m_deleter)) { };
    Foo & operator=(const Foo &) = delete;
    Foo & operator=(Foo &&src) { m_deleter = std::move(src.m_deleter); return *this; }
    ~Foo()
    {
        m_deleter();
    }
private:
    std::function<void()> m_deleter;
};

int main() {
    Foo foo(1);
    Foo bar(2);
    std::swap(foo, bar);
}

You can then use the debugger in Visual Studio to verify what's going on. Put a breakpoint at your std::swap call. You will end up in the VC implementation of the function:
_Ty _Tmp = _Move(_Left);
_Left = _Move(_Right);
_Right = _Move(_Tmp);

All three of these moves will work correctly. But then the scope of the function ends, and so does the lifetime of the _Tmp variable. The destructor will be called on it while its m_deleter is empty, as you can see in the "Locals" section of the debugger GUI:

Moving means that the moved-from object has to remain in a valid state for destruction, and a state which results in calling an empty std::function is not valid. Others have shown you the fix in the destructor already.
Now about this...

It turns out it crashes with Visual Studio 2015 and GCC 4.9.2, but not
  with Clang 3.5.

Both your original code and my modification crash with Clang 3.5:
terminate called after throwing an instance of 'std::bad_function_call'

  what():  bad_function_call

bash: line 7: 25250 Aborted                 (core dumped) ./a.out

I tried it at http://coliru.stacked-crooked.com/, which according to clang++ --version uses clang version 3.5.0 (tags/RELEASE_350/final 217394).


text:
Q: How to store sensor data into Apache Hadoop HDFS, Hive, HBase or other Imagine you are reading millions of data rows from a CSV file. Each line shows the sensor-name, the current sensor-value and the timestamp when that value was observed.
key, value, timestamp
temp_x, 8°C, 10:52am
temp_x, 25°C, 11:02am
temp_x, 30°C, 11:12am

This relates to a signal like this:

So I wonder what's the best and most efficient way to store that into Apache Hadoop HDFS. First idea is using BigTable aka HBase. Here the signal name is the row-key while the value is a column-group that saves the values over time. One could add more column-groups (as for instance statistics) to that row-key.

Another idea is using a tabular (or SQL like) structure. But then you replicate the key in each row. And you have to calculate statistics on demand and store them separately (here into a second table).

I wonder if there is any better idea. Once stored, I want to read that data in Python/PySpark and do data analytics and machine learning. Therefore the data should be easily accessible using a schema (Spark RDD).

A: I would consider to use.

*

*Load data from CSV file with databricks csv

*Cleaning the data

*Write to qarquet file (to save space and time)

*Load data from parquet file

*Analyse it

*Perhaps save as intermediate result


text:
Q: SceneKit Swift - using HDR environment light map from file I'm trying to use a spherical HDR image as the environment light in a Swift project using SceneKit and am having trouble using standard 32bpc HDR imaging formats to do it. I can use PNG maps easily, but have trouble loading images from an OpenEXR .exr or Radiance .hdr file.
In this documentation page it seems to describe the feature I'm after.
I can't find any apple documentation describing it, so my current best guess is to write my own function to load the files and then create a CGImage instance using a custom CGDataProvider, as it seems that this container supports floating point and high dynamic range values. Then set that CGImage as the content of the environment light.
Is anyone able to confirm if this is the right idea or if this is actually already implemented somewhere.
I've not done any apple development before (come from a graphics background) and am not sure if I'm on a bit of a wild goose chase at the moment.

A: What "troubles" do you have exactly? scene.lightingEnvironment.contents = "envmap.exr" should work.


text:
Q: Meaning of Exponential map I've been studying differential geometry using Do Carmo's book. There's the notion of exponential map, but I don't understand why it is called "exponential" map. How does it has something to do with our common notion of exponentiation?
I read from the book The road to reality (by R. Penrose) that it is related to taking exponentiation when making (finite) Lie group elements from Lie algebra elements. It seems like using Taylor's theorem on a manifold so we have, for example, there was the following equation explaining why it is the case.
$f(t) = f(0) + f'(0)t + \frac{1}{2!}f''(0) t^2+\cdots = (1+t\frac{d}{dx}+\frac{1}{2!}t^2\frac{d^2}{dx^2}+\cdots)f(x)|_{x=0} = e^{t\frac{d}{dx}}f(x)|_{x=0}$.
The differential operator can be thought of as a vector field on a manifold, and it is how Lie algebra elements (which are vectors, on a group manifold (Lie group), in a tangent space at the identity element). If I understood correctly, the truth is that this is exactly the exponential map that sends a vector on a tangent space into the manifold in such a way that it becomes the end point of a geodesic (determined by the vector) having the same length.
Why is the above Taylor expansion valid on a manifold? Why is the exponential map the same as taking exponentiation?

A: The idea of an exponential is the continuous compounding of small actions. Suppose you start with an object $p$, perform an action on it $v$, and then add the result back to the original object. What happens if you instead take half as much action but do it twice? What about if you take one tenth the action but do it ten times? The exponential function tries to capture this idea:
$$\exp (\text{action}) = \lim_{n \rightarrow \infty} \left(\text{identity} + \frac{\text{action}}{n}\right)^n.$$
On a differentiable manifold there is no addition, but we can consider this action as pushing a point a short distance in the direction of the tangent vector,
$$``\left(\text{identity} + \frac{\text{v}}{n}\right)"p := \text{push }p\text{ by} \frac{1}{n} \text{ units of distance in the }v \text{ direction}.$$
Doing this over and over, we have
$``\left(\text{identity} + \frac{\text{v}}{n}\right)^n"p$ means push $p$ by $\frac{1}{n}$ units of distance in the $v$ direction, then push it again in the same direction you already pushed it, and keep doing so until you have pushed it $n$ times.
So long as $\frac{1}{n}$ is small enough that pushing points and vectors in a tangent direction makes sense, what we end out doing is pushing the point $p$ a total of $1$ unit of distance along the geodesic generated by $v$.

A: Consider the following:
Let $a\in\mathbb{R}$, and define a smooth vector field $X$ on $\mathbb{R}_+$, by $X(p)=ap$. Note that $X$ is left-invariant, when thinking of $\mathbb{R}_+$ as a Lie group. Now let $\gamma$ be a trajectory of $X$, with $\gamma(0)=1$. By solving a simple ODE, one verifies that $\gamma(1)=e^a$, thus the term "exponential map" for Lie gropus coincides with what we know as exponential map on $\mathbb{R}$.


text:
Q: 'choices' must be an iterable containing (actual value, human readable name) tuples django 3.1 whene i want to makemigration it show me this error
user.User.allowd_to_take_appointement: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.
user.User.type_of_user: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.

this is my models.py
class TypeOfUser(models.TextChoices):
    PATIENT = 'patient', 'Patient'
    DOCTOR = 'doctor', 'Doctor'
    RECEPTION = 'reception', 'Reception'
    TEMPORARY = 'temporary', 'Temporary'

class AllowdToTakeAppointement(models.TextChoices):
    YES = ('yes', 'Yes')
    NO = ('no', 'No')

class User(AbstractUser):
    type_of_user = models.CharField(max_length=200, choices=TypeOfUser, default=TypeOfUser.PATIENT)
    allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement, default=AllowdToTakeAppointement.YES)

    def is_doctor(self):
        return self.type_of_user == TypeOfUser.DOCTOR

    def can_add_appointment(self):
        return self.type_of_user == AllowdToTakeAppointement.YES

i'm using django 3.1

A: The choices=… should be provided the outcome of the .choices property of your TypeOfUser and AllowdToTakeAppointment:
class User(AbstractUser):
    type_of_user = models.CharField(
        max_length=200,
        #            .choices ↓
        choices=TypeOfUser.choices,
        default=TypeOfUser.PATIENT
    )
    allowd_to_take_appointement = models.CharField(
        max_length=20,
        #                          .choices ↓
        choices=AllowdToTakeAppointement.choices,
        default=AllowdToTakeAppointement.YES
    )

    def is_doctor(self):
        return self.type_of_user == TypeOfUser.DOCTOR

    def can_add_appointment(self):
        return self.type_of_user == AllowdToTakeAppointement.YES


text:
Q: is it possible to update the data (from API) with the "nuxt generate" command in "target: static" mode without "build"? my generated .html file always keeps the old data, is there a solution or am I obliged to launch the "build" each time ?
routes: function (callback) {
    var _routes = []
...
    axios.all(requests).then(axios.spread((...responses) => {
      responses.forEach((response, key) => {
        // fresh data is well recovered
        _routes.concat(generateRoutes(_routes, routes[key], response))
      })
      callback(null, _routes)
    })).catch(callback)
...
}

A: If you are trying to update the data when the user enters your site, I'm afraid that the 'npm run generate' command will not be useful to you since it is intended to generate sites that don't change at all.
For production, you will have to stick to the 'npm run build' (run it only once) and then the 'npm run start' command to init the server.
For development, just simple use the 'npm run dev' command and you will get a server with hot reload as you write your code.


text:
Q: Python - Pandas (Insert a new row in between but not overriding existing row) I am trying to insert a new row in between data frame (6th row precisely) and I am unable to without overriding the existing row. Can you please help me correct this?
out2.loc[6] = ['EMPTY LINE']
out2.index = out2.index + 1
out2 = out2.sort_index()
print(out2)


text:
Q: Issues creating table from bucket file I have a big table (About 10 million rows) that I'm trying to pull into my bigquery. I had to upload the CSV into the bucket due to the size constraints when creating the table. When I try to create the table using the Datastore, the job fails with the error:
Error Reason:invalid. Get more information about this error at Troubleshooting Errors: invalid.
Errors:
gs://es_main/provider.csv does not contain valid backup metadata.
Job ID: liquid-cumulus:job_KXxmLZI0Ulch5WmkIthqZ4boGgM
Start Time: Dec 16, 2015, 3:00:51 PM
End Time: Dec 16, 2015, 3:00:51 PM
Destination Table: liquid-cumulus:ES_Main.providercloudtest
Source URI: gs://es_main/provider.csv
Source Format: Datastore Backup

I've troubleshot by using a small sample file of rows from the same table and just uploading using the CSV feature in the table creation without any errors and can view the data just fine.
I'm just wondering what the metadata should be set as with the "Edit metadata" option within the bucket or if there is some other work around I'm missing. Thanks

A: The error message for the job that you posted is telling you that the file you're providing is not a Datastore Backup file.  Note that "Datastore" here means Google Cloud Datastore, which is another storage solution that it sounds like you aren't using.  A Cloud Datastore Backup is a specific file type from that storage product which is different from CSV or JSON.
Setting the file metadata within the Google Cloud Storage browser, which is where the "Edit metadata" option you're talking about lives, should have no impact on how BigQuery imports your file.  It might be important if you were doing something more involved with your file from Cloud Storage, but it isn't important to BigQuery as far as I know.
To upload a CSV file from Google Cloud Storage to BigQuery, make sure to select the CSV source format and the Google Storage load source as pictured below.


text:
Q: how to compute a^x %p Hi I want to calculate $a^x mod p$ where p is prime and $x$ is large. What I know is that since $p$ is prime, it forms a cyclic group with order $p$ ie $ a^p$ $mod$ $p = a$. Thus, my problem will be easier if I do $x = $$t $ $mod(p-1) $ and then compute $a^t$ $mod$ $p$. But while computing my $x$ in the earlier stage i have expression like
$x = c(2n,n)^b$  which i can compute only by using modular inverse. since here $(p-1) $ is not prime( actually an even number ) I cannot proceed with it. Can anybody help to find any progress in this.

A: The real problem here seems to be to compute the value of the (central) binomial coefficient $\binom{2n}n$ modulo an integer $m$ (where $m+1$ is the prime number $p$, but this gives us little useful information about the factorisation of $m$, except that it $m$ is almost certainly composite).
Since you did not say that the prime $p$ was huge, I'll suppose that it is feasible to find the factorisation of $m=p-1$ effectively. Even if this is not the case, you might be able to proceed by ignoring any remaining divisor$~D$ of$~m$ for which you checked that $D$ has no prime factors less than $2n$, because $\tbinom{2n}n$ is guaranteed to be invertible modulo$~D$, and the inverse can effectively be computed using the extended Euclidean algorithm. For the prime factors $q<2n$ of $m$,  Kummer's theorem is your friend (though I guess you could get its result here by direct reasoning as well, if you had not heard about it before). It tells you that you can find the multiplicity of $q$ as factor of $\tbinom{2n}n$ by performing the addition $n+n$ numerically in base $q$ representation, and paying attention to any carries that may be generated; the number of carries gives the multiplicity you are after. Once the powers of such $q$ are dealt with, you can find the remaining factor of $\tbinom{2n}n$ by taking the fraction
$$
  \frac{2n(2n-1)(2n-2)\ldots(n+1)}{n(n-1)(n-2)\ldots1} \tag1
$$
and dividing each factor by the largest powers of such $q$ possible; the remaining quotient of products can be computed directly modulo $m$, since everything has become relatively prime to $m$.
The "direct reasoning" above amounts to simply keeping track of the factors $q$ you are simplifying by, and multiplying the end result by any excess power that was removed from the numerator but not from the denominator. Come to think of it, you can do this using only very basic theory: simply write every factor in$~(1)$ as product of all the prime factors it has common with$~m$, and a remaining part that is relatively prime with $m$; then perform separate computations for the "common" and "relatively prime" parts. Warning: the "product of common prime factors with $m$"  of a number need not be equal to its GCD with$~m$ (it could be larger); nonetheless it can be found by repeated GCD computations.


text:
Q: How to find "public" intents we can use in using other apps in our apps SO searching around stackoverflow I found Intents List: Invoking Google Applications on Android Devices which tells me how to use intents to dial the phone, look at a map, or look at a streetview.
It does NOT tell me how to use intents to access the contacts lists, the calendar items, email, text messaging, media player, camera, bluetooth, or any of the other apps which exist on virtually every android phone.
It CERTAINLY doesn't tell me how to access with apps things like ES File Explorer, Dropbox, facebook, google voice, or any of these other very useful apps many of us download for free and might LOVE to automatically use from apps we write.
If any body out there knows how to find the "API" of intents for accessing these various things from apps, it would be so great to be able to peruse these lists.
PS I realize I can LAUNCH any of these apps with an intent, I know how to do that.  But to automatically upload something to dropbox rather than bringing up Dropbox's entry screen so that I can manually try to guess what my app wanted to upload and then upload it by hand, obviously automatic is better or we wouldn't be programming phones.

A: This was the biggest list of intents I could find. I use those quite often. All the intents listed here are the ones that various apps let developers access to. If youre looking for a specific app's intents, then they would list that on their developer forums/site. Apart from this I dont think there are other ways of knowing which app provides which intents.
EDIT: You can find another list of intents here.


text:
Q: Box Sizing irregularity in Safari I'm having difficulty getting an
 divided evenly in safari so that the inline
 elements make up 100% of the width.
The html code is basically:

red

blue

green

orange

purple

with css:
ul {
   list-style: none;
   margin: 0;
   padding: 0;
   width: 500px;
   background-color: #9999ff;
}
li {
   text-align: center;
   text-decoration: none;
   display: inline-block;
   border-left: 1px solid #000;
   width: 20%;
   box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
li:last-child {
   border-right: 1px solid #000;
}

It seems like this would make 5 evenly spaces list elements which take up 20% (including borders) of the total width each.  Works perfectly in Firefox and Chrome but Safari leaves an extra 6 pixels or so at the end.  When I remove the box-sizing property then the list becomes too long.  I can't seem to make this simple thing work for the life of me.
Here's JSFiddle: http://jsfiddle.net/z2Xdf/7/

A: It was rendering the wrong way for me in Chrome...at least using jsFiddle.
Inline-block puts some white space on the sides. Remove from li display:inline block and add
display:block;
float:left;

Also, move your background color to li from ul.
If you wanted to keep display:inline-block, you can apparently do this...

<!-
    ->
stuff
<!-
    ->
stuff
<!-
->

but that seems like a hassle to type?
More "hacks"  here (check comments)...


text:
Q: rails 3, when handling a POST from a remote web app, how do we return a basic http "ok" after processing a upload file received from an external website, we need to send back some sort of basically empty http "ok" message. So we don't have a 'view' associated with this method... I assume we need to do render SOMETHING_GOES_HERE ?

A: Try using head instead of render:
head 200

From the docs, it looks like you can use more readable symbols instead of numeric HTTP status codes, but I haven't found the list anywhere...
You can also include other headers, if you like (from the docs):
head :created, :location => person_path(@person)

Hope this helps!

A: render :text => "ok"
You may need to pass :layout => false if there is a layout specified for the entire controller.

A: render :nothing => true, :status => 200


text:
Q: Changing Apple developer company/organization name Say an independent US-based developer creates an Apple Developer account as an individual contributor. They choose a company/organization name "XYZ Apps". They never create an LLP or file any type of business paperwork other than reporting taxes.
Now the developer wishes to change the company/organization name. Apple requests "court/business" documentation verifying the new name. The developer doesn't have said docs because there hasn't been any official business name change or anything.
How can the independent developer update their company/organization name in this case?
Perhaps they can tell Apple it's just an aesthetic name change. Any feedback from people with experience is greatly appreciated!
Edit: after reading around the web it seems like creating another developer account might be the easiest route. This assumes you don't have apps with the original account where the exact name is important.

A: Apple does not appear to allow any "aesthetic" name changes, only a legal incorporation name or a legal corporate name change.  So you may need to incorporate your business, and request Apple change your developer enrollment to a company enrollment, in order to change the name on your developer account.


text: Q: Logging from AppleScript in Automator I am writing an AppleScript (Run AppleScript item) from within an application in Apple Automator, but the Log panel at the bottom of the window does not display any logged messages (that is, anything logged using the log ... AppleScript command). Is there something I'm missing as to how this should work?


text:
Q: Confused on how to install PythonMagick module Use Case - I'm trying to convert TIFF to PDFs and I stumbled on PythonMagick .9 but I have trouble installing it.
Most of the questions I have found both here and from Google are related to older versions of PythonMagick which leads to dead links or the tutorial is used for MACs. How can I install it on Windows (using Python 2.7) or should I not use PythonMagick? Thanks
Edit: Or if there is an updated installer guide that would be great.

A: You can download it from https://www.imagemagick.org/download/python/, As it maintained by the Debian repo, So you could't install it by pip or easy_install.


text:
Q: ScreenFlow: select an area to capture or crop the video, how? I'm trying to use ScreenFlow (together with SimFinger) to make an iPhone Simulator video.
Is it possibile to select a particular area to capture? Or how could I crop the video after the capture?

A: ScreenFlow (I'm using version 4 here) allows you to resize the canvas, and crop the video clip.  These are two separate things.

*

*Resizing the canvas is done by clicking the square button at bottom left.  This affects the dimensions of your exported result.  (Eg set 500 x 400 here, and set scale to 100% when exporting to produce a result of that size.)

*Cropping the video clip is done by selecting it in the timeline, then using the Crop sliders in the Video Properties pane, or alternatively, ctrl-dragging the handles around the video.  This doesn't affect the size of the exported version: this feature is more for when you want to show multiple objects on the screen at once (eg reduce the size of your screen capture so that you can include a caption underneath it).
The entire screen is always recorded, and these adjustments must be made after the capture.

A: Please use QuickTime Player.app instead.
///////////////
Software  OS X 10.8.3 (12D78)

*

*Open QuickTime Player.app

*File-->New ScreenRecording...

*Choose your own settings, and press the RED BUTTON.

*Select a particular area, and then Click mouse.

*....

*Stop

*Saving

A: Press Ctrl and drag the corners of the video.

A: It is posible to do in ScreenFlow. This may help.
http://www.youtube.com/watch?v=vfxWUnspy-o

A: The QuickTime Player.app would have done the trick IF one could select the computer audio track for capture together with the video on screen. Since the functionality is not there, you need something like ScreenFlow.


text:
Q: Invalid static method invocation syntax: "[MSBuild]::IsRunningFromVisualStudio()" After upgrading to Visual Studio 2017 15.5 none of my project will load correctly. All are marked unavailable.
I'm getting the following error for every project:

error  : Invalid static method invocation syntax: "[MSBuild]::IsRunningFromVisualStudio()". Method '[MSBuild]::IsRunningFromVisualStudio' not found. Static method invocation should be of the form: $([FullTypeName]::Method()), e.g. $([System.IO.Path]::Combine(a, b)).   C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets

Reloading project produces this error prompt:

Adding new projects produce this error prompt:

A: 1. Close all running instances of Visual Studio 2017
2. Launch (as Administrator) "Developer Command Prompt for VS 2017"
3. Type the following commands (replace Professional with your edition, either Enterprise or Community, or adjust the path accordingly):
gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.Framework.dll"

gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.dll"

gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.Engine.dll"

gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.Conversion.Core.dll"

gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.Tasks.Core.dll"

gacutil /i "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Build.Utilities.Core.dll"

4. Restart Visual Studio 2017

A: The solution, provided by henkmollema in this thread: https://github.com/Microsoft/msbuild/issues/2775 was to start the visual studio installer from the start menu and run a repair.

A: It seems from the responses to this issue on github that it is often caused by having an older version of MSBuild in the GAC. This will then be used in preference to the bundled version that ships with the updated version of VS.
The solution is to remove the old version of Microsoft.Build from the gac.

*

*Find the gac'd versions:
gacutil /l | findstr Microsoft.Build

*Look for any of version 15.x.x.x and then remove them:
gacutil /u "Microsoft.Build, Version=15.{version_found}"

*Restart Visual Studio
It may also be necessary to remove the related assemblies Microsoft.Build.Utilities.Core, Microsoft.Build.Framework and Microsoft.Build.Tasks.Core of that version.

A: After installing the latest Visual Studio Version via the Updater, I received the same error messages.
The issue was resolved, at least in my case, by rebooting after installing the Visual Studio update.

A: Besides the assemblies mentioned in Yuriy Oleynik's answer, I found I need to add an additional assembly (see the last command below) in gac (I'm using VS 2019):
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.Conversion.Core.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.Engine.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.Framework.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.Tasks.Core.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Build.Utilities.Core.dll"
gacutil.exe -i "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\System.Collections.Immutable.dll"

A: I've come accross this problem in vs2019 with Framework Core 3.1. The problem was two fold.
First of all i've updated my VS2019 to the last version, the project was loading, but I got compilation errors.
I've opened C:\Windows\Microsoft.NET\assembly\GAC_MSIL and removed all microsoft.buid.* except Microsoft.Build.Utilities.Core, Microsoft.Build.Utilities.v4.0 and Microsoft.Build.Utilities.v4.0.resources
And all worked

A: I had this problem with Visual Studio 2017 on a Windows 7 PC on a corporate network.  I tried to fix the issue in the following ways:

*

*restarting the computer/Visual Studio several times (as mentioned by an answer here).

*upgrading to the newest version of Visual Studio found in "Extensions and Updates"

*Using the "Repair" option in the installer.

*Uninstalling it completely by uninstalling the "Visual Studio Installer" (Control Panel → Add remove programs), and then re-installing it.

I noticed that on a colleague's computer, which never had VS2017 installed, when I installed VS2017 Community Edition version 15.5, there was no issue.
At this point, I have to admit defeat.  The only simple solution is to replace the line in the file:

*

*C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets

There is a line near the end of the file:

<NuGetRestoreTargets Condition="'$(NuGetRestoreTargets)'=='' and '$([MSBuild]::IsRunningFromVisualStudio())'=='true'">$(MSBuildToolsPath32)\..\..\..\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.targets</NuGetRestoreTargets>

just replace the $([MSBuild]::IsRunningFromVisualStudio()) with true:

<NuGetRestoreTargets Condition="'$(NuGetRestoreTargets)'=='' and 'true'=='true'">$(MSBuildToolsPath32)\..\..\..\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.targets</NuGetRestoreTargets>

however this only allows the projects to load up - you cannot use it to build the project.
I am going to ask for my machine to be re-imaged so I can just download and install Visual Studio from scratch.
(I hope Microsoft come up with a fix soon.)


text:
Q: What's the best way to create fragment anchors in GitHub markdown? I'm trying to create fragment anchors to use for link destinations in GitHub markdown. I'm trying to avoid embedding HTML  elements since best-practice markdown is to avoid inline HTML.
I'm not talking about heading anchors (though if a heading has non-letter characters, getting auto-generated heading links to work can be a trial-and-error headache). I need to have anchors for arbitrary locations in a .md file.
I've come across GitHub documentation for link reference definitions, but that documentation doesn't really explain clearly how to create an anchor. I tried following Example 168 of creating a link reference without specifying a destination, but that doesn't create an anchor; it just creates a "road to nowhere", so to speak.
What's the best option?

A: Markdown doesn't support custom anchors out-of-the-box (however, some markdown flavors may do) so you have to use HTML.
Create an anchor:

Refer to this anchor:
Take me to something [custom](#location)


text:
Q: How to animate arrow with CSS3 so that it looks like it would be growing? I have the following picture of an arrow
What I would like to achieve is to let this arrow arise (grow) via CSS.
How could I achieve this? I would prefer a CSS3 only solution if it was possible.

A: <!DOCTYPE html>

Hope this helps

A: A simple example using CSS3 tranform and transition properties :
HTML :

CSS :
#arrow {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 2s ease-in-out;
    -ms-transition: all 2s ease-in-out;
    transition: all 2s ease-in-out;
    -webkit-transform: scale(0.3);
    -moz-transform: scale(0.3);
    -o-transform: scale(0.3);
    -ms-transform: scale(0.3);
    transform: scale(0.3);
}

#arrow:hover {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -o-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
}

See Fiddle
Then you can play with other transform property values if you need a different effect (rotate, translate, skew, or more complex transformations).


text:
Q: How to trigger the event listener for a div element using Javascript? I would like to simulate the clicking of the "Download the CSV data for..." button on this page https://aqicn.org/data-platform/register/ using javascript. The problem is that the button is a
 with an event listener rather than a <button> or <input>.

I assume I have to use document.dispatchEvent() but I don't know what parameter to put. I would appreciate any help.

A: You can trigger an event using document.createEvent.

// http://youmightnotneedjquery.com/#trigger_native
const triggerNative = (el, eventName) => {
  const event = document.createEvent('HTMLEvents');
  event.initEvent(eventName, true, false);
  el.dispatchEvent(event);
};

const btn = document.querySelector('#historical-aqidata .primary.button');
const handleClick = e => console.log('clicked button...');

btn.addEventListener('click', handleClick); // Pre-existing event listener
triggerNative(btn, 'click');                // Call the event
html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

#historical-aqidata {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button {
  display: flex;
  padding: 1em;
  border-radius: 0.5em;
  font-weight: bold;
  cursor: pointer;
}

.primary {
  background: #0085D6;
  color: #FFFFFF;
}

.primary:hover {
  background: #419ED3;
  color: #FFFFFF;
}

.as-console-wrapper { max-height: 5em !important; }

Download the SCV data for Seoul

Note: MDN recommends that you use event constructors instead:

"Many methods used with createEvent, such as initCustomEvent, are deprecated. Use event constructors instead."

// http://youmightnotneedjquery.com/#trigger_custom
const triggerCustom = (el, eventName, data) => {
  let event;
  if (window.CustomEvent && typeof window.CustomEvent === 'function') {
    event = new CustomEvent(eventName, { detail: data });
  } else {
    event = document.createEvent('CustomEvent');
    event.initCustomEvent(eventName, true, true, data);
  }
  el.dispatchEvent(event);
};

You can call the custom function just like the native one, as the data is optional.
triggerCustom(btn, 'click');

A: I always suggest referring to MDN for API references.
dispatchEvent is used on the element you want to simulate something on; in your case, your div is your target because you want to simulate click on it.
This is how the dispatchEvent API is used:
const div = document.getElementById('my-div');
div.dispatchEvent(new Event('click'));

A: you can add an Id to your div and then You can do something like below:
HTML:

javascript:
document.getElementById("myBtn").addEventListener("click", function() {
  //write your functionality here
});

A: There is no need of using the dispatchEvent API, just use the native div.addEventListener('click', () => //do something) and you'll be good to do, this is because of the fact that divs, like buttons, can be clicked, its just that they can't be focused by default.


text:
Q: Find the complex numbers $z=x+yi$
$$|\frac{z-4}{z-8}| =1$$ and $$|\frac{z-12}{z-8i}| =\frac{5}{3}$$

This is what I thought to do:
$$(z-4)^2/(z-8)^2=1$$
$$-z+2=-2z+8$$
$$-x-yi+2=-2(x+yi)+8$$
$$x=6, y=0.$$
The answer in my book is $6+8i$ or $6+17i$. I don't know how to solve these two equationstogether.

A: You do not have $|z|^2=z^2$ for complex $z$.  Instead $|z|^2=x^2+y^2$ where $z=x+yi$, with $x$ and $y$ being the real and imaginary parts of $z$.
Thus $|z-4|=|z-8|$ implies
$(x-4)^2+y^2=(x-8)^2+y^2$
$x^2-8x+16+y^2=x^2-16x+64+y^2$
The quadratic terms cancel leaving just a linear equation for $x$ which you then solve.  Thus $x=6$.
Now put this into the second equation
$|z-12|=(5/3)|z-8i|$
$(x-12)^2+y^2=(25/9)(x^2+(y-8)^2)$
Put $x=6$ into that and solve for $y$ getting the quoted answers from the book.

A: HINT:Suppose $z=x+iy$.
Now the equations you have becomes $| \frac{x-4+iy}{x-8+iy}|=1$ and $|\frac{x-12+iy}{x+i(y-8)}|$.
Now if you solve this data {rationalise} then you will get that $|(x^2-12x+32+y^2)-i(4y)|=1$ and $|(x^2-1x+y^2-8y)+i(12y+8x)|=5/3$.
Can you take it from here to solve for x and y??

A: Solve a more general problem, when $\exists\space\text{z}\in\mathbb{C}$ and $\exists\space\text{n}\in\mathbb{R}$:
$$\left|\frac{\text{z}-\text{n}}{\text{z}-2\text{n}}\right|=1\space\Longleftrightarrow\space\left|\text{z}-\text{n}\right|=\left|\text{z}-2\text{n}\right|\space\Longleftrightarrow\space$$
$$\sqrt{\left(\Re\left[\text{z}\right]-\text{n}\right)^2+\Im^2\left[\text{z}\right]}=\sqrt{\left(\Re\left[\text{z}\right]-2\text{n}\right)^2+\Im^2\left[\text{z}\right]}$$
Which leads to:
$$\left(\Re\left[\text{z}\right]-\text{n}\right)^2=\left(\Re\left[\text{z}\right]-2\text{n}\right)^2\space\Longleftrightarrow\space\Re\left[\text{z}\right]=\frac{3\text{n}}{2}$$


text:
Q: Tutorials for feature engineering As is known to all, feature engineering is extremely important to machine learning, however I found few materials associated with this area. I participated to several competitions in Kaggle and believe that good features may even be more important than a good classifier in some cases.
Does anyone know any tutorials about feature engineering, or is this pure experience?

A: I would say experience -- basic ideas are:

*

*to fit how classifiers work; giving a geometry problem to a tree, oversized dimension to a kNN and interval data to an SVM are not a good ideas

*remove as much nonlinearities as possible; expecting that some classifier will do Fourier analysis inside is rather naive (even if, it will waste a lot of complexity there)

*make features generic to all objects so that some sampling in the chain won't knock them out

*check previous works -- often transformation used for visualisation or testing similar types of data is already tuned to uncover interesting aspects

*avoid unstable, optimizing transformations like PCA which may lead to overfitting

*experiment a lot

A: There is a book from O'Reilly called "Feature Engineering for Machine Learning" by Zheng et al.
I read the book and it covers different types of data (e.g categorical, text...) and describes different aspects of feature engineering that go with it. This includes things like normalization of data, feature selection, tf-idf in text.


text:
Q: Is a blocking function on an asynchronous api idiomatic? Is it more idiomatic to have an async api, with a blocking function as the synchronous api that simply calls the async api and waits for an answer before returning, rather than using a non-concurrent api and let the caller run it in their own goroutine if they want it async?
In my current case I have a worker goroutine that reads from a request channel and sends the return value down the response channel (that it got in a request struct from the request channel).
This seems to differ from the linked question since I need the return values, or to synchronize so that I can be sure the api call finishes before I do something else, to avoid race conditions.

A: For golang, I recommend Effective Go-concurrency. Especially I think everyone using golang need to known the basics of goroutine and parallelization:
Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.
The current implementation of the Go runtime dedicates only a single core to user-level processing. An arbitrary number of goroutines can be blocked in system calls, but by default only one can be executing user-level code at any time.


text:
Q: Changing permissions discord.js Ok so I've been working on a bot that creates channel overrides using discord.js. I'm kind of new to discord.js but I checked the documentary and it seems that the correct method to use when changing overrides is what I used in the code below, but I get an error message and I have absolutely no clue as to how I can fix it.
if (command == 'lockdown') {
 if (commandArgs == '') {
  let channel = msg.channel;
  let roles = msg.guild.roles;
  console.log(roles);
  let testRole = 708384707015868486;
  channel
   .overwritePermissions(testRole, { SEND_MESSAGES: false }, 'closing up shop')
   .then(console.log)
   .catch(console.log);
 }
}

This is the code for that specific command, but I get the following error message.
TypeError [INVALID_TYPE]: Supplied overwrites is not an Array or Collection of Permission Overwrites.
    at TextChannel.overwritePermissions (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/structures/GuildChannel.js:208:9)
    at Client.<anonymous> (/home/runner/Ecliptical-Productions-V3/index.js:25:17)
    at Client.emit (events.js:315:20)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/Ecliptical-Productions-V3/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/Ecliptical-Productions-V3/node_modules/ws/lib/event-target.js:125:16) {
      [Symbol(code)]: 'INVALID_TYPE'
    }

How can I fix this error? I checked the channel overrides after the command and the changes weren't made, I've been trying to fix this for ages but I can't find the error.

A: The overwritePermissions method wants an Array or a Collection of OverwriteResolvables as the first argument. Instead, your first argument is the id of the role you want to change the permissions for.
Change the channel.overwritePermissions to the example code below and give it a try.
channel.overwritePermissions(
 [
  {
   id: testRole,
   deny: ['SEND_MESSAGES'],
  },
 ],
 'Closing up shop'
);

In this example, the supplied OverwriteResolvable is of type OverwriteData which can be defined with a simple Object structure.

A: overwritePermissions expects an array and you supplied it with 2 objects.
channel.overwritePermissions(
 [  //<--- you are missing these
  {
   id: message.author.id,
   deny: ['SEND_MESSAGES'],
  },
 ], //<--- you are missing these
 'Needed to change permissions'
);

https://discord.js.org/#/docs/main/stable/class/GuildChannel?scrollTo=overwritePermissions

A: If you have "message" defined you can use "message.channel" to get the channel you typed the message in.
message.channel.createOverwrite(message.guild.id, { SEND_MESSAGES: false })
You can see that above that would change send messages permissions for all roles except moderation roles and if you wanted to send a message after you can use the ".then()" function, If you use V12 everything i told you will work fine, I suggest you research before asking there's loads of information and tutorials online you can find.


text:
Q: viewPager with tab in android hi i have a fragmentAdapter:
public class TitleAdapter extends FragmentPagerAdapter {

    private final String titles[] = new String[] { "Home", "Eventi"};
    private final Fragment frags[] = new Fragment[titles.length];
    Context context;
    public TitleAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.v("TitleAdapter - getPageTitle=", titles[position]);
        return titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        Log.v("TitleAdapter - getItem=", String.valueOf(position));
        //return frags[position];
        switch (position) {
        case 0:
            return Home.newInstance(0, "aa");
        case 1:
            return Eventi.newInstance(1, "bbbb");
        }
        return null;
    }

    @Override
    public int getCount() {
        return frags.length;
    }
}

in each fragment (Home and Eventi) i have a list fragment. What i see in the logcat is that all the fragments are loaded when the activity starts. What i'd like to do is to load one fragment each time . how to do that??

A: Sorry to disappoint, but you cannot load only a single fragment at a time with the Android library ViewPager. Generally in order to set how many fragments for the ViewPager to render, you would use this method public void setOffscreenPageLimit (int limit).
The problem though, is that the default and minimum value for the off-screen page limit is 1, which means that the ViewPager will render and keep in memory the fragments on either side of the currently selected fragment. You would think that you could set the limit to 0, but it will still default to 1 (see ViewPager.setOffscreenPageLimit(0) doesn't work as expected).
I assume you're forced to render at least 1 fragment ahead in order to ensure smooth scrolling. I hope this info helps!


text:
Q: How to evaluate gcc format-overflow checking size 72 My sample code (t.c)
#include <stdio.h>
#include <time.h>
int main() {
        /* 12345678901234567890
         * 2017/09/06 12:28:30  */
        char wtime[19];
        time_t t=time(NULL);
        struct tm *pt = localtime(&t);
        sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
            pt->tm_mon+1, pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec);
        printf("%s %ld\n", wtime, sizeof(int));
        return 0;
}

Warning message by gcc -Wall -Wformat=2 -m64 t.c (gcc 7.1.1)
t.c:9:47: warning: 'sprintf' writing a terminating nul past the end of the destination [-Wformat-overflow=]
  sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
                                               ^
t.c:9:2: note: 'sprintf' output between 20 and 72 bytes into a destination of size 19
  sprintf(wtime, "%04d/%02d/%02d %02d:%02d:%02d", pt->tm_year+1900,
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      pt->tm_mon+1, pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec);
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The number 20 in the message is 19 and one terminator ('\0').
I am wonder, why there is a number 72? How to evaluate it.  It is not necessary to increase wtime as size 72 in this sample.

A: Every string in C must have a null terminator, in order to know where the string ends, but I guess you already know that from your reputation.
The error message says the string can have any number between 20 and 72 bytes, that is between 19 and 71 characters plus the null terminator.
19 characters is found by finding the minimum possible string, which contains 19 characters because of the leading zeroes at each value. This formatted string can also contain up to 71 characters because of the limits of int (a number that can go up to 10 digits), so summing 11 in each %d occurrence (worst-case scenario with a leading negative sign) plus the other characters gives us 71).
By having only 19 bytes to store the string, it is impossible to fit it all plus the null terminator, hence the error. So if you increase the size of your char array to 20 it is possible that it works because it is within the limits, but it is not guaranteed since the numbers can exceed this size.

A: The "%d" format is for int, which is usually a 32-bit signed integer type. That means it can have up to 11 characters when printed (10 digits plus a possible minus for negative numbers). You have six of those meaning that's up to 66 character.
Then you have five other characters (two each of '/' and ':', and a space).
Plus terminator.
That's 72.
And remember that the "04" part of "%04d" means it will print four digits left-padded with zeros, but if there's more digits then it will print all of them. It's not an absolute limit.
Therefore at least 20 characters, but up to 72.


text:
Q: preventDefault not blocking keys that use Alt modifier I am making a chrome extension that occasionally prevents all keyboard inputs from reaching the webpage temporarily (as the extension's handler performs its own tasks with the keyboard inputs that it catches). And the extension does a good job listening to all of those inputs.
HOWEVER, some keyboard inputs still get through the webpage! Specifically, certain keyboard inputs that use the Alt modifier key reach the webpage. I have replicated the issue with this code:
$(window).get(0).addEventListener("keypress",
    function(e){
        e.stopPropagation();
        e.preventDefault();
}, true);

You can interact with the code in this jsfiddle: https://jsfiddle.net/Sophtware/5ucefew2/
Can someone help me figure out why this is happening and how to fix it?
EDIT #1: I found out that the symbols that are coming through the preventDefault call are things like accents or other "combining characters" (like ´, ˆ, ¨). In fact, once a combining character has been typed, the next character typed will always also fail to be blocked.

A: Well, first, you didn't have jQuery loaded in your Fiddle.
Second, you need to use the keydown event, not keypress because keypress doesn't fire when keys that don't produce visible characters are pressed. This is why you found that some characters work with it and others don't.
Third, your event binding code isn't really written correctly. There is no need to use get(0) when jQuery returns a wrapped set that contains only one item. And since there is only one window or document, that code isn't needed.
Additionally, you can check explicitly for the ALT key being pressed.
Lastly, please don't post your code to 3rd party sites because those links can become broken over time. Instead post your code snippets right here.
See comments inline:

// Set the event on the document, but then test for the input element when it happens
$(document).on("keydown", "input[type='text']", function(e){
  // Check the event for the ALT key press
  console.log("Keystroke cancelled!");
  e.preventDefault();
  e.stopPropagation();
});

Type in Alt + 'e', Alt + 'i', or other Alt combinations! They get typed in even though they're not supposed to!

Strangely, Alt+j and Alt+k cannot be written more than once in a row and act strange in general.

If you type in Alt + e and then a regular letter key press, the letter gets typed! ??????

<input type="text">


text:
Q: SQLite error attempt to write to a read-only database I've been struggling to deploy my django project with Apache and mod_wsgi. I've had many problems that I managed to handle, but this one just seems not to be solvable.
I get the following error in my apache log when I enter the address setakshop.ir:8080 :
[Wed May 27 05:54:24 2015] [error] Internal Server Error: /en-gb/
[Wed May 27 05:54:24 2015] [error] Traceback (most recent call last):
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 87, in get_response
[Wed May 27 05:54:24 2015] [error]     response = middleware_method(request)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/oscar/apps/basket/middleware.py", line 26, in process_request
[Wed May 27 05:54:24 2015] [error]     strategy = selector.strategy(request=request, user=request.user)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/oscar/apps/partner/strategy.py", line 39, in strategy
[Wed May 27 05:54:24 2015] [error]     return Default(request)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/oscar/apps/partner/strategy.py", line 57, in __init__
[Wed May 27 05:54:24 2015] [error]     if request and request.user.is_authenticated():
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 224, in inner
[Wed May 27 05:54:24 2015] [error]     self._setup()
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 357, in _setup
[Wed May 27 05:54:24 2015] [error]     self._wrapped = self._setupfunc()
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/middleware.py", line 22, in <lambda>
[Wed May 27 05:54:24 2015] [error]     request.user = SimpleLazyObject(lambda: get_user(request))
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/middleware.py", line 10, in get_user
[Wed May 27 05:54:24 2015] [error]     request._cached_user = auth.get_user(request)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py", line 152, in get_user
[Wed May 27 05:54:24 2015] [error]     user_id = request.session[SESSION_KEY]
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 49, in __getitem__
[Wed May 27 05:54:24 2015] [error]     return self._session[key]
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 175, in _get_session
[Wed May 27 05:54:24 2015] [error]     self._session_cache = self.load()
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py", line 29, in load
[Wed May 27 05:54:24 2015] [error]     self.create()
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py", line 41, in create
[Wed May 27 05:54:24 2015] [error]     self.save(must_create=True)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py", line 64, in save
[Wed May 27 05:54:24 2015] [error]     obj.save(force_insert=must_create, using=using)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 589, in save
[Wed May 27 05:54:24 2015] [error]     force_update=force_update, update_fields=update_fields)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 617, in save_base
[Wed May 27 05:54:24 2015] [error]     updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 698, in _save_table
[Wed May 27 05:54:24 2015] [error]     result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 731, in _do_insert
[Wed May 27 05:54:24 2015] [error]     using=using, raw=raw)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method
[Wed May 27 05:54:24 2015] [error]     return getattr(self.get_queryset(), name)(*args, **kwargs)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 921, in _insert
[Wed May 27 05:54:24 2015] [error]     return query.get_compiler(using=using).execute_sql(return_id)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 921, in execute_sql
[Wed May 27 05:54:24 2015] [error]     cursor.execute(sql, params)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
[Wed May 27 05:54:24 2015] [error]     return self.cursor.execute(sql, params)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
[Wed May 27 05:54:24 2015] [error]     six.reraise(dj_exc_type, dj_exc_value, traceback)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
[Wed May 27 05:54:24 2015] [error]     return self.cursor.execute(sql, params)
[Wed May 27 05:54:24 2015] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 485, in execute
[Wed May 27 05:54:24 2015] [error]     return Database.Cursor.execute(self, query, params)
[Wed May 27 05:54:24 2015] [error] OperationalError: attempt to write a readonly database

Now I googled this error and searched a lot, I mean a lot! I know that the db.sqlite file must have write permissions and it should be owned by apache ( www-data ), also the directory containing it must have write permissions and be owned by www-data. and I have done these two things. I don't have selinux installed, I've ran ./manage.py migrate, and I don't know what else I can do to make this work, I even chmoded both the directory and the db.sqlite file to 777 to just see if it will work, but it didn't and I know that's not a safe thing to do.
now for your information this is the folder containing the db.sqlite file:
-rw-rw-r-- 1 ashkan   ashkan      382 Jan 30 11:54 README.rst
-rw-rw-r-- 1 ashkan   ashkan        0 Jan 30 11:54 __init__.py
drwxrwxr-x 4 ashkan   ashkan     4096 Feb  6 15:15 apps
-rwxrwxrwx 1 www-data www-data 741376 May 27 09:11 db.sqlite
drwxrwxr-x 7 ashkan   ashkan     4096 Jan 30 11:54 deploy
drwxrwxr-x 2 ashkan   ashkan     4096 Jan 30 11:54 fixtures
drwxrwxr-x 2 ashkan   ashkan     4096 Feb 22 00:14 i18n
drwxrwxr-x 3 ashkan   ashkan     4096 Feb 23 21:45 locale
drwxr-xr-x 2 ashkan   ashkan     4096 May 26 08:33 logs
-rwxrwxr-x 1 ashkan   ashkan      242 May 26 00:22 manage.py
lrwxrwxrwx 1 ashkan   ashkan       10 May 25 23:15 oscar -> i18n/oscar
drwxrwxr-x 4 ashkan   ashkan     4096 Jan 30 21:53 public
-rw-rw-r-- 1 ashkan   ashkan    14306 May 26 00:07 settings.py
-rw-r--r-- 1 ashkan   ashkan    10230 May 26 00:23 settings.pyc
-rw-rw-r-- 1 ashkan   ashkan    14876 Feb  6 14:26 settings.py~
-rw-rw-r-- 1 ashkan   ashkan      293 Jan 30 11:54 settings_mysql.py
-rw-rw-r-- 1 ashkan   ashkan      266 May 26 00:16 settings_postgres.py
-rw-rw-r-- 1 ashkan   ashkan      162 Jan 30 11:54 settings_sphinx.py
drwxrwxr-x 2 ashkan   ashkan     4096 Feb 23 21:45 static
drwxrwxr-x 3 ashkan   ashkan     4096 Jan 30 11:54 templates
-rwxrwxr-x 1 ashkan   ashkan     1114 Jan 30 11:54 test_migrations.sh
-rwxrwxr-x 1 ashkan   ashkan     1138 Jan 30 11:54 update_latest.sh
-rw-rw-r-- 1 ashkan   ashkan     1573 Jan 30 11:54 urls.py
-rw-rw-r-- 1 ashkan   ashkan     1427 Jan 30 21:53 urls.pyc
drwxr-xr-x 2 ashkan   ashkan     4096 Jan 30 20:58 whoosh_index
-rw-rw-r-- 1 ashkan   ashkan      778 May 26 00:23 wsgi.py

and this is the directory containing the db.sqlite file:
-rw-rw-r--  1 ashkan   ashkan       866 Jan 30 11:54 README.rst
drwxrwxr-x  2 ashkan   ashkan      4096 Jan 30 11:54 _fixtures
-rw-rw-r--  1 ashkan   ashkan    897149 Feb  6 15:34 alaki
-rw-rw-r--  1 ashkan   ashkan   1818857 Feb  6 15:37 alaki.txt
drwxrwxr-x  9 ashkan   ashkan      4096 Jan 30 11:54 demo
-rw-rw-r--  1 ashkan   ashkan    443627 Feb  6 15:34 out
drwxrwxrwx 12 www-data www-data    4096 May 27 09:11 sandbox
drwxrwxr-x  5 ashkan   ashkan      4096 Jan 30 11:54 us

any idea what's causing this problem? thank you.
update 1 :
here is my apache config :
Listen 8080

<VirtualHost *:8080>
    WSGIDaemonProcess setak python-path=/home/ashkan/freshcopy/django-oscar/sites/sandbox:/usr/local/lib/python2.7/site-packages
    WSGIProcessGroup setak
    WSGIScriptAlias / /home/ashkan/freshcopy/django-oscar/sites/sandbox/wsgi.py
    ServerAdmin admin@setakshop.ir
    ServerName setakshop.ir:8000
    DocumentRoot /var/www/

    Alias /media/ /home/ashkan/freshcopy/django-oscar/sites/sandbox/public/media/
    Alias /static/ /home/ashkan/freshcopy/django-oscar/sites/sandbox/public/static/

    <Directory /home/ashkan/freshcopy/django-oscar/sites/sandbox>
    <Files wsgi.py>
        Order allow,deny
        allow from all
    </Files>
    </Directory>

    <Directory /home/ashkan/freshcopy/django-oscar/sites/sandbox/public/static>
        Order allow,deny
        allow from all
    </Directory>

    <Directory /home/ashkan/freshcopy/django-oscar/sites/sandbox/public/media>
        Order allow,deny
        allow from all
    </Directory>

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel info

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

update 2 :
here is my wsgi.py :
import os
import sys
import site
import urllib

sys.stdout = sys.stderr

# Project root
root = '/home/ashkan/django-oscar/sites/sandbox'
sys.path.insert(0, root)

# Packages from virtualenv
activate_this = '/home/ashkan/django-oscar/oscar/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

# Set environmental variable for Django and fire WSGI handler
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()

def application(environ, start_response):
    environ['PATH_INFO'] = urllib.unquote(environ['REQUEST_URI'].split('?')[0])
    return _application(environ, start_response)


text:
Q: Calculate Refractive index of sapphire with sellmeier equation I am trying to calculate the refracrive index of Sapphire with the Sellmeier equation. i defined the equation but now i cant figure out how to input the wavelengths in nanometers.  see code below...
import numpy as np
import matplotlib.pyplot as plt

def nsell( lam ):

B1=1.023798
B2=1.058264
B3=5.280792
C1=0.0614482
C2=0.110700
C3=17.92656

lam=lam*10**-9

nsq = 1   + [B1] * lam**2 / (lam **2 - [C1])
nsq = nsq + [B2] * lam**2 / (lam **2 - [C2])
nsq = nsq + [B3] * lam**2 / (lam **2 - [C3])

return nsq**0.5

Lab=np.linspace(300,400,20)
test=nsell(Lab)
print(test)

i get weird result or i just do not understand it.
runfile('C:/Users/Kevin/Documents/Python Scripts/ligei.py', wdir='C:/Users/Kevin/Documents/Python Scripts')
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.
  1.  1.]

A: The coefficients you are using appear to be based on micrometers, so you have to use micrometers for lambda as well. Just use
Lab=np.linspace(0.3,0.4,20)

Since it looks like you want 300 nm to 400 nm, which is 0.3 um to 0.4 um.
Alternatively, you could convert your coefficients to the units you want to use.
Also, the square brackets around your coefficients are unnecessary.


text:
Q: How to find the difference in decimal points in Java Let us say we have the following numbers:
23.499999959800466
23.49999995949621
23.49999995980162
23.499999956586194
23.499999954013447
23.499999959041133

By looking at them, one can notice the difference in the 9th decimal point. My question is how to identify such a difference in Java?

A: If you know two numbers have the same integer part, use base 10 log:
double n1 = 23.499999959800466d;
double n2 = 23.49999995949621d;

// index of the last identical decimal place between n1 and n2
int decimalDiff = (int) Math.abs(Math.log10(n1 - n2));

System.out.println(decimalDiff);

Output: 9
If you have many numbers and you know they all have the same integer part, then calculate the decimal difference between the smallest and largest of the list:
List<Double> numbers = Arrays.asList(
                23.499999959800466,
                23.49999995949621,
                23.49999995980162,
                23.499999956586194,
                23.499999954013447,
                23.499999959041133);

        double smallest = Collections.min(numbers);
        double largest = Collections.max(numbers);

        System.out.println((int) -Math.log10(largest - smallest));

Output: 8. The numbers all have 8 decimal places in common.

A: You can use java.math.BigDecimal class for your solution.
The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.
A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point.strong text.
BigDecimal bigDecimal = new BigDecimal(num);

Java BigDecimal Methods
BigDecimal add(BigDecimal bigDecimal2)
BigInteger bigInt = new BigInteger("233233233233");
BigDecimal bigDecimal = new BigDecimal(bigInt);
BigDecimal bigDecimal2 = new BigDecimal(55662.3);
System.out.println(bigDecimal.add(bigDecimal2));

BigDecimal subtract(BigDecimal bigDecimal2):
bigDecimal.subtract(bigDecimal2)

You can use subtract method of BigDecimal class for you solution and easily compute difference between two BigDecimal number.
BigDecimal setScale(int newScale, RoundingMode roundingMode):
You can also set scale for numbers using setScale function.
UP: to round away from zero
CEILING: to round towards positive infinity
DOWN: to round towards zero
FLOOR: to round towards negative infinity
HALF_DOWN: to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down
HALF_EVEN: to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor
HALF_UP: to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up
UNNECESSARY: to assert that the requested operation has an exact result, hence no rounding is necessary
BigDecimal bigDecimal = new BigDecimal("23323323.3533");
bigDecimal.setScale(2,RoundingMode.CEILING)
bigDecimal.setScale(2,RoundingMode.DOWN)
bigDecimal.setScale(2,RoundingMode.FLOOR)

Output:
23323323.3533
CEILING: 23323323.36
DOWN: 23323323.35
FLOOR: 23323323.35
Hope this will help.


text: Q: UBUNTU 20.04 SHUTDOWN AUTOMATICALLY ON SERVER We had bought new server intel xeon 24 core processor. i install ubuntu 20.04 LTS. it is shutting down frequently. what is the solution for the same.please help us.


text:
Q: How to change UIViewController Orientation to UIInterfaceOrientationLandscapeLeft for one view in iOS7 I've tried the following methods to force landscape on one of my views:
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscape;

}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeLeft;

}
- (BOOL)shouldAutorotate{
return YES;

}
Neither did work. Note that I'm testing on the simulator and on an iPhone
Thanks

A: please goto Targets in Xcode and in Generate Category select Device Orientation ticked for Landscape Orientation.


text:
Q: 2 boxes of same height (percentage) How to create two boxes (floating side by side) of same height.
I want to create boxes of height 40% of the container/window?

A: See the Example Here

If that is what you are looking for, here is more:
CSS:
  #parent{
    width:205px;
    height:200px;
    border:1px solid #000000;
    overflow:auto;
  }

  #child1{
    height:40%;
    background:#00ff00;
    float:left;
  }

  #child2{
    height:40%;
    background:#0000ff;
    float:left;
  }

The Important Points:

*

*The float:left is used to align the two boxes side-by-side

*The height is specified in % for both child boxes so that they inherit from their parent.

HTML:

        This is first box

        This is second box

A: This should be a simple solution for you. Here's my example:
jsfiddle
HTML:

        Content

        More content

CSS:
.wrap
{
    width: 400px;
    height: 500px;
    border: 1px solid #000;
}

.left, .right
{
    float: left;
    width: 45%;a
    height: 40%;
    margin: 2%;
}

.left
{
    border: 1px solid #f00;
}

.right
{
    border: 1px solid #00f;
}

A: Using a % as height is relative to your parent container's height. Therefore you need to declare the height of your parent container. Take a look at this tutorial: Equal Height Columns.

A: The question specifically mentions floating, and there have been several good answers for that, but I thought it might be worth posting an answer that doesn't use floats in case the the mention of floating was accidental:
.wrapper {
    width: 400px;
    height: 400px;
    outline: 1px solid #000;
}
.wrapper div {
    display: inline-block;
    width: 198px;
    height: 40%;
    background: #66c;
}
.wrapper div:first-child {
    background: #6c6;
}

This is the first box

This is the second box

Some other content

It doesn't currently work in WebKit, but I assume that's a bug and there'll be a workaround, I am investigating.  If you need it to work in IE < 8 add a conditional comment:


text:
Q: Node Js url.format() not working properly inside Angular 6 I'm having problem loading a local pdf file using url.format(). Here is my code:
win.loadURL(url.format({
      pathname: path.join(__dirname, 'assets/file.pdf'),
      protocol: 'file:',
      slashes: true
}));

But getting two times c:\ inside the formatted url. This is the error i'm getting
ERROR Error: Uncaught (in promise):
Error: ENOENT: no such file or directory, open 'C:\C:\Projects\Experiments\Electron\angular-electron\dist\assets\file.pdf'


text:
Q: Loop in C gone wrong I have this code
for (i = 0; i < s; i++) // for i from 0 to Runners
{
    for (j = 0; j < 4; j++) //for j from 0 to laps
    {
        printf("\nEnter the time of lap %d for runner %d in minutes: ", j+1, i+1); // prompt for time for each runner in minutes
        while (scanf("%d", &Runnerm[i][j]) != 1) // While scanf returns not equal to 1 (value parsed == TRUE)
        {
            while ((ch = getchar()) != '\n') putchar(ch); // check if ch=character, compare last entry (\n if character)
            printf(" is not an integer.\nPlease enter only an "); // print error
            printf("integer, such as 1, 5, or 9 : \n"); // cnt print error
        }

        printf("Enter the time of lap %d for runner %d in seconds: ", j+1, i+1); //prompt for time for each runner in seconds
        while (scanf("%d", &Runners[i][j]) != 1) // While scanf returns not equal to 1 (value parsed == TRUE)
        {
            while ((ch = getchar()) != '\n') putchar(ch); // check if ch=character, compare last entry (\n if character)
            printf(" is not an integer.\nPlease enter only an "); // print error
            printf("integer, such as 1, 5, or 9 : \n"); // cnt print error
        }

        printf(" \n check 1 \n ");
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][j], Runners[i][j]); // Correct Check!

        printf(" \n check 1.5 \n ");
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][0], Runners[i][0]); // Incorrect Check!
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][1], Runners[i][1]); // Incorrect Check!
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][2], Runners[i][2]); // Incorrect Check!
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][3], Runners[i][3]); // Incorrect Check!

    }
}

The problem is, when check 1.5 runs the second time, Runnerm[i][j] gets values from Runners[i+1][j]
In short, when i changes value, the previous stored value of Runnerm will get the value of the Runners that is currently being stored..
Why is that? I can't find the reason..
Edit: The "check 1" and "check 1.5" exist for the whole purpose of -checking- the values at any given time of the loop. SO, even if I delete them, the program will still be broken.
ALSO when this is all fixed, the checks will be deleted, because I won't need to check the values any more. Thank you all for answering but I don't get why you suggest to do something with the checks, they are there for debugging. :\
Edit Found what caused the problem, when I used another version of the program that used fewer arrays, the problem was solved, when I started adding random un-used arrays, the problem appears.
Why is that? (New problem)
Could it be that the memory overlaps to the one that Runners[i][j] use?

A: It appears that your printf statement is showing the next runner/next time, but recording for the runner/time before:
printf("\nEnter the time of lap %d for runner %d in minutes: ", j+1, i+1);
                                                                ^^^^ ^^^^

Why not i j

A: Move these lines of code:
printf(" \n check 1.5 \n ");
printf("\n %d minutes -- %d seconds \n", Runnerm[i][0], Runners[i][0]);
printf("\n %d minutes -- %d seconds \n", Runnerm[i][1], Runners[i][1]);
printf("\n %d minutes -- %d seconds \n", Runnerm[i][2], Runners[i][2]);
printf("\n %d minutes -- %d seconds \n", Runnerm[i][3], Runners[i][3]);

to outside the j loop, remove the redundant prompt, and get rid of the magic constants used as loop bounds.
#define RUNNERS s
#define LAPS 4

for (i = 0; i < RUNNERS; i++)
{
    for (j = 0; j < LAPS; j++)
    {
        printf("Enter the time of lap %d for runner %d in seconds: ", j+1, i+1)
        while (scanf("%d", &Runners[i][j]) != 1)
        {
            while ((ch = getchar()) != '\n') putchar(ch);
            printf(" is not an integer.\nPlease enter only an integer, such as 1, 5, or 9 : \n");
        }

        printf(" \n check 1 \n ");
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][j], Runners[i][j]);

    }

    printf(" \n check 1.5 \n ");

    for (j = 0; j < LAPS; j++)
        printf("\n %d minutes -- %d seconds \n", Runnerm[i][j], Runners[i][j]);
}

Although personally, I think that nonfunctionality is the least of your problems: your code is overcommented and soaking WET, and your output has way too many line breaks in it.

A: Fleshed-out the question code to an actual program:
#include <stdio.h>

int main()
  {
  int s = 3;
  int i;
  int j;
  int ch;
  int Runnerm[s][4]; //Runners / minutes
  int Runners[s][4]; //Runners / seconds

  for (i = 0; i < s; i++) // for i from 0 to Runners
     {
     for (j = 0; j < 4; j++) //for j from 0 to laps
        {
        printf("\nEnter the time of lap %d for runner %d in minutes: ", j+1, i+1); // prompt for time for each runner in minutes
        while (scanf("%d", &Runnerm[i][j]) != 1) // While scanf returns not equal to 1 (value parsed == TRUE)
           {
           while ((ch = getchar()) != '\n') putchar(ch); // check if ch=character, compare last entry (\n if character)
           printf(" is not an integer.\nPlease enter only an "); // print error
           printf("integer, such as 1, 5, or 9 : \n"); // cnt print error
           }

        printf("Enter the time of lap %d for runner %d in seconds: ", j+1, i+1); //prompt for time for each runner in seconds
        while (scanf("%d", &Runners[i][j]) != 1) // While scanf returns not equal to 1 (value parsed == TRUE)
           {
           while ((ch = getchar()) != '\n') putchar(ch); // check if ch=character, compare last entry (\n if character)
           printf(" is not an integer.\nPlease enter only an "); // print error
           printf("integer, such as 1, 5, or 9 : \n"); // cnt print error
           }

        printf("check 1 \n ");
        printf("\t %d minutes -- %d seconds \n", Runnerm[i][j], Runners[i][j]); // Correct Check!

        printf("check 1.5 \n ");
        printf("\t %d minutes -- %d seconds \n", Runnerm[i][0], Runners[i][0]); // Incorrect Check!

Added the following if(j > ... in order to not print uninitialized array values:
        if(j > 0) printf("\t %d minutes -- %d seconds \n", Runnerm[i][1], Runners[i][1]); // Incorrect Check!
        if(j > 1) printf("\t %d minutes -- %d seconds \n", Runnerm[i][2], Runners[i][2]); // Incorrect Check!
        if(j > 2) printf("\t %d minutes -- %d seconds \n", Runnerm[i][3], Runners[i][3]); // Incorrect Check!
        }
     }

  return(0);
  }

Then I compiled the code:
SLES11SP2:~/SO> gcc -Wall -o test *.c

And ran the code:
SLES11SP2:~/SO> ./test

Enter the time of lap 1 for runner 1 in minutes: 1
Enter the time of lap 1 for runner 1 in seconds: 2
check 1
   1 minutes -- 2 seconds
check 1.5
   1 minutes -- 2 seconds

Enter the time of lap 2 for runner 1 in minutes: 3
Enter the time of lap 2 for runner 1 in seconds: 4
check 1
   3 minutes -- 4 seconds
check 1.5
   1 minutes -- 2 seconds
   3 minutes -- 4 seconds

Enter the time of lap 3 for runner 1 in minutes: 5
Enter the time of lap 3 for runner 1 in seconds: 6
check 1
   5 minutes -- 6 seconds
check 1.5
   1 minutes -- 2 seconds
   3 minutes -- 4 seconds
   5 minutes -- 6 seconds

Enter the time of lap 4 for runner 1 in minutes: 7
Enter the time of lap 4 for runner 1 in seconds: 8
check 1
   7 minutes -- 8 seconds
check 1.5
   1 minutes -- 2 seconds
   3 minutes -- 4 seconds
   5 minutes -- 6 seconds
   7 minutes -- 8 seconds

Enter the time of lap 1 for runner 2 in minutes: 9
Enter the time of lap 1 for runner 2 in seconds: 10
check 1
   9 minutes -- 10 seconds
check 1.5
   9 minutes -- 10 seconds

Enter the time of lap 2 for runner 2 in minutes: 11
Enter the time of lap 2 for runner 2 in seconds: 12
check 1
   11 minutes -- 12 seconds
check 1.5
   9 minutes -- 10 seconds
   11 minutes -- 12 seconds

Enter the time of lap 3 for runner 2 in minutes: 13
Enter the time of lap 3 for runner 2 in seconds: 14
check 1
   13 minutes -- 14 seconds
check 1.5
   9 minutes -- 10 seconds
   11 minutes -- 12 seconds
   13 minutes -- 14 seconds

Enter the time of lap 4 for runner 2 in minutes: 15
Enter the time of lap 4 for runner 2 in seconds: 16
check 1
   15 minutes -- 16 seconds
check 1.5
   9 minutes -- 10 seconds
   11 minutes -- 12 seconds
   13 minutes -- 14 seconds
   15 minutes -- 16 seconds

Enter the time of lap 1 for runner 3 in minutes: 17
Enter the time of lap 1 for runner 3 in seconds: 18
check 1
   17 minutes -- 18 seconds
check 1.5
   17 minutes -- 18 seconds

Enter the time of lap 2 for runner 3 in minutes: 19
Enter the time of lap 2 for runner 3 in seconds: 20
check 1
   19 minutes -- 20 seconds
check 1.5
   17 minutes -- 18 seconds
   19 minutes -- 20 seconds

Enter the time of lap 3 for runner 3 in minutes: 21
Enter the time of lap 3 for runner 3 in seconds: 22
check 1
   21 minutes -- 22 seconds
check 1.5
   17 minutes -- 18 seconds
   19 minutes -- 20 seconds
   21 minutes -- 22 seconds

Enter the time of lap 4 for runner 3 in minutes: 23
Enter the time of lap 4 for runner 3 in seconds: 24
check 1
   23 minutes -- 24 seconds
check 1.5
   17 minutes -- 18 seconds
   19 minutes -- 20 seconds
   21 minutes -- 22 seconds
   23 minutes -- 24 seconds
SLES11SP2:~/SO>

It seem to work fine.


text:
Q: Send an email from Python Script I am trying to send an email from a python script. I am using this example but somehow the code keeps on running and does give back anything.
import smtplib

to = 'receiver'
gmail_user = 'username'
gmail_pwd = 'password'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()

I also enabled the allow less secure apps in google account. The error I get on interrupting this code is :
Traceback (most recent call last):
  File "/Users/kgandh003c/PycharmProjects/kandarp_exercise/kandarp.py", line 6, in <module>
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 316, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 291, in _get_socket
    return socket.create_connection((host, port), timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 575, in create_connection
    raise err
socket.error: [Errno 60] Operation timed out

Please let me know what could be wrong with this if anyone has faced this issue.
Thanks


text:
Q: How can I test that the default cache is working correctly? I changed "Enable External Cache" to "no" and flush the cache for a few mins to see if that effected loading times, but they were about the same. Is that an effective way of testing if the cache is being using?
(I know the cache files are being created ok, I can see them in FTP, I just suspect that they are not being used when loading the pages)

A: You are talking about the "External Full Page Cache", which is not what one would consider the default Magento cache. It has nothing to do with block caching and the other cache types in "System > Cache Management" which store cache files in var/cache.
The external full page cache only works if you are running the Zend Server with its cache extension. You won't see anything of it "in FTP".
Read more: http://merch.docs.magento.com/ce/user_guide/system-operations/cache-page-external.html

A: Use any page speed test to compare the loading time with and without cache on. If you use Firefox you can install the addon Firebug.

A: Could you output a dynamic timestamp on your page (with milliseconds) so that a refresh shows whether it's changed? You could use HTML comments (http://www.w3schools.com/tags/tag_comment.asp) if you don't want to publicly show any timestamps on your public site.
Be sure to use a Magento block that actually gets cached. The base template files, such as 1column.phtml, aren't part of the caching.


text:
Q: How to convert a coroutine to a list in Python? I use the aiohttp library, I receive data from the server in json format. Of all the data, I need only two fields that need to be displayed in a list. But when the function is called, the coroutine is returned. How do I get the list back?
async def request_geocoder_api(city):
url = f"https://nominatim.openstreetmap.org/search?city={city}&format=json"

async with aiohttp.ClientSession() as session:
    async with session.get(url) as response:
        response_json = await response.json
        latitude = response_json[0]['lat']
        longitude = response_json[0]['lon']
return [latitude, longitude]

Function call:
answer_list = await request_geocoder_api(answer)

Error:
TypeError: object method can't be used in 'await' expression

A: To get the awaitable coroutine, call the json() function. You are missing the () and just getting the function "pointer".
    response_json = await response.json()


text:
Q: use provider in two screens I have one problem with provider. I don't want to create global provider. I mean, creating provider for a particular screen. And I want to use same provider in two screen without creating anther instance.
for example.

my provider (for particular screen)

class ServiceScreenProvider with ChangeNotifier {
  final BuildContext _context;
  ServiceScreenProvider(this._context);
}

my first screen (for input)

class ServiceScreen extends StatefulWidget {
  const ServiceScreen({Key? key}) : super(key: key);

  @override
  _ServiceScreenState createState() => _ServiceScreenState();
}

class _ServiceScreenState extends State<ServiceScreen> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ServiceScreenProvider>(
      create: (ctx) => ServiceScreenProvider(ctx),
      child: Column(
        children: const [
          ServiceLogo(),
          FormWidget(),
        ],
      ),
    );
  }
}

here i am creating privider first time.
now I want to use this provider for anther screen

class ServiceDetailScreen extends StatefulWidget {
  const ServiceDetailScreen({Key? key}) : super(key: key);

  @override
  _ServiceDetailScreenState createState() => _ServiceDetailScreenState();
}

class _ServiceDetailScreenState extends State<ServiceDetailScreen> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: const [
        ServiceLogo(),
        FormWidget(),
      ],
    );
  }
}

text
I passing the context in constructor of ServiceDetailScreen screen while open the new sServiceDetailScreen. and I am using the ServiceScreenProvider.
Is any other way to get the instance of ServiceScreenProvider without passing the context in constructor.
thank you.