Q: How to remove table name prefix from aspnetboilerplate Core 2 I am trying to use aspnetboilerplate Core 2 in MVC (not Angular version).
After running Add-Migration and Update-Database, all of the created tables have Abp prefix.
Such as: AbpUsers, AbpRoles, AbpFeatures, ...
How can I remove Abp from table names?
I see some instructions but all of them are related to MVC5 version of aspnetboilerplate.

A: Answered in this issue: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2382

For Entity Framework Core
Override OnModelCreating and call modelBuilder.ChangeAbpTablePrefix. Example:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.ChangeAbpTablePrefix<Tenant, Role, User>(""); // Removes table prefixes. You can specify another prefix.
}

Remember to add using Abp.Zero.EntityFrameworkCore; to your code file in order to access ChangeAbpTablePrefix extension method.


Q: Remove a specific file name using htaccess I have not enough experience in writing rules in .htaccess.
My site url is like
http://exampletest.com/detail.php?i=my-url
I want to rewrite that url to
http://exampletest.com/my-url
What I have tried so far:
RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC]
RewriteRule ^ detail %1? [R=302,L]

That makes me able to access my site using:
http://exampletest.com/detail/my-url
But I want to omit  detail from url as well.

A: You should redirect internally as well so your code should looks like this :
RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC]
RewriteRule ^  %1? [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$    /detail.php?i=$1 [L]

A: Try this:
RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC]
RewriteRule ^ %1? [R=302,L]


Q: db2 for zos - prohibit changes in columns I would like to ask if there is a way to prohibit programs to change data in certain columns, at db2 level.
The problem is that I have some programs that change data in a group of tables but now I must not change data in some columns and I would like to know if there is a way that db2 can make that restriction.
I could change all the programs but would like to know if there is an easier way to block changes in a column.

A: You may create, let's say, BEFORE UPDATE OF COL1, ..., COLx trigger on this table with a SIGNAL statement inside.
Alternatively you may revoke the update privilege on this table from everyone and grant update on a subset of columns needed only.

A: Another option is to create a view with a subset of the columns you need to update. It may be a little more complex in case you need to rebind your program(s)


Q: Maxscript - align selection of meshs pivots perpendicular to mesh I have a 3D Globe and each of the countries are seperate meshes.
I am in the process of writing a script in 3D Max that automates centring the pivots.
for all in selection do(all.pivot = all.center)

This part is fine.  However I am bringing this into Unity and want to position a gameobject to each of these pivots.  To have this looking aesthetically pleasing the pivots of each mesh should be perpendicular.
Now I have been looking online for direction of solutions and I've been struggling - perhaps down to misunderstanding.
I thought getting numFaces and dividing it by 2 would give an appropriate position and rotation alignment but unfortunately the halfway polygon is not close enough to the mesh centre.
I was wondering is there a way to do this by selecting the closest polygon in the mesh to the overall pivot or maybe by selecting the centre polygon through an intersection with a newly created mesh.
Perhaps I am complicating this.
Would anyone have any input that could set me in the right direction?
Thank you.

A: Ok I figured it out after some headbutting.  The solution 'for me' was provided by the pivot point of the spherical globe's ocean.  By finding a question provided by Joker Martini to design a lookAt for each pivot of every mesh to look at a target (the pivot of the spherical world water that is centered)  and then flipping through rotation the pivot by learning about objectoffsetrot.
Here it is as it may be useful for someone.
for all in selection do(

    one =  all
    target = $'Globe Sea'
    pivotLookAt one two
    RotatePivotOnly one ((eulerangles 0 180 0) as quat)

    )

 fn pivotLookAt obj target =
 (
 ResetXForm obj
 old_tm = obj.transform
 obj.dir = normalize (target.pos - obj.pos)
 obj.objectOffsetRot = old_tm * (inverse obj.transform)

 )

 fn RotatePivotOnly obj rotation =
 (
 local rotValInv = inverse (rotation as quat)
 animate off in coordsys local obj.rotation *= RotValInv
 obj.objectoffsetrot*=RotValInv
 obj.objectoffsetpos*=RotValInv
 )

Happy to hear of any opinions out there on this for optimising or constructive  improving.
Thank you.


Q: MySQL Update and Select in one statement I am attempting to do an UPDATE and a SELECT in the same sql statement. For some reason, the below code is failing.
$sql = "UPDATE mytable SET last_activity=CURRENT_TIMESTAMP,
info1=:info1, info2=:info2 WHERE id = {$id};";

$sql .= "SELECT id, info1, info2 FROM myTable
WHERE info1 >=:valueA AND info2>:valueB;"

$stmt = $conn->prepare($sql);
$stmt->bindParam(":info1", $info1);
$stmt->bindParam(":info2", $info2);

$stmt->bindParam(":valueA", $valueA);
$stmt->bindParam(":valueB", $valueB);

$stmt->execute();

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($result);

QUESTION: what might I be doing wrong? I have been spending hours on this issue knowing that it's probably a small error right under my nose.

Edited:
I obtained this error message when loading the page that contains the php code:

Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]:
  General error' in ajaxCall.php:89 Stack trace: #0 ajaxCall.php(89):
  PDOStatement->fetchAll(2) #1 {main} thrown in ajaxCall.php on line 89

I am using ajax to call the php page that contains the above code, and when I load the php page from the browser, I get the above error message.
Line 89 is: $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

A: Since you are running two queries, you need to call nextRowset to access the results from the second one.
So, do it like this:
// code
$stmt->execute();
$stmt->nextRowset();
// code

When you run two or more queries, you get a multi-rowset result. That means that you get something like this (representation only, not really this):
Array(
    [0] => rowset1,
    [1] => rowset2,
    ...
)

Since you want the second set -the result from the SELECT-, you can consume the first one by calling nextRowset. That way, you'll be able to fetch the results from the 'important' set.
(Even though 'consume' might not be the right word for this, it fits for understanding purposes)

A: Executing two queries with one call is only allowed when you are using mysqlnd. Even then, you must have PDO::ATTR_EMULATE_PREPARES set to 1 when using prepared statements. You can set this using:
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

Alternatively, you can use $conn->exec($sql), which works regardless. However, it will not allow you to bind any data to the executed SQL.
All in all, don't execute multiple queries with one call.


Q: Form-Select saving more than 1 value I want to save two values to the DB (user id and user name) with only one form selection field. Is that even possible? This is what I got so far:
<%= f.collection_select(:user_id, User.where(brand: current_user.brand), :id, :name, {prompt:true}, {class: 'form-control'}) %>
That only saves the user_id (from :id) to the DB. How would you extend this to save also the user_name (from :name) to the DB?
<%= f.collection_select(:user_id, :user_name, User.where(brand: current_user.brand), :id, :name, {prompt:true}, {class: 'form-control'}) %>
does not work.
Many thanks in advance!

A: You really only need to save the user_id in order to reference all of the other attributes.
I like to use options_for_select and pass it a two dimensional array when I'm saving an id. The first value will be what the user sees. The second value will be what I actually save. In this case, I'm guessing that you'd like the user to see a username but you'd like to actually save the user_id.
That would look something like:
<%= f.select :user_id, options_for_select(User.choices) %>

and then in user.rb:
def self.choices
  choices = []
  User.find_each { |u| choices << [u.username, u.id] }
  choices
end

You don't need to save both values because you can always access any attribute saved on user with the id.
EDIT:
per your comment, you actually don't need a select box at all. Just set them in your orders controller create action:
 @order.username = current_user.username
 @order.user_id = current_user.id

 if @order.save
   # etc

Again, though, you don't really need to save the username if you have the user_id as a foreign key. With a foreign key you'll always be able to take an instance of order and say order.user.username and get the appropriate username for that user_id.


Q: Group array of object nesting some of the keys with specific names I have this array of objects, that I need to modify to make it easier the rendering.
const items = [
  {
    tab: 'Results',
    section: '2017',
    title: 'Full year Results',
    description: 'Something here',
  },
    {
    tab: 'Results',
    section: '2017',
    title: 'Half year Results',
    description: 'Something here',
  },
    {
    tab: 'Reports',
    section: 'Marketing',
    title: 'First Report',
    description: 'Something here',
  },
  ...
];

and I'm trying to modify it, grouping them by specific keys. The idea is to have this output. As you can see the names of the keys could be different than the actual names in the items. I think that makes a bit different from previous posts.
const output = [
  {
    tab: 'Results',
    sections: [
      {
         section: '2017',
         items: [ { 'item that belongs here' }, { ... } ],
      },
  },
  {
    tab: 'Reports',
    sections: [
      {
         section: 'Marketing',
         items: [ { ... }, { ... } ],
      },
  },
...
]

I tried using lodash.groupby, but it doesn't do exactly what i'm looking for.
Any idea about how to approach it?
Many thanks!!

A: This can be done with a clever combinartion of _.map and _.groupBy.

const items = [
  {
    tab: 'Results',
    section: '2017',
    title: 'Full year Results',
    description: 'Something here',
  },
    {
    tab: 'Results',
    section: '2017',
    title: 'Half year Results',
    description: 'Something here',
  },
    {
    tab: 'Reports',
    section: 'Marketing',
    title: 'First Report',
    description: 'Something here',
  }
];

function groupAndMap(items, itemKey, childKey, predic){
    return _.map(_.groupBy(items,itemKey), (obj,key) => ({
        [itemKey]: key,
        [childKey]: (predic && predic(obj)) || obj
    }));
}

var result = groupAndMap(items,"tab","sections",
                   arr => groupAndMap(arr,"section", "items"));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

A: You could use an object without additional libraries.
The object contains a property _ which keeps the nested arrays of the given nested group.

var items = [{ tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here' }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here' }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here' }],
    keys = { tab: 'sections', section: 'items' }, // or more if required
    result = [],
    temp = { _: result };

items.forEach(function (object) {
    Object.keys(keys).reduce(function (level, key) {
        if (!level[object[key]]) {
            level[object[key]] = { _: [] };
            level._.push({ [key]: object[key], [keys[key]]: level[object[key]]._ });
        }
        return level[object[key]];
    }, temp)._.push({ title: object.title, description: object.description });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q: Using JOIN (?) to intentionally return more results than rows Sorry for the length of detail required to ask the question.
There are four tables (related to research, not really having anything to do with a sporting facility). They're as follows:
1)  Let's say the first table is a list of tennis courts, and let's say there are hundreds of possibilities (not just indoor and outdoor).
-------------
TENNIS_COURTS
ID  Type
-------------
1   Indoor
2   Outdoor
…

2)  We want to note which day of the year they're available for rental. To prevent redundant rows, we can list individual days (e.g., just the 2nd day of the year, entered as "From:2", "To:2") or blocks (e.g., from the 24th day through the 25th day, entered as "From:24", "To:25"). In this example, the indoor court is the most available while the outdoor court has only two date ranges (obviously unrealistic for winter).
---------------------------
      DAYS_AVAILABLE
ID  ProductID  From    To
---------------------------
 1      1         2      2   《 Indoor
 2      2        24     25   《 Outdoor
 3      2       140    170   《 Outdoor
 4      1       280    300   《 Indoor
 5      1       340    345   《 Indoor
 …

3)  We also want to add a list of attributes which will grow quite long over time. So rather than incorporating these in a field rule, there's an Attributes table.
-----------------------
       ATTRIBUTES
ID  Attribute
-----------------------
 1  Age of Player
 2  Time of Day
 3  Outside Temperature
 …

4)  Lastly, we want to add a list of Considerations (or factors) to consider when renting a court. In this example, risk of injury applies to both indoor and outdoor courts, but visibility and temperature only applies to outdoor.
--------------------------------------------------
                  CONSIDERATIONS
ID  ProductID  AttributeID  Effect           Link
--------------------------------------------------
 1      1           1       Risk of injury   www…  《 Indoor
 2      2           1       Risk of injury   www…  《 Outdoor
 3      2           2       Hard to see      www…  《 Outdoor
 4      2           3       Gets cold        www…  《 Outdoor
 …

Utilizing the individual tables above, we'd like to create a consolidated saved view that contains at least one row for each date in the range, starting from the first day of the year (in which a court is available) through the last day of the year (for which a court is available). We also want to repeat the applicable considerations for each day listed.
Based on the data shown above, it would look like this:
----------------------------------------
           CONSOLIDATED VIEW
Day     Court     Consideration     Link
----------------------------------------
 2      Indoor                            《 from DAYS_AVAILABLE
 2      Indoor    Risk of injury    www…  《 from CONSIDERATIONS
24      Outdoor                           《 from DAYS_AVAILABLE
24      Outdoor   Risk of injury    www…  《 from CONSIDERATIONS
24      Outdoor   Hard to see       www…  《 from CONSIDERATIONS
24      Outdoor   Gets cold         www…  《 from CONSIDERATIONS
25      Outdoor                           《 from DAYS_AVAILABLE
25      Outdoor   Risk of injury    www…  《 from CONSIDERATIONS
25      Outdoor   Hard to see       www…  《 from CONSIDERATIONS
25      Outdoor   Gets cold         www…  《 from CONSIDERATIONS
…

We can then query the consolidated view (e.g., "SELECT * FROM CONSOLIDATED_VIEW where Day = 24") to produce a simple output like:
    Court:  Indoor
Available:  24th day
     Note:  Risk of injury (www…)
            Hard to see (www…)
            Gets cold (www…)

We want to produce the above shown example from a consolidated view because once the data is stored, it won't be changing frequently, and we very likely will not be querying single days at a time anyhow. It's more likely that a web client will fetch all of the rows into a large array (TBD based on determining the total size), and will then present it to users without further server interaction.
Can we produce the CONSLIDATED_TABLE solely with an SQL query or do we need to perform some other coding (e.g., PHP or NodeJS)?

A: The real deal in your question is: how can I get a list of the available days so I can join my other tables and produce my output, right? I mean, having a list of days, all you need to is JOIN the other tables.
As you have a limited list (days of the year), I'd suggest creating a table with a single column containing the 365 (or 366) days (1, 2, 3, ...) and JOIN it with your other tables. The query would be smtg similar to:
SELECT ... -- fields u want
FROM YOUR_NEW_TABLE n
JOIN DAYS_AVAILABLE D on (n.DAY between D.From and D.To)
JOIN ... -- other tables that you need info


Q: Bootstrap navbar stopping ng-view I'm trying to build a angular application with node.js and jade. Here's the relevant code
block body
 div(ng-controller='AppCtrl')
   .navbar.navbar-default.navbar-fixed-top(role='navigation')
     .container
       .navbar-header
         button.navbar-toggle(type='button', data-toggle='collapse', data-target='.navbar-collapse')
           span.sr-only Toggle navigation
           span.icon-bar
           span.icon-bar
           span.icon-bar
        a.navbar-brand(href='/') Halló {{name}}
       .navbar-collapse.collapse
         ul.nav.navbar-nav
           li.active
             a(href='/frettir') Fréttir
           li
             a(href='/dagskra') Dagskrá
           li
             a(href='/skaramuss') Skaramúss
   div(ng-view)

And then ng-view doesn't work. But when I comment out the navbar the ng-view works. What am I doing wrong?


Q: Unity 2D: Gravitational Pull I'm working on a small game: I want all GameObjects to be pulled into the middle of the screen where they should collide with another GameObject.
I tried this attempt:
using UnityEngine;
using System.Collections;
public class Planet : MonoBehaviour
{
    public Transform bird;
    private float gravitationalForce = 5;
    private Vector3 directionOfBirdFromPlanet;

    void Start ()
    {
        directionOfGameObjectFromMiddle = Vector3.zero;
    }

    void FixedUpdate ()
    {
        directionOfGameObjectFromMiddle = (transform.position-bird.position).normalized;
        bird.rigidbody2D.AddForce (directionOfGameObjectFromMiddle * gravitationalForce);
    }
}

sadly I can't get it to work. I've been told that I have to give the object that is being pulled another script but is it possible to do this just with one script that is used on the object that pulls?

A: So first you have a lot of typos / code that doesn't even compile.
You use e.g. once directionOfBirdFromPlanet but later call it directionOfGameObjectFromMiddle ;) Your Start is quite redundant.
As said bird.rigidbody2D is deprecaded and you should rather use GetComponent<Rigidbody2D>() or even better directly make your field of type
public Rigidbody2D bird;

For having multiple objects you could simply assign them to a List and do
public class Planet : MonoBehaviour
{
    // Directly use the correct field type
    public List<Rigidbody2D> birds;

    // Make this field adjustable via the Inspector for fine tuning
    [SerializeField] private float gravitationalForce = 5;

    // Your start was redundant

    private void FixedUpdate()
    {
        // iterate through all birds
        foreach (var bird in birds)
        {
            // Since transform.position is a Vector3 but bird.position is a Vector2 you now have to cast
            var directionOfBirdFromPlanet = ((Vector2) transform.position - bird.position).normalized;

            // Adds the force towards the center
            bird.AddForce(directionOfBirdFromPlanet * gravitationalForce);
        }
    }
}

Then on the planet you reference all the bird objects

On the birds' Rigidbody2D component make sure to set
Gravity Scale -> 0
you also can play with the Linear Drag so in simple words how much should the object slow down itself while moving
E.g. this is how it looks like with Linear Drag = 0 so your objects will continue to move away from the center with the same "energy"

this is what happens with Linear Drag = 0.3 so your objects lose "energy" over time


Q: I get 'NoneType' object is not callable when try to scale dataframe I have dataframe training_x like this:
>>> print(training_x)
         Pregnancies  Glucose  BloodPressure
762            9       89             62
127            1      118             58
564            0       91             80
375           12      140             82
663            9      145             80
..           ...      ...            ...
763           10      101             76
192            7      159             66
629            4       94             65
559           11       85             74
684            5      136             82
[576 rows x 3 columns]

When I run the following code on training_x dataframe to do StandardScale its values with below code:
from sklearn.preprocessing import StandardScaler

s_c = StandardScaler(with_mean=False)
testing_x = s_c.fit_transform(training_x)
test_x = s_c.transform(testing_x, dt)

I get below exception at the step when doing fit_transform
'NoneType' object is not callable

I don't know what is the issue, the dataframe doesn't had any none or empty values.


Q: How to avoid restart during development?
Possible Duplicate:
How do I clear all user defined symbols?

During package development things get messed up quite often. (especially when playing with notations)
Is there a simple way to reset MMA from within a notebook (Maple has "Restart")?

A: Like acl says, Quit[] kills the kernel, as does its synonym Exit[]. The complete internal state will be lost. When the MathKernel process isn't running, it is automatically restarted when you press Shift+Enter to evaluate an input line.

A: How about Quit[]/Exit[], which kills the kernel?


Q: Modal to interrupt form submission I have a form that I'm using to execute an account cancellation. I'm trying to display a pure CSS modal form to interrupt the form post so that the user can confirm the submission. So far, to achieve this, I have triggered the modal on form submission. Using the code below however the modal appears but does not interrupt the post, i.e. the post occurs.
Does anyone know how to get the modal to interrupt the submission until a further button within the modal is pressed to confirm the post?
Form:
    <form method='post' action='' onsubmit='return validate();'>
      <fieldset>
        <input type='hidden' id='cancel' name='cancel' value='cancel'>
        <input type='submit' id='submit' name='submit' value='submit'>
      </fieldset>
    </form>

Modal Javascript Trigger:
<script>
function validate() {
    var result = document.getElementById('myLink').click();
//    var result = confirm("Do you want to submit!");
    return result;
}
</script>

A: Change
<input type='submit' id='submit' name='submit' value='submit'>

to a type button
<input type='button' id='submit' name='submit' value='submit'>

Handle button click so it opens confirm or whatever confirmation thing you will be using.
And then, based on the result yes or no submit the form http://www.w3schools.com/jsref/met_form_submit.asp
The problem with your implementation it that
document.getElementById('myLink').click();

doesn't really return true or false, at least the result cannot be interpreted as what you expect


Q: java.lang.NoClassDefFoundError: com.google.firebase.FirebaseOptions after updating to Firebase on Play Store I updated my app to use Firebase, it was working perfectly on my device. However its crashing on many of my users devices
java.lang.NoClassDefFoundError: com.google.firebase.FirebaseOptions
at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1058)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5021)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4633)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4573)
at android.app.ActivityThread.access$1400(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5319)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)

This is the crash.
dependencies {
compile 'com.android.support:multidex:1.0.0'
 compile 'com.splunk.mint:mint:4.0'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:support-v4:24.0.0'
compile 'com.google.android.gms:play-services:9.0.2'
compile 'com.google.firebase:firebase-core:9.0.2'
compile "com.mixpanel.android:mixpanel-android:4.+"
compile('com.crashlytics.sdk.android:crashlytics:2.6.3@aar') {
    transitive = true;
}
}

This is my build.gradle.
Any pointers here?

A: It looks like the problem is with google play services version of your users. You can try:
private boolean checkGooglePlayServices() {
    final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (status != ConnectionResult.SUCCESS) {
        Log.e(TAG, GooglePlayServicesUtil.getErrorString(status));

        // ask user to update google play services.
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1);
        dialog.show();
        return false;
    } else {
        Log.i(TAG, GooglePlayServicesUtil.getErrorString(status));
        // google play services is updated.
        //your code goes here...
        return true;
    }
}

To verify google play services is available.

A: You need to lower the firebase version you have, they have some problems with the new versions on some devices.


Q: InvalidClientTokenId error aws when trying to get caller identity hi I am unable to run this command  aws sts get-caller-identity.
when I do  sudo nano ~/.aws/credentials I can only locate this
[default]
aws_access_key_id = my_id
aws_secret_access_key = my_secret_id

and after doing successful steps of command aws configure when I am doing aws sts get-caller-identity  I am getting this error
An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid.
any reason which could cause this ?

A: Sometimes this kind of issues are caused by another credential configuration.
Environment variables credential configuration takes prority over credentials config file.
So in case there are present the environment variables "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY" or "AWS_SESSION_TOKEN" these could generate issues if it were missconfigured or have been expired.
Try checking the env vars associated to AWS Credentials and removing them using the 'unset' command in linux.
Additionally, to remove env vars permanently you need to remove the lines related on configuration files like:

*

*/etc/environment

*/etc/profile

*~/.profile

*~/.bashrc

Reference:
Configuration settings and precedence

A: I had my default region disabled by default (eu-south-1), so I had to enable it via the Web console at first, then it worked.


Q: How to show column from another table in list_display without foreign key relation? I have these database relationships:

Now in my admin.py in the list_display I want to display the orders table plus the quantity row from order_items. To do so, I would use this sql query:
SELECT
    order_id, quantity
FROM
    orders
INNER JOIN
        order_items
    ON
        orders.order_id = order_items.order_id;

Now I don't know how to do this in the correct way with django without using a raw query.
So what do I add in the line
list_display = ('order_id')
in order to show the quantity row?

A: In order to get the quantity for order_items for a particular related order write the following code -
>>> from django.db.models import Sum
>>> order.order_items_set.aggregate(quantity=Sum('quantity'))

It will return you a dictionary like - {'quantity': 3}
Refer to here for more information about aggregations
In order to show it in your Admin for Order model -
class OrderAdmin(admin.ModelAdmin):
    list_display = ('id', 'user_id', 'status', 'created_at', 'get_quantity')

    class Meta:
        model = Order

    def get_quantity(self, obj):
        result = obj.order_items_set.aggregate(quantity=Sum('quantity'))
        return result.get('quantity',0)

    get_quantity.short_description = 'Quantity'

admin.site.register(Order, OrderAdmin)

Refer to here to know more about django-admin customizations.


Q: Cert Revoked when calling API to my server with self signed cert I'm using Axios in ReactJS to call my API that is hosted on the cloud with a self-signed certificate. The error for the request returns net::ERR_CERT_REVOKED.
I've added the self-signed code to my login keychain on MacOS running reactjs. But the cert is still getting revoked when I view the error on the logs on Chrome. On safari, the error is Failed to load resource: The certificate for this server is invalid.
try {
        const response = await axios.post(
            'https://1.1.1.1:3000/login',
            { withCredentials: true },
            { auth: apiAuth },
            { data: bodyFormData },
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
          )
          return response.data;
    } catch (error) {
        console.log(error);
    }

IP address has been changed for the question.
I've tried to use the following code in the Axios request but it doesn't help
const agent = new https.Agent({
  rejectUnauthorized: false
});

Expected the server to give a response but getting cert revoked as response.

A:
self-signed certificate ... net::ERR_CERT_REVOKED ... MacOS

You probably run into the new requirements for certificates in MacOS 10.15 and iOS 13 which seem to be enforced also for self-signed certificates. While you don't provide any details about your specific certificate I guess it is valid for more than 825 days. It might of course also be any other of the new requirements - see Requirements for trusted certificates in iOS 13 and macOS 10.15 for the details.


Q: Angular animations not working on Firefox due to CSP (with web-animations-js in polyfills.ts) I have issue applying Angular animations on Firefox (and Safari).
Yes I know that there are a lot of answers out there saying you can simply adding web-animations-js in polyfills.ts and it should do the trick. Unfortunately, it's not working in my case. For your context, this is the CSP policy that we're using default-src 'self'; img-src: *.
This is the animation code:
    animations: [
        trigger('toggleCommunicationPanel', [
            state('close', style({
                maxWidth: '64px',
                width: '4vw'
            })),
            state('open', style({
                width: '25vw',
                minWidth: '480px'
            })),
            transition('open=>close', animate('250ms')),
            transition('close=>open', animate('250ms'))
        ])
    ]

This is a chunk of polyfills.ts
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/**
 * Web Animations `@angular/platform-browser/animations`
 * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
 * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
 */
import 'web-animations-js';  // Run `npm install --save web-animations-js`.

I have configured Angular to extract scss into a single big .css file (to avoid CSP issue). Because by default, Angular CLI will not extract your styles into a stylesheet file, instead it will inject the styles into the DOM using <style> element, this is done for each component style. Hence, you will end up having a lot of <style> element in the <head> element. This of course violates the CSP rule above.
I've noticed that, in Chrome, IE and Edge, the css of the animation is extracted as expected, so it's working fine. However, in Firefox, it is injected using <style> element.
<style>@keyframes gen_css_kf_2 {
 0% {
  width: 492px;
  min-Width: 0px;
  max-Width: none;
  }
 100% {
  width: 4vw;
  min-Width: 0px;
  max-Width: 64px;
  }
}
</style>

So I suspect it is because of this, the animation will not work on Firefox.
The solution might be to change configuration so that Angular CLI will extract css for animations (even we're using Firefox or Safari).
This is the configuration for production, as you can see extractCss has been turned on.
"configurations": {
    "production": {
        "fileReplacements": [{
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
        }],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true,
        "budgets": [{
                "type": "initial",
                "maximumWarning": "2mb",
                "maximumError": "5mb"
            },
            {
                "type": "anyComponentStyle",
                "maximumWarning": "6kb",
                "maximumError": "10kb"
            }
        ]
    },
    "es5": {
        "tsConfig": "./tsconfig.es5.json"
    }
}

A: For the moment, I see no way of working around this issue. The only solution is to not to use Angular animation if CSP is set to prohibit inline style. Simply translating Angular animation code to css and use ngClass to achieve the same effect.


Q: mvc radiobuttonfor in editortemplate keyboard navigation does not set model Context:
Model generating some RadioButtonFor groupings as input to answer questions.
What is happening:
Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired.
Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load.
Here is the code that makes the radio group:
@model NexusPWI.ViewModels.Wizard.QuestionModel
@* Dynamically generate and model bind controls for QuestionModel *@
@{

                            @YesNoNAOptions.Yes.ToString().ToUpper()
                            @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" })

                            @YesNoNAOptions.No.ToString().ToUpper()
                            @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" })

                        @if (!Model.NaInvalid)
                        {

                                N/A
                                @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" })

                        }

                            @Model.Question

                    @Html.HiddenFor(x => Model.Question_IdentityMarker, new { @class = "Question_IdentityMarker" })

}

Here is an example of the html that is generated:

                    YES
                    <input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio">

                    NO
                    <input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio">

                        N/A
                        <input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio">

                    Do you charge sales tax?

            <input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden">

EDIT Adding onFocus & onBlur at request:
onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page.
function radiofocus(event) {
    // Get event object  if using Internet Explorer
    var e = event || window.event;
     // Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
    if (e.target) {
        var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
        e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
    } else {
        var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
        e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
    }
};
function radioblur(event) {
    // Get event object  if using Internet Explorer
    var e = event || window.event;
    var removeClass = focusClass("", "r").trim();
    // Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
    if (e.target) {
        e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
    } else {
        e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
    }
};

Why do the keyboard navigated changes not get back to the controller?
Anything to add to make this clearer?
Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.


Q: Syntax error: missing : after property (jQuery validate) I am building a set of jQuery validate rules to be used for a form prototype.
I am getting a JS error with my code. Chromes complains with the error
[14:30:27.722] SyntaxError: missing : after property id

at the location specified in the code comments.
here is the code:
    $.validator.addMethod("regex", function(value, element, regexpr) {
        return regexpr.test(value);
    }, "Entree invalide");

    $('#mainform').validate({
        rules: {
            form-nocivique: { //Chrome complains here
                required: true,
                digits: true
            },
            form-rue: "required",
            form-province: "required",
            form-codepostal: {
                required: true,
                regex: /([ABCEGHJKLMNPRSTVWXYZ]\d){3}/i
            }
        },
    });

Any idea why?

A: Your property names (some of them) are invalid identifiers.
You can quote it to fix the problem:
   rules: {
        "form-nocivique": { //Chrome complains here
            required: true,
            digits: true
        },

You can't use - in an identifier in JavaScript; it's a token (the "minus" operator).


Q: Testing @Retryable and @Recover methods in Spring Boot + Mockito For one class e.g. called Class A, I call an external api (with exceptions and I have mocked the class). In Class B, I have a method that calls Class A's method with the potential exceptions that could occur. Class B has the @Retryable and @Recover method. I have Class A as a mock object and Class B as a spy. When I mock Class A to throw an exception and I verify the times it has been called - I get the correct maxAttempts called. However, when I try to check and verify the method for recover or retryable I get:
UnfinishedVerificationException
..
Missing method call for verify....

Does anyone know if it is possible to verify these method calls?

A: Those methods can't be mocked because they they are final methods created by spring-retry using a CGLIB proxy.


Q: AttributeError 'module' object has no attribute 'decodebytes' I'm doing some processing on an image using OpenCV. Now I need to convert the base64 string to bytes. In Python-3.6 I could use base64.decodebytes but I can't find the alternate module in Python-2.7 . Is there any other alternative present in Python-2.7 ?
cvimg = cv2.imdecode(np_img_array, cv2.IMREAD_COLOR)
tmp_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = base64.b64encode(cv2.imencode('.jpg', tmp_img)[1])
img = base64.decodebytes(img)

NOTE: I'm using Python-2.7 as one of the module I'm using has not been converted to Python-3.6

A: Python 2 still has the base64 module built in.
Using
base64.standard_b64encode(s)
#and
base64.standard_b64decode(s)
#Where 's' is an encoded string

Should still work.


Q: What short movie was about humans having a 7-day lifespan? I've seen this short movie when I was a kid, but I don't remember the title. The story is that humans live underground, and have a lifespan of seven days.
They train a newborn on his first day and send him on a quest to open some door that will lift the curse.
On his way he battles with some monsters, plays some kind of chess with some other monster, and on the seventh day opens the door.
I remember that the short movie had animatronics, and even some CGI (this was around the late '80-ties, I think), but I can't find it anywhere.

A: Caution Dr. Who Spoilers:
The Dr. Who episode "The Doctors Daughter" plays with the concept of short lifespans. The entire history and mythology of the clones in that episode takes place over the course of 7 Days.

A: Ray Bradbury's short story was actually the basis for the short movie "Quest" (1983)--I found the film on YouTube--here's the links (it's in two parts):
http://www.youtube.com/watch?v=O0v9CrmEpT8
http://www.youtube.com/watch?v=st64go_iXnk&feature=related

A: I can't think of a particular film either, but there's an episode in Stargate: SG-1 where an alien scientist has altered the metabolism of an isolated pocket of human beings such that their lifespan is on the order of a hundred days. Not quite the seven, but still.

A: Could it possibly be Quest (1984)?

On a distant planet, descendants of a crashed spaceship are subjected
  to mysterious forces that cause them to age and die in just eight
  days..

A: I haven't heard of a movie that fits all your details, but the plot sounds a lot like Ray Bradbury's short story "Frost and Fire".


Q: Live local coding in IntelliJ Can I make IntelliJ re-compile and run when I change the code? All I could find was this infinitest plugin that specifically runs all tests.
Maybe something similar to http://www.romaniancoder.com/spring-boot-live-reload-with-intellij/


Q: default constructor for POCO entity in EF6 Code first approach I'm new in EF.
I'm making an app with EF6 Code First approach, I've made all my POCO entities to derive from a base class which define an Id.
What I don't know is how to declare the constructor for an entity that handles many to many relatioship.
For example:
I've got this entity:
 public partial class ArqAppRole
    {
        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ApplicationId { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int RoleId { get; set; }

        public DateTime SinceDate { get; set; }

        public DateTime? UntilDate { get; set; }

        public bool IsActive { get; set; }

        public virtual ArqApplication ArqApplication { get; set; }

        public virtual ArqRole ArqRole { get; set; }
    }

this was auto-generated by EF, what I want is to set it superclass to BaseEntity class that has a default constructor which sets it Id and I don't know how to handle ArqApplication and ArqRole properties and their propper Ids
My base class is:
public abstract class BaseEntity
    {
        private object _id;

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public object Id
        {
            get
            {
                return _id;
            }
            protected set
            {
                _id = value;
            }
        }

        protected BaseEntity() : this(null) { }

        protected BaseEntity(object id)
        {
            _id = id;
        }
}

A: You can leave the Id on the base class and in this use case you have to configure your one-to-one releshinship with Fluent API.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<ArqAppRole>()
              .HasRequired(s => s.Application)
              .WithRequiredPrincipal(ad => ad.ArqAppRole);
}

Fluent API will override your code first. But putting the Id in the base class is a bad practice and you have to find tricks everywhere. Just use the conventional way and use the EF as should be used.
More info: Code first self referencing foreign key (more than one)


Q: Remove 'spaces' between html tags in text from Excel In MsExcel/LibreOfficeCalc I have text like this:

Ways to stretch your budget

passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?

passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?

Instrument Rentals  passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?

passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?

How do I remove the text between html tags ?
Example:

content

content>

A: Just use regular expressions:
import re

result = re.sub('>\s*<', '><', text, 0, re.M)


Q: Is there a way to see if a statement is True during a give time? I have been playing around with the raspberry pi for a bit now and was trying to do a small project. I want my program to recognize when a button is pressed during a given time, i.e 1 seconds, then light up an LED.
My attempt was to see if the button was pressed (True), then make the program sleep for 2 seconds, and see if it is still true. This did work but not as efficiently I wanted it to. Is there a way to see if a statement remains True for a given time?
edit: more information about my setup and code.
I've dissembled an old flashlight, and taken the button from it. The Button does have a two metal pieces on the sides, that i have connected to one GND cable and the other the a 1k ohm resistor and a gpio cable. When i tried the following code:
import RPi.GPIO as gpio
from time import sleep

gpio.setmode(gpio.BOARD)
gpio.setup(19, gpio.IN)
gpio.setup(11, gpio.OUT)

try:
    while True:
        if gpio.input(19) == 1:
            sleep(0.05)
            if gpio.input(19) == 1:
                sleep(0.05)
                if gpio.input(19) == 1:
                    print("on")
                    gpio.output(11, True)
        else:
            print("off")
            gpio.output(11, False)
            sleep(0.1)

finally:
    print("\nInterrupted.\nCleaning code")
    gpio.cleanup()

Im aware of how gross this code looks, i'm terribly sorry. The reason for the triple if statement was to see if the code returns "on" in 3 different lines after another. This is because for some reason when the input value of the button "is set to" 0, it is actually jumping around 1 and 0 for some reason. This leads to it returning "On \nOff \nOn etc". My thought was if this prints "on" 3 times in a row then this must be on the stable side, so turn the LED on, else turn it off. This works but i'm not really happy with the code. If there was a way for me to see if it is "on" for a second or two then this must be the stable side and i can turn the LED on. And it would make my code in the future of making something similar, include a lot less if statements for a cleaner looking code.


Q: Zend Framework 3 AJAX responding data I try to do async contact form validation in ZF3 by using ajax.
Thats my ContactController
public function contactAction()
{
    $form = $this->form;
    $request = $this->getRequest();
    $response = $this->getResponse();
    $vm = new ViewModel(['form' => $this->form]);

    $form->setInputFilter(new ContactFormFilter());

    if (!$this->getRequest()->isPost())
        return new ViewModel(['form' => $this->form]);

    $data = $request->getPost();

    $form->setData($data);

        if (!$form->isValid())
        {
            $vm->setTerminal(true);
             return $response->setContent(\Zend\Json\Json::encode($form->getMessages()));
        }

}

and below is contact.phtml with jquery script.
$(function(){
    $("#foo").submit(function(event){
        event.preventDefault();

        $.ajax({
            url: '/kontakt',
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            async: true,
            data: ($("#foo").serialize()),
            success: function (data) {
                console.log(data);
                alert(data);
            },
            error: function (data) {
                console.log(data);

            }
        });
    })
})

Form has "foo" id;
The problem is, that when I submit I get respond like this each time: (its from console)
Object
-email :Object
-message :Object
-subject :Object
-personal-data :Object

and when I open for exmaple "message Object"
it shows me : isEmpty :" Field is required" even when the message field isn't empty!
Could anyone know what I am doing wrong?

A: Remove contentType: "application/json; charset=utf-8", to send the data as url encoded


Q: String variable is not returning properly in C I have been trying to make a function, is_isogram, return a value that is an alphabetized string. When I pass the value through the function from main, the variable to be returned is set to the correct value.
However, when I return the variable from the function, it does not return anything in main. Along with this, I get an error for unable to read memory when I initialize the variable to hold the return value in main.
#include <stdbool.h>
#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <Windows.h>
#include "isogram.h"

char  is_isogram(char phrase[])
{
    int i;
    for (i = 0; phrase[i]; i++) {
        tolower(phrase[i]);
    }

    if (phrase == NULL) {
        return false;
    }
    char temp;
    int count1;
    int count2;
    char *alphabet = (char *)malloc(sizeof(char) * (strlen(phrase) + 1));
    int n = strlen(phrase);
    for (count1 = 0; count1 < n - 1; count1++) {
        for (count2 = count1 + 1; count2 < n; count2++) {
            if (phrase[count1] > phrase[count2]) {
                temp = phrase[count1];
                phrase[count1] = phrase[count2];
                phrase[count2] = temp;
                alphabet = phrase;
                break;
            }
        }
    }
    return alphabet;
}

This function does not return the variable alphabet. I have been trying to use malloc and other techniques to return this local variable as a value. I wanted to use every character string as an array with "[]," however I would get errors about needing to initialize an array. The value returned is currently just a sizeable garbage value, however, when I step through the process of debugging, the variable alphabet is 'abb.'
int main() {
    char *bet = is_isogram("bab\0");
    if (bet == 'abb\0') {
        return 0;
    } else {
        return -1;
    }
}

The variable bet is throwing an error before even accessing the function. It tells me it was unable to read the memory and the value for bet is close to NULL for the remainder of the program.
In conclusion, the program is not giving returning a value of 'abb' when from the function locally, nor is it saving the variable in memory. It throws garbage into the variable, but the variable is killed, and a new variable cannot be adequately initialized in main.

A: There are multiple problems in your code:

*

*Function is_isogram() is defined as returning a char, it should instead return a string, hence type char *.

*is_isogram() attempts to modify the string pointed to by its argument. Since it is called with a string literal from main, this has undefined behavior, potentially a program crash.

*You allocate memory for alphabet, but you reset this pointer to phrase in the sorting loop.

*The comparison bet == 'abb\0' does not do what you think it does. bet should be a char * and you should use strcmp() to compare the string values.

Here is a modified version:
#include <ctype.h>
#include <string.h>
#include <stdio.h>

char *is_isogram(const char *phrase) {
    char *alphabet;
    int count1, count2, n;

    if (phrase == NULL)
        return NULL;
    alphabet = strdup(phrase);
    n = strlen(alphabet);
    for (count1 = 0; count1 < n; count1++)
        alphabet[count1] = tolower((unsigned char)alphabet[count1]);
    for (count1 = 0; count1 < n - 1; count1++) {
        for (count2 = count1 + 1; count2 < n; count2++) {
            if (alphabet[count1] > alphabet[count2]) {
                char temp = alphabet[count1];
                alphabet[count1] = alphabet[count2];
                alphabet[count2] = temp;
            }
        }
    }
    return alphabet;
}

int main(void) {
    char *bet = is_isogram("bab");
    if (strcmp(bet, "abb") == 0) {
        return 0;
    } else {
        return -1;
    }
}


Q: Update JTable programmatically I have this code to edit contents of already existing JTable:
DefaultTableModel items = new DefaultTableModel();
items.addColumn("qwe1");
items.addColumn("qwe2");
items.addColumn("qwe3");

items.addRow(new Object[]{1,2,3});

jTable1.setModel(items);

But nothing is displayed in the jTable... I can't quite figure out what I am doing wrong.
PS:
I know about these:
Updating JTable
Updating a JTable
JTable not updating
But that's not exactly what I am trying to do...


Q: Excel Solver: define constraint to be zero OR greater than I'm creating a model to optimize purchase orders.
The amount to be ordered must be greater than 500 or equal to zero.
How do I define such a constraint in Solver?
I tried a binary constraint and I also tried several different formulas but nothing seems to work.
Basically I need to be able to express OR in Solver, how do I do that?
EDIT: in the following link you may see the excel file I'm using:
Click here

A: So 0 is allowed, 1 is not allowed, 499 is not allowed, and 501 is allowed? Looks like a non-contiguous area. So it's not a pure optimization problem but also a kind of combinatorial problem. I'm afraid Solver can't handle this.
You should analyze two use cases separately:

*

*The amount is zero (fixed value, simple calculation);

*The amount is 500 or greater (optimize in Solver using constraint >=500);

and then compare these two cases using an IF formula.

EDIT:
I tried to use "binary" and "integer" constraints as Karl suggested but they did not work.

*

*Create a binary variable 0-1 and a continuous variable >=500, and then use IF to either copy the continuous variable or write 0 to the purchases value

*Create a binary variable 0-1 and a continuous variable >=500, and then calculate purchases as their product

*Create an integer variable >=499, and then use IF to replace 499 by 0 for the purchases value

In all cases, the result was often wrong and depended on initial conditions. Apparently Solver doesn't like such things.
Then I thought about applying my above proposal to all six purchase values, and optimizing them independently, for example, by optimizing the sum of costs for all months. But it turns out that they are not independent: the opening inventory depends on the previous month, and the optimal purchase for a month depends on whether a purchase was made in the previous month. So it't not possible to add a simple IF to each month.
The best I could do is the following.
I added a binary variable 0-1 and a continuous variable >=500, and calculated each month's purchases using IF. But I optimized only the continuous variables using Solver. The binary variables are a parameter. That is, we select the months when a purchase will be made, then use the Solver to calculate the values of these purchases, and then note the resulting total cost.
This should be repeated for all combinations of purchases and non-purchases. The number of these combinations is 26=64. But actually, if you don't purchase anything in January, you end up with a negative closing inventory which is not allowed. So there are only 32 valid combinations. I added formulae to calculate the binary values from the combination index, iterated the index 32 times, launched the Solver each time by hand and copied the results "as values only" for each combination.
The result is that minimum cost is 4 625,00 € and there are two combinations to reach this value.
Here is the file uploaded to Google Docs, with a Solver screenshot.
Launching Solver multiple times by hand is tedious, I believe it can be automated using macros.

A: Create a binary variable by adding a constraint stating that the value of the variable (in the objective function) is binary. The coefficient of this variable in the objective function must be 0.
then you add the following constraints as you would normally do:
-500B+X>=0 (never go under 500)
-MB+X<=0 (combined with previous constraint forces 0 when B is 0)
B= Binary variable1
M=Very large positive number (Greater than X can ever be)
X= continuous variable
[Edit]
I understand you want to do something like this (I also made some changes in your sheets file, but I cant share the excel file I worked on here):


Q: Runtime error 462 when saving word file from excel I have an excel sheet that is to create numerous word files while looping through the code. After pasting data från excel, the word files are to be named and saved to the hard drive. The first iteration goes perfect, but on the second I get a Runtime error 462 just before saving the word file.
Any suggestions? Thanks in advance!
Sub Kopiera_Excel_Till_Word(FilVag As String)

Selection.Copy

Dim appWord As Word.Application

Set appWord = New Word.Application

Dim FilNamnVag As String

With appWord

.Visible = True

.Activate

End With

appWord.Documents.Add

appWord.Activate

appWord.Selection.Paste

Application.CutCopyMode = False

With appWord

.Visible = True

.Activate

End With

'****It runs this far the second iteration, then I get Runtime error 462*****

ActiveDocument.SaveAs2 filename:= _
    FilVag, FileFormat:= _
    wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
    :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
    :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
    SaveAsAOCELetter:=False, CompatibilityMode:=15
Application.CutCopyMode = False
ActiveDocument.Close SaveChanges:=False

appWord.Quit

A: When working in VBA it pays to be specific rather than rely on objects such as ActiveDocument
Sub Kopiera_Excel_Till_Word(FilVag As String)

    Selection.Copy

    Dim appWord As Word.Application
    Set appWord = New Word.Application

    Dim FilNamnVag As String

    Dim docWord As Word.Document
    Set docWord = appWord.Documents.Add

    docWord.Range.Paste

    Application.CutCopyMode = False

    docWord.SaveAs2 Filename:= _
        FilVag, FileFormat:= _
        wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
        :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
        :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
        SaveAsAOCELetter:=False, CompatibilityMode:=15
    docWord.Close SaveChanges:=False
    appWord.Quit

    Application.CutCopyMode = False
End Sub


Q: How to reload content blockers while they are active? I have an app with several content blockers extension. Their configuration is fine and they act as they are supposed to.
However I need to call reloadContentBlocker(withIdentifier:completionHandler:) from SFContentBlockerManager when I've updated the filter lists for example.
Here is a code example (with NSLog for timestamp purposes below):
func reload(_ callback: @escaping((Bool) -> Void)) {
    NSLog("Reload start")

    let contentBlockersIdentifiers = ["com.aaa.bbb.ContentBlocker.ExampleA", "com.aaa.bbb.ContentBlocker.ExampleB", "com.aaa.bbb.ContentBlocker.ExampleC", "com.aaa.bbb.ContentBlocker.ExampleD", "com.aaa.bbb.ContentBlocker.ExampleE"]

    var failures: [String] = [String]()

    let dispatchSemaphore = DispatchSemaphore(value: 0)
    let dispatchQueue = DispatchQueue(label: "reload-queue", qos: .userInitiated)

    dispatchQueue.async {
        NSLog("Reloading content blockers")
        for aContentBlockerIdentifier in contentBlockersIdentifiers {
            NSLog("Reloading '\(aContentBlockerIdentifier)'")
            SFContentBlockerManager.reloadContentBlocker(withIdentifier: aContentBlockerIdentifier) { (error) in
                if let error = error?.localizedDescription {
                    NSLog("Failed to reload '\(aContentBlockerIdentifier)': \(error)")
                    failures.append(aContentBlockerIdentifier)
                } else {
                    NSLog("Successfully reloaded '\(aContentBlockerIdentifier)'")
                }
                dispatchSemaphore.signal()
            }
            dispatchSemaphore.wait()
        }

        callback(failures.isEmpty)
        NSLog("Reload end")
    }
}

This is what is prints:

16:41:43.391543+0200 Reload start
16:41:43.392003+0200 Reloading content blockers
16:41:43.392125+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleA'
16:41:50.010102+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleA'
16:41:50.010299+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleB'
16:41:50.351554+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleB': The operation couldn’t be completed. (WKErrorDomain error 2.)
16:41:50.351676+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleC'
16:41:50.493327+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleC': The operation couldn’t be completed. (WKErrorDomain error 2.)
16:41:50.493429+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleD'
16:41:50.631578+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleD': The operation couldn’t be completed. (WKErrorDomain error 2.)
16:41:50.631681+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleE'
16:41:50.718466+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleE': The operation couldn’t be completed. (WKErrorDomain error 2.)
16:41:50.718600+0200 Reload end

It apparently tries to do the reload one content blocker after another (as I wanted to do with the DispatchSemaphore). However after the first one succeeded the following are failures.
Now let's go and disable the Content Blockers in Setting App > Safari > Content Blockers and try again:

16:55:05.699392+0200 Reload start
16:55:05.700171+0200 Reloading content blockers
16:55:05.700564+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleA'
16:55:05.714444+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleB'
16:55:05.714909+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleB'
16:55:05.723056+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleB'
16:55:05.723343+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleC'
16:55:05.730565+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleC'
16:55:05.730775+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleD'
16:55:05.735733+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleD'
16:55:05.735841+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleE'
16:55:05.740758+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleE'
16:55:05.740865+0200 Reload end

Surprise... it works. But I would rather not ask my users to :

*

*go manually disable the Content Blockers in the Settings

*perform the update manually (while waiting to develop automatic refresh)

*go manually re-enable the Content Blockers in the Settings

I'm missing something somewhere (maybe a thread issue). Hopefully someone will be able to help!

A: Most likely, it means that you have rules that contains incorrect syntax or rules file have more the 50 000 rules.
Also the error can happened when you fill returningItems with nil context.completeRequest(returningItems: nil, completionHandler: nil) in your NSExtensionRequestHandling where context is NSExtensionContext


Q: Applying single symbology definition to multiple TIFFs in ArcMap? I have 143 separate TIFF files representing bathymetric data, all with different data ranges (high/low values). I want to create and apply a single symbology file having 6 levels corresponding to 6 discrete data ranges although individual TIFFs may only contain data with 1 or 2 of the 6 data ranges.
How do I do that in ArcMap 10.4?

A: To apply consistent symbology to each of your TIFF files, open the properties of one in your table of contents, go to symbology, apply manual classification, and define the break points for the 6 classes you want to apply to your dataset. ArcMap will allow you to create breaks that fall outside the range of individual TIFFs, so it's not a problem if they have different data ranges.

Once you have your symbology classes defined for the first TIFF, right click on the layer in your TOC and Save as Layer File. Then for each new TIFF, open up the Symbology tab in Properties and click the folder icon at the top right to import symbology (circled in image). Click the folder icon in the window that opens up (circled in image) to browse to the location of the layer file you saved in the previous step.

It will be a little tedious to do this for each of your 143 TIFFs, but it will definitely work.


Q: BeautifulSoup: how to get all article links from this link? I want to get all article link from "https://www.cnnindonesia.com/search?query=covid"
Here is my code:
links = []
base_url = requests.get(f"https://www.cnnindonesia.com/search?query=covid")
soup = bs(base_url.text, 'html.parser')
cont = soup.find_all('div', class_='container')

for l in cont:
    l_cont = l.find_all('div', class_='l_content')
    for bf in l_cont:
        bf_cont = bf.find_all('div', class_='box feed')
        for lm in bf_cont:
            lm_cont = lm.find('div', class_='list media_rows middle')
            for article in lm_cont.find_all('article'):
                a_cont = article.find('a', href=True)
                if url:
                    link = a['href']
                    links.append(link)

and result is as follows:
links
[]

A: Each article has this structure:

       ...

...

Simpler to iterate over the article elements then look for a elements.
Try:
from bs4 import BeautifulSoup
import requests

links = []
response = requests.get(f"https://www.cnnindonesia.com/search?query=covid")
soup = BeautifulSoup(response.text, 'html.parser')
for article in soup.find_all('article'):
    url = article.find('a', href=True)
    if url:
        link = url['href']
        print(link)
        links.append(link)
print(links)

Output:
https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara
...
['https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara', ...
'https://www.cnnindonesia.com/gaya-hidup/...ikut-penerbangan-gravitasi-nol']

Update:
If want to extract the URLs that are dynamically added by JavaScript inside the
 element then you must use something like Selenium that can extract the content after the full page is rendered in the web browser.
from selenium import webdriver
from selenium.webdriver.common.by import By

url = 'https://www.cnnindonesia.com/search?query=covid'
links = []

options = webdriver.ChromeOptions()
pathToChromeDriver = "chromedriver.exe"
browser = webdriver.Chrome(executable_path=pathToChromeDriver,
                           options=options)
try:
    browser.get(url)
    browser.implicitly_wait(10)
    html = browser.page_source
    content = browser.find_element(By.CLASS_NAME, 'media_rows')
    for elt in content.find_elements(By.TAG_NAME, 'article'):
        link = elt.find_element(By.TAG_NAME, 'a')
        href = link.get_attribute('href')
        if href:
            print(href)
            links.append(href)
finally:
    browser.quit()

A: Sorry, can't add comments not enough reputation.
I think this line:
for url in lm_row_cont.find_all('a'):
Should have the a tag as ''
Or you could use regex (skipping the above) to match the relevant items after grabbing a div.


Q: Monitor stays black after update (18.04) I started my laptop after 3 months off time and I have serious problems with my monitors. When I start my laptop plugged in to a docking station (with 2 monitors), all monitors stay black after login (even the integrated display). Restart is the only solution for now.
The only way I can work for a while is that I switch on my Laptop and then plugin to the docking station. But when I lock my screen (with "Windows" - oh, how I miss that!! - and "L"), I cannot work anymore with my laptop, since all displays stay black --> restart.
It's a DELL Laptop and DELL monitors (all same brand - Apple style). So, I'm wondering what went wrong in updates of the last three months.
Thanks for any hints!!

A: It sounds like you may have your power management set to sleep or turn hard disk off after a set time.  Dell used to have major issues with laptops resuming from sleep or hibernate, along with Toshiba laptops having similarly bad sleep/resume problems.


Q: How can I install only install_requires but not the lib with setup.py I want to make a docker image for my OpenERP.
I have modified OpenERP source code and I want to use the image to run it. So the image should be "libs ready" but have no OpenERP pre-installed on it.
The OpenERP project has a setup.py. I'd like to install all the libs specified by install_requires.
In other words, I'd like to run pip install -r requirements.txt if there it is. Unfortunately, the pip and apt-get just install quite different versions of libs. So it would be quite a lot of work to make the requirements.txt file myself, nor to maintain it.
What choices do I have?


Q: strcpy segfault copying file content to array This is my code
char url[MAX_WORD + 1];
char *urls[MAX_WORD + 1];
//char word[MAX_WORD + 1];

while(fscanf(fp, "%100s", url) == 1) {
    strcpy(urls[index], url);
    index++;
}

This is the error I'm getting on valgrind:

==43177== Process terminating with default action of signal 11 (SIGSEGV)
==43177==  Access not within mapped region at address 0x4844000
==43177==    at 0x4838DC8: strcpy (vg_replace_strmem.c:512)
==43177==    by 0x109898: generateInvertedIndex (invertedIndex.c:102)
==43177==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==43177==    by 0x109244: main (testInvertedIndex.c:23)

This is the content of the file it is copying from

nasa.txt
news1.txt
file11.txt
mixed.txt
planets.txt
file21.txt
info31.txt

I don't know how I am getting this error. I just want to copy the content of the file to an array of Urls. But it doesn't work.

A: You have an array of uninitialized pointers or null pointers if the array is declared in the file scope
char *urls[MAX_WORD + 1];

So this call
strcpy(urls[index], url);

invokes undefined behavior.
It seems what you need is to declare a two-dimensional array like for example
char urls[MAX_WORD + 1][MAX_WORD + 1];

Or in the original array allocate dynamically memory for the stored string. Something like
urls[index] = malloc( strlen( url ) + 1 );
if ( urls[index] != NULL ) strcpy(urls[index], url);
else /* some error processing */;


Q: A function for calculating velocity at several distances as you fall towards the earth's center Assuming there is no drag, no friction and no other objects affecting you. If you drop into the earth (through a tube). Your velocity will be 7900 m/s at the center of the earth according to http://hyperphysics.phy-astr.gsu.edu/hbase/mechanics/earthole.html
I assume that was the summation of all the velocity gained as gravitational force changes/decreases such as v= (9.8* first nano-meter traveled) + (9.7...*next nano-meter traveled)+...+(0*last nano-meters traveled)
I am sure there is a way to write a function using calculus (integration) that calculates your velocity at every point as you get closer. Lets approximate the earth's radius is 6,371 km and the acceleration due to gravity on the earth's surface is 9.807 m/s^2.
I will like a function that calculates your velocity at every given distance from the earth center as you fall.

A: This is a surprisingly simple thing to calculate.
It is a well known result that a consequence of the inverse square law is that there is no force inside a symmetrical hollow shell. This means that as the object falls into the hole, it will appear to be attracted by a sphere of decreasing radius - the mass outside "doesn't count."
The acceleration of gravity at the surface of a sphere of radius R (assuming uniform density $\rho$) is given by
$$\begin{align}
a &= \frac{GM}{R^2} \\
&= \frac{4G\pi R^3\rho}{3R^2} \\
&= \frac43\pi \rho G R\\
\end{align}$$
Where $G$ is the gravitational constant, and $R$ is the distance to the center of the earth. In other words - the acceleration is proportional to the distance to the center. The corollary is that an object dropped into a hole through the center of the earth will exhibit simple harmonic motion.
Let's do the math in more detail. Put the distance from the center as $r$, then the acceleration $\frac{d^2r}{dt^2}$ is given by
$$\frac{d^2r}{dt^2}=-\frac43 \pi \rho G r$$
(since the acceleration is pointing towards the center). This looks like the differential equation for simple harmonic motion:
$$\frac{d^2x}{dt^2} = -\omega^2 x$$
for which the solution (if velocity is zero at t=0, and amplitude is $x_0$) is
$$x(t) = x_0 \cos\omega t$$
and the velocity is
$$v(t) = -\omega x_0 \sin\omega t$$
It follows that we can write the expression for the velocity as a function of position by eliminating time:
$$\begin{align}\\
v(x) &= -\omega x_0 \sin \cos^{-1}\left(\frac{x}{x_0}\right)\\
&= -\omega x_0\sqrt{1-\left(\frac{x}{x_0}\right)^2}\end{align}$$
If we now substitute $\omega^2 = \frac43 \pi \rho G = \frac{g}{R}$ where $g$ is the gravitational acceleration at the surface of the earth, we get
$$\begin{align}\\
v(r) &= -\sqrt{\frac{g}{R}} R \sqrt{1-\left(\frac{r}{R}\right)^2}\\
&=\sqrt{\frac{g}{R}\left(R^2-r^2\right)}
\end{align}$$
If we substitute $r=R$, we get $v=0$ as expected; and when we put in $r=0$, we get $v = \sqrt{gR}$ = 7904 m/s using your values for $R$ and $g$. I think that's pretty close...

A: A curious result of the physics involved is that the dropped mass oscillating  up and down through the hole (say from North Pole to South Pole and back) would be matched exactly by a mass in a polar circular orbit at ground level.
Note that the max velocity in the answer above is the same as the circular orbital velocity.
If the object were dropped at the North Pole end, just as the satellite passed by, the two objects would cross the equator plane together and reach the South Pole together, and so on...


Q: Unable to login in Wordpress Admin on Local I am currently doing work for a live wordpress site and created a local installation using local by flywheel. When I use the admin credentials on the live site it logs in fine. However when I try to login on the local installation using the same credentials it says invalid username or password. I checked the users table in the sql database file and the username is in the table. How do i change the password on the local installation?
Edit: I created the local version of the website using the wp-content folder and a sql file of the exported databases from the live website. This was how I was instructed per local by flywheel's tutorial

A: https://wordpress.org/support/article/resetting-your-password/
This article will probably be your best bet. While it holds all the information. I highly recommend either going down the route of wp-cli or direct to the database.
For MySQL this will effectively change the password for you
UPDATE wp_options SET user_pass=MD5('newpass') WHERE user_login = <username>;

However, for wp-cli you can run this
wp-cli user update <username> --user_pass=<newpass>

Overall wp-cli is the best option because it has tooling to solve so many other problems too!
Good luck out there.

A: Below article will set a resetting your password, and you can go to wp_users and edit your account pass
https://wordpress.org/support/article/resetting-your-password/


Q: How use BufferList with SocketAsyncEventArgs and not get SocketError InvalidArgument? I can use SetBuffer with SocketAsyncEventArgs just fine.
If I try to use BufferList (after doing SetBuffer(null, 0, 0)) I always and immediately get SocketError InvalidArgument (10022) when I do SendAsync on the socket.
There are NO examples or documentation on how to use BufferList and what I am doing makes sense (to me anyway).
Can someone point out an example program or code snippet?
I'm tearing my hair out over this and don't have much left ...
Here is basically what I am doing (e is SocketAsyncEventArgs and lSocket is the same socket I use for SetBuffer which works)
// null the buffer since we will use a buffer list
e.SetBuffer(null, 0, 0);

// create a bufferlist
e.BufferList = new List<ArraySegment<byte>>();

// create the bufferlist with the network header and the response bytes
e.BufferList.Add(new ArraySegment<byte>(lTxBytes)); // add the 4 character total length
e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); // echo back the incoming sequence number
e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse)));

// *** the SendAsync always completes IMMEDIATELY (returns false) gets SocketError InvalidArgument (10022)

if (lSocket.SendAsync(e) == false)
{
      // data was already sent back to the client.
      AppSupport.WriteLog(LogLevel.Flow, "ProcessReceive had SendAsync complete synchronously (bytes transferred {0}).", e.BytesTransferred);
      ProcessSend(e);
}

A: The reason you are getting an exception is that under the hood the SocketAsyncEventArgs only uses the buffers present in the list at the time of setting the BufferList property.
Basically you are trying to send en empty buffer with the code :
e.BufferList = new List<ArraySegment<byte>>();
e.BufferList.Add(new ArraySegment<byte>(lTxBytes));
e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity)));
e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse)));

Instead try to do :
var list = new List<ArraySegment<byte>>();
list.Add(new ArraySegment<byte>(lTxBytes));
list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity)));
list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse)));
e.BufferList = list;

This behavior is not well documented at all and can only be understood by looking at the BufferList setter code in detail. Behind the scenes the SocketAsyncEventArgs has a WSABuffer array field(for interop with native code) where it copies and pins the byte arrays references when you set the BufferList. Since it is this WSABuffer[] that is sent to native code, that explains why your code throws an exception.


Q: Using Dictionaries for DataGridView in c# WPF I have a Dictionary that I want to display in DataGridView in a WPF App. I have another list with the column headers that I want. The list of doubles is 200 items long, and the headers 201 items long. Im wondering if there is an way of displaying them all in a table ?
Dictionary<string, List<double>> properties = new Dictionary<string, List<double>>();
List<string> gPropertyNames = new List<string>();

propertiesDataGrid.ItemsSource = properties;

Trying the ToArray() and Values.ToList() after the dictionary name are not helping me. All I see in the datagrid is two columns, Key and Value, with the value column saying (Collection).
I can manually set the column headers in XAML, but if there is an automated way, that would be awesome, especially if I need to change the headers.

A: do you need to use some methods specific to the dictionaries ? If not, here is my suggestion :

*

*Create a class which has a string and a double properties

*Create an ObservableCollection of that class

*Set that collection as the items source of your datagrid.

And that's it ! The headers will be the the name of the properties specified in your class, so easy to change afterward.
Hope it's help

A: Can bind rows to a collection but not columns
Create a class with 200 properties like Jacques answer
For the get you would return Value[0],  Value[1], ...
And it can be List
Or you could could build up the columns in code being and in the case you can bind to Value[0],  Value[1], ...


Q: How to reset postgres password I am on Windows 10 using WAMP, I added PostgreSQL and PhpPgAdmin, everything was working fine.  Today I can not log in to PostgreSQL through PhpPgAdmin or a php_pdo web app.
I tried editing pg_hba.conf in 2 locations c:\PostgreSQL\pg96\init\ and c:\PostgreSQL\data\pg96\ and changed the 'method' to trust as per many answers here, none of the CLI answers worked either.
I also restarted "WAMP" and even the whole computer, but no luck.
The default password worked before postgres and root but not now.
How do I reset the postgre password?
UPDATE
runing psql -U postgres returns;
psql: could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

contents of pg_hba.conf
# TYPE  DATABASE        USER            CIDR-ADDRESS            METHOD

# IPv4 local & remote connections:
host    all             all             127.0.0.1/32            trust
host    all             all             0.0.0.0/0               trust
# IPv6 local connections:
host    all             all             ::1/128                 trust

A: so after a lot more diging, it was not that the password was wrong, but for whatever reason PostgreSQL was not even running.  Windows is such a PITA!
in the end, running pg_ctl -D "C:\PostgreSQL\data\pg96" start from CMD got it going.  Now we will see if it starts tomorrow.... I miss my Unix Environment.
----- UPDATE -----
While the above code works, it is moving in the wrong direction.
goto Control Panel->Administrative Tools->Services and find 'PostgreSQL ...' in the list.  Right click and open Properties.
My Startup type: was set to 'Automatic' but it was not starting, I set it to 'Automatic (Delayed Start)' and now it is working, automagically!


Q: Same API returns different results I need some advice. I need to get data from API to display it on my application. The API is working both through Postman or through the browser, but when I upload the same code to the server, my API response returns NULL.
Here is the response I am getting with POSTMAN:

And here is the code I am using:
$ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://www.instagram.com/myexcellentuser/?__a=1');
  curl_setopt($ch, CURLOPT_AUTOREFERER, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_VERBOSE, 1);
  $file_data = json_decode(curl_exec($ch));
  curl_close($ch);
  var_dump($file_data);

And here is what this same code returns on the app hosted on a server:

I would be extremely grateful for the advice!
Thanks!


Q: How to populate an html page using data from a SQL table I want to populate an html page using data from a SQL table... data will be categorized based the year
Table will look something like this:
Year  Month   article
-----------------------
2010  Jan     Sql101
2010  Feb     Html101
2010  Mar     Smsht101
2011  jan     test101

I want the output to look something like this
2010
Jan sql101
Feb html101
Mar smsht101

2011
Jan test101

What is the easiest method to do this? I'm fairly new to ASP.NET.
Maybe using a repeater?


Q: How find this value$\sum\limits_{n=0}^{\infty}\frac{(2n)!}{(n!)^22^{3n+1}}$ show  that:
$$\sum_{n=0}^{\infty}\dfrac{(2n)!}{(n!)^22^{3n+1}}=\left(\frac{1}{2}\right)^{1/2}?$$
this sum is from  other problem,if I solve this,then the other problem is solve it

A: Hint: what is $\frac{f^{(n)}(0)}{n!}$ when $f(x) = \sqrt{1-x}$?

Compute the first terms:
\begin{align}
f^{(0)}(x) &= \sqrt{1-x}\\
f^{(1)}(x) &= -\frac 12 (1-x)^{-1/2} \\
f^{(2)}(x) &= -\frac 14 (1-x)^{-3/2} \\
\end{align}
The exponent of $1-x$ in $f^{(n)}(x)$ is obviously $1/2 - n$. So when you derivate,
the front factor gets multiplied by $1/2 - n$ to get $f^{(n+1)}(x)$, and by $-1 $ because of the chain rule.
Hence the result is
\begin{align}f^{(n+1)}(0)
&= 1\times \left(\frac 12 - 0\right) \times \left(\frac 12 - 1\right)
\times \dots \times \left(\frac 12 - n\right) \times (-1)^{n+1} \\
&= \frac{1\times 3 \times \dots \times (2n-1)}{2^{n+1}} (-1)^n  \times (-1)^{n+1}
= -\frac{1\times 3 \times \dots \times (2n-1)}{2^{n+1}}\\
&= -\frac{(2n)!}{2^{n+1} 2\times 4 \times \dots \times 2n} = -\frac{(2n)!}{2^{2n+1} n!} \end{align}
You can check that this is true for the first values:
\begin{align}
f^{(1)}(x) &= -\frac 12 = 1\times \frac 12 &\times (-1)^1 \\
f^{(2)}(x) &= -\frac 14 = 1\times \frac 12 \times \left(-\frac 12\right)
&\times (-1)^2
\end{align}
Then, you must show that the series is convergent for $x=\frac 12$ and you will get:
\begin{align}
\sqrt{1-x}
&= 1 + \sum_{n=0}^\infty \frac{f^{(n+1)}(0) }{(n+1)!}x^{n+1} \\
&= 1 - \sum_{n=0}^\infty \frac{(2n)!}{2^{2n+1} (n!)^2 (n+1)} x^{n+1}
\end{align}

Unfortunately, when evaluated in $\frac 12$, this does not make appear the desired sum, because of the factor $n+1$.
We can get rid of it just using tern by term derivation:
\begin{align}
-\frac 12 (1-x)^{-1/2}
&=- \sum_{n=0}^\infty \frac{(2n)!}{2^{2n+1} (n!)^2} x^n\\
 (1-x)^{-1/2}
&= \sum_{n=0}^\infty \frac{(2n)!}{2^{2n} (n!)^2} x^n
\end{align}
And now we get, with $x=1/2$:
$$
 \left(1-\frac 12\right)^{-1/2}
= \sum_{n=0}^\infty \frac{(2n)!}{2^{3n} (n!)^2}
$$

A: Hint: Using the generalized binomial theorem, we get
$$
\begin{align}
\left(1-x\right)^{-1/2}
&=1+\frac12x+\frac{\frac12\cdot\frac32}{2!}x^2+\frac{\frac12\cdot\frac32\cdot\frac52}{3!}x^3+\frac{\frac12\cdot\frac32\cdot\frac52\cdot\frac72}{4!}x^4+\dots\\[6pt]
&=\sum_{k=0}^\infty\frac{(2k-1)!!}{2^kk!}x^k\\
&=\sum_{k=0}^\infty\frac{(2k)!}{2^{2k}k!^2}x^k\\
\end{align}
$$
Plug in $x=\frac12$ and check the result.

A: This is a binomial series. Try to rewrite $\bigg(\dfrac12\bigg)^\tfrac12$ as $\bigg(1-\dfrac12\bigg)^\tfrac12$ or as $\Big(1+1\Big)^{^{-\tfrac12}}$. Then expand, simplify the general term, and see what happens. :-$)$


Q: Div "jumping" over page I made chat, and I am using ajax to refresh messages
function loadlink(){
    $('#porukice').load('messages.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 2000);

The div

Is moving over a page three times, then it stops but in odd place.
The first time element appear on page everything is fine, but after 2 ajax reloads it change place and stops, ajax still works.
I really can't figure out why is this happening.

That is how it moves with ajax reload.

A: You guys wont believe what was problem.
I just realized that because text input box had size="150"set, div element above jumped like insane. It's fixed now.


Q: ASP.Net url rewrite from ...pdf to ...aspx (IIS 7) I am trying to rewrite a url for a pdf to an aspx page it isn't working.
I doesen't see the request in my iis-log either.
<rewrite>
  <rules>
    <rule name="PDF" stopProcessing="true">
      <match url="PDF/(.*?)/(\d*)/(.*?.pdf)$" />
      <action type="Rewrite" url="SISPdf.aspx?id={R:2}&fn={R:1}" logRewrittenUrl="true" />
    </rule>
  </rules>
</rewrite>

An example:
http://myserver:8089/PDF/ABC/123/DEF_456.pdf

should be rewritten to:
http://myserver:8089/SISPdf.aspx?id=123&fn=ABC

With all my attempts I get HTTP 500 or HTTP 404.
Is it possible to debug rewrite-rules?
Edit:
At the old IIS (<= 6) i remember me that i must set the ISAPI-Filter for ASP/ASP.Net on PDF or Image file extension so the IIS know that he must handle this. Is there any equivalent?

A: Try changing
<match url="PDF/(.*?)/(\d*)/(.*?.pdf)$" />

to
<match url="PDF/(.*)/(\d*)/(.*).pdf$" />

Also, take off "stopProcessing='true'". Since you're doing a rewrite, you would actually like to continue processing.

A: To debug the URL Rewrite module, you can use the IIS 7.x "Failed Request Tracing," which, contrary to its name, can be used to trace successful as well as failed requests. This learn.iis.net page illustrates how to configure this and amount of detailed debugging information that is available.  You don't need to create a test page as suggested in the blog entry--- just jump to the "Configure Failed Request Tracing" section.


Q: Poligonos Google Maps Estou usando a API do google porém preciso de uma forma de fazer os poligonos de "tal" estado automatico sem ter que ficar fazendo isto manualmente.
Pois são vários estados que precisarei contornar, há alguma forma de fazer isto ?


Q: Непонятная ошибка в Mongoose Есть следующие модели:
var BookSchema = new mongoose.Schema({
  title: String,
  cover: String,
  author: String,
  about: String,
  genders: [{ type: mongoose.Schema.ObjectId, ref: 'Gender' }]
});
var GenderSchema = new mongoose.Schema({
  name: String
});

export default mongoose.model('Gender', GenderSchema);
export default mongoose.model('Book', BookSchema);

Думаю, следует отметить, что тут 2 файла обьеденены в 1 для более удобного чтения.
Я пытаюсь создать некоторые данные вот так:
Gender.find({}).remove()
  .then(() => {
    Gender.create({
      _id: '561fa3aac09d1fa4egender1',
      name: 'Фантастика'
    }, {
      _id: '561fa3aac09d1fa4egender2',
      name: 'Приключения'
    }, {
      _id: '561fa3aac09d1fa4egender3',
      name: 'Фэнтези'
    })
    .then(() => console.log('finished populating genders'));
  });

Book.find({}).remove()
  .then(() => {
    Book.create({
      title: 'Свободные (СИ)',
      cover: '/assets/images/placeholder.png',
      author: 'Анна Дарк',
      about: 'Криста любила, ждала и верила, но её любовь разбилась о предательство. Адриану не оставили выбора и он решился на отчаянный шаг',
      genders: ['561fa3aac09d1fa4egender1']
    }, {
      title: 'Энигматист (Дело о Божьей Матери)',
      cover: '/assets/images/placeholder.png',
      author: 'Крупенин Артур Борисович',
      about: 'Во второй книге, продолжающей серию детективов о Глебе Стольцеве, главному герою предстоит разгадать загадку, связанную с кражей из московских музеев двух очень похожих между собой икон.',
      genders: ['561fa3aac09d1fa4egender2']
    }, {
      title: 'Город Дождя(СИ)',
      cover: '/assets/images/placeholder.png',
      author: 'Манскова Ольга Витальевна',
      about: 'Не нашел достойного описания, поэтому будет просто текст рандомный =).',
      genders: ['561fa3aac09d1fa4egender3','561fa3aac09d1fa4egender2']
    })
    .then(() => console.log('finished populating books'));
  });

И получается ошибка в стиле:
Unhandled rejection ValidationError: CastError: Cast to Array failed for value "561fa3aac09d1fa4egender1" at path "genders"
В комментарии (в коде) выше стрелкой указано куда указывает валидатор. Может, кто сталкивался? Как это исправить? Может, я не так создаю ссылку на другой документ?

A: Надеюсь, поможет тому, кто будет гуглить этот вопрос. Поле _id должно задаваться как строка ХЕКС символов, размером 24. Хекс символы это 0..9, a..f.


Q: Theorem 3-8, Spivak Calculus on Manifolds This is a question about the proof of Theorem 3-8.

Theorem 3-8: Let $A$ be a closed rectangle and $f:A\rightarrow \mathbb R$ a bounded function. Let $B = \{x:f\hspace{1mm} \text{is not continuous at}\hspace{1mm} x\}$. Then $f$ is integrable if and only if $B$ is a set of measure $0$.

In the proof of this theorem, I do not understand the following quote:

If $\varepsilon>0$, let $P$ be a partition of $A$ such that $U(f,P)-L(f,P)<\frac{\varepsilon}{n}$. Let $\mathscr S$ be the collection of subrectangles $S$ of $P$ which intersect $B_{\frac{1}{n}}$. Then $\mathscr S$ is a cover of $B_{\frac{1}{n}}$. Now if $S\in \mathscr S$, then $M_S(f)-m_S(f)\geq \frac{1}{n}$.

The last inequality is what I do not understand. (From this post Error in theorem 3-8 “Calculus on manifolds”, I know that the inequality is true only if the interior of $S$ intersects $B_{\frac{1}{n}}$, but I am also not able to understand why this statement is true).

A: Let us recall the definitons:
$$B_{1/n}=\{x:\ o(f,x)\geq 1/n\} \\ o(f,x)=\lim _{\delta \to 0} \{ \sup _{|t-x|<\delta} f(t)- \inf _{|t-x|<\delta} f(t)\} \\ M_S(f)=\sup _{t\in S} f(t) \\ m_s(f)=\inf _{t\in S} f(t) $$
Let us moreover define for $\delta > 0$
$$U_\delta(x) = \{ t \in A \mid \lvert t - x \rvert < \delta \} \\o(f,x,\delta) =  \sup _{t \in U_\delta(x)} f(t)- \inf_{t \in U_\delta(x)} f(t).$$
Since $U_{\delta'}(x) \subset U_\delta(x)$ for $\delta' < \delta$, the function $\phi(\delta) = o(f,x,\delta) : (0,\infty) \to \mathbb R$ is decreasing with $\lim_{\delta \to 0} \phi(\delta) = o(f,x)$. In particular $o(f,x,\delta) \ge o(f,x)$ for all $\delta > 0$.
Assume that the interior of $S$ intersects $B_{1/n}$. Then there exists $x \in \operatorname{int} S$ such that $o(f,x) \ge 1/n$. Choose $\delta > 0$ such that $U_\delta(x) \subset S$. Then we get
$$M_S(f) - m_S(f) = \sup _{t \in S} f(t) - \inf_{t\in S} f(t) \ge \sup _{t \in U_\delta(x)} f(t)- \inf_{t \in U_\delta(x)} f(t) = o(f,x,\delta) \ge o(f,x) \ge 1/n .$$
Note that if $x \in S \setminus \operatorname{int} S$, then no $U_\delta(x)$ is contained in $S$ and our above argument breaks down.


Q: Android: How to change TextView periodically I'm recently working on a ShoutCast radio project. By using streamscrapper library I'm able to get the current song name and the current artist. Here is the problem. Once I open the app, it gets the song name and the artist name, however since then it does not update it. I tried to do it with timer but couldn't figure out.
And here is the method which I get the current song id:
private void initializeMediaPlayer() {

    player = new AACPlayer();
    scraper = new ShoutCastScraper();
    try {
        streams = scraper.scrape(new URI("http://sunucu2.radyolarburada.com:5000/"));
        String str = "asd";
        for (Stream stream: streams) {
            str = stream.getCurrentSong();
            currPlayView.setText("Now Playing: " + str);
        }
    } catch (ScrapeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

A: Maybe something like a runnable:
private Handler handler = new Handler();

handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);

private Runnable timeTask = new Runnable() {
    public void run() {
        //do stuff here

        //do it again soon
        handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);
    }
};

Before you leave make sure to stop the tasks:
handler.removeCallbacksAndMessages(null);

A: use a Handler to update it ,
Handler handler=new Handler();
int FREQ=5000; // the update frequency
handler.postDelayed(new Runnable()
        {
            public void run()
            {
                try
                {
                      String currStr;     // get your next song name
                      currPlayView.setText(currStr);
                }
                finally
                {
                    handler.postDelayed(this, FREQ);
                }
            }
        }, FREQ);


Q: Python Big O Determination I'm writing a program where I have to determine the growth rate of some code.
It might be run like this:
python3 my_program.py program_with_code_to_test

Here is where I am stuck:
The executable code accepts one int argument n. I can assume that "N0" (that is N subscript zero), is equal to 2^10 which is = 1024, and that every N is another power of 2.
So I know that the data size doubles every time. I need to determine how the growth rate in time changes.
SO if
some_code 1024 # 1024 being n

Takes 0.5 seconds to execute and
some_code 2048 # = 2^11

Takes 0.5 seconds to execute. Then I know that the growth rate is constant, i.e. the time it takes is irrelevant to the data size. One more example:
if
some_code 1024 # takes 0.5 seconds
some_code 2048 # takes roughly 2.0 seconds

then I need to output that the Big O time is quadratic (because the time it takes for the program to execute roughly quadruples as the data doubles).
So I think I need to do something like this:
before = time.process_time()
# whatever code I am passing in
after = time.process_time()
totalTime = after - before

But then how can I save totalTime so that I can see how totalTime changes as N (or the data size) doubles? How can I compare totalTime with the last totalTime? Or am I thinking about this the wrong way? Thanks for any help.
Note: Now I know I need to use subprocess.call for my code but I will figure that out later.