text:
Q: Regex range between 0 and 100 including two decimal I'm trying to figure out a regex expression that does the following. Both conditions below must be true:
1) Between 0 and 100 inclusive
2) Can contain one or two decimals only but not obligatory.
It should not allow 100.01 or 100.1
100 is the maximum value, or 100.0 or 100.00
I tried ^(100(?:\.00)?|0(?:\.\d\d)?|\d?\d(?:\.\d\d)?)$
which helped me in this question
but this does not accept 99.0 (one decimal).
I'm probably very close.

A: You just need to make each second decimal digit optional:
^(?:100(?:\.00?)?|\d?\d(?:\.\d\d?)?)$
              ^                 ^

See the updated regex demo. The 0(?:\.\d\d)? alternative is covered by \d?\d(?:\.\d\d)? one (as per Sebastian's comment)  and can thus be removed.
The ? quantifier matches one or zero occurrences of the subpattern it quantifies.
Pattern details:

*

*^ - start of string

*(?: - start of an alternation group:

*

*100(?:\.00?)? - 100, 100.0 or 100.00 (the .00 is optional and the last 0 is optional, too)

*\d?\d(?:\.\d\d?)? - an optional digit followed by an obligatory digit followed with an optional sequence of a dot, a digit and an optional digit.

*) - end of the alternation group

*$ - end of string.

BONUS: If the number can have either . (dot) or , (comma) as a decimal separator, you can replace all \. patterns in the regex with [.,]:
^(?:100(?:[.,]00?)?|\d?\d(?:[.,]\d\d?)?)$


text:
Q: How Hibernate/Jpa differs transient and detached instance/object? Actually these two are very good questions:
How Hibernate differs transient and detached entities?
Check for detached entity in Hibernate
I have actually read this many time, and check some posts in stackoverflow. A lot of answers are just copied from the persistence state definition without further explanation.
Let see the example below:
Person person = new Person();
person.id = 123; // 123 identifier exist in database.
person.name = "abc";

Hibernate doc state that for a transient instance, it must be:

*

*instantiated using the new operator

*has no persistent representation in the database

*no identifier value has been assigned

This doesn't look like a transient instance, it doesn't fulfill the definition.
It doesn't look like a detached instance too, obviously it is not detached from a closed session.
So, is this a transient or detached instance?

A: from Pro JPA 2.1 :

An entity has a persistent identity when there exists a representation of it in the data store; that is, a
  row in a database table. If it is not in the database, then even though the in-memory entity may have its identity set in
  a field, it does not have a persistent identity

So persistence id is only considered after the entity is already persisted, not by assigning a value to the id element

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exibir icone de carregamento sempre que clicarem em um link Sou novo em desenvolvimento Android e estou trabalhando em um aplicativo que carrega uma página da web através de um WebView. Porém, sempre que abro algum link dentro deste app, há um certo delay [o tempo da outra página carregar].
Gostaria que um icone de carregamento fosse exibido sempre que alguém clicasse em um link e que ele sumisse após o carregamento completo da página.
Meus códigos são estes:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ga.traveltreasure.traveltreasureparty.MainActivity"
    android:background="#000000">

<WebView
    android:id="@+id/ttpWv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    tools:layout_editor_absoluteX="8dp"
    android:background="#fc466b"
    app:layout_constraintBottom_toBottomOf="parent">
</WebView>

</android.support.constraint.ConstraintLayout>

-
package ga.traveltreasure.traveltreasureparty;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.StrictMode;
import android.support.annotation.StringDef;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {

    WebView webView;

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

        getSupportActionBar().hide();

        final WebView wv = (WebView) findViewById(R.id.ttpWv);

        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setSupportZoom(false);

        wv.loadUrl("LINK-PARA-A-PÁGINA");

        wv.setWebViewClient(new WebViewClient()
        {
            public void onReceivedError(WebView webview, int i, String s, String s1)
            {
                wv.loadUrl("file:///android_asset/error.html");
            }
        });

    }
}

A: No seu WebViewClient, implemente os métodos onPageStarted e onPageFinished, dessa forma:
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    // Aqui você EXIBE o ícone carregando, por exemplo um ProgressBar
}

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    // Aqui você ESCONDE o ícone carregando, por exemplo um ProgressBar
}

Espero ter ajudado!


text:
Q: how to do speech recognition for windows power-point I am undergraduate student and my third year computer mini project is the artificial intelligence. I am going to control windows power-point presentation using voice commands so here is the things i want.
windows power point slideshow should be in full screen when i say "full screen"  and it should go to next slide when i say "next".. when i say "back" previous slide should be displayed. only these thing i want but  I can't use windows speech recognition system in my project. so can anyone help me. i am using c#.

A: If you google for C# speech recognition library, you will find:
C# Speech Recognition
and
http://www.codeproject.com/Articles/483347/Speech-recognition-speech-to-text-text-to-speech-a
Once you are able to recognize speech, you can issue controls to PowerPoint. If you google "controlling PowerPoint programmatically", you will find
Controlling PowerPoint Slideshow
Those two things should get you going.


text:
Q: Storing json, jsonb, hstore, xml, enum, ipaddr, etc fails with "column "x" is of type json but expression is of type character varying" When using PostgreSQL to store data in a field of a string-like validated type, like xml, json, jsonb, xml, ltree, etc, the INSERT or UPDATE fails with an error like:
column "the_col" is of type json but expression is of type character varying

... or
column "the_col" is of type json but expression is of type text

Why? What can I do about it?
I'm using JDBC (PgJDBC).
This happens via Hibernate, JPA, and all sorts of other abstraction layers.
The "standard" advice from the PostgreSQL team is to use a CAST in the SQL. This is not useful for people using query generators or ORMs, especially if those systems don't have explicit support for database types like json, so they're mapped via String in the application.
Some ORMs permit the implementation of custom type handlers, but I don't really want to write a custom handler for each data type for each ORM, e.g. json on Hibernate, json on EclipseLink, json on OpenJPA, xml on Hibernate, ... etc. There's no JPA2 SPI for writing a generic custom type handler. I'm looking for a general solution.

A: Why it happens
The problem is that PostgreSQL is overly strict about casts between text and non-text data types. It will not allow an implicit cast (one without a CAST or :: in the SQL) from a text type like text or varchar (character varying) to a text-like non-text type like json, xml, etc.
The PgJDBC driver specifies the data type of varchar when you call setString to assign a parameter. If the database type of the column, function argument, etc, is not actually varchar or text, but instead another type, you get a type error. This is also true of quite a lot of other drivers and ORMs.
PgJDBC: stringtype=unspecified
The best option when using PgJDBC is generally to pass the parameter stringtype=unspecified. This overrides the default behaviour of passing setString values as varchar and instead leaves it up to the database to "guess" their data type. In almost all cases this does exactly what you want, passing the string to the input validator for the type you want to store.
All: CREATE CAST ... WITH FUNCTION ...
You can instead CREATE CAST to define a data-type specific cast to permit this on a type-by-type basis, but this can have side effects elsewhere. If you do this, do not use WITHOUT FUNCTION casts, they will bypass type validation and result in errors. You must use the input/validation function for the data type. Using CREATE CAST is suitable for users of other database drivers that don't have any way to stop the driver specifying the type for string/text parameters.
e.g.
CREATE OR REPLACE FUNCTION json_intext(text) RETURNS json AS $$
SELECT json_in($1::cstring);
$$ LANGUAGE SQL IMMUTABLE;

CREATE CAST (text AS json)
WITH FUNCTION json_intext(text) AS IMPLICIT;

All: Custom type handler
If your ORM permits, you can implement a custom type handler for the data type and that specific ORM. This mostly useful when you're using native Java type that maps well to the PostgreSQL type, rather than using String, though it can also work if your ORM lets you specify type handlers using annotations etc.
Methods for implementing custom type handlers are driver-, language- and ORM-specific. Here's an example for Java and Hibernate for json.
PgJDBC: type handler using PGObject
If you're using a native Java type in Java, you can extend PGObject to provide a PgJDBC type mapping for your type. You will probably also need to implement an ORM-specific type handler to use your PGObject, since most ORMs will just call toString on types they don't recognise. This is the preferred way to map complex types between Java and PostgreSQL, but also the most complex.
PgJDBC: Type handler using setObject(int, Object)
If you're using String to hold the value in Java, rather than a more specific type, you can invoke the JDBC method setObject(integer, Object) to store the string with no particular data type specified. The JDBC driver will send the string representation, and the database will infer the type from the destination column type or function argument type.
See also
Questions:

*

*Mapping postgreSQL JSON column to Hibernate value type

*Are JPA (EclipseLink) custom types possible?
External:

*

*http://www.postgresql.org/message-id/54096082.1090009@2ndquadrant.com

*https://github.com/pgjdbc/pgjdbc/issues/265

*http://www.pateldenish.com/2013/05/inserting-json-data-into-postgres-using-jdbc-driver.html


text:
Q: New ReactNative App Triggers Bundler Error: error Unexpected token = Every time I try to create a new React Native app, I receive this error in the Metro Bundler:
error Unexpected token =.
/Users/lukeschoenberger/repos/PodApp/node_modules/metro-cache/src/stores/HttpStore.js:31
  static HttpError = HttpError;
                   ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/Users/lukeschoenberger/repos/PodApp/node_modules/metro-cache/src/stores/HttpGetStore.js:12:19)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
info Run CLI with --verbose flag for more details.
Process terminated. Press <enter> to close the window

I'm running: npx react-native run-ios.
When I create the script, I create the app, I run: npx react-native init AppName
I'm on node v14.17.1.
The startup script also says: success Successfully launched the app on the simulator
What am I doing wrong?

A: I had the same error because I was running on node v10.
After switching to node v14.17.5 (npm v6.14.14) via nvm, it solved the issue.
Can you verify you are really on v14.17.1?

A: For me, I tried using node v14.17.5 and it didn't work. I removed:
static HttpError = HttpError;
static NetworkError = NetworkError;

from node_modules/metro-config/node_modules/metro-cache/src/stores/HttpStore.js
and it worked.
Can use patch-package as well:
yarn patch-package metro-config/metro-cache


text:
Q: jQuery replace text with alt tag when changing img I am basically trying to replace the text on the large img with the alt text of the thumbnail after replacing them using jquery but i cant make it work.
Here is my code

$(document).ready(function() {
  $('.small-img').click(function() {
    var imgsrc = $(this).attr('src');
    $('#lgPic').attr('src', imgsrc);
    $('#lgTitle').prop("alt");
  });
});

  Yellow PomPom Mum

I would appretiate all the help!, thanks

A: The $('#lgTitle').prop("alt"); will return the alt property of the element with id equal #lgTitle, in your case it will return nothing since the span has no alt.
If you want to change the text value you should use .text() function like :
$('#lgTitle').text($(this).attr('alt'));

Hope this helps.

A: Adding $('#lgTitle').text($(this).attr('alt')); to jQuery fixed the issue
HTML

      Yellow PomPom Mum

JQuery
$(document).ready(function() {
         $('.small-img').click(function() {
            var imgsrc = $(this).attr('src');
            $('#lgPic').attr('src', imgsrc);
            $('#lgTitle').text($(this).attr('alt'));
        });
    });


text:
Q: java.net.UnknownHostException: messages.cucumber.io can't solve in selenium bdd When running scripts in Selenium BDD, it was showing error like:
java.net.UnknownHostException: messages.cucumber.io

 Error:
    java.lang.RuntimeException: java.net.UnknownHostException: messages.cucumber.io
        at io.cucumber.core.plugin.MessageFormatter.writeMessage(MessageFormatter.java:36)
        at io.cucumber.core.eventbus.AbstractEventPublisher.send(AbstractEventPublisher.java:51)
        at io.cucumber.core.eventbus.AbstractEventBus.send(AbstractEventBus.java:12)

A: This has been resolved: after heavy debugging I have identified the root cause:-cucumber was trying to publish the report on cloud which is prevented by the infrastructure. resolved by putting "cucumber.publish.enabled=false" in the properties file. Thank you all for the support


text:
Q: How can I delete all the records which varchar contains any of a list of elements? I have Trees:
Trees(IDNodo, Path, color, ....)

IDMytable is a autonumeric (bigint) and path is a varchar(MAX) that contains the complete  route to a node in my tree.
I would like to delete all the nodes and subnodes, so I can do:
delete from trees where Path like '%[IDNode]'%

This delete the node and all the subnodes.
But if I want to delete all the nodes that have an specific property, I can get these nodes with this query:
select * from Trees where Color = 'Red';

This gives me all the nodes in all the trees that are red. I get many IDNodes. Then I want to delete all the subnodes of each red node.
delete from trees where Path like IN (select * from Trees where Color = 'Red');

If path is a long, for example, I can use "IN" but I don't know if there is an equivalent when the field is a varchar.
I would like to avoid the use of a recursive procedure.

A: You want to make your delete query like below
delete from trees where Path
IN (select Path from Trees where Color = 'Red');

But the above query is same as saying
delete from Trees where Color = 'Red';


text:
Q: EntityFramework - why so many entity keys? I've created an Entity Data Model from my SQL Server database. Despite only having one primary key in each of my tables, almost all of my properties are marked as Entity Keys. I can of course modify these, but can anyone tell me why this happens?

A: Most likely by default it has determined that the columns marked as keys make the entry unique. It will do this with imported views as well.
That said, I have imported table definitions with unique constraints and primary keys and have not seen this behavior.

A: Open the edmx file with the Xml editor (right click the Edmx file in the solution and select "Open with...). Once you do it you will see Xml comments in the file explaining why the existing key column could not be used. Oftentimes it is because the column is of a type that is not supported by EF (e.g. HierarchyId) so the column is not supported and therefore is excluded. This way you end up with a table without a key column and an artificial key will be created which, in such cases, consists of all columns of types that are valid types for key columns (e.g. columns of spatial types will be excluded from this list since they are not valid key columns is EF)


text:
Q: WPF Evento OnLoad Estoy empezando a aprender C# con WPF y acabo de empezar con mi primer apalicación "útil", pero me encuentro con un pequeño bloqueo. Agradecería un poco de orientación para entender cómo resolverlo y si estoy haciendo algo mal.
Tengo la siguiente clase (recortada para quitar lo que no se usa ahora):
class SubjectManager
{
    private string filePath = "preguntas.txt";

    public List<ListBoxItem> SubjectList = new List<ListBoxItem>();

    public TextBlock ouputTextblock = new TextBlock();

    public void getSubjectList()
    {
        StreamReader sr;
        string line;

        sr = File.OpenText(filePath);
        addSystemMessage("El archivo " + filePath + " se ha abierto correctamente en modo lectura");
        while ((line = sr.ReadLine()) != null)
        {
            addNewSubject(getSubject(line));
        }
    }

    private void addSystemMessage(string message)
    {
        ouputTextblock.Inlines.Add(new Bold(new Run("System: ")));
        ouputTextblock.Inlines.Add(new Run(message + "\n"));
    }
}

En la ventana tengo un Listbox y un TextBlock con lo siguientes eventos OnLoad:
private void ListBox_Loaded(object sender, RoutedEventArgs e)
    {
        SubjectManager mySubjectmanager = new SubjectManager();
        mySubjectmanager.ouputTextblock = TextBlock_Messages;
        mySubjectmanager.getSubjectList();
        SubjectsListbox.ItemsSource = mySubjectmanager.SubjectList;
    }

private void TextBlock_Messages_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock_Messages.Text = string.Empty;
    }

El objetivo era que cuando todo carga, el TextBlock se limpie con la instrucción TextBlock_Messages.Text = string.Empty y que posteriormente se vayan cargando los mensajes que vengan de la clase SubjectManager.
Pero el efecto que obtengo es el contrario, primero se cargan los mensajes y luego se limpia.
¿Hay alguna forma de ver/controlar el flujo de los eventos onLoad? Dicho de otro modo, forzar a que los controles se carguen en un orden deseado.
Muchas gracias.
Un saludo,

A: Posible solución:
Pasarlo todo al evento Loaded de la window
private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Clear textblock
        TextBlock_Messages.Text = string.Empty;

        // Create and fill subjectmanager
        SubjectManager subjectmanager = new SubjectManager();
        subjectmanager.ouputTextblock = TextBlock_Messages;
        subjectmanager.getSubjectList();
        SubjectsListbox.ItemsSource = subjectmanager.SubjectList;
    }


text:
Q: Information about gtalkservice I'm trying to find more information about keeping a open internet connections for push trough messages or data. I've read that the xmpp protocol could be suitable for this, and that it's replaced by the gtalkservice of android.
Unfortunately i have no be able to find more package information about com.google.android.gtalkservice on the internet.
Does anyone know where i can find this information?
Thanks.


text:
Q: Find $\sec \theta + \tan \theta$. If $\tan \theta=x-\frac{1}{x}$, find $\sec \theta + \tan \theta$.
This was the question ask in my unit test.
My Efforts:
$\tan^2 \theta=(x-\frac{1}{x})^2$
$\tan^2 \theta= (\frac {x^2-1}{x})^2$
Now we can use identity $\sec^2 \theta= 1 + \tan^2 \theta$.
But i am not able to get the answer using this.
I don't know the correct answer but I had got $2x\ or\ -\frac{2}{x} $, which was given wrong.

Also please tell me if there is better way to do this.

A: You have the core of it. You are given that $ \tan \theta = x - \frac {1}{x} $, and you know that $ \sec^2 \theta = 1 + \tan^2 \theta $. Since $ \tan^2 \theta = x^2 + \frac {1}{x^2} - 2 $, you have $ \sec^2 \theta = x^2 + \frac {1}{x^2} - 1 $.
Therefore, $ \sec \theta = \sqrt {x^2 - \frac {1}{x^2} - 1} $ and $ \tan \theta = x - \frac {1}{x} $, so the answer is $$ \sec \theta + \tan \theta = x - \frac {1}{x} + \sqrt {x^2 + \frac {1}{x^2} - 1}. $$ I am not sure why you are saying the answer is $ 2x $ or $ - \frac {2}{x} $.

A: As you have written $\sec^2 \theta = 1 + \tan^2 \theta$. From this you could get
$$ \sec \theta + \tan \theta = \pm \sqrt{1+\tan^2 \theta} + \tan \theta = \pm \sqrt{1 + \left( x - \frac{1}{x} \right)^2} + x - \frac{1}{x}.$$


text:
Q: enter next for iteration only when the last ajax request complete in javascript I have an array noti_array which has two elements, noti_array[0]='meghan&3', noti_arra[1]='tylor&5', the username and number concatenated by '&', in each iteration, I want to send the username to a ajax request
for(var i=0;i<noti_array.length;i++)
{

    var mesg_array = new Array();
    mesg_array=noti_array[i].split('&');
    who_sent=mesg_array[0]; //first iteration, meghan
    sent_num=mesg_array[1]; //3

    //send the user name to a ajax request
    $.ajax({
        url:'getLastCon.php',
        method:'post',
        data:{who_sent:who_sent},
        success:function(data){
          alert(who_sent);
          }
     });
 }

this code above would not alert meghan and tylor, instead, it alerts twice tylor, and if I use a 'break' after the ajax request, it would alert meghan once only, I think it's probably the loop enter the next iteration even the ajax request have not completed

A: It looks like who_sent could be a global variable. In that case, because of the asynchronous nature of your AJAX calls, the alert would trigger for the last assigned value of who_sent. Make who_sent a local variable or add another variable by adding var: var who_sent = mesg_array[0];.
Edit:
The above is wrong on how variables persist in a loop. I'm sorry for the inaccurate info. The following code will do what you want:
for( var i=0 ; i < noti_array.length ; i++ ) {

    var mesg_array = noti_array[i].split('&');
    who_sent = mesg_array[0]; //first iteration, meghan
    sent_num = mesg_array[1]; //3

    (function(who) {
        //send the user name to a ajax request
        $.ajax({
            url: 'getLastCon.php',
            method: 'post',
            data: { who_sent:who },
            success: function(data) {
                alert(who);
            }
        });
    })(who_sent);
}


text:
Q: Returning a value from an async call within a PCL I have a non PCL method that grabs data from a RESTful service which is then deserialised and returns the data back. It looks like this
    public WeatherData GetWeather
    {
        get
        {
            if (!ftrackData.Online)
                return new WeatherData();

            string param = string.Format("lat={0}&lon={1}&APPID={2}", AppDelegate.Self.Latitude, AppDelegate.Self.Longitude, AppDelegate.Self.WeatherID);
            var request = WebRequest.Create("http://api.openweathermap.org/data/2.5/forecast?" + param) as HttpWebRequest;
            request.Method = "GET";
            request.Accept = "application/json";
            request.ContentType = "application/json";

            string responseContent;
            try
            {
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
                var deserial = Deserialize<WeatherData>(responseContent);
                return deserial;
            }
            catch (WebException ex)
            {
                Console.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
                return null;
            }
        }
    }

(the data is coming from openweathermap)
I've moved this over to my PCL and come up with the following
    public WeatherData GetWeather
    {
        get
        {
            var param = string.Format("lat={0}&lon={1}&APPID={2}", App.Self.Latitude, App.Self.Longitude, App.Self.WeatherID);
            var request = WebRequest.Create("http://api.openweathermap.org/data/2.5/forecast?" + param) as HttpWebRequest;
            request.Method = "GET";
            request.Accept = "application/json";
            request.ContentType = "application/json";

            var Weather = new WeatherData();
            string responseContent;
            try
            {
                var asyncResult = request.BeginGetResponse(new AsyncCallback(s =>
                        {
                            var response = (s.AsyncState as WebRequest).EndGetResponse(s);

                            using (var reader = new StreamReader(response.GetResponseStream()))
                            {
                                responseContent = reader.ReadToEnd();
                            }
                            Weather = Deserialize<WeatherData>(responseContent);
                        }), request);
                return Weather;

            }
            catch (WebException ex)
            {
                Debug.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
                return Weather;
            }
        }
    }

The code builds without an issue, but is not awaiting before returning the weather data.
I've tried adding .AsyncWaitHandle.WaitOne() to the end of the BeginGetResponse but the Weather object is still returned before the call completes.
The return can't be added into the anonymous callback as the callback returns void.
I've also tried adding
if (asyncResult.IsCompleted)
   return Weather;

but this will no compile as not all paths return a value.
How can get the return not to return until Weather has been filled from within the anonymous call back?


text:
Q: Clone ScatterViewItem control in Surface Application I'm working on a Windows multitouch application using Surface 2.0 SDK.
I need to "clone" a control, in this specific case a ScatterViewItem, in which I've added a ElementMenu with a "CopyButton" with a Click event handler.
This is my ScatterViewItem:
<s:ScatterViewItem x:Name="PhotoPadSVI"  MinWidth="296" Background="Transparent" Style="{StaticResource ScatterViewItemStyle}">......</ScatterViewItem>

And this is the code that I used and that doesn't work:
void DocumentDuplicate_Click(object sender,  RoutedEventArgs e)
{
    ScatterViewItem swi = PhotoPadSVI; //error is already here cause I set it as the same, but I cannot found a ".Clone()" like method
    swi.Visibility = System.Windows.Visibility.Visible;
    swi.ZIndex = 100;
    swi.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;

    //sView.Items.Add(swi); cannot add to ScatterView cause swi is equal to PhotoPadSVI
}

Question: Do you know in which way could I replicate the ScatterViewItem?

A: You need to construct a new instance of ScatterViewItem. It should work if you set its Content the same as PhotoPadSVI's.
ScatterViewItem swi = new ScatterViewItem() { Content = PhotoPadSVI.Content };

If there is still error indicating you can't add the same item to ScatterView, you have to do from scratch, create the new ScatterViewItem's Content from code, this can be a lot more complicated if PhotoPadSVI's Content is a bunch of XAML code.
Also refer to this blog.


text:
Q: Django Celery cannot query postgres db inside task In my celery task I try to query my postgres db. But I always get following error:

task.py
@shared_task(bind=True)
def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list):
    print('Task ImportFiles started')
    myuser = User.objects.get(pk=user_id_list[0])
    print("USER:")
    print(myuser)

settings.py
INSTALLED_APPS = [
...
    'celery',
...
]
...
DATABASES = {
'default': {
     'ENGINE': 'django.contrib.gis.db.backends.postgis',
     'NAME': 'geodjango',
     'USER': 'postgres',
     'PASSWORD': 'postgres',
},
}

...

CELERY_BROKER_URL = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'

celery.py
# Default settings from celery tutorial:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geodjango.settings')
app = Celery('geodjango', broker='redis://localhost')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

Following easy scenario works:
If I change my task.py and execute just a simple for loop.
task.py
@shared_task(bind=True)
def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list):
    print('Task ImportFiles started')
    progress_recorder = ProgressRecorder(self)
    result = 0
    seconds = 10
    for i in range(seconds):
        print("for: " + str(i))
        time.sleep(1)
        result += i
        progress_recorder.set_progress(i + 1, seconds, description="Downloading")
    print("FOR LOOP FINISHED")
    return 'Task Complete'

Celery output:

So it looks like celery is working, but somehow I cannot make querys to my postgres db. I'm devolping currently on a windows machine... Can someone please help me?
Edit: I start celery with following commandline:
celery -A geodjango.celery worker --loglevel=info --pool=eventlet

A: I found a solution for windows:
I started my celery with following command:
celery -A geodjango.celery worker --loglevel=info --pool=eventlet

The problem seems the --pool=eventlet --> if I change pool to solo it works.
Following command works now and I can make my postgres queries.
celery -A geodjango.celery worker --loglevel=info --pool=solo

I'm not an expert, I think I saw --pool=eventlet in a tutorial so I used that. But with --pool=solo it works.
Here I found an article about the different pool options, maybe it also helps someone else: https://www.distributedpython.com/2018/10/26/celery-execution-pool/


text:
Q: Split by comma where not between ( and ) i've problem by using the preg_split method. I wanna split by comma but only if the comma isn't between ( and ).
For example:
id,user(id,firstname),image(id)

Should return:
0 => id
1 => user(id,firstname)
2 => image(id)

A: Quick and readable solution might be this:
<?php
function parse($str) {
    $str = preg_replace('~(\(.*?),(.*?\))~', '$1_#_PLACEHOLDER_#_$2', $str);

    $items = array();
    foreach (explode(',', $str) as $item) {
        $items[] = str_replace('_#_PLACEHOLDER_#_', ',', $item);
    };
    return $items;
}

var_dump(parse('id,user(id,firstname),image(id)'));

It could definitely be done with a single regex, but readability would be severely hurt.

A: You may want to try a parser-generator rather than a regex. I'm not familiar with the alternatives in PHP, but this answer indicates a couple alternatives.

A: I would suggest trying to find a parser instead, but it can be done using regular expressions.
Use the following regular expression: /\G(?> *)(?|([^,]*\((?>\\.|[^()])+\)[^,]*)|(?![()])([^,]+?)) *(?:,|$)/g
More details here: http://regex101.com/r/nA7dW5
Good luck

A: I have solved this issue using preg_split with PREG_SPLIT_DELIM_CAPTURE.
$tokens = preg_split('#(\,|\(|\))#', 'id,user(id,firstname),image(id)', PREG_SPLIT_DELIM_CAPTURE);

Returns:
["id", ",", "user", "(", "id", "firstname", ")", "image", "(", "id", ")"]

After that you can parse that array with a simple switch case.

A: The regex /(\([^()]+\))|([^,]+)/ will match everything, except the commas outside parentheses. Does it helps?


text:
Q: Python 3.6 - IndexError: list index out of range I understand that "list index out of range" means that I am trying to reference something that is outside of my list. However, I just can't seem to identify where I am doing this and how to fix it.
In my code I use a list of numbers from 1 to 39 (All Time) that I call "myranges". The numbers in this list represent a month and year starting in Nov 2014 and ending in Jan 2018. I then have other lists that help with my naming conventions that I zip with the "myranges" list.
This code has worked fine in the past when I run it for All Time, but now I only want to run it from Sept 2017 to Jan 2018 (35 to 39) and it gives me the Index Error.
Here is the full error:
cumulativepoints = "CumulativePatientVisits{0}_{1}_{2}".format(row[0], row[2], month_descr[myrange-1][1])

IndexError: list index out of range

Obviously, the error is coming from my naming convention, I assume the "month_desc" which is my zip list. However, whenever I print the "month_desc" it look correct to me.
Here is the month_desc printed out :
[(35, 'Sep2017', 'September', 9, 'Sep', 2017), (36, 'Oct2017', 'October', 10, 'Oct', 2017), (37, 'Nov2017', 'November', 11, 'Nov', 2017), (38, 'Dec2017', 'December', 12, 'Dec', 2017), (39, 'Jan2018', 'January', 1, 'Jan', 2018)]

Here is my full code. Could someone help me see what I'm doing wrong.
import arcpy
import datetime
from datetime import timedelta
import time

#Document Start Time in-order to calculate Run Time
time1 = time.clock()

#now = datetime.datetime.now()

arcpy.env.overwriteOutput = True

#Set the workspace
from arcpy import env
env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps10.gdb"

#Declare variables
fc = 'Open_GoHealth_Centers'
fields = ['USER_market_id','USER_GoHealth_ID','USER_GoHealth_Center_Name', 'USER_Opening_Date', 'USER_MonthsSinceFHOpening']
fieldname = 'USER_market_id'

#Define SQL clause statement
sqlclause = (None, 'Order By USER_market_id, USER_GoHealth_ID')

# loop through market
markets = [1000]

#lists that allow for A SPECIFIC month/year to be selected and named
myranges = [35,36,37,38,39]

monthyear = ['Sep2017','Oct2017','Nov2017','Dec2017','Jan2018','Feb2018','Mar2018','Apr2018','May2018','Jun2018','Jul2018','Aug2018','Sep2018','Oct2018','Nov2018','Dec2018','Jan2019','Feb2019','Mar2019','Apr2019','May2019','Jun2019','Jul2019','Aug2019','Sep2019','Oct2019','Nov2019','Dec2019','Jan2020','Feb2020','Mar2020','Apr2020','May2020','Jun2020','Jul2020','Aug2020','Sep2020','Oct2020','Nov2020','Dec2020','Jan2021','Feb2021','Mar2021','Apr2021','May2021','Jun2021','Jul2021','Aug2021','Sep2021','Oct2021','Nov2021','Dec2021','Jan2022','Feb2022','Mar2022','Apr2022','May2022','Jun2022','Jul2022','Aug2022','Sep2022','Oct2022','Nov2022','Dec2022','Jan2023','Feb2023','Mar2023','Apr2023','May2023','Jun2023','Jul2023','Aug2023','Sep2023','Oct2023','Nov2023','Dec2023','Jan2024','Feb2024','Mar2024','Apr2024','May2024','Jun2024','Jul2024','Aug2024','Sep2024','Oct2024','Nov2024','Dec2024','Jan2025','Feb2025','Mar2025','Apr2025','May2025','Jun2025','Jul2025','Aug2025','Sep2025','Oct2025','Nov2025','Dec2025']
monthname = ['September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',]
monthnum = [9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12]
monthabbr = ['Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
year = [2017,2017,2017,2017,2018,2018,2018,2018,2018,2018,2018,2018,2018,2018,2018,2018,2019,2019,2019,2019,2019,2019,2019,2019,2019,   2019,   2019,   2019,2020,2020,2020,2020,2020,2020,2020,2020,   2020,   2020,   2020,2020,2021,2021,2021,2021,2021,2021,2021,   2021,   2021,   2021,   2021,   2021,2022,2022,2022,2022,2022,2022,2022,2022,   2022,   2022,   2022,   2022,2023,2023,2023,2023,2023,2023,2023,2023,   2023,   2023,   2023,   2023,2024,2024,2024,2024,2024,2024,2024,2024,   2024,   2024,   2024,   2024,2025,2025,2025,2025,2025,2025,2025,2025,   2025,   2025,   2025,   2025]

month_description = zip(myranges,monthyear,monthname,monthnum,monthabbr,year)
month_descr = list(month_description)
print (month_descr)

#returns last day of each month
def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)

for market in markets:
    print (market)
    #Define WHERE clause statement
    whereclause = """{} = """.format(arcpy.AddFieldDelimiters(fc, fieldname)) + str(market)

    for myrange in myranges:
        print(myrange)
        #Cursor to create list of centers to loop through
        with arcpy.da.SearchCursor(in_table = fc, where_clause = whereclause, field_names = fields, sql_clause = sqlclause) as cursor:

            #Loop to run SummarizeWithin by center
            for row in (cursor):
                Set variables for SummarizeWithin
                #Specify type of summarization, either Blocks or ZIPS, as part of the polys argument
                polys = "Market{0}".format(row[0])+"Blocks"

                cumulativepoints = "CumulativePatientVisits{0}_{1}_{2}".format(row[0], row[2], month_descr[myrange-1][1])

                cumulativeoutFeatureClass = "CumulativeSumWithin{0}_{1}_{2}".format(row[0], row[2], month_descr[myrange-1][1])
                keepAll = 'ONLY_INTERSECTING'
                sumFields = [['USER_VisitCount', 'Sum']]
                addShapeSum = 'ADD_SHAPE_SUM'

#                    This If statement determines if the Opening_Date of the respective center is before the last day of the month being run.
#               If it is, the summarize-within is performed, if not, the feature class is skipped.
                year = month_descr[myrange-1][5]
                month = month_descr[myrange-1][3]
                if last_day_of_month(datetime.date(year, month, 1)) >= row[3].date():

                    arcpy.SummarizeWithin_analysis(in_polygons = polys, in_sum_features = cumulativepoints, out_feature_class = cumulativeoutFeatureClass, keep_all_polygons = keepAll, sum_fields = sumFields, sum_shape = addShapeSum)

                    #Print Results
                    print(row[2])
                    print(myrange)

                    print (arcpy.GetMessages())

#Document End Time
time2 = time.clock()

#Run time in second
runtime = (time2-time1)

print (str(timedelta(seconds=runtime)))

A: The problem has arisen due to cutting down the code to only work for a certain period.
Your problem reduces down to the following:
myranges = [35,36,37,38,39]

month_descr = [(35, 'Sep2017', 'September', 9, 'Sep', 2017), (36, 'Oct2017', 'October', 10, 'Oct', 2017),
              (37, 'Nov2017', 'November', 11, 'Nov', 2017), (38, 'Dec2017', 'December', 12, 'Dec', 2017),
              (39, 'Jan2018', 'January', 1, 'Jan', 2018)]

for myrange in myranges:
    month_descr[myrange-1][1]

Here you are looping through myranges. The first value is 35 which you use as an index in the list month_descr which has only 5 elements.
Your full code (1 to 39) works because your list would have 39 elements in and would produce no index error


text:
Q: I wrote an optimization model of a paper with imaginary data in AMPL but there is some problem in running in terms of one of constraints about Years All you need explain in question title. The mentioned Optimization model belong to a paper with same content but I tried to write the code and analyze what happen exactly through that. I will add the codes to have access to data and find out what is the problem when you are running that. I added the three segment of AMPL code down. Please help me with this.
MOD:

set O;
set J;
set Q;
set R; #use R instead of K because we have K in line 11 as parameter
set T;

param D {q in Q, t in T};
param K {o in O, q in Q};
param C {q in Q, j in J};
param S {r in R, q in Q};
param H {r in R, q in Q};
param F {q in Q};
param G {q in Q};
param B {q in Q};
param Delta;
param Omega;
param I;
param A;
param M;

var X {o in O, q in Q, j in J, t in T} binary;
var Z {o in O, q in Q, t in T} binary;
var P {q in Q, t in T} binary;
var Y {q in Q, t in T} binary;
var z {q in Q, t in T} binary;
var n {q in Q, t in T} integer >=0;
var m {q in Q, t in T} integer >=0;
var N {q in Q, t in T} integer >=0;
var Teta {q in Q, t in T} integer >=0;
var a {r in R, q in Q, t in T} integer >=0;
var b {r in R, q in Q, t in T} integer >=0;
var u binary;
var v binary;
var w binary;

minimize OF: sum {q in Q, j in J, o in O, t in T} C[q, j] * D[q, t] * X[o, q, j, t]
+ sum {o in O, q in Q, t in T} K[o, q] * Z[o, q, t]
+ sum {q in Q , t in T} N[q, t] * Delta
+ sum {t in T, q in Q} Omega * Teta[q, t]
+ sum {t in T, r in R, q in Q} S[r, q] * a[r, q, t]
+ sum {t in T, r in R, q in Q} H[r, q] * b[r, q, t]
+ sum {t in T, q in Q} F[q] * z[q, t]
+ sum {t in T, q in Q} G[q] * Y[q, t]
+ sum {t in T, q in Q} B[q] * P[q, t]
+ I * v + A * u;

subject to c1{q in Q , t in T}: sum {o in O} Z[o, q, t] = D[q, t];
subject to c2{o in O , q in Q , t in T}: sum {j in J} X[o, q, j, t] >= Z[o, q, t];
subject to c3{q in Q , t in T}: n[q, t]= n[q, t-1] + sum {r in R} a[r, q, t-1] + N[q, t] - sum {r in R} a[q, r, t-1];
subject to c4{q in Q , t in T}: m[q, t]= m[q, t-1] + sum {r in R} b[r, q, t-1] + Teta[q, t] - sum {r in R} b[q, r, t-1];
subject to c5{o in O , q in Q , t in T}: Z[o, q, t]<= n[q, t];
subject to c6{q in Q , t in T}: sum {o in O} X[o, q, 1, t]<= m[q, t];
subject to c7{t in T, r in R}: sum {q in Q} a[q, r, t]<= sum{q in Q} n[q, t-1]+ a[r, r, t];
subject to c8{r in R , t in T}: sum {q in Q} b[q, r, t]<= sum{q in Q} m[q, t-1]+ b[r, r, t];
subject to c91{o in O , q in Q , t in T}: X[o, q, 2, t-1]<= X[o, q, 2, t];
subject to c92{o in O , q in Q , t in T}: X[o, q, 3, t-1]<= X[o, q, 3, t];
subject to c10{q in Q , t in T}: sum {o in O} X[o, q, 2, t]- sum {o in O} X[o, q, 2, t-1]<= z[q, t];
subject to c11{q in Q , t in T}: sum {o in O} X[o, q, 3, t]- sum {o in O} X[o, q, 3, t-1]<= P[q, t];
subject to c12{q in Q , t in T , j in J}: X[3, q, j, t]- X[3, q, j, t-1]<= Y[q, t];
subject to c13: sum {t in T, q in Q} Z[4, q, t]<= M * u;
subject to c14: sum {t in T, q in Q} Z[5, q, t]<= M * v;
subject to c15{o in O , q in Q , t in T}: X[o, q, 1, t]<= M * (w-1);
subject to c16{q in Q , t in T}: Z[3, q, t]<= M * w;
subject to c17{q in Q , t in T}: Z[2, q, t]<= X[2, q, 1, t];

DATA:

set O := Treat1 Treat2  Treat3  Treat4  Treat5;
set J := Dewater1   Dewater2    Dewater3;
set Q := ArcticBay  Arviat  CambridgeBay    CapeDorse   ClydeRiver  GjoaHaven;
set R := ArcticBay  Arviat  CambridgeBay    CapeDorse   ClydeRiver  GjoaHaven;   #use R instead of K because we have K in line 15 as parameter
set T := Year1  Year2   Year3   Year4   Year5;

param D :
    Year1   Year2   Year3   Year4   Year5 :=
ArcticBay       0   1   0   1   0
Arviat          1   0   0   1   1
CambridgeBay    1   0   0   1   1
CapeDorse       1   0   1   1   1
ClydeRiver      1   1   0   1   0
GjoaHaven       0   0   1   0   1 ;

param K :
    ArcticBay   Arviat  CambridgeBay    CapeDorse   ClydeRiver  GjoaHaven :=
Treat1  4051    4221    6477    5205    6443    4088
Treat2  6758    4012    4994    5437    6215    6267
Treat3  5162    4051    6755    6742    6589    4139
Treat4  6556    5094    5963    6043    5745    5428
Treat5  5289    6050    5144    4456    6474    4432 ;

param C :
            Dewater1    Dewater2    Dewater3 :=
ArcticBay       56299   32825   11894
Arviat          5977    15550   5958
CambridgeBay    20654   28654   19782
CapeDorse       3073    35237   33822
ClydeRiver      19218   48466   34032
GjoaHaven       23650   23304   42540 ;

param S :
    ArcticBay   Arviat  CambridgeBay    CapeDorse   ClydeRiver  GjoaHaven :=
ArcticBay       0   1359    1480    1458    1728    849
Arviat          2863    0   1229    1873    2353    2731
CambridgeBay    1821    1972    0   1772    1680    2726
CapeDorse       2754    2219    1817    0   1266    2814
ClydeRiver      1216    2632    2527    2782    0   949
GjoaHaven       1229    1238    2605    1060    2673    0;

param H :
    ArcticBay   Arviat  CambridgeBay    CapeDorse   ClydeRiver  GjoaHaven :=
ArcticBay       0   2269    1497    1218    2290    2344
Arviat          1424    0   1123    2494    2107    1114
CambridgeBay    2452    2365    0   1924    1292    1722
CapeDorse       1799    2003    2071    0   1216    1150
ClydeRiver      1322    1097    1827    1259    0   1191
GjoaHaven       1163    1444    2085    2398    1308    0;

param F :=
ArcticBay       1981
Arviat          1845
CambridgeBay    1529
CapeDorse       1721
ClydeRiver      1778
GjoaHaven       1802;

param G :=
ArcticBay       8639
Arviat          8829
CambridgeBay    11737
CapeDorse       8167
ClydeRiver      8573
GjoaHaven       10890;

param B :=
ArcticBay       6427
Arviat          9508
CambridgeBay    6661
CapeDorse       8016
ClydeRiver      6196
GjoaHaven       8359;

param Delta := 15000;
param Omega := 12000;
param I := 20000;
param A := 17000;
param M := 100000000;

RUN:
reset;

option solver CPLEX;

model SM.mod;

data SM.dat;

solve;

display X, Z, P, Y, z, n, m, N, Teta, a, b, u, v, w>b.out;

A: You got an error on constraint collection c3 because you are trying to do aritmetic calculations with values of set T, when in fact set T contains only strings (Year1, Year2, etc).
For instance, you wrote n[q, t-1], where t is in T. But what is 'Year1'-1 is not a valid AMPL expression. Other constraint collections have the same problem.
You could simply change the data of set T to be 1 2 3 4 5. But then you would run into other problems, because 1-1 is 0, and n[q,0] does not exist. You have to work on your formulation.
View project on PIFOP


text:
Q: Solving the recurrence relation $T(n) = (T(\sqrt{n}))^2$ I am stuck on this one recurrence relation, trying to find the asymptotic upper bound, and I have done it in two ways with two different answers, but I think they are both wrong.
Recurrence: $T(n) = (T(\sqrt{n}))^2$
Firstly, I tried guessing $O(n^2)$, therefore:
$T(n) = (\sqrt{n^2})^2 = n^2$ which is $\in O(n^2)$
So $T(n) = O(n^2)$ ?
Then I tried another way, assuming $n = 2^k$ for some k. Then,
$T(2^k) = (T(2^{k/2}))^2 = T(2^k)$ (Can you do that? I don't think so?)
If so, then since $n = 2^k$ that means $k = log(n)$, so finally:
$T(n) = 2^{log(n)}$ ?
Any advice on how I could go about this would be very much appreciated!


text:
Q: python smtp receipt confirmation DSN I am dealing with sporadic non-delivery of emails sent using python2.7.6 from a linux cluster to internal email recipients whose addresses are known to be valid. Since the originating code used the deprecated syntax of cat <file> | mailx -s <subject> <recipient> to generate a cmd for submission as a subprocess(cmd, shell=True), I have some working amended code-in-progress using smtp as below.
import smtplib
from email.mime.text import MIMEText
def emailer(from_addr, to_addr, subj, email_body):
    if not os.path.isfile(email_body):
        msg = MIMEText(email_body)
    else:
        with open(email_body, 'rb') as FHrb:
            msg = MIMEText(FHrb.read())
    msg['Subject']=subj
    s = smtplib.SMTP('localhost'); s.set_debuglevel(True)
    try:
        s.sendmail(from_addr,
               ','.join(to_addr) if isinstance(to_addr, list) else to_addr.split(','),
               msg.as_string())
    except Exception as e:
        print e

    s.quit()

When called this code returns to console the verbosity below (specific details masked by  to protect the innocent & reduce post size)
send: 'ehlo <localhost>.<localdomain>\r\n'
reply: '250-<localhost>.localdomain\r\n'
reply: '250-PIPELINING\r\n'
reply: '250-SIZE 10240000\r\n'
reply: '250-VRFY\r\n'
reply: '250-ETRN\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250-8BITMIME\r\n'
reply: '250 DSN\r\n'
reply: retcode (250); Msg: <localhost>.localdomain
PIPELINING
SIZE 10240000
VRFY
ETRN
ENHANCEDSTATUSCODES
8BITMIME
DSN
send: 'mail FROM:<SENDER> size=4178\r\n'
reply: '250 2.1.0 Ok\r\n'
reply: retcode (250); Msg: 2.1.0 Ok
send: 'rcpt TO:<me@my_email_address>\r\n'
reply: '250 2.1.5 Ok\r\n'
reply: retcode (250); Msg: 2.1.5 Ok
send: 'data\r\n'
reply: '354 End data with <CR><LF>.<CR><LF>\r\n'
reply: retcode (354); Msg: End data with <CR><LF>.<CR><LF>
data: (354, 'End data with <CR><LF>.<CR><LF>')
send: 'Content-Type: text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\nSubject: subject supplied\r\n\r\n\r\n<CONTENT REMOVED>.\r\n'
reply: '250 2.0.0 Ok: queued as 7548F12004F\r\n'
reply: retcode (250); Msg: 2.0.0 Ok: queued as 7548F12004F
data: (250, '2.0.0 Ok: queued as 7548F12004F')
{}

The trailing empty {} indicates success. Which is confirmed by the maillogs:
Feb  1 11:02:06 <localhost> postfix/smtpd[19642]: 7548F12004F: client=localhost[127.0.0.1]
Feb  1 11:02:06 <localhost> postfix/cleanup[18681]: 7548F12004F: message-id=<20170201110206.7548F12004F@<localhost>.localdomain>
Feb  1 11:02:06 <localhost> postfix/qmgr[2243]: 7548F12004F: from=<ngsservice@<localhost>.localdomain>, size=4685, nrcpt=1 (queue active)
Feb  1 11:02:06 <localhost> postfix/smtp[19867]: 7548F12004F: to=me@my_email_address, relay=<our ip address>[<our ip address>]:25, delay=0.5, delays=0/0.01/0/0.48, dsn=2.6.0, status=sent (250 2.6.0 <20170201110206.7548F12004F@<localhost>.localdomain> [InternalId=32804943] Queued mail for delivery)
Feb  1 11:02:06 <localhost> postfix/qmgr[2243]: 7548F12004F: removed

However I get the exact same return if I pass an entirely invalid email address (one which when tested from e.g. Outlook returns a non-delivery receipt).
Console output indicates the system is capable of DSN. Running the debug command sendmail -bv <me@my_email_address> returns the console message Mail Delivery Status Report will be mailed to <me>, and the maillog has DSN entries:
Jan 26 08:34:38 <localdomain> postfix/pickup[16208]: 83BC11200A5: uid=<my_uid> from=<me>
Jan 26 08:34:38 <localdomain> postfix/cleanup[8341]: 83BC11200A5: message-id=<20170126083438.83BC11200A5@<localdomain>.localdomain>
Jan 26 08:34:38 <localdomain> postfix/qmgr[2243]: 83BC11200A5: from=<me@<localdomain>.localdomain>, size=316, nrcpt=1 (queue active)
Jan 26 08:34:38 <localdomain> postfix/smtp[8343]: 83BC11200A5: to=<me@my_email_address>, relay=<our ip address>[<our ip address>]:25, delay=0.06, delays=0.03/0.01/0.01/0.02, dsn=2.1.5, status=deliverable (250 2.1.5 Recipient OK)
Jan 26 08:34:38 <localdomain> postfix/cleanup[8341]: 8F0591200A7: message-id=<20170126083438.8F0591200A7@<localdomain>.localdomain>
Jan 26 08:34:38 <localdomain> postfix/bounce[8344]: 83BC11200A5: sender delivery status notification: 8F0591200A7
Jan 26 08:34:38 <localdomain> postfix/qmgr[2243]: 83BC11200A5: removed
Jan 26 08:34:38 <localdomain> postfix/qmgr[2243]: 8F0591200A7: from=<>, size=1988, nrcpt=1 (queue active)
Jan 26 08:34:38 <localdomain> postfix/local[8345]: 8F0591200A7: to=<me@<localdomain>.localdomain>, relay=local, delay=0.02, delays=0/0.01/0/0.01, dsn=2.0.0, status=sent (delivered to mailbox)
Jan 26 08:34:38 <localdomain> postfix/qmgr[2243]: 8F0591200A7: removed

So the system appears to be capable of DSN Delivery Status Notification which would appear a good way fwd but I need to help on how to implement this. This is a new area for me so explicit details would be great. Many thanks


text:
Q: Can't include / use inAppBrowser in phonegap I've taken a look at the other questions but none of the solutions worked
Here is my line of code:
cordova.InAppBrowser.open(url, target, options);

Here is the error:
cordova is not defined (or InAppBrowser is not defined if I remove cordova in the code)
Here are my config.xml includes:
(...)
<gap:plugin name="org.apache.cordova.inappbrowser"  />
(...)
<access origin="*"/>
 <feature name="InAppBrowser">
  <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
</feature>
<feature name="InAppBrowser">
    <param name="ios-package" value="CDVInAppBrowser" />
</feature>
(...)

I have done nothing more. I have not installed via cordova plugin (...) command on Windows 10 because 'cordova' is not recognized as an internal or external command, operable program or batch file. in the command line interface. I have only installed Phonegap. I think I understand what I am missing but I do not understand how I should do about it in windows. Can someone help me get there? Tyvm! :)

A: I use it and did something like this.
    var ref = window.open('http://mylink.com','_blank','location=yes','closebuttoncaption=Return');

Here's a reference:
https://cordova.apache.org/docs/en/2.9.0/cordova/inappbrowser/inappbrowser.html


text:
Q: Unable to access tables written to duckdb when starting new R session (but .duckdb file is not empty) I am having trouble with Duckdb (through R) since I have changed computer and reinstalled all of my software.
I have a local duckdb connection through which I am writing datasets (with DBI). For example:
path_db <- "~/data/duckdb/pmeasyr.duckdb"
connection_db <- DBI::dbConnect(duckdb::duckdb(), path_db)
DBI::dbWriteTable(connection_db, "mco_22_ium", struct )

which then does appear among my list of tables
> dbListTables(connection_db)
 [1] "mco_22_ium"

I am then accessing them in R through dplyr.
dplyr::tbl(conn_serveur, "mco_22_ium")

I used to easily access the tables I had written to my connection. Now, the tables keep « disappearing » every time I restart my R session. I do see that the size of my local duckdb connection is constant or increasing when writing new tables (over 16 000 000 Ko at the moment). But with each new session, the commands:
path_db <- "~/data/duckdb/pmeasyr.duckdb"
connection_db <- DBI::dbConnect(duckdb::duckdb(), path_db)
dbListTables(connection_db)

Keep returning :
character 0

And trying to reach the tables directly with
dplyr ::tbl(connection_db, "table")

I always get the error message.
« Error: rapi_prepare: Failed to prepare query SELECT *
FROM table AS "q01"
WHERE (0 = 1)
Error: Catalog Error: Table with name table does not exist! »

Every time I reload the tables into my duckdb connection, I am able to access them, collect them, etc., until I close the R session. Once I reopen it, the tables are lost again.
I haven't find any similar question reported online...
So far, I have tried :

*

*uninstalling DBI, duckdb, dplyr,

*deleting the .duckdb file to start one from scratch

*changing the path to the duckdb .duckdb file

*updating R,

*uninstalling and reinstalling R

My sessionInfo :
R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.utf8  LC_CTYPE=French_France.utf8    LC_MONETARY=French_France.utf8
[4] LC_NUMERIC=C                   LC_TIME=French_France.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] magrittr_2.0.3          openxlsx_4.2.5          referime_0.1.0          rAphpQueries_0.0.0.9000
 [5] testthat_3.1.4          ggplot2_3.3.6           dplyr_1.0.9             pmeasyr_0.2.9
 [9] duckdb_0.4.0            DBI_1.1.3               RPostgres_1.4.4

loaded via a namespace (and not attached):
 [1] pkgload_1.3.0     tidyr_1.2.0       vroom_1.5.7       bit64_4.0.5       jsonlite_1.8.0    gsubfn_0.7
 [7] brio_1.1.3        assertthat_0.2.1  blob_1.2.3        cellranger_1.1.0  yaml_2.3.5        remotes_2.4.2
[13] sessioninfo_1.2.2 pillar_1.8.0      RSQLite_2.2.15    lattice_0.20-45   glue_1.6.2        chron_2.3-57
[19] colorspace_2.0-3  pkgconfig_2.0.3   devtools_2.4.3    haven_2.5.0       purrr_0.3.4       scales_1.2.0
[25] processx_3.7.0    tzdb_0.3.0        tibble_3.1.7      generics_0.1.3    tictoc_1.0.1      sqldf_0.4-11
[31] sjlabelled_1.2.0  usethis_2.1.6     ellipsis_0.3.2    cachem_1.0.6      withr_2.5.0       RPostgreSQL_0.7-3
[37] cli_3.3.0         proto_1.0.0       crayon_1.5.1      readxl_1.4.0      memoise_2.0.1     ps_1.7.1
[43] fs_1.5.2          fansi_1.0.3       forcats_0.5.1     pkgbuild_1.3.1    tools_4.2.1       prettyunits_1.1.1
[49] hms_1.1.1         lifecycle_1.0.1   stringr_1.4.0     munsell_0.5.0     zip_2.2.0         callr_3.7.2
[55] RODBC_1.3-19      compiler_4.2.1    rlang_1.0.4       grid_4.2.1        rstudioapi_0.13   gtable_0.3.0
[61] curl_4.3.2        R6_2.5.1          zoo_1.8-10        lubridate_1.8.0   fastmap_1.1.0     bit_4.0.4
[67] utf8_1.2.2        rprojroot_2.0.3   insight_0.18.0    readr_2.1.2       desc_1.4.1        stringi_1.7.8
[73] parallel_4.2.1    Rcpp_1.0.9        vctrs_0.4.1       dbplyr_2.2.1      tidyselect_1.1.2

Thank you in advance if you have advice on the matter !
Edit : I had switched to an older version of duckdb during my tests to solve the problem. Following Mause's advice (thank you !) I switched back to duckdb's latest version (along with DBI).
Trying to connect, I got :
Error: rapi_startup: Failed to open database: IO Error: Trying to read a database file with version number 33, but we can only read version 38.
The database file was created with an older version of DuckDB.

The storage of DuckDB is not yet stable; newer versions of DuckDB cannot read old database files and vice versa.
The storage will be stabilized when version 1.0 releases.

For now, we recommend that you load the database file in a supported version of DuckDB, and use the EXPORT DATABASE command followed by IMPORT DATABASE on the current version of DuckDB.

I created a .duckdb file from scratch with the package latest version. It seems like my tables are kept now. But it has already happened in the last weeks that they « disappeared » after a few days so I will wait a few days and let you know whether the problem is well resolved !


text:
Q: Ajax Div Reload after 5 seconds i have seen many examples but they all seem to call a ".php" file.
What i would like to do is rather simple in terms of logic.
I need to auto refresh a div that contains PHP that fetches mysql data.
Is there anyway to do this without calling another .php file.
Div name:  #autoload

phpdata

A: As far as I know, this isn't possible, and I wouldn't recommend doing it that way either.
It's best to separate your PHP code into another file, and then request that file with AJAX.

A: If I'm correct you are trying to refresh a specific div with new content every 5 secs. One solution could be to use javascript setInterval like:
javascript
function refreshContent() {
    $.ajax({
        url: '/echo/json/' //here is the php file that returns the new data
    }).done(function () {
        $("#autoload").append("new content")
    });
}

setInterval(refreshContent, 5000);

fiddle


text:
Q: silverlight 4 file upload to mvc 3 controller HttpPostedFileBase is null I have a mvc 3 page that I want to be able to upload images to my website using silverlight to do the uploading and present a progress bar and a cancel button as it uploads. But I keep getting null value in my controller for the HttpPostedFileBase argument.
Here is my silverlight upload code ...
        var client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "multipart/form-data";
        client.OpenWriteCompleted += (sender1, e1) =>
        {
            PushData(stream, e1.Result);
            e1.Result.Close();
            stream.Close();
        };

        client.UploadProgressChanged += (sender1, e1) =>
        {
            this.pbStatus.Value = e1.ProgressPercentage;
        };

        // get uri from params
        param = App.Current.Host.InitParams["url"];
        var uri = new Uri(param, UriKind.Relative);
        client.OpenWriteAsync(uri, "POST");

Push Data method ...
    private void PushData(Stream input, Stream output)
    {
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }

And my controller code ...
[HttpPost]
public ActionResult UploadTexture(HttpPostedFileBase file)
{
}

The file param in my controller is null when the controller is called. Anyone know what I am doing wrong ?
I've seen examples that implement a IHttpHandler but I'm trying to avoid doing that and stick with just straight mvc 3 controllers.

A: I was having the same issue that you were.  I was able to solve this issue another way.
foreach (FileInfo fi in uploadedFiles)
        {
            UriBuilder ub = new UriBuilder(Application.Current.Host.Source.Host + "/Excel/?fileName=" + fi.Name);
            WebClient wc = new WebClient();
            wc.Headers[HttpRequestHeader.ContentType] = "multipart/form-data";
            wc.OpenWriteCompleted += (sender, e) =>
            {
                FileStream data = fi.OpenRead();
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            wc.OpenWriteAsync(ub.Uri, "POST");
        }

Main difference you will see is that I attach the filename to the URL.  My PushData() is the same.  On the MVC side, I have:
[HttpPost]
    public ActionResult Index(string fileName)
    {
        using (FileStream fs = System.IO.File.Create(Server.MapPath("~/FilesExcel/" + fileName)))
        {
            SaveFile(Request.InputStream, fs);
        }

        return View();
    }

    private void SaveFile(Stream stream, FileStream fs)
    {
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            fs.Write(buffer, 0, bytesRead);
        }
    }


text:
Q: Twitter oauth/request_token API using Fiddler results in 401 error I am trying to use fiddler to test the oauth/request_token api but am getting a 'Failed to validate oauth signature and token' 401 error. I copied the authorization header values directly from my application and added an oauth_callback header. I am trying to follow the example in the following documentation:
https://dev.twitter.com/docs/api/1/post/oauth/request_token.

Any help would be greatly appreciated.

REQUEST:

POST https://api.twitter.com/oauth/request_token HTTP/1.1
Authorization: OAuth oauth_callback="http%3A%2F%2Flocalhost%3A61921%2Ftwitter%2Fprocesscallback",  oauth_consumer_key="XXXXXXXXXXXXXXXXXXXXX", oauth_nonce="53891723ad7b32501c669d97f56c6d47", oauth_signature="qzN516EVspIA0NWBbpND83YcTr4%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1402955245",
oauth_token="2514015781-KqTbOPPag7p0CYQ6xByIibV3WEk8xLsWrhb9U4M",
oauth_version="1.0"
Host: api.twitter.com
Content-Length: 0
RESPONSE:
HTTP/1.1 401 Unauthorized
cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
content-length: 44
content-type: text/html; charset=utf-8
date: Mon, 16 Jun 2014 21:54:56 GMT
expires: Tue, 31 Mar 1981 05:00:00 GMT
last-modified: Mon, 16 Jun 2014 21:54:56 GMT
pragma: no-cache
server: tfe
set-cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCEIJraZGAToHaWQiJTlmOTQ3Y2MyYWNlMTkx%250AYTMyYzVlZmYyMTA4ZjU4ZTdkIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--3afebfe1105e8a7315baba72651e76a24f53e6d2; domain=.twitter.com; path=/; secure; HttpOnly
set-cookie: guest_id=v1%3A140295569643962216; Domain=.twitter.com; Path=/; Expires=Wed, 15-Jun-2016 21:54:56 UTC
status: 401 Unauthorized
strict-transport-security: max-age=631138519
vary: Accept-Encoding
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-mid: d31abfd0b6cbb0aa6434a6ffc6efdfac089ab0a5
x-runtime: 0.01273
x-transaction: 2dd94ca53f553801
x-ua-compatible: IE=edge,chrome=1
x-xss-protection: 1; mode=block

Failed to validate oauth signature and token


text:
Q: Check if Download Link Works in Email I am creating an email that will send out a link to a PDF in an Azure Blob Container. I am also playing a time limit on the link so it will no longer work after 30 days. Here is what my code that creates the azure link and email message looks like:
// Establishes a connection with Azure.
            string storageConnection = CloudConfigurationManager.GetSetting("AzureBlobConnectionString");
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnection);

            // Gets access to the quote blob container.
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("quotes");
            cloudBlobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

            // Inserts the pdf into Azure Blob.
            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("Quote_" + orderId + "_" + DateTime.Now.ToString("yyyy_MM_dd") + ".pdf"); ;
            await cloudBlockBlob.UploadFromStreamAsync(report.ExportToStream(ExportFormatType.PortableDocFormat));

            // Creates the 30 day time limit to access the pdf.
            DateTime expirationDate = DateTime.UtcNow.Add(new TimeSpan(30, 0, 0, 0));
            SharedAccessBlobPolicy sharedAccessBlobPolicy = new SharedAccessBlobPolicy();
            sharedAccessBlobPolicy.SharedAccessExpiryTime = expirationDate;
            sharedAccessBlobPolicy.Permissions = SharedAccessBlobPermissions.Read;

            // Creates the uri with the time limit.
            string sharedAccesSignature = cloudBlockBlob.GetSharedAccessSignature(sharedAccessBlobPolicy);
            string uri = cloudBlockBlob.Uri.AbsoluteUri + sharedAccesSignature;

            StringBuilder messageBody = new StringBuilder();
            messageBody.Append("Your Quote is attached.

");
            if (additionalNotes.Replace(" ", "").Length > 0)
            {
                messageBody.Append("Addtional Notes:
");
                messageBody.Append(additionalNotes + "

");
            }
            messageBody.Append("Download Quote PDF
");
            messageBody.Append("*** Link will expire after 30 days (" + expirationDate.ToString("MM/dd/yyyy") + ") ***

");
            messageBody.Append("Please do not reply back to this email.");

Is there a way to redirect the user to a designed error page if they click the link after the time limit?

A: You can set static page in Azure Blobs.
You can refer the offical document to create your download page which contains the logic of time limit. If the link does not expire, download it, and if it expires, jump to your custom error page.

You can upload your DownloadPage.html,and modify code. The value of uri set like  https://pan**storage.blob.core.windows.net/asset-*****-4baf-48a5-9ea1-6cb09319e679/DownloadPage.html?downloadurl=XXXXXXXX&expirationDate=2020-05-22 15:40:30
messageBody.Append("Download Quote PDF
");

In the DownloadPage.html, you can check the link does not expire by parameter expirationDate.
This is just a suggestion, of course, you can also use your own application website for better logic processing.


text:
Q: How does APA define "SD"? (I apologize if this is off-topic.  Also, I've read the numerous questions here about standard deviations, but I believe my question is different.)
I've read the 7th edition of the Publication Manual of the American Psychological Association and it doesn't seem to mention how it defines the abbreviation "SD," that is, it doesn't say whether this represents the sample standard deviation or the population standard deviation, it just calls it "standard deviation."  (It does define "s" as a sample standard deviation.)  What further complicates the matter is that APA uses "N" to denote the size of the total sample and "n" to denote the size of a subsample (section 6.44).
My question is:  If I read a paper that follows APA style and it says something like "Participants were on average 21.2 years old (SD = 3.2)," is the SD to be understood as a sample standard deviation or as a population standard deviation?


text:
Q: Does ITU govern both spectrum, and applied power? I'm really not sure whether EE Stackexchange is the right place to ask. At the same time I'm sure it is the right place to expect a coherent reply.
I am aware of the various bands (C, S, K, X...) that are governed/allocated by the ITU globally, and allocated for utilization. From what I read online at no place is the amount of power to use on a particular band mentioned by the ITU.
I get the impression that ITU merely assigns spectrum; the amount of power to use on any particular band is a state subject. Is this correct?


text:
Q: Adding item to cart do not work properly after removing that same item from cart I am having a problem with adding item to cart after i delete same item from cart. When the item is added to cart and that item is deleted from cart, that same item does not display in cart when i try to add it again in cart. The item can only add in cart again when i delete it from the admin panel.
Models.py:
class Item(models.Model):
    title = models.CharField(max_length=250)
    image = models.ImageField(null=True)
    price = models.IntegerField()
    old_price = models.IntegerField(null=True, blank=True)
    description = HTMLField()
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    slug = AutoSlugField(populate_from='title')
    timestamp = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ['-timestamp']
        db_table = 'items'
        verbose_name_plural = 'Items'

    def __str__(self):
        return self.title

class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    variation = models.ManyToManyField(Variation)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)
    billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True)

    def __str__(self):
        return self.user.username

Views.py:
@login_required
def add_to_cart(request, slug):

item = get_object_or_404(Item, slug=slug)

item_var = [] #item variation
if request.method == 'POST':
    print(request.POST)
    qty = request.POST['quantity']
    for items in request.POST:
        key = items
        val = request.POST[key]
        print(key,val)

        try:
            v = Variation.objects.get(
                item=item,
                category__iexact=key,
                title__iexact=val
            )
            item_var.append(v)
        except:
            pass

order_item_qs = OrderItem.objects.filter(
    item=item,
    user=request.user,
    ordered=False
)
print(order_item_qs)

if len(item_var) > 0:
    for items in item_var:
        order_item_qs = order_item_qs.filter(
                    variation__exact=items,
                )

if order_item_qs.exists():
    order_item = order_item_qs.first()
    order_item.quantity = qty
    order_item.save()
    print(order_item_qs)

else:
    order_item = OrderItem.objects.create(
        item=item,
        user=request.user,
        ordered=False
    )
    order_item.variation.add(*item_var)
    order_item.quantity = qty
    order_item.save()
    print(order_item)

    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        #check if the order item is in the order
        if not order.items.filter(item__id=order_item.id).exists():
            order.items.quantity = qty
            order.items.add(order_item)
            messages.info(request, "This item quantity was updated.")
            return redirect("shop:order-summary")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to cart.")
return redirect("shop:order-summary")

@login_required
def remove_from_cart(request, slug):

    id = request.POST.get('id', None) #retrieve id
    print(id)

    item = get_object_or_404(Item, slug=slug) #if no item found raise page not found
    print(item)

    obj_order_qs = Order.objects.filter(
        user=request.user,
        ordered=False
    )
    if obj_order_qs.exists():
        order = obj_order_qs[0]
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.filter(
                id=id,
                item=item,
                user=request.user,
                ordered=False
            )[0]
            order.items.remove(order_item)
            messages.info(request, "This item was removed from cart.")
            return redirect("shop:order-summary")
        else:
            messages.info(request, "This item was not in your cart.")
            return redirect("shop:order-summary")
    else:
        messages.info(request, "You do not have an active order.")
        return redirect("shop:order-summary")

Template:
<form action="{{ order_item.item.get_remove_from_cart_url }}" method="post">
    {% csrf_token %}
    <input name="id" type="hidden" value="{{ order_item.id }}" />
    <input type="submit" value="Delete" />
</form>

A: I'm not quite sure what the problem is, but there are a number of things you can change that will make your application a bit easier to understand and more robust.
First your data model could use some improvement. An OrderItem will only be assigned to a single Order so it should have the Foreign Key to order on it. Then you can remove OrderItem.user because only the user on the Order should have access to it. Item.slug should be unique.
class Item(models.Model):
    # The slug for every item should be unique since it's used in the URL.
    slug = AutoSlugField(populate_from='title', unique=True)

class Order(models.Model):
    # This is no longer necessary with the FK on OrderItem.
    # items = models.ManyToManyField(OrderItem)

class OrderItem(models.Model):
    # The user for the Order will be the same here. Normalizing your db makes authorization easier.
    # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="items")
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    variation = models.ManyToManyField(Variation)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

Then you remove view can look like this:
@login_required
def remove_from_cart(request, slug):
    order_items = OrderItem.objects.select_related('order').filter(
        order__user=request.user,
        item__slug=slug
   )

    order_item = get_object_or_404(
        order_items,
        id=request.POST.get('id', None),
    )

    # I'd recommend just filtering these out in the .filter() above
    if order_item.order.ordered:
        messages.info(request, "This order is no longer active.")
        return redirect("shop:order-summary")

    order_item.delete()
    messages.info(request, "This item was removed from your cart.")
    return redirect("shop:order-summary")

I also updated your add to cart view:
@login_required
def add_to_cart(request, slug):
    ordered_date = timezone.now()
    order, created = Order.objects.get_or_create(user=request.user, ordered_date=ordered_date, ordered=False)

    item = get_object_or_404(Item, slug=slug)

    item_var = []  # item variation
    if request.method == 'POST':
        print(request.POST)
        qty = request.POST['quantity']
        for items in request.POST:
            key = items
            val = request.POST[key]
            print(key, val)

            try:
                v = Variation.objects.get(
                    item=item,
                    category__iexact=key,
                    title__iexact=val
                )
                item_var.append(v)
            except:
                pass

    order_item_qs = OrderItem.objects.filter(
        order=order,
        item=item,
    )
    print(order_item_qs)

    if len(item_var) > 0:
        for items in item_var:
            order_item_qs = order_item_qs.filter(
                variation__exact=items,
            )

    order_item = order_item_qs.first()
    if order_item:
        order_item.quantity = qty
        order_item.save()
        print(order_item)
        messages.info(request, "This item quantity was updated.")
        return redirect("shop:order-summary")
    else:
        order_item = OrderItem.objects.create(
            item=item,
            user=request.user,
            ordered=False,
            quantity=qty,
        )
        order_item.variation.add(*item_var)
        order_item.save()
        print(order_item)
        messages.info(request, "This item was added to cart.")
    return redirect("shop:order-summary")


text:
Q: Cannot select row programmatically inside a modal in ng2 smart table Angular I have an ng2 smart table in my parent component and from this table i open a modal in which i display a second ng2 smart table
So on the second table the row should be programmatically selected using this code,
let selectedElement: Element =  document.querySelectorAll('table tbody tr')
          .item(ind);
         if (selectedElement) {
            let row: HTMLElement = selectedElement.querySelector('td') as HTMLElement;
            row.click();
          }
       }

but that did not happen as expected, the code selects the row of parents table (table 1)
to resolve this problem i tried to get the second table by ID using this code :
let selectedElement2 : Element = document.querySelectorAll('#tableS table tbody tr').item(ind);
Unfortunately the code didn't find the tr


text:
Q: NumPy Stack multidimensional arrays I have 3 nD arrays as follows
x = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

y = [[10, 11, 12],
     [13, 14, 15],
     [16, 17, 18]]

z = [[ 19,  20,  21],
     [ 22,  23,  24],
     [ 25,  26,  27]]

Without using for loop, I am trying to append every 2x2 matrix elements together such that
a1 = [[1,2]
      [4,5]]

a2 = [[10,11],
      [13,14]]

a3 = [[19,20],
      [22,23]]

should append to

a = [[1,10,19],[2,11,20],[4,13,22],[5,14,23]]

Please note, the NxN matrix will always be N = j - 1 where j is x.shape(i,j)

Similarly for other 2x2 matrices, the arrays are as follows

b = [[2,11,20],[3,12,21],[5,14,23],[6,15,24]]
c = [[4,13,22],[5,14,23],[7,16,25],[8,17,26]]
d = [[5,14,23],[6,15,24],[8,17,26],[9,18,27]]

For large datasets, the for loop impacts runtime so I am trying to see if there is a way using NumPy stacking techniques

A: Your 3 arrays:
In [46]: x=np.arange(1,10).reshape(3,3)
In [48]: y=np.arange(10,19).reshape(3,3)
In [49]: z=np.arange(19,28).reshape(3,3)

combined into one:
In [50]: xyz=np.stack((x,y,z))
In [51]: xyz
Out[51]:
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]],

       [[19, 20, 21],
        [22, 23, 24],
        [25, 26, 27]]])

Your a1 (2,2) array:
In [55]: xyz[0,:2,:2]
Out[55]:
array([[1, 2],
       [4, 5]])

and all 3:
In [56]: xyz[:,:2,:2]
Out[56]:
array([[[ 1,  2],
        [ 4,  5]],

       [[10, 11],
        [13, 14]],

       [[19, 20],
        [22, 23]]])

and rearrange them into the desired (4,3):
In [57]: xyz[:,:2,:2].transpose(1,2,0)
Out[57]:
array([[[ 1, 10, 19],
        [ 2, 11, 20]],

       [[ 4, 13, 22],
        [ 5, 14, 23]]])
In [58]: xyz[:,:2,:2].transpose(1,2,0).reshape(4,3)
Out[58]:
array([[ 1, 10, 19],
       [ 2, 11, 20],
       [ 4, 13, 22],
       [ 5, 14, 23]])

similarly for the other windows:
In [59]: xyz[:,1:3,:2].transpose(1,2,0).reshape(4,3)
Out[59]:
array([[ 4, 13, 22],
       [ 5, 14, 23],
       [ 7, 16, 25],
       [ 8, 17, 26]])
In [60]: xyz[:,0:2,1:3].transpose(1,2,0).reshape(4,3)
Out[60]:
array([[ 2, 11, 20],
       [ 3, 12, 21],
       [ 5, 14, 23],
       [ 6, 15, 24]])
In [61]: xyz[:,1:3,1:3].transpose(1,2,0).reshape(4,3)
Out[61]:
array([[ 5, 14, 23],
       [ 6, 15, 24],
       [ 8, 17, 26],
       [ 9, 18, 27]])

We could also the view_as_windows as @Divakar suggested (or as_strided), but conceptually that's trickier.
====
I can skip the transpose if I stack differently:
In [65]: xyz=np.stack((x,y,z), axis=2)
In [66]: xyz
Out[66]:
array([[[ 1, 10, 19],
        [ 2, 11, 20],
        [ 3, 12, 21]],

       [[ 4, 13, 22],
        [ 5, 14, 23],
        [ 6, 15, 24]],

       [[ 7, 16, 25],
        [ 8, 17, 26],
        [ 9, 18, 27]]])

In [68]: xyz[:2,:2].reshape(4,3)
Out[68]:
array([[ 1, 10, 19],
       [ 2, 11, 20],
       [ 4, 13, 22],
       [ 5, 14, 23]])

===
In [84]: import skimage
In [85]: skimage.util.view_as_windows(xyz,(2,2,3),1).shape
Out[85]: (2, 2, 1, 2, 2, 3)
In [86]: skimage.util.view_as_windows(xyz,(2,2,3),1).reshape(4,4,3)
Out[86]:
array([[[ 1, 10, 19],
        [ 2, 11, 20],
        [ 4, 13, 22],
        [ 5, 14, 23]],

       [[ 2, 11, 20],
        [ 3, 12, 21],
        [ 5, 14, 23],
        [ 6, 15, 24]],

       [[ 4, 13, 22],
        [ 5, 14, 23],
        [ 7, 16, 25],
        [ 8, 17, 26]],

       [[ 5, 14, 23],
        [ 6, 15, 24],
        [ 8, 17, 26],
        [ 9, 18, 27]]])

A:
a1 = np.array([[1,2],[4,5]])

a2 = np.array([[10,11],[13,14]])

a3 = np.array([[19,20],[22,23]])

def everything(a1,a2,a3):

    b1 = a1.reshape(-1)
    b2 = a2.reshape(-1)
    b3 = a3.reshape(-1)
    c = np.concatenate((b1, b2, b3))
    b = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
    def inner(a, i):
        while i < len(a):
            i = i + 1
            return a[i - 1]
    def looping(a, c):
        k = 0
        j = 0
        while j < len(a) - 1:
            i = 0
            while i < len(a):
                b[i][j] = inner(c, k)
                i += 1
                k += 1
            j += 1
    looping(b3, c)
    print(b)
everything(a1,a2,a3)


text:
Q: Domain forwarding and DNS entries In Google domains I have a main domain at examplesite.com
and a secondary domain example-site.com that is forwarded to main's URL:
Domain (example-site.com) forwards to
https://www.examplesite.com

Redirect Type
Permanent redirect (301)

Path forwarding
Do not forward path

SSL
SSL On

What's confusing me are leftover DNS entries for example-site.com.
ftp  CNAME 1h  example-site.com.
imap CNAME 55m imap.secureserver.net.
mail CNAME 55  mpop.secureserver.net.
pop  CNAME 1h  pop.secureserver.net.
smtp CNAME 55m smtp.secureserver.net.

It seems like main this was main domain once (years ago) and it was dumped in favor of examplesite.com. Can I delete all DNS entries for this redirected domain?

A: Those entries read as follows:

*

*ftp.example-site.com will load example-site.com

*imap.example-site.com will load imap.secureserver.net

*mail.example-site.com will load mpop.secureserver.net

*pop.example-site.com will load pop.secureserver.net

*smtp.example-site.com will load smtp.secureserver.net

The first one you might want to redirect to examplesite.com, assuming the ftp subdomain is still relevant. The other ones, you might want to set up CNAMEs at examplesite.com to do the same. Those 4 entries appear to be configured for folks to use the Godaddy email services but by using your old domain; likely so they don't have to remember the GoDaddy URLs. If they use SSL/TLS connections for their email however (which they should), they'll probably end up with certificate errors when using those addresses because the GoDaddy server certificates won't have your domain listed.


text:
Q: How to make python3.7 default I have installed python3.7 however I am not sure how to make it the default python.
See below:
~/Documents/robosuite$ python3.7
Python 3.7.1 (default, Oct 22 2018, 11:21:55)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
KeyboardInterrupt
>>>

~/Documents/robosuite$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

I want python3.7 to show up when I use the command python3

A: I would like to expand on a previous answer as the two approaches given are not equivalent, and one of them can even break the system. The issue is there are two different things one could be trying to do by "changing the default python version".
Quick summary
Add
alias python3=python3.7

to .bashrc.
Do not use update-alternatives to change your default python version, as this will break system applications.
Further details
Bash alias
The first, is that for an interactive shell, one simply wishes to easily open the desired python by writing
$ python

or
$ python3

This is accomplished by adding the line
alias python3=python3.7

to .bashrc. If one is using another shell, add this to the appropriate config file. This also has the advantage that if it causes problems for any reason, one can simply remove the offending line in .bashrc and restart the terminal.
update-alternatives
The second thing one could mean by "changing the default python version", is to change the default python version for all programs, including those not launched from an interactive shell. This is the result of running
$ sudo update-alternatives --config python3

However, if you run this in a clean install of Debian/Ubuntu, you will notice that the command returns
update-alternatives: error: no alternatives for python3

even if you have multiple versions of python 3 installed via apt. There is a very good reason for this.
The problem with the this is that many system applications use python, and depending on the exact distribution, many use python 3. Changing which version is called by the command python3 globally will force these applications to use this version. Although different version of python 3 are largely compatible, there are still features moved and removed between releases. If a system application uses these features, changing python3 to launch a newer version will break the application.
Testing
I created a fresh install of Ubuntu 18.04 in a VM. Adding the bash alias caused no immediate issues.
Using the update-alternatives method caused issues with apt. Specifically, I got
ModuleNotFoundError: No module named 'apt_pkg'

Fixing your system if you ran the update-alternatives method
If we ran update-alternatives and broke apt, we can still fix the system. During my testing, the terminal was still able to be opened. One can go back to the default python by running
$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.X 1000

where 3.X is your systems original python 3 version, and 1000 is just some high priority to make sure it is on top. Then, one can run
$ sudo update-alternatives --config python3

and make sure the original system python is selected. Reboot the system and it will be back to normal.

A: Simple solution is edit .bashrc and put this line:
alias python3=python3.7

Whenever you will write python3 it will replace it with python3.7.
Or you can use command update-alternatives which is preferred i.e:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2

So here python3.7 will have higher priority then python3.6.
Then use:
sudo update-alternatives --config python3

Press the enter key if you are satisfied

A: $ sudo su
$ update-alternatives --install /usr/bin/python python /usr/bin/python3 1

... when already python3.7 is installed

A: For machines which don't have the update-alternatives command, one can do a quick&dirty solution like
sudo ln -sf `which python3.7` `which python3`

Usually (at least in all cases I've seen), python3/python2/python are only symlinks to the python executable of a specific version. Changing this symlink should change the 'default python'


text:
Q: realloc() отказывается выделять память. В чем может быть дело? Пишу лабораторку, при перевыделении памяти происходит ошибка:
a.out: realloc(): invalid old size: 0x089d4008

Код, где выделяется память, такой:
graph = (vertex*) malloc(sizeof(vertex)*(N+1));
    res = (int*) malloc(sizeof(int)*N);
    for(int i = 1; i <= N; i++)
    {
        graph[i].color = 0;
        graph[i].num_edges = 0;
        graph[i].max_edges = 5;
        graph[i].edges = (edge*) malloc(sizeof(edge)*graph[i].max_edges);
        graph[i].value = i;
    }
    for(int i = 0; i < M; i++)
    {
        int temp1, temp2;
        scanf("%d %d", &temp2, &temp1);
        if(graph[temp1].num_edges >= graph[temp1].max_edges)
        {
            graph[temp1].max_edges *= 2;
            graph[temp1].edges = (edge*) realloc(graph[temp1].edges, graph[temp1].max_edges);
        }
        graph[temp1].num_edges += 1;
        graph[temp1].edges[graph[temp1].num_edges - 1].to = graph+temp2;
    }

В чем ошибка, не понимаю.
A: Возможно, потому что вы в первом цикле используете итерацию с 1 вместо 0.
temp1 какое значение принимает?
A: А malloc-то корректно сработал? Нечего realloc'ить, если malloc не отработал корректно.


text:
Q: What do modern GPUs not have? There was a time when the difference between a CPU and GPU was very clear, but it has become increasingly blurred over the years both from the former side (SIMD vector instructions) and even more from the latter, to the point where not only are GPU's doing general computation, but Nvidia talks about using the RISC-V instruction set in their next one.
Yet even if they can now in principle compute the same things, in practice they are not good at the same things. GPU's are much faster than CPUs on some workloads, but slower on others. Clearly this is partly because the implementations optimize for different things, but is presumably also partly due to architectural differences.
In particular, presumably GPU's omit some features of CPUs, which for some workloads would be baggage the omission of which lets GPU's run much faster, and for other workloads means GPU's cannot run existing code except by slow and awkward workarounds.
I'm interested in just what architectural features GPU's still do not have, to account for their distinctive characteristics relative to CPUs.
Guesses:

*

*IEEE 754 semantics

*Unaligned memory access

*Transparent caches (i.e. on-chip memory that does not have to be managed explicitly by software)

*Cache-coherent SMP

*Paged virtual memory

*Out of order execution

Are any of those on target? What else have I not thought of? Which features are the most important (both in saving transistors/nanojoules per flop on the one hand, and making GPU's unable to run CPU workloads on the other hand)?

A: Branches are a big one. GPU instruction sets have some way to deal with if/then/else, but typically they handle conditionals by bitmasking a particular result with ones or zeroes.


text:
Q: find the parametric equation of a line in $2$ space Given $2x-3y=5$ find the parametric equation of the line in $\mathbb R^2$
First I set $x$ to $0$ to find point $p1=(0,\frac{-5}{3})$ and $x$ to 1 to find point $p2=(1,-1)$ $p2-p1=v$ parallel to the line. $v=(1,\frac{2}{3})$
Now I have a point on the line $p2$ or $p1$ and a vector parallel to the line and can write the line as $(x,y)=(1,-1)+t(1,\frac{2}{3});t\in \mathbb R$
Yet this is completly different wrom the answer in my book $(x,y)=(4,1)+t(3,2);t \in \mathbb R$ what am I doing wrong?

A: In fact, your answer and the book's answer are equivalent.
Note that
$$\begin{align}(x, y) &= (1, -1) + t\left(1, \frac{2}{3}\right)\\
&= (1 , -1) + \frac{t}{3}(3, 2)\\
&= (4, 1) + \left(\frac{t}{3} - 1\right)(3, 2)\end{align}$$
so if you made the substitution $t' = \frac{t}{3} - 1$, you get
$$(x, y) = (4, 1)+ t'(3,2)$$
The geometrical intuition is that two lines are equivalent if their directions are parallel, and their constant terms differ by a scalar multiple of their equivalent directions.


text:
Q: Setting Layout to null in _Layout.cshtml Is there a reason why you would want to set the Layout property to null in a _Layout.cshtml?
For example, like this, before rendering the body view?
    ...
    <section id="content">
        @{ Layout = null; }
        @RenderBody()
    </section>
    ...

It seems pretty nonsensical to me, and removing the line setting Layout doesn't change the way page loads work observationally.
Is there any reason why you would want to set the Layout property in _Layout.cshtml?

A: Layout pages can have a layout too. In nested layouts , you intentionally use Layout property to define super layout of layout page . By default it is null in your layout page if you do not specify any. When you make @{Layout=null} you are explicitly saying that this your final layout so it is not nested in any super layout.

A: If you want to create a partial view that will not inherit any layout from _Layout than you will use  @{ Layout = null; } in the begining of your partial view.

A: I know this is an old thread but my problem solved by this trick!
I like to share my solution here

*

*First change _ViewStart.cshtml to :
@{
 if (Layout != "")
 {
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 }
As you can see Layout is a property and we will check that if it is not equals to ""

*

*Next you have to add this in your views
@{
Layout = "";
}
And you will have happy views without layout!


text:
Q: Validate construction of typescript model So I have a person model for example
export class Person {

    name: string;
    id: Number;
}

I want to make sure that name and id are the only fields to be defined
So when I construct the Object like the following(METHOD 1)
let person = new Person({name: 'john', id:2, invalidField: 'notAllowed'})

Typescript does not allow this above
However if I get the data from the backend it will allow it to construct the object like the following(METHOD 2)
  let data: any = {name: 'john', id:2, invalidField: 'notAllowed'}// resp from backend
  let person = new Person(data)

Typescript allows this above
Is there anyway to make sure that constructing the object via method two gets invalidated?
The reason I want to able to do this is so I can create unit tests to make sure that data from the backend is in the format that I expect
Not sure if this is clear I'm fairly new to typescript
Any questions please add a comments
Maybe some run-time check in the constructor?

A: TypeScript is transpiled to JavaScript. Such verifications will not work at runtime.
You need to implement that manually. I believe you are looking for something like validate.js.