text:
Q: How to set up a connection with Kerberos in Golang app? I have task to create SSO (single sign-on) in Golang application with the help of Kerberos and Active Directory. In other words, if an employee of the company makes a request for a specific URL, the service must return information about him.
I decided to use gokrb5 library.
What I have done so far:
1) SPN name for the service was created in Active Directory.
2) krb5.keytab file for the service was created.
3) Active Directory and Kerberos server located on remote Windows server.
4) Golang application would be in Linux Docker container.
5) I install Kerberos client to Docker container.
6) I put krb5.keytab file to etc folder of Docker container.
7) Kerberos Realm: EXAMPLE.LOCAL.
8)  hostname for the KDC Server: CS001, CS002, CS003
What the configuration file krb5.conf for Kerberos client should look like? How in Golang application I can correctly send token to Kerberos?


text:
Q: What is an instance variable in JavaScript? In a React tutorial video, the instructor said you need to use this.props rather than just props in a React class component because in that case, it's an instance variable. I'm not totally sure what an instance variable is in that context.
I found a lot of questions explaining what an instance variable is in the context of Java and other languages besides JavaScript--in one question (tagged objective-c), someone answered "In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the class."
However, I know ES6 classes are just objects and are syntactical sugar for prototype-based inheritance --would that answer hold true in the case of JS classes?

A: To understand this thing, you need to know about function expression, lexical environment, prototype inheritance.
'this' keyword refers to the object it belongs to.
let say we have a class like this,
class Hello{
   constructor(name){
      this.name = name
   }
   hello(){
      console.log(this.name);
   }
}

now let's make a new object with the help of this class.
var person = new Hello('Alex')

Now I can do something like this,
person.hello();

This line will return 'Alex';
Now let's console.log(person);
console.log(person)

person ==> {
              name : 'Alex'
              <prototype> {
                  constructor: function Hello()
              }
           }

You will notice that Hello function is not at the top level of the person object. It is at the first prototype level of that object. Everything inside of this prototype will refer to the class or Factory function or
Constructor function that helps to define that person object. In this case, it refers to Hello class.
var person is defined on the global level. so when you call to person.hello() it will check at the top level of that object.  If it is not in there, then it will go to the outside environment and try to find out what is this hello() thing. The outer environment of this person object is the global level. hello() function is not at the global level. When javaScript did not find the hello() in the outer environment then it will throw an error that saying hello() is undefined.
When we use 'this' keyword, it will say check on prototypes too. go through all the prototypes until you meet that thing. If it is not in there, then go outer environment and check if it is there.
'this' keyword will refer anything, to the object it belongs to. Also, remember everything in javaScript is an object expect primitive data

A: An instance variable is just a property of an object, as Felix Kling said.
You can't use props because that's referencing a global or local variable called props. What you want to access is the current value of props for the current component, stored in this.props.
See a jsfiddle: https://jsfiddle.net/vd5ymhcz/1/

A: An object is an instance of the class that it is created from. And an instance variable is any property defined in the class for that object (typically inside constructor).
Every instance variable is accessible using 'this.' prefix inside any method of the class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: passing variables from one sub-routine to another I am making for fun, a small program in VB.net Console, that allows users to enter films, the director and the genre, and then can sort/order them however the user wants. Essentially the problem I am hitting is that I can't pass a variable between sub routines. I thought this was achieved by using aa an example: (ByRef CurrentIndex As Integer), which would be referencing the variable that was declared in another sub-routine. This isn't working though, and I think I am not understanding some of the theory behind this.
This is the block where the variable is declared:
Sub AddDvdToDatabase()
    Dim choice As String = ""
    Dim i As Integer
    Dim CurrentIndex As Integer = 1
    i = CurrentIndex
    Do Until choice = "exit"
        choice = ""
        Console.WriteLine("Add the title of the film")
        dvd(i).Title = Console.ReadLine()

        Console.WriteLine("Add the director of the film")
        dvd(i).Director = Console.ReadLine()
        Console.WriteLine("Add the genre of the film")
        dvd(i).Genre = Console.ReadLine()

        Do Until choice = "yes" Or choice = "exit"
            Console.WriteLine("Would you like to add another fim to the database? <yes/exit>")
            choice = Console.ReadLine()
        Loop
        i += 1  'Save the value of i to a separate text file to read from when opening again. This stops previuos elements from the array being overwritten.

    Loop
    CurrentIndex = i
    Menu(CurrentIndex)
End Sub

And then here is where I am trying to pass the value of CurrentIndex to:
Sub ViewDatabase(ByRef CurrentIndex As Integer)
    Console.Clear()
    Dim i As Integer
    For i = 1 To CurrentIndex
        Console.WriteLine(i & ". " & dvd(i).Title & "  " & dvd(i).Director & "  " & dvd(i).Genre)
    Next
    Console.ReadLine()
End Sub

edit
I am calling it in the Sub Menu(), when the user selects to view the database after entering films.
I am getting the error "Argument not specified for parameter 'CurrentIndex' of 'Public Sub ViewDatabase(ByRef CurrentIndex As Integer)'"
Sorry, I am very new to Stack Overflow and I'm still learning the conventions etc.

A: I see that this post is old however it appears that you are tying to get the value of  CurrentIndex at the end of your sub routine AddDvdToDatabase and use the output in  ViewDatabase. To do this you could simply make the variable global outside of both sub routines.
Dim CurrentIndex as Integer
Your code would look like this:
Dim CurrentIndex As Integer

Sub AddDvdToDatabase()
Dim choice As String = ""
Dim i As Integer
CurrentIndex = 1
i = CurrentIndex
Do Until choice = "exit"
    choice = ""
    Console.WriteLine("Add the title of the film")
    dvd(i).Title = Console.ReadLine()

    Console.WriteLine("Add the director of the film")
    dvd(i).Director = Console.ReadLine()
    Console.WriteLine("Add the genre of the film")
    dvd(i).Genre = Console.ReadLine()

    Do Until choice = "yes" Or choice = "exit"
        Console.WriteLine("Would you like to add another fim to the database? <yes/exit>")
        choice = Console.ReadLine()
    Loop
    i += 1  'Save the value of i to a separate text file to read from when opening again. This stops previuos elements from the array being overwritten.

Loop
CurrentIndex = i
Menu(CurrentIndex)
End Sub

Sub ViewDatabase()
Console.Clear()
Dim i As Integer
For i = 1 To CurrentIndex
    Console.WriteLine(i & ". " & dvd(i).Title & "  " & dvd(i).Director & "  " & dvd(i).Genre)
Next
Console.ReadLine()

End Sub


text: Q: Redirect to Another Webpage at a Specific Time I'm using a web webpage to display digital signage. Once loaded, I need the webpage to wait until 10am and then automatically redirect to another webpage. Could this be done with JavaScript?


text:
Q: When is PSU(2,q^2) = PSL(2,q) ? The context for this question is from page 284 - 287 of Berger's paper: http://pdn.sciencedirect.com/science?_ob=MiamiImageURL&_cid=272332&_user=209810&_pii=S0021869398976785&_check=y&_origin=article&_zone=toolbar&_coverDate=1999--01&view=c&originContentFamily=serial&wchp=dGLbVlS-zSkzS&md5=2dd8e0d714d264cf7c4acdd9ec58ac84&pid=1-s2.0-S0021869398976785-main.pdf
Particularly, in his assumption at the top of page 287, he says that "From now on, assume that our map $\pi_\mathfrak{p}$ surjects onto $\text{PU}_2(\zeta,\mathcal{O}_K/\mathfrak{p})\cong \text{PSL}_2(\mathbb{F}_q)$, that $q$ is odd, and that $(6,k) = 1$, where $k = \sharp\langle -\zeta\rangle$."
I'm guessing that he's assuming the conditions in proposition 2 (from the previous page) to be true, so that $\pi_\mathfrak{p}$ surjects onto $\text{PU}_2(\zeta,\mathcal{O}_K/\mathfrak{p}) = \text{PSU}_2(\mathcal{O}_K/\mathfrak{p})$, and that he's claiming that the latter group is isomorphic to $\text{PSL}_2(\mathbb{F}_q)$.
Is this generally true?
Also, on page 284, where he gives the matrix $H$ for the hermitian form, he claims that $H\in GL_{n-1}(\mathbb{Z}[t,t^{-1}])$, but the matrix he gives obviously does not lie in that group.
Where might I find a good book on unitary matrices over finite fields?
thanks,

*

*will

A: Here is a more bare hands explanation. Let $\phi$ be the field automorphism of ${\rm SL}_n(q^2)$ that acts by applying $x \mapsto x^q$ to the matrix entries. Let $\gamma$ be the graph automorphism that maps matrices $A$ to their inverse-tranpose $A^{- \mathrm{T}}$. Then ${\rm SL}_n(q)$ is the subgroup of ${\rm SL}_n(q^2)$ that is centralized by $\phi$, whereas the group ${\rm SU}_n(q^2)$ (which is confusingly often denoted by ${\rm SU}_n(q)$) that fixes the identity matrix as unitary form is the subgroup of ${\rm SL}_n(q^2)$ that is centralized by $\phi\gamma$.
The automorphism $\gamma$ is outer for $n>2$, but when $n=2$ it is inner and acts in the same way as conjugation by the matrix $\left( \begin{array}{rr}0&1\\ -1&0\end{array} \right)$. It turns out in this case that $\phi$ and $\phi\gamma$ are conjugate in the automorphism group of ${\rm SL}_2(q^2)$ by (the projective image of) an element $g \in {\rm GL}_2(q^2)$, and hence that ${\rm SL}_2(q)$ is conjugate to ${\rm SU}_2(q^2)$ in ${\rm GL}_2(q^2)$. With a bit of calculation on the back of an envelope, we find that $g = \left( \begin{array}{rr}a&b\\ c&d\end{array} \right)$, where $b = -t^qa^q$ and $d= -t^qc^q$ for some field element $t$ with $t^{q+1} = -1$.

A: It is a fairly standard result that $SU(2,q^2)$ and $SL(2,q)$ are isomorphic, see e.g. II.8.8. in Huppert's Endliche Gruppen. I would expect that it is also in the third volume of The Classification of the Finite Simple Groups by Gorenstein-Lyons-Solomon, but I don't have the volume at hand right now.


text:
Q: Chrome copies address bar contents as a link When I copy URL of current page from address bar Chrome doesn't copy it as a plain text. As a result when I have to send it on Microsoft Lync, the link is pasted twice. Below is the screen grab of Lync window:

Here I had copied the link of superuser.com and pasted it in Lync window, it pasted twice. If the same is done inside a notepad it copies the link as a plain text.
Update:

*

*I don't get option 'Paste As Plain Text' inside Microsoft Lync when I right click: Here is a snapshot:


text:
Q: How to merge multiple rows into one row with filtering rules in SQL Server I have a table like this:
+---------------+---------------+----------------+---------------------+
| MedicalCardId | DiagnosisType | DiagnosisOrder |       Symptom       |
+---------------+---------------+----------------+---------------------+
|       1       |      Main     |       1        |     Lung Cancer     |
|       1       |    Secondary  |       1        | High Blood Pressure |
|       1       |    Secondary  |       2        |     Heart Attack    |
|       1       |    Secondary  |       3        |      Gastritis      |
|       2       |      Main     |       1        |      Diabetes       |
|       2       |    Secondary  |       1        |  Kidney Malfunction |
|       3       |      Main     |       1        |         Flu         |
+---------------+---------------+----------------+---------------------+

The DiagnosisOrder for each 'Main' DiagnosisType is 1, and for 'Secondary' DiagnosisType of the same MedicalCardId, it restarts to increase from 1.
I would like to merge multiple rows of the same MedicalCardId into a single row, and each Symptom becomes a new column depending on its DiagnosisType and DiagnosisOrder
The query result is expected to be like:
+---------------+-------------+---------------------+-------------------+-------------------+
| MedicalCardId | MainSymptom |  SecondarySymptom1  | SecondarySymptom2 | SecondarySymptom3 |
+---------------+-------------+---------------------+-------------------+-------------------+
|       1       | Lung Cancer | High Blood Pressure |    Heart Attack   |     Gastritis     |
|       2       |   Diabetes  |  Kidney Malfunction |                   |                   |
|       3       |     Flu     |                     |                   |                   |
+---------------+-------------+---------------------+-------------------+-------------------+

I've tried using PIVOT, but I'm unable to apply it to my practice.

A: You can try with conditional aggregation -
select MedicalCardId,
       max(case when DiagnosisType='Main' then Symptom end) as MainSymptom,
       max(case when DiagnosisType='Secondary' and DiagnosisOrder=1 then Symptom end) as SecondarySymptom1,
       max(case when DiagnosisType='Secondary' and DiagnosisOrder=2 then Symptom end) as SecondarySymptom2,
       max(case when DiagnosisType='Secondary' and DiagnosisOrder=3 then Symptom end) as SecondarySymptom3
from tablename
group by MedicalCardId

A: I believe you need to create a dynamic pivot table. The reason why you can't use a normal pivot table query is because you don't know how many Secondary Symptoms there are and therefore you don't know how many columns to create. Below is a stored procedure that works. The first step is creating a VARCHAR (@Columns) variable that will be used to store the dynamic column names these will be [Main], [Secondary1], [Secondary2], [Secondary3] so on and so forth (I used a case statement to create the column names per your expected query result). The second step is creating another VARCHAR (@SQL) variable that will contain the pivot table SQL query. In this step you will use string concatenation to put this variable together.
Kris Wenzel has a great tutorial on dynamic pivot tables at essentialsql.com here is the link https://www.essentialsql.com/create-dynamic-pivot-table-sql-server/
Here is the stored procedure.
USE [TestDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GenerateData]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

--GATHER PIVOT COLUMNS DYNAMICALLY
DECLARE @Columns as VARCHAR(MAX)
SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME([Diagnosis])
FROM
   (SELECT DISTINCT case when [DiagnosisOrder] = 1 and [DiagnosisType] = 'Main' then 'MainSymptom' else 'SecondarySymptom' + CAST([DiagnosisOrder] AS VARCHAR) end [Diagnosis] FROM [TestDB].[dbo].[test] ) AS B
ORDER BY B.[Diagnosis]

--CREATE SQL QUERY FOR PIVOT TABLE
DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 'SELECT MedicalCardId, ' + @Columns + '
FROM
(
select [MedicalCardId]
      ,[Diagnosis]
      ,[Sympton]
      from
      (
SELECT [MedicalCardId]
      ,case when [DiagnosisOrder] = 1 and [DiagnosisType] = ''Main'' then ''MainSymptom'' else ''SecondarySymptom'' + CAST([DiagnosisOrder] AS VARCHAR) end [Diagnosis]
      ,[Sympton]
  FROM [TestDB].[dbo].[test]
      ) A
) t
PIVOT(
    MAX([Sympton])
    FOR [Diagnosis] IN (' + @Columns + ')
) AS pivot_table order by [MedicalCardId]'

--EXECUTE SQL
EXEC(@SQL)

END
GO


text:
Q: Is it safe to pass auth token via iOS deep link? I'm designing a webapp/mobileapp security flow where there are no passwords, only an auth token sent to the phone via sms. Flaws in this?
The plan:

*

*Phone receives sms link with embedded invite token http://domain.com/invite/ABCD

*User clicks, goes to web app which asks user to install mobile app (via deep link, which passes same token myapp://invite/ABCD

*When app is loaded, invite token ABCD is sent to server and exchanged for an auth token and a session token.

*Auth token is stored permanently in local storage in app.

*Session token is used for successive api calls and valid for 24hrs then Auth token will be used again to exchange for new session token

                                                                +---+
                                                                |   |
+---------+ <---------------------------------------------------+   |
| Invite  |                                                     | S |
| Link    |                               send invite           | E |
| rec'd   |   +---------+   +--------+    token                 | R |
| via     |   |WebApp:  |   |        +----------------------->  | V |
| SMS     |   |deep     |   | ios App|                          | E |
|         +-> |linked   +-> |        |   receiv auth &          | R |
| (token) |   |to mobile|   |        |   session token          |   |
+---------+   |app      |   |        | <----------------------+ |   |
              |(install)|   |        |                          |   |
              |         |   |        |  use session token       |   |
              |         |   |        |  for all api calls       |   |
              +---------+   +--------+ +--------------------->  +---+

Questions:

*

*Is it safe to pass the token via deep link?

*See any other flaws with this scenario?

*Is auth/session combo even needed? Rationale was that session expires 24h since its exposed more over the network, but since its over ssl, maybe i only need an auth token that is stored forever and also used for api auth?

A: Seems like it should work, but be careful of your user experience. You don't want people sharing the link and having unauthorized logins, instead of treating it like a private password. Making your invite links usable only once would make them similar to the "Magic Link" pattern that Slack uses, however I would avoid calling it "invite", since these tend to be things you would give to other people.


text: Q: UIImage Scroll in background like a slow motion effect I have  a scrollView with an image inside. Is it possible to animate the image in such a way that the moves slowly in the background. Like the Login page of Uber App.


text:
Q: How do I use a method to return / calculate an attribute? I want to do something like:
class Model:
    def __init__(self, X, y):
        self.X = X
        self.y = y
        self.X_train = self.split_scale_data(X,y)[0]
        self.X_test = self.split_scale_data(X,y)[1]

    def split_scale_data(self, X, y):
        X_train, X_test, y_train, y_test = train_test_split(X, y)
        scaler = MinMaxScaler()
        X_train_scaled = scaler.fit_transform(X_train)
        X_test_scaled = scaler.transform(X_test)
        return self.X_train, self.X_test

But I can't get this to work, and I can't find any examples online where someone uses a method to calculate an attribute. I get Attribute Error: 'Model' object has no attribute 'X_train'. Am I missing something?

A: Your method split_scale_data returns the following
return self.X_train, self.X_test

but it should return the local variables from that method
return X_train, X_test

By the way you can also modify your __init__ method to use this method as
self.X_train, self.X_test = self.split_scale_data(X,y)

A: You are returning attributes which are not defined
return self.X_train, self.X_test

and here the error. You should change it to
return X_train, X_test

However, for your use case it might be worth to use a classmethod and keep the __init__ simple.
class Model:
    def __init__(self, X, y, X_train, X_test):
        self.X = X
        self.y = y
        self.X_train = X_train
        self.X_test = X_test

    @classmethod
    def from_data(cls, X, y):
       ...
       return cls(X, y, X_train, X_test)


text:
Q: Intellij IDEA cannot resolve React Native import
The React import is ok, but other import can not used in autocompletion.
If I import as import Text from 'react-native', this can be resolve correctly, but this is incorrect import.So I assume IDE will resolve symbol by lookup import Class name only, The question is how can I work around this ?

A: I use Webstorm 2017.2 and I experienced this error. I tried various solutions, and following solution was worked on my IDE.
Step 1: This step is optional, but I did it. Remove all of the Webstrom preferences. Please check document for related folders: https://www.jetbrains.com/help/phpstorm/project-and-ide-settings.html
Step 2: Remove .idea file in the project directory.
Step 3: Select React JSX under Languages & Frameworks > JavaScript.

Step 4: Download and select react-native under Languages & Frameworks > JavaScript > Libraries.

Step 5: Invalidate Caches / Restart...

A: This worked for me, go to:

Preferences -> Languages & Frameworks -> JavaScript

and then where it says JavaScript language version, choose in the drop down ReactJSX.
Good luck!

A: The problem occurs because of a tricky way react-native modules are defined. I'd suggest using typescript community stubs to solve the issue: Preferences | Languages & Frameworks | JavaScript | Libraries, press Download, then choose 'react-native' from the stubs list

A: *

*Install flow-typed globally. example: $ npm install -g flow-typed

*flow-typed create-stub react-native

*open /flow-typed/npm/react-native-vx.x.x.js

*Copy and paste the entire following code below into react-native.xxx.js.
https://gist.githubusercontent.com/lelandrichardson/c037f46885af67ceb447091c908d1471/raw/829a0e311ce619bbb224cf68780a16753feaf2b6/react-native.js
P.S. This is the setting when the react-native library component/type cannot be found when designating js as the flow type in the intelliJ platform.


text:
Q: TableView: method editingStyleForRowAtIndexPath which editingStyle i have to use to have the result of this tutorial?
Table View Programming
I would like have a editingStyle without "-" or "+". If in the method editingStyleForRowAtIndexPath i return UITableViewCellEditingStyleNone i don't have "-" (for delete) or "+" (for insert) but i have my table's rows shifted to right e with blank space.
In the apple's tutorial there is not the blank space before of the rows's content.
What is the way to resolve this issue?
Thanks in advance

A: If you don't want the row to be editable and you don't want the row indented when the table view is in edit mode, then indicate that the rows can't be edited by returning NO from the tableView:canEditRowAtIndexPath: data source method. Of course you need to return YES for the index paths that can be edited but return NO for the index paths that can't.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (/* this index path can be edited */) {
        return YES;
    } else {
        return NO;
    }
}

A: To resolve my issue I have implemented this UITableViewDelegate method
-(BOOL)tableView:(UITableView*)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath*)indexPath;

that for every row of my table returns NO;
Thanks to all.


text:
Q: Is it free to use Amazon Cognito to authenticate users? According to Amazon Cognito Pricing, performing sync operations and/or using sync store space costs money.
But, what if I just want to use Amazon Cognito to authenticate users so that they can access AWS resources (S3 in my case). Is that free? I.e., does authenticating users with Cognito require performing sync operations or using sync store space?

A: Yes, using Amazon Cognito for authenticating users and retrieving temporary, limited privilege credentials for AWS resources is free.


text:
Q: The following RangeError was thrown building AnimatedBuilder: RangeError (index): Invalid value: Only valid value is 0: 1 I tried to make a list that can replace the items in it and animete when I remove and add items so I used the function ImplicitlyAnimatedReorderableList<> and when I tried to delete items from the list it's shows me this error:
 ════════ Exception caught by widgets library══════════════════════════════
The following RangeError was thrown building AnimatedBuilder(animation: AnimationController#1fbd2(⏮ 0.000; paused)➩_Linear, dirty, state: _AnimatedState#040d2):
RangeError (index): Invalid value: Only valid value is 0: 1

The relevant error-causing widget was:
  Reorderable-[<'1'>] file:///C:/Users/bentau/Desktop/checkIt/lib/SlideBar/Pages/ToDo.dart:172:26
When the exception was thrown, this was the stack:
#0      List.[] (dart:core-patch/growable_array.dart:149:60)
#1      _ToDoState.build.<anonymous closure>.<anonymous closure> (package:flutterapp/SlideBar/Pages/ToDo.dart:189:44)
#2      ReorderableState.build.buildChild (package:implicitly_animated_reorderable_list/src/reorderable.dart:123:21)
#3      ReorderableState.build.<anonymous closure> (package:implicitly_animated_reorderable_list/src/reorderable.dart:130:44)
#4      AnimatedBuilder.build (package:flutter/src/widgets/transitions.dart:1012:12)
................................................................................................................

This is my code:
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/SlideBar/Function/SlideBarMain.dart';
import 'package:flutterapp/SlideBar/Function/ToDoClass.dart';
import 'package:implicitly_animated_reorderable_list/implicitly_animated_reorderable_list.dart';
import 'package:implicitly_animated_reorderable_list/transitions.dart';
class ToDo extends StatefulWidget {
  @override
  _ToDoState createState() => _ToDoState();
}

class _ToDoState extends State<ToDo> {
  final GlobalKey<SlideBarMainState> _key = GlobalKey();
  final GlobalKey <FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<AnimatedListState> listKey = GlobalKey();
  List<ToDoData> restory = [ToDoData(Title: null, Context: null, done: false)];
  List<ToDoData> Data = [
    ToDoData(Title: "Finishing the ToDo", Context: "finish it fast", done: false),
  ];
  int yetdone = 1;
  String title;
  String TodoContext;
//  bool inReorder = false;
//
//  ScrollController scrollController;
//
//  @override
//  void initState() {
//    super.initState();
//    scrollController = ScrollController();
//  }

  void onReorderFinished(List<ToDoData> newItems) {
//    scrollController.jumpTo(scrollController.offset);
    setState(() {
//      inReorder = false;
      Data
        ..clear()
        ..addAll(newItems);
    });
  }
  Widget buildTitle() {
    //create title limiting
    return TextFormField(
      decoration: InputDecoration(labelText: "Title"),
      maxLength: 50, //75
      // ignore: missing_return
      validator: (String value) {
        if (value.isEmpty) {
          return 'Title is Required';
        }
      },
      onSaved: (String value) {
        title = value;
      },
    );
  }

  Widget buildTodoContext() {
    //create the context
    return TextFormField(
      decoration: InputDecoration(labelText: "context"),
      maxLength: 100,
      onSaved: (String value) {
        TodoContext = value;
      },
    );
  }

  createAddFunction(BuildContext context) {
    //new task creator screen
    return showDialog(context: context, builder: (context) {
      return AlertDialog(
          title: Text("Add New ToDo"),
          content: Container(
              margin: EdgeInsets.all(24),
              child: Form(key: formKey, child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  buildTitle(),
                  buildTodoContext(),
                  SizedBox(height: 50,),
                  RaisedButton(
                    child: Text("Save"),
                    onPressed: () {
                      formKey.currentState.save();
                      if (!formKey.currentState.validate()) {
                        return;
                      }
                      else {

                        Data.insert(yetdone, ToDoData(Title: title, Context: TodoContext, done: false,));
                        setState(() {
                          yetdone++;
                        });
                        Navigator.of(context).pop();
                      };
                    },
                  )
                ],
              )
              ))
      );
    });
  }

  Widget DoneBack() {
    //the background when you slide task right
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 20.0),
      color: Colors.green,
      child: const Icon(Icons.done, color: Colors.white,),
    );
  }

  Widget DeleteBack() {
    return Container(
      alignment: Alignment.centerRight,
      padding: EdgeInsets.only(right: 20.0),
      color: Colors.red,
      child: const Icon(Icons.delete, color: Colors.white,),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( // screen background
        backgroundColor: Colors.grey[600],
        appBar: AppBar(
          backgroundColor: Colors.grey[900],
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () => createAddFunction(context),
            ),
          ],
          leading:
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () => _key.currentState.SwitchFunc(),
          ),
          title: Text('ToDo'),
          centerTitle: true,

        ),
        body:
        Stack( // list of tasks
            children: <Widget>[
              ImplicitlyAnimatedReorderableList<ToDoData>(

                items: Data,
                shrinkWrap: true,
                areItemsTheSame: (a, b) => a.Index == b.Index,
                onReorderFinished: (item, from, to, newItems) => onReorderFinished(newItems),
                removeDuration: Duration.zero,
                itemBuilder: (context, itemAnimation, item, index) {
                  return Reorderable(
                    key: ValueKey(index.toString()),
                    builder: (context, dragAnimation, inDrag) {
                      final t = dragAnimation.value;
                      final elevation = lerpDouble(0, 8, t);
                      final color = Color.lerp(Colors.white, Colors.white.withOpacity(0.8), t);
                      return SizeFadeTransition(
                        sizeFraction: 0.7,
                        curve: Curves.easeInOut,
                        animation: itemAnimation,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(35, 5, 35, 5),
                            child: Dismissible(
                              key: UniqueKey(),
                              child: Card(
                                elevation: elevation,
                                color: color,
                                child: Data[index].done ? Stack(
                                    children: <Widget>[
                                      ListTile(
                                        title: RichText(text: TextSpan(
                                            text: Data[index].Title,
                                            style: TextStyle(color: Colors.black,
                                                decoration: TextDecoration.lineThrough)),),
                                        subtitle: RichText(text: TextSpan(
                                            text: Data[index].Context,
                                            style: TextStyle(color: Colors.grey[800],
                                                decoration: TextDecoration.lineThrough)),),
                                      ),
                                      Center(
                                        child: SizedBox(height: 80, width: 80, child: Image(image: AssetImage('assets/checkItEmpty.png'),)
                                        ),
                                      )
                                    ]
                                ) :
                                ListTile(
                                  title: RichText(text: TextSpan(text: Data[index].Title,
                                      style: TextStyle(color: Colors.black)),),
                                  subtitle: RichText(text: TextSpan(text: Data[index].Context,
                                      style: TextStyle(color: Colors.grey[800])),),
                                  trailing:Handle (
                                    delay: const Duration(milliseconds: 100),
                                    child: Icon(
                                      Icons.list,
                                      color: Colors.grey,
                                    ),
                                  )
                                ),
                              ),

                              onDismissed: (direction) {
                                setState(() {
                                  restory.add(ToDoData(Title: Data[index].Title, Context: Data[index].Context, Index: index, done: Data[index].done));
                                  Data[index].done ? null : yetdone--;
//                                  listKey.currentState.removeItem(
//                                    index,
//                                        (BuildContext context, Animation<double> animation) => buildItems(scaffold,animation,index),
//                                    duration: Duration.zero,);
                                });
                                  setState(
                                        () => Data.removeAt(index),
                                  );

                                if (direction == DismissDirection.startToEnd) {
                                  Data.insert(yetdone, ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: true));
restory.last.Context, done: true));

                                  restory.removeLast();
                                  setState(() {});
                                }
                                else {
                                Scaffold.of(context).showSnackBar(
                                      SnackBar(content: Text(
                                          "${restory.last.Title} task has removed"),
                                        action: SnackBarAction(
                                            label: "UNDO",
                                            onPressed: () {
                                              Data.insert(restory.last.Index < yetdone ? restory.last.Index : yetdone, ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: false));
//                                            Data.add( ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: false));
//                                              listKey.currentState.insertItem(restory.last.Index < yetdone ? restory.last.Index : yetdone);
                                              restory.removeLast();
                                              setState(() {
                                                yetdone++;
                                              });
                                            }
                                        ),
                                      ));
                                }
                              },
                              background: DoneBack(),
                              secondaryBackground: DeleteBack(),
                            )
                        )
                      );
                    },
                  );
                },

              ),

//              AnimatedList(
//                key: listKey,
//                initialItemCount:Data.length,
//                itemBuilder: (context,index,animation){
//                  return buildItems(Scaffold.of(context),animation,index);
//                },
//              ),
              Container(
                child: Align(
                  alignment: Alignment(0, 0.90),
                  child: RaisedButton(
                    padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
                    color: Colors.white,
                    onPressed: () => createAddFunction(context),
                    child: Text('Add Task',
                        style: TextStyle(fontSize: 20, color: Colors.black)),
                  ),
                ),
              ),
              ////////////////////////slide bar////////////////
              SlideBarMain(
                IsHome: false,
                key: _key,
              ),
            ]
        )
    );
  }


text:
Q: phpmyadmin - cannot create database I have a localhost installation of wordpress and have finished a website there. I want to make a second website so I created a new folder and downloaded and unzipped  WordPress in the folder. I am now trying to create a database for the second website.
I have opened phpMyAdmin:
1. When I click on create database it says 'no priveliges' but will not give me any further information.
2. If I go to the top and click on server:localhost, I get two messages:
  a. Version information: 4.1.4, latest stable version: 4.1.11.
  b.The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click here.
      1).  Clicking 'here' gets me this:
             PMA Database ... not OK [ Documentation ]
             General relation features Disabled
        a).  Clicking 'Documentation' gets me this:
                      404 Not Found
                      The requested URL /phpmyadmin/pmadb was not found on this server.
Being new to this, I am not sure what to do next and am afraid of doing something that will damage the work I have already done on my 1st site. My questions are:
1. how to update phpMyAdmin since I don't see that option and will that clobber my existing site in any way.
2. can anyone tell me why I can't create a database and what to do about it.
(note, I read somewhere to edit config.inc.php in phpmyadmin but inside of the files it warns not to edit it and I didn't know what change to make anyway).
Any advice will be greatly appreciated!!

A: I figured it out. I needed to log in to phpMyAdmin with username of 'root' (along with a previously established password).


text:
Q: Plot with Matplotlib using List - Datetime - Different Behaviour on Format Why Matplotlib has this strange behaviour with Date Data Type?

Matplotlib allows you to natively plots python datetime instances, and for the most part does a good job picking tick locations and string formats.
  From the documentation  "Fixing common date annoyances"

I also read this question that gave me some clues related to Matplotlib Date Format.
I also read the most voted questions about matplotlib and Datetime but I still don't understand the following behaviour.
#timestamp is a <class 'list'>
timestamp=['2019-02-04', '2019-01-15', '2018-10-08', '2018-07-09',
           '2018-04-09', '2018-02-08', '2017-09-08', '2017-09-08',
           '2017-07-07', '2017-04-07', '2017-01-09', '2016-10-07',
           '2016-07-01', '2016-03-25', '2015-12-27', '2015-09-25',
           '2015-06-26', '2015-03-27', '2014-12-24', '2014-10-06',
           '2014-07-02', '2014-03-28', '2013-12-20', '2013-09-27',
           '2013-06-11', '2013-03-27', '2012-12-27', '2012-09-26',
           '2012-06-13', '2012-03-28', '2011-12-14', '2011-09-28',
           '2011-06-14', '2011-03-30', '2010-12-15', '2010-09-29',
           '2010-06-19', '2010-03-31', '2009-12-29', '2009-09-30',
           '2009-06-17', '2009-04-01', '2008-12-20', '2008-08-25',
           '2008-08-25', '2008-06-19', '2008-03-19', '2008-03-19',
           '2006-04-11', '2005-12-27', '2005-09-28', '2005-07-02',
           '2005-04-20', '2004-12-21', '2004-10-20', '2004-07-21',
           '2003-09-22', '2003-08-20', '2002-12-31']

#time_python is a <class 'datetime.datetime'>
time_python=[datetime.strptime(d, "%Y-%m-%d") for d in timestamp]
#time_series is a <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
time_series=pd.to_datetime(timestamp)

array=np.arange(1,len(timestamp)+1)

time_2_num=mdates.date2num(time_series.to_pydatetime())

#First plot using the List Format as x axes
plt.subplot(411)
plt.bar(timestamp,array)
plt.xticks(rotation='vertical')

#Second plot using the padas Datatime Format as x axes
plt.subplot(412)
plt.bar(time_series,array)
plt.xticks(rotation='vertical')
plt.subplots_adjust(hspace = 1.2)

#Third plot using the DateTime Format as x axes
plt.subplot(413)
plt.bar(time_python,array)
plt.xticks(rotation='vertical')
plt.subplots_adjust(hspace = 1.2)

#Fourth plot using the Matplot Date Format as x axes
plt.subplot(414)
plt.bar(time_2_num,array)
plt.xticks(rotation='vertical')
plt.subplots_adjust(hspace = 1.2)

plt.gcf().autofmt_xdate()

plt.show()

The desired result is obviously the first plot.

I want to understand better why the bars of the II,III,IV plot has this representation, different from the I. The y input is the same for the 4 plots.

A: First, the difference become more obvious if you remove the line plt.gcf().autofmt_xdate() because that removes the labels from all but the last plot.

First Plot
The first plot is "categorical" plot. The values for the x axis are strings. They are shown one by one in the order they appear in the input list/array and each gets its own label. In this case matplotlib does not know that the strings represent dates and indeed you could also supply a list of fruits instead (["Apple", "Banana", "Cherry", ...])
Second / Third plot
Those is the intended behaviour for datetime plots in matplotlib. Matplotlib works with datetime or numpy.datetime64 objects equally well. The axis is a true scale in the sense of a line with a defined linear metric (i.e. the distance between monday and wednesday is twice as large as between saturday and sunday). Concerning the units of such datetime axes the documentation states

Matplotlib represents dates using floating point numbers specifying the number of days since 0001-01-01 UTC, plus 1.

Because matplotlib recognizes the datetime input, it will automatically choose a date locator and formatter as to have the ticks at useful locations
Fourth plot
The fourth plot is in principle identical to the two above. The only difference that matplotlib has no chance of knowing that the numbers (like 731000) are meant to denote dates (they could be distance between earth and satellites as well).
You can still get the same appearance as in the two plots above by manually setting a locator and formatter, e.g. adding the following lines to the last plot
loc = mdates.AutoDateLocator()
plt.gca().xaxis.set_major_locator(loc)
plt.gca().xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))

results in the same plot as the second, third plot

A: For the first graph, you are sending timestamp which is purely strings. Matplotlib treats it as strings. If you look at the plot on its own, you will see the labels are just the strings from timestamp in the same order.
The other 3 methods convert this string into timestamps, which matplotlib treats differently.
timestamp=['2019-02-04', '2019-01-15', '2018-10-08', '2018-07-09',
       '2018-04-09', '2018-02-08', '2017-09-08', '2017-09-08',
       '2017-07-07', '2017-04-07', '2017-01-09', '2016-10-07',
       '2016-07-01', '2016-03-25', '2015-12-27', '2015-09-25',
       '2015-06-26', '2015-03-27', '2014-12-24', '2014-10-06',
       '2014-07-02', '2014-03-28', '2013-12-20', '2013-09-27',
       '2013-06-11', '2013-03-27', '2012-12-27', '2012-09-26',
       '2012-06-13', '2012-03-28', '2011-12-14', '2011-09-28',
       '2011-06-14', '2011-03-30', '2010-12-15', '2010-09-29',
       '2010-06-19', '2010-03-31', '2009-12-29', '2009-09-30',
       '2009-06-17', '2009-04-01', '2008-12-20', '2008-08-25',
       '2008-08-25', '2008-06-19', '2008-03-19', '2008-03-19',
       '2006-04-11', '2005-12-27', '2005-09-28', '2005-07-02',
       '2005-04-20', '2004-12-21', '2004-10-20', '2004-07-21',
       '2003-09-22', '2003-08-20', '2002-12-31']

array=np.arange(1,len(timestamp)+1)
plt.bar(timestamp,array)
plt.xticks(rotation='vertical')
fig = plt.gcf()
fig.set_size_inches(18.5, 10.5)


text:
Q: SQL avoid duplicate being inserted into staging/temp table I have a site that handles uploads of CSV files and inserts them to the DB. The CSV templates are 229 fields, with multiple rows per file. Since there are multiple rows, there may be times that two CSV files have a record from a previous file and I want to avoid duplicates.
I have the CSV files currently being uploaded into a 230 field staging table (one more field than the CSV for an auto incrementing primary key), and then they split into smaller tables.
My issue: when the CSV is uploaded I want any records that already exist to overwrite or ignore so that I only have one of each 229 field record.
Is there a way to do this just on the staging table so I don't have to worry about the smaller tables?

A: If all your previously imported records are in the temp table, you could use something like this:
select *
from `table`
group by Col1, Col2, Col3 [,...]
having count(*) = 1
order by id asc;

Basically, select all the records, then group them by each column which you want to distinct them, and filter the result by the group count (where the group count > 1 there is a multiple of the same records).
After this, you only have to filter out the newly added records.
But keep in mind, if there is a possibility of duplicates in the same csv file, they going to be skipped by this method. If that's the case, you can use distinct first for your dataset.

A: First load data from the file into a temp_table and then run a query
SELECT * FROM temp_table INTO target_table
WHERE temp_table.value NOT IN (SELECT value FROM target_table)

Here temp_table.value is the value by which you define if the rows you copy already exist in a target_table


text:
Q: How to use np.random.uniform() for real world examples
What I tried
from numpy import random
import matplotlib.pyplot as plt

import seaborn as sns

sns.distplot(random.uniform(0,30, 5), hist=True)

plt.show()

Result which I got
Here its showing 8% and 12%, but my required answer as according to manual prediction is 16%. I think I am confused about the size parameter in `random.binomial()

A: From what I understand you want to simulate the result.
Try the following
import numpy as np

# sample 100k uniform random values (it can be any large number) from 0 to 30
waiting_time = np.random.uniform(0, 30, size = 100_000)

# caclulate the proportion that are between 10 and 15
np.mean((waiting_time >=10) & (waiting_time <= 15))
# will be around 0.166 i.e. around 16.6%.

Plot
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(waiting_time)
plt.show();

# OR
import matplotlib.pyplot as plt
plt.hist(waiting_time);


text:
Q: Unexpected token 'BillingState' My Code is:
public with sharing class AccountTriggerHandler {
    public static List<Account> CreateAccounts(){
        return [SELECT Id, Name FROM Account WHERE ShippingState == BillingState];
    }
}

why there is an error

"unexpected token BillingState"?

The requirement is:

Create an Apex class named AccountTriggerHandler that contains a
  public static method called CreateAccounts to accept the List of
  Account objects For each Account record, before saving, ensure that
  the ShippingState field has the same value as the BillingState field

A: You need to ensure that the ShippingState field has the same value as the BillingState field before records are saved. You need to invoke it in before insert context and assign BillingState to ShippingState
Trigger:
trigger AccountTrigger on Account (before insert) {

    if(Trigger.isBefore && Trigger.isInsert)
        AccountTriggerHandler.CreateAccounts(Trigger.new);

}

AccountTriggerHandler:
public class AccountTriggerHandler {

    public static void CreateAccounts(List<Account> accounts) {
        for(Account acc : accounts) {
            acc.ShippingState = acc.BillingState;
        }
    }

}

A: As far as this requirement is concerned, you are going a little bit off direction, the requirement says to accept a List of Accounts and not return List of Accounts and ensure that the ShippingState field has the same value as the BillingState field. So you will have to create a method

*

*Which accepts list of Account records.

*Loop through the records and assign ShippingState equal to BillingState
And regarding the things you are trying, unfortunately you cannot do field to field comparison in salesforce i.e. you cannot compare values of BillingState and ShippingState. For such kind of scenarios, you can refer salesforce help documentation i.e. Field to field comparison in an SOQL WHERE clause wherein you will have to create a boolean formula field (where formula will be ShippingState=BillingState) and query for those records where this boolean field is true.
And if you want to compare values without using a new formula field, you can do that in Apex which you cannot do in SOQL
for(Account acc: lstAccount){
    if(acc.ShippingState==acc.BillingState){
        //do your stuff here
    }
}

And just a note about the the bind variable, you should use : in the SOQL query when using bind variables. You can check this Using Apex Variables in SOQL and SOSL Queries for further help on this topic. Also, you should be using = instead of == in the SOQL query. Example of using variables in Apex
string sBillingState='SE';
[SELECT Id, Name FROM Account WHERE ShippingState =:sBillingState];

A: Hi I think you are looking to query account where ShippingState and BillingState are equals.
In this scenario, you can create a formula field, the return type for formula field will be boolean/Checkbox. Formula should be ShippingState = BillingState.
This formula field will return you either true or false.
You can use this formula field in your query
public with sharing class AccountTriggerHandler {
    public static List<Account> CreateAccounts(){
        return [SELECT Id, Name FROM Account WHERE CustomforMulaField__c = true];
    }
}

Hope it answer your question


text:
Q: How to create an option under "Open With" option when i right click on a file? I am developing a RCP application that creates and shows chart. I have already developed the chart creation part. So now my goal is to when my runtime eclipse starts the package explorer already has the .csv file based on which i am creating chart. Now i want to right click on the .csv file and "Open with" should have an option called "ChartView" that on click will create a view with the chart which defines the selected file.
So how can i create a new option in "Open With" category that will create a new view on click. I tried to search this issue but unfortunately did not find any clue. Please help. Thanks

A: The "Open With" category is populated by the list of Editors that say they can open the file. You add an editor using the org.eclipse.ui.editors extension point.
http://help.eclipse.org/oxygen/topic/org.eclipse.platform.doc.isv/reference/extension-points/org_eclipse_ui_editors.html?cp=2_1_1_147


text:
Q: uploading png images with transparent background using php and keeping the background transparent I have a php page which takes a user image and uploads it to my webserver.
I have just noticed that if I have a png with a transparent background, and upload it, the background is changed to white.
For example I create a new image in photoshop with a transparent background and then add a coloured circle to the page. I save the image as a png and uplod to the server via ftp then the image is shown as a circle on the webpage as the background is transparent.
If I upload the image using php with a file input box the image is changed to white.
I have tried to use imagealphablending,imagecolorallocatealpha,imagefill and imagesavealpha to retain the transparent background but it just changes the bg to black.
any clues?
heres my php code
        <?php
    $path = "../userfiles/orig/";
    $userpath="../".$_REQUEST['userpath']."/";

    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }

    $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");

    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name)){
                 $ext = getExtension($name);

                if(in_array($ext,$valid_formats)){

                    if($size<(2048*2048)){
                        $time1=time();
                        $actual_image_name =$time1."_".str_replace(" ", "_", $name);
                        $tmp = $_FILES['photoimg']['tmp_name'];

                        if(move_uploaded_file($tmp, $path.$actual_image_name)){
                                     $image=$actual_image_name;
                                     /*--------resize image-----------*/
                                     $size = 320; // the imageheight
                                     $filedir = '../userfiles/orig/'; // the directory for the original image
                                     $thumbdir = $userpath; // the directory for the resized image
                                     $prefix = $time1.'_'; // the prefix to be added to the original name
                                     $maxfile = '20000000';
                                     $mode = '0666';
                                     $userfile_name =str_replace(" ", "", $_FILES['photoimg']['name']);
                                     $userfile_tmp = str_replace(" ", "", $_FILES['photoimg']['tmp_name']);
                                     $userfile_size =$_FILES['photoimg']['size'];
                                     $userfile_type = $_FILES['photoimg']['type'];

                                     if (isset($_FILES['photoimg']['name'])){
                                         $prod_img = $filedir.$actual_image_name;
                                         $prod_img_thumb = $thumbdir.$prefix.$userfile_name;
                                         move_uploaded_file($userfile_tmp, $prod_img);
                                         chmod ($prod_img, octdec($mode));
                                         $sizes = getimagesize($prod_img);
                                         $aspect_ratio = $sizes[1]/$sizes[0];

                                         if ($sizes[1] <= $size){
                                             $new_width = $sizes[0];
                                             $new_height = $sizes[1];
                                         }else{
                                             $new_height = $size;
                                             $new_width = abs($new_height/$aspect_ratio);
                                         }
                                         $destimg=ImageCreateTrueColor($new_width,$new_height)
                                             or die('Problem In Creating image');

                                        switch($ext){
                                            case "jpg":
                                            case "jpeg":
                                            case "JPG":
                                            case "JPEG":
                                                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            case "PNG":
                                            case "png":
                                                $srcimg = imageCreateFromPng($prod_img)or die('Problem In opening Source Image');
                                                imagealphablending($destimg, false);
                                                $colorTransparent = imagecolorallocatealpha($destimg, 0, 0, 0x7fff0000);
                                                imagefill($destimg, 0, 0, $colorTransparent);
                                                imagesavealpha($destimg, true);

                                            break;
                                            case "BMP":
                                            case "bmp":
                                                $srcimg = imageCreateFromBmp($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            case "GIF":
                                            case "gif":
                                                $srcimg = imageCreateFromGif($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            default:
                                                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                                        }

                                        if(function_exists('imagecopyresampled')){
                                             imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                                             or die('Problem In resizing');
                                         }else{
                                             Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                                             or die('Problem In resizing');
                                         }
                                         ImageJPEG($destimg,$prod_img_thumb,90)
                                             or die('Problem In saving');

                                     }
                                unlink($prod_img);
                                echo "";
                            }else{
                            echo "Fail upload folder with read access.";
                            }
                    }else{
                    echo "Image file size max 3 MB";
                    }

                }else{
                    echo "Invalid file format..";
                }
            }else{
            echo "Please select image..!";
            }

        exit;
    }
    ?>

A: <?php
$path = "../userfiles/orig/";
$userpath="../".$_REQUEST['userpath']."/";

function getExtension($str) {
  $i = strrpos($str,".");
  if (!$i) { return ""; }
  $l = strlen($str) - $i;
  $ext = substr($str,$i+1,$l);
  return $ext;
}

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
  $name = $_FILES['photoimg']['name'];
  $size = $_FILES['photoimg']['size'];

  if(strlen($name)){
    $ext = getExtension($name);

    if(in_array($ext,$valid_formats)){

      if($size<(2048*2048)){
        $time1=time();
        $actual_image_name =$time1."_".str_replace(" ", "_", $name);
        $tmp = $_FILES['photoimg']['tmp_name'];

        if(move_uploaded_file($tmp, $path.$actual_image_name)){
          $image=$actual_image_name;
          /*--------resize image-----------*/
          $size = 320; // the imageheight
          $filedir = '../userfiles/orig/'; // the directory for the original image
          $thumbdir = $userpath; // the directory for the resized image
          $prefix = $time1.'_'; // the prefix to be added to the original name
          $maxfile = '20000000';
          $mode = '0666';
          $userfile_name =str_replace(" ", "", $_FILES['photoimg']['name']);
          $userfile_tmp = str_replace(" ", "", $_FILES['photoimg']['tmp_name']);
          $userfile_size =$_FILES['photoimg']['size'];
          $userfile_type = $_FILES['photoimg']['type'];

          if (isset($_FILES['photoimg']['name'])){
            $prod_img = $filedir.$actual_image_name;
            $prod_img_thumb = $thumbdir.$prefix.$userfile_name;
            move_uploaded_file($userfile_tmp, $prod_img);
            chmod ($prod_img, octdec($mode));
            $sizes = getimagesize($prod_img);
            $aspect_ratio = $sizes[1]/$sizes[0];

            if ($sizes[1] <= $size){
              $new_width = $sizes[0];
              $new_height = $sizes[1];
            }else{
              $new_height = $size;
              $new_width = abs($new_height/$aspect_ratio);
            }
            $destimg=ImageCreateTrueColor($new_width,$new_height)
            or die('Problem In Creating image');

            switch($ext){
              case "jpg":
              case "jpeg":
              case "JPG":
              case "JPEG":
                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                break;
              case "PNG":
              case "png":
                $srcimg = imageCreateFromPng($prod_img)or die('Problem In opening Source Image');
                imagealphablending($destimg, false);
                $colorTransparent = imagecolorallocatealpha($destimg, 0, 0, 0, 0x7fff0000);
                imagefill($destimg, 0, 0, $colorTransparent);
                imagesavealpha($destimg, true);

                break;
              case "BMP":
              case "bmp":
                $srcimg = imageCreateFromBmp($prod_img)or die('Problem In opening Source Image');
                break;
              case "GIF":
              case "gif":
                $srcimg = imageCreateFromGif($prod_img)or die('Problem In opening Source Image');
                break;
              default:
                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
            }

            if(function_exists('imagecopyresampled')){
              imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
              or die('Problem In resizing');
            }else{
              Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
              or die('Problem In resizing');
            }

            // Saving an image
            switch(strtolower($ext)){
              case "jpg":
              case "jpeg":
                ImageJPEG($destimg,$prod_img_thumb,90) or die('Problem In saving');
                break;

              case "png":
                imagepng($destimg,$prod_img_thumb) or die('Problem In saving');
                break;

              case "bmp":
                imagewbmp($destimg, $prod_img_thumb)or die('Problem In saving');
                break;

              case "gif":
                imagegif($destimg,$prod_img_thumb) or die('Problem In saving');
                break;

              default:
                // if image format is unknown, and you whant save it as jpeg, maybe you should change file extension
                imagejpeg($destimg,$prod_img_thumb,90) or die('Problem In saving');
            }

          }
          unlink($prod_img);
          echo "";
        }else{
          echo "Fail upload folder with read access.";
        }
      }else{
        echo "Image file size max 3 MB";
      }

    }else{
      echo "Invalid file format..";
    }
  }else{
    echo "Please select image..!";
  }

  exit;
}
?>

Sorry for my english. Problem is it that you trying to save image using imagejpeg, which means new image can't use transparent color anymore. If source image was PNG, you should save it using imagepng.


text:
Q: Banach limit for nets It is well known that on the Banach space $l^{\infty}\left(\mathbb{N}\right)$ of bounded functions $f:\mathbb{N}\to\mathbb{C}$ with the sup-norm, there exists a (non-unique) Banach limit. This is a linear functional $L$ that is positive, bounded and shift-invariant. It can be seen that such a functional satisfies, for every real-valued $f\in l^{\infty}\left(\mathbb{N}\right)$,
$$\liminf_{n\to\infty} f\left(n\right) \leq L\left(f\right) \leq \limsup_{n\to\infty}f\left(n\right).$$
I was wondering what if we replace $\mathbb{N}$ by a directed set. More specifically, let $\mathbf{N}$ be a directed set and consider the Banach space $l^{\infty}\left(\mathbf{N}\right)$ of bounded functions (nets) $f:\mathbf{N}\to\mathbb{C}$ with the sup-norm. While it seems that there is no a natural analog to the shift-invariance property, there are notions of liminf and limsup for nets (see for instance here). Then my question is as follows.

Let $\mathbf{N}$ be a directed set. Does there exist a bounded linear functional $L$ on $l^{\infty}\left(\mathbf{N}\right)$ such that
$$\liminf_{n\in\mathbf{N}} f\left(n\right) \leq L\left(f\right) \leq \limsup_{n\in\mathbf{N}}f\left(n\right)$$
for every real-valued net $f\in l^{\infty}\left(\mathbf{N}\right)$?

When reading the standard proofs that a Banach limit exists for $l^{\infty}\left(\mathbb{N}\right)$, there is an essential use of partial sums. Namely, we are looking at the subspace of those elements in $l^{\infty}\left(\mathbb{N}\right)$ whose finite partial sums are uniformly bounded, and using Hahn-Banach theorem to extend a seminorm from it to the whole space. For general nets (say uncountable) it seems that this should not work anymore.


text:
Q: asp.net, deleting a cookie This isn't the same as answered elsewhere (afaik), I'm documenting my answer for my own future use, but I'd also be interested in knowing more
I've created a cookie on the client in javascript like so
document.cookie = "Navigating=true";

and I've tried removing it on the server by setting the expiry date with
string cookieName = "Navigating";
Response.Cookies.Remove(cookieName);

HttpCookie myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-2);
Response.Cookies.Add(myCookie);

It doesn't work, here's the network trace

Note the name is wrong, it's cookie11 (I've removed the other cookies from the screenshot, it was the 11th cookie)
So now I set the value of the cookie to be something
myCookie.Value = "true";

and try again, it still doesn't work, screenshot 2

The key is now right but the path is still wrong, so finally
        if (Request.Cookies[cookieName] != null)
        {
            //Response.Cookies.Remove(cookieName);

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie.Expires = DateTime.Now.AddDays(-2);
            myCookie.Value = "true";
            myCookie.Path = "";
            Response.Cookies.Add(myCookie);
        }

and now the server removes the cookie correctly

This works, so there's no question, but I'd be interested in knowing why the javascript cookie doesn't have a path but the asp.net one does by default

A: Javascript cookies are without path by default. As you wrote, this can cause mismatches when using ASP.NET with Javascript when handling cookies. By default, ASP.NET sets the cookie path as / (root). So - to ensure full compatability, when creating cookies via Javascript, you can set a path by simply using:
document.cookie="Navigating=true;path=/";


text:
Q: For some $A \in \left(-\frac{1}{2},\frac{1}{2} \right)$ and $c \in (0,1), \; f(1)=f(0)+f'\left(\frac{1}{2}\right)+Af''(c)$
Suppose $f(x)$ is continuous on $[0,1]$ and twice differentiable on $(0,1)$.
Show that there exists $A \in \left(-\frac{1}{2},\frac{1}{2} \right)$ and $c \in (0,1)$ such that
\begin{equation}
f(1)=f(0)+f'\left(\frac{1}{2}\right)+Af''(c)
\end{equation}

By MVT, there exists $c \in (0,1)$ such that
\begin{equation}
f'(c)=\frac{f(1)-f(0)}{1-0} = f(1)-f(0)
\end{equation}
Comparing with the required statement I see that it suffices to show, for some $A \in \left(-\frac{1}{2},\frac{1}{2} \right)$,
\begin{equation}
f'(c)=f'\left(\frac{1}{2}\right)+Af''(c)
\end{equation}
Rearranging,
\begin{equation}
\frac{f'(c)-f'\left(\frac{1}{2}\right)}{A}=f''(c)
\end{equation}
This looks like an application of MVT again, but I'm not very sure how to proceed, as $c$ appears on both LHS and RHS.
Any help would be appreciated!

A: $f'(c)-f'(\frac 1 2) =(c-\frac 1 2)f''(d)$ for some $d$ between $c$ and $\frac 1 2$ Note that $|c-\frac 1 2| \leq \frac 1 2$. Hence the required equation holds with $A=c-\frac 1 2$ and $c$ changed to $d$.


text:
Q: What are the differences between "shop," "shoppe," and "store"? What are the differences between shop, shoppe, and store?

A: While I like @Jigar Joshi's answer, I'll provide some American Connotation, if I can. (Caveat, not a professional culturist)
Shop
I would say that a shop is somewhere you go to have a service preformed, or only provides a single or narrowly focused good.  Usually contains a workshop of some kind where the goods are made on-site for the customer.

*

*Body Shop refers to an auto repair facility (autobody shop)

*Wood Shop refers to a place where you can go to get custom woodworking done

*Coffee Shop a place you can go to get hand-made drinks

*Butcher's Shop a place to get custom cuts of meat

Store
I would say that a store is the more common American term for a place you go to buy something.  They usually have many different sections and offer a wider variety of goods than a shop.  The goods you purchase are usually made off-site and only stored on location.

*

*Department Store buy furnishings and clothes for each room of the house

*Grocery Store buy food and many other consumables

*Online Store buy anything! :D

Shoppe
Generally a fancier term, as @Jigar Joshi mentioned, to give an air of authenticity and aristocracy.

*

*Coffee Shoppe here you can buy even more expensive fancy coffee.

But where ever you go, you'll end up shopping regardless of the store.

A: I'm presuming you're referring to these words used as nouns to mean a mercantile business of some sort. Historically, stores were businesses which kept inventory to be sold and shops where businesses where items were manufactured or repaired. Nowadays, shop and store are generally synonymous, but each has slightly more typical uses depending on what is being sold.
In my part of the world (Canada) you would generally refer to most commercial places of business as a store (grocery, convenience, clothes, book, furniture) while shops are reserved for repair, flowers, or gifts (gift shop is quite idiomatic.) Thus, you would typically hear bicycle shop, rather than store, because repairs are done there. It would not sound that strange to hear shop when referring to clothes, book or furniture stores, however.
Shoppe is an archaic spelling of shop and is used only in proper names of places wanting to sound quaint and old-fashioned. The Pop Shoppe and The Medicine Shoppe are a couple canadian examples.

A: In England and Australia a shop is what North Americans refer to as a store.  A shop is a place for conducting retail business.
As pointed out above, some retailers may brand their shop as a Megastore because the term store has become trendy in advertising but it is nevertheless still a shop.
Store only applies to a 'department store' (a shop with several departments) or a 'general store' in a village or small community which sells a variety of essentials.
Another international curiosity:  I notice in the spread of English in German websites, they have online shops rather than stores.

A: In American English:
Store - A place to purchase things.
Shop - I think primarily is used as a short form of 'workshop'.  I don't hear it being used very often as a synonym of 'store', although it is a valid usage.
Shoppe - Used on stores to make them sound medieval.

A: A store usually 'stores' perishable items. Shoppe is a mediaeval term which is unlikely to have been in actual use when the shop was first opened, unless it is very old. Shops can sell anything, and I would say include a store.


text:
Q: How to scrape Google SERP using Python I am trying to scrape some Google search results. I followed several tutorials on the web, however I have the problem, that the results contain the "cookie box" that you first need to accept.
This is my code:
from bs4 import BeautifulSoup
import requests
import csv
import re

urls = ["https://google.de/search?q=AL-KO Robolinho 110 preis",
        "https://google.de/search?q=AL-KO Robolinho 1150 W preis",
        "https://google.de/search?q=AL-KO Robolinho 300 E preis",
        "https://google.de/search?q=Yard Force X80i"]

fields = ["Price"]

with open('crawl-single-attribute/price.csv', 'w', newline="") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(fields)

    for url in urls:
        print('URL: ' + url)
        source = requests.get(url).text
        soup = BeautifulSoup(source, 'lxml')
        model = dict()

        print(soup)

And this is my result:
URL: https://google.de/search?q=AL-KO Robolinho 110 preis
<!DOCTYPE html>
<title>Bevor Sie zur Google Suche weitergehen</title><meta content="initial-scale=1, maximum-scale=5, width=device-width" name="viewport"/><link href="//www.google.com/favicon.ico" rel="shortcut icon"/>
Anmelden

Bevor Sie zur Google Suche weitergehen

Google verwendet Cookies und Daten für Folgendes:

Dienste anbieten und betreiben, z. B. Störungen prüfen und Maßnahmen gegen Spam, Betrug oder Missbrauch ergreifen

Daten zu Zielgruppeninteraktionen und Websitestatistiken erheben, um zu verstehen, wie unsere Dienste verwendet werden

Wenn Sie zustimmen, verwenden wir Cookies und Daten auch für Folgendes:

Qualität unserer Dienste verbessern und neue Dienste entwickeln

Werbung ausliefern und die Effektivität von Werbung messen

Personalisierte Inhalte anzeigen, abhängig von Ihren Einstellungen

Personalisierte oder allgemeine Werbung bei Google und im Web anzeigen, abhängig von Ihren Einstellungen

Die Auswahl nicht personalisierter Inhalte und Werbeanzeigen kann davon abhängen, welche Inhalte Sie sich gerade ansehen und wo Sie sich befinden (die Anzeigenbereitstellung basiert auf dem allgemeinen Standort). Personalisierte Inhalte und Werbeanzeigen können ebenfalls darauf basieren, darüber hinaus aber auch auf Aktivitäten wie Suchanfragen bei Google und Videos, die Sie sich bei YouTube ansehen. Zu personalisierten Inhalten und Werbeanzeigen gehören beispielsweise Dinge wie relevantere Ergebnisse und Empfehlungen, eine individuelle YouTube-Startseite und Werbung, die auf Ihre Interessen zugeschnitten ist.
Klicken Sie auf "Anpassen", um sich Ihre Möglichkeiten anzusehen. Zu diesen gehören zum Beispiel Steuerelemente, um Cookies für die Personalisierung zu deaktivieren, oder Informationen zu Steuerelementen auf Browserebene, mit denen einige oder alle Cookies für andere Zwecke deaktiviert werden können.  Besuchen Sie bei Bedarf jederzeit g.co/privacytools.

Anpassen<form action="https://consent.google.de/s" method="POST" style="display:inline;"><input name="gl" type="hidden" value="DE"/><input name="m" type="hidden" value="0"/><input name="pc" type="hidden" value="srp"/><input name="continue" type="hidden" value="https://www.google.de/search?q=AL-KO%20Robolinho%20110%20preis"/><input name="ca" type="hidden" value="r"/><input name="x" type="hidden" value="8"/><input name="v" type="hidden" value="cb.20210615-14-p0.de+FX+101"/><input name="t" type="hidden" value="ADw3F8gm29ymoJbw-6FRb_NfSx3E0sy9CQ:1624224939770"/><input name="hl" type="hidden" value="de"/><input name="src" type="hidden" value="1"/><input aria-label="In die Verwendung von Cookies und anderen Daten zu den beschriebenen Zwecken einwilligen" class="button" type="submit" value="Ich stimme zu"/></form>

<form action="https://consent.google.de/ml" method="get"><select id="languageselect" name="hl"><option value="af">Afrikaans</option><option value="az">azərbaycan</option><option value="bs">bosanski</option><option value="ca">català</option><option value="cs">Čeština</option><option value="cy">Cymraeg</option><option value="da">Dansk</option><option selected="" value="de">Deutsch</option><option value="et">eesti</option><option value="en-GB">English (United Kingdom)</option><option value="en">English (United States)</option><option value="es">Español (España)</option><option value="es-419">Español (Latinoamérica)</option><option value="eu">euskara</option><option value="fil">Filipino</option><option value="fr-CA">Français (Canada)</option><option value="fr">Français (France)</option><option value="ga">Gaeilge</option><option value="gl">galego</option><option value="hr">Hrvatski</option><option value="id">Indonesia</option><option value="zu">isiZulu</option><option value="is">íslenska</option><option value="it">Italiano</option><option value="sw">Kiswahili</option><option value="lv">latviešu</option><option value="lt">lietuvių</option><option value="hu">magyar</option><option value="ms">Melayu</option><option value="nl">Nederlands</option><option value="no">norsk</option><option value="uz">o'zbek</option><option value="pl">polski</option><option value="pt-BR">Português (Brasil)</option><option value="pt-PT">Português (Portugal)</option><option value="ro">română</option><option value="sq">shqip</option><option value="sk">Slovenčina</option><option value="sl">slovenščina</option><option value="sr-Latn">srpski (latinica)</option><option value="fi">Suomi</option><option value="sv">Svenska</option><option value="vi">Tiếng Việt</option><option value="tr">Türkçe</option><option value="el">Ελληνικά</option><option value="be">беларуская</option><option value="bg">български</option><option value="ky">кыргызча</option><option value="kk">қазақ тілі</option><option value="mk">македонски</option><option value="mn">монгол</option><option value="ru">Русский</option><option value="sr">српски</option><option value="uk">Українська</option><option value="ka">ქართული</option><option value="hy">հայերեն</option><option value="iw">עברית</option><option value="ur">اردو</option><option value="ar">العربية</option><option value="fa">فارسی</option><option value="am">አማርኛ</option><option value="ne">नेपाली</option><option value="mr">मराठी</option><option value="hi">हिन्दी</option><option value="as">অসমীয়া</option><option value="bn">বাংলা</option><option value="pa">ਪੰਜਾਬੀ</option><option value="gu">ગુજરાતી</option><option value="or">ଓଡ଼ିଆ</option><option value="ta">தமிழ்</option><option value="te">తెలుగు</option><option value="kn">ಕನ್ನಡ</option><option value="ml">മലയാളം</option><option value="si">සිංහල</option><option value="th">ไทย</option><option value="lo">ລາວ</option><option value="my">မြန်မာ</option><option value="km">ខ្មែរ</option><option value="ko">한국어</option><option value="ja">日本語</option><option value="zh-CN">简体中文</option><option value="zh-TW">繁體中文</option><option value="zh-HK">繁體中文 (香港)</option></select><input name="oldhl" type="hidden" value="de"/><input name="gl" type="hidden" value="DE"/><input name="m" type="hidden" value="0"/><input name="pc" type="hidden" value="srp"/><input name="continue" type="hidden" value="https://www.google.de/search?q=AL-KO%20Robolinho%20110%20preis"/><input name="src" type="hidden" value="1"/><input type="submit" value="Sprache ändern"/></form>Datenschutzerklärung Nutzungsbedingungen

[Finished in 0.539s]

I get the results page in German, "Bevor Sie zur Google Suche weitergehen" translates to "Before you move on to Google Search". And so on... this is the cookie notice you always get if you are not logged in and haven't accepted the cookies yet. How can I bypass that?

A: This is a common problem when scraping websites.
Actually the library you are using, namely BeautifulSoup is built around the idea of parsing HTML code to extract data from it:

Beautiful Soup transforms a complex HTML document into a complex tree of Python objects. /beautiful-soup-4 doc.

And that's fairly normal since it is used for web-scraping. However this is not really meant to interact with the page. For that, you will need a "real" browser. This can be automated with other tools better suited for the job like Selenium which allows you to interact with the page and even connect yourself to an account. Selenium uses a real browser and interact with it using an API.
Actually, I'm currently working on a project to reconnect to my ISP using Selenium. It can be a good example and starting point for you: qt-autoconnect.
Just remember you can use both at the same time: using Selenium to accept cookies, get connected and retrieve the raw HTML then use BeautifulSoup to parse the HTML!
As a conclusion, here | Medium.com is a nice tutorial on how to use Selenium then BeautifulSoup to keep you going.
Have fun!

A: You are getting the cookie pop-up because you are not passing the user-agent to the request headers to act as a "real" user visit. By default requests user-agent is python-requests and websites understand that it's most likely a script that sends a request. Check what's your user-agent.
Besides passing headers, you can also pass URL parameters to the request, for example:
params = {
    "q": query,
    "hl": "de",             # language of the search
    "gl": "de",             # country of the search
}

html = requests.get("<URL>", params=params)

I propose to change the list of urls to the list of search queries in order to pass them to the query parameters.
Code example:
from bs4 import BeautifulSoup
import requests, lxml

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}

query_list = [
    "AL-KO Robolinho 110 price",
    "AL-KO Robolinho 1150 W price",
    "AL-KO Robolinho 300 E price",
    "Yard Force X80i price"
]

for query in query_list:
    # https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
    params = {
        "q": query,
        "hl": "de",             # language of the search
        "gl": "de",             # country of the search
    }

    print('Query: https://google.de/search?q=' + query)

    html = requests.get("https://google.de/search", params=params, headers=headers, timeout=30)
    soup = BeautifulSoup(html.text, "lxml")

I'm assuming you meant to extract the price in the response field:

I have 2 ways to find out this price:

*

*To extract all text.

price = soup.select_one(".IZ6rdc").text
print(price)

Output:
799 Euro
"899,00 €"
"449,78 €"

*To extract only the price.

# https://regex101.com/r/rxH4fo/1
price = float(re.search(r"^(\S+)", soup.select_one(".IZ6rdc").text).group().replace(",", ".").replace('"', ''))
print(price)

Code
Explanation

re.search()
to find a price without a currency and return matched object.

group()
to extract the value from the matched object.

replace()
to replace all commas with dots and remove quotes.

float()
to convert string to float.

Output:
799.0
899.0
449.78

Code and full example in online IDE:
from bs4 import BeautifulSoup
import requests, csv, re, lxml

# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}

query_list = [
    "AL-KO Robolinho 110 price",
    "AL-KO Robolinho 1150 W price",
    "AL-KO Robolinho 300 E price",
    "Yard Force X80i price"
]

fields = ["Price"]

with open('crawl-single-attribute/price.csv', 'w', newline="") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(fields)

    for query in query_list:
        # https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
        params = {
            "q": query,
            "hl": "de",             # language of the search
            "gl": "de",             # country of the search
        }

        print('Query: https://google.de/search?q=' + query)

        html = requests.get("https://google.de/search", params=params, headers=headers, timeout=30)
        soup = BeautifulSoup(html.text, "lxml")

        try:
            # https://regex101.com/r/rxH4fo/1
            price = float(re.search(r"^(\S+)", soup.select_one(".IZ6rdc").text).group().replace(",", ".").replace('"', ''))
            # price = soup.select_one(".IZ6rdc").text
            print(price)
            writer.writerow([price])
        except:
            pass                    # this an example, you need to handle for a specific Exception

Result in the price.csv file:
Price
799.0
899.0
449.78

Or you can use Google Direct Answer Box API from SerpApi. It will bypass blocks from search engines and you don't have to create the parser from scratch and maintain it. The result will be the same.
Code example:
from serpapi import GoogleSearch
import os, csv, re

query_list = [
    "AL-KO Robolinho 110 price",
    "AL-KO Robolinho 1150 W price",
    "AL-KO Robolinho 300 E price",
    "Yard Force X80i price"
]

fields = ["Price"]

with open('crawl-single-attribute/price.csv', 'w', newline="") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(fields)

    for query in query_list:
        # https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
        params = {
            "q": query,
            "location": "Dallas",               # location from where search comes from
            "hl": "de",                         # language of the search
            "gl": "de",                         # country of the search
            "api_key": os.getenv("API_KEY"),    # your serpapi api
            # other parameters
        }

        print('Query: https://google.de/search?q=' + query)

        search = GoogleSearch(params)           # where data extraction happens on the SerpApi backend
        result_dict = search.get_dict()         # JSON -> Python dict

        try:
            # https://regex101.com/r/rxH4fo/1
            price = float(re.search(r"^(\S+)", result_dict["answer_box"]["answer"]).group().replace(",", ".").replace('"', ''))
            # price = result_dict["answer_box"]["answer"]
            print(price)
            writer.writerow([price])
        except:
            pass                                # this an example, you need to handle for a specific Exception

Disclaimer, I work for SerpApi.


text:
Q: QTreeView: Show "loading" message when expanding item With PyQT and a QTreeView, I need to display a "loading" message or a "spinning wheel" when the user expands an item, because the childs are retrieved by making a http request.
Any ideas on how to implement this?
Thanks

A: If the time taken to retrieve the child items is relatively short (say, a few seconds), then by far the simplest solution is to display a busy/wait cursor.
You can either set the cursor on the treeview:
treeview.setCursor(QtCore.Qt.BusyCursor)
# retrieve and insert child items ...
treeview.unsetCursor()

or set it globally:
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor))
# retrieve and insert child items ...
QtGui.QApplication.restoreOverrideCursor()

But other solutions will be much more complicated than this.
For instance you could show a QProgressBar in the status bar, or perhaps use a QMovie to display an animated icon somehow.


text:
Q: Capture DOM click event in JavaScript and trigger at later time Been researching this concept for a while now, and still not certain on best approach.
I'd like to capture a click event and trigger any (default or manually attached) events that follow it at a later time. More specifically, I want to record a tracking event when an element in the .container is clicked. After it's been recorded, I want to resume the behaviors of the clicked element. Is this functionality attainable in this manner?

    My Text
    My Link
    <button type="submit">My Button</button>

I'm adding a click event to the element (whether it has others already or not), and capturing and preventing it's default behavior:
elementInsideContainer.addEventListener('click',e => {
    e.preventDefault();
    // submit some click tracking data via ajax
    // carry on with other events on element
});

I know I have access to srcElement.href and could window.location the user there when capturing a click event on an  tag, but could that really be the best way to do this? What if the element is a type=submit button or just a CLICK ME! that I want to track (as shown above)? Been reading about dispatchEvent(event) but not sure if it's what I'm looking for.

A: I think you shouldn't block the event flow just because you want to record an event. If this is part of analytics it should always be outside your main implementation. I suggest you to register a generic event handler in capturing phase and track the event calls through that. The events should continue irrespective of whether the events are saved in your database or not.
This script should reside in your tag manager. So you don't have to copy the script again and again.
Sample implementation:
var body = document.querySelector('body');

body.addEventListener('click',e=> {
   console.log(e.target, e.type)
   var data = {"name": e.target.nodeName, "id": e.target.id, "class": e.target.classList, "eventType": e.type };
    fetch("https://requestb.in/14ihhbd1", {
        body: JSON.stringify(data),
        method: 'POST',
    mode: 'cors',
    });
}, true);

Note: The bin url will timeout after sometime. But you can create your own and play with it and see how it captures all the actions.


text:
Q: How do I read a struct from a Memory? Is it possible to create a struct from a Memory<byte> without copying to an array? Or better yet, create a struct and a Memory<byte> that share the same managed memory?
Reading a C/C++ data structure in C# from a byte array is tantalizingly close but not quite applicable. Memory<T> has a Pin method, but it returns a MemoryHandle instead of a GCHandle.
XY: I'm reading and writing Memory<byte> from a socket, using BinaryPrimitives on spans obtained from slices to get and set individual fields. Representing the Memory as a struct would be nicer.

A: .Net Core / .Net Standard 2.1 supports MemoryMarshal.Cast<TFrom, TTo> to do a reinterpret cast on a Span<TFrom> to a Span<TTo>. You should be able to use the Memory<T>.Span property to get a Span and then convert it to your struct.


text:
Q: Вывести все id категорий к новости в текущей категории. SQL - PHP У меня есть скрипт вывода статей из базы данных.
3 таблицы:
news
news_id title
1 Вышел новый Audi A4
categories
category_id category_title
1 Новости мира
2 Новости автомобилей
3 Новости спорта
news_categories
news_id category_id
1 1
1 2
Чтобы вывести все новости на главной, при этом указывая все id категорий новости, делаю такой запрос:

select group_concat(nc.category_id) as ids, n.news_id id, n.news_title
  title from news n join news_category nc on nc.news_id = n.news_id
  group by n.news_id

Этот запрос отлично выводит все новости и id категорий к новости.
Вывод:
ids     id  title
1,2     1   Вышел новый Audi A4
Но, как поступить, если нужен список новостей с id всех категорий на странице определенной категории?
Например, если мы находимся в категории 1:

select group_concat(nc.category_id) as ids, n.news_id id, n.news_title
  title from news n join news_category nc on nc.news_id = n.news_id
  where nc.category_id = 1 group by n.news_id

Вывод:
ids     id  title
1   1   Вышел новый Audi A4
А нужно, чтобы и id 2-ой категории был, как раньше.
Напрашивается решение с дополнительным запросом (select category_id from news_category where news_id = N) внутри while при выводе на php, но получится если на странице 15 новостей, будет 15 запросов к базе.
Может быть кто-то решил подобную задачу как-то иначе?


text:
Q: A way to set win32 window scrollbar to the left? Is there a way in Win32 API to set the place of vertical scrollbar to the left border of the window(a native one maybe).
I've looked at the WS definition and there is only WS_EX_LEFTSCROLLBAR but its for right to left text.
Thank you in advance.

A: Interesting.  It seems that the documentation varies depending on where you look.  If you look under "Extended Window Styles", it says:

WS_EX_LEFTSCROLLBAR   Places a vertical scroll bar to the left of the client area.

But if you look under CreateWindowEx, it says:

WS_EX_LEFTSCROLLBAR
  If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored.

So I have no idea what the official answer is.  I did try it on my machine (Windows 7 Professional) and the scrollbar appeared on the left.
CreateWindowEx( WS_EX_LEFTSCROLLBAR,
                (LPCTSTR)classAtom,
                _T( "Test Window" ),
                WS_VISIBLE | WS_VSCROLL | WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                NULL,
                NULL,
                hInstance,
                NULL );


text:
Q: preventing users to create duplicate primary keys How would you prevent users to create duplicate primary keys?
My question is worded quite poorly so ill give an example to make it more clear (not sure how to put this in better words).
Let's say there are two users who are both trying to insert an item into our db. Now the ID (primary key) for this item is auto-incremented by 1 whenever a new item is inserted.
When two users try to insert an item into the db at the same time, the moment they insert the item, both items would be assigned with same ID but with different details and hence would cause a problem later when we look up that item b/c now there are two items with same ID.
How would you prevent this from Oracle?
Please comment if my question is not clear!


text:
Q: Passing data to ajax call on success I wanted to pass the data from json_encode() function into jquery. And on success I wanted to reload the specific div.
Trigger:
<a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value['id'].'/'. $value['filename']) ?>">Remove

PHP:
public function remove ($id=null, $filename) {

    $dir = "_resources/docs/";
    if ($this->doc_item->remove($id)) {
        unlink($dir.$filename);
        $status = 'success';
        $msg = 'File successfully deleted';
    } else {
        $status = 'error';
        $msg = 'Something went wrong when deleting the file, please try again';
      }

      echo json_encode(array('status' => $status, 'msg' => $msg));
  }

JQUERY:
$('#js-delete-file').click(function(e){

    var url = $(this).attr('data-url');
    $.ajax({
      type: 'POST',
      url: url,
      success: function(result) {
        $('#uploaded-files').html(result);
      },
    });
  });

after I click the button it will give me this {"status":"success","msg":"File successfully deleted"} instead of the actual html.

A: Use param dataType for access to field status
$.ajax({
      type: 'POST',
      url: url,
      dataType: "json",
      success: function(result) {
        if (result.status == 'success') {
          $('#uploaded-files').html(result.msg);
        }
      }
    });

A: Try this
$('#js-delete-file').click(function(e){

    var url = $(this).attr('data-url');
    $.ajax({
      type: 'POST',
      url: url,
      success: function(result) {
         var data = JSON.parse(result);
         $('#uploaded-files').html(data.msg);
      },
    });
});


text:
Q: REST update on entity's joint value: do it by key or by value? I'm developing my first REST API, and have a design question.

I would like to use this api in a native Android mobile application

Suppose I have a Car table and a Brand table, like this:
Car( car_id, name, brand_id );
Brand( brand_id, name );

How do I represent the joint of Car and Brand in the Rest api updates and reads?
Use-cases:
1) User reads his car: in the response, it's enough to send the brand name, we do not care about the brand id, it's meaningles to the user.
2) User wants to update car data: We have to do a 1) first, to retrieve current details of the car, then represent a select list to the user to chose from brands.
THE QUESTION
Should I represent two kind of read for my Car entity: one for updates with brand id, another for reads with brand name?
Or should I repeatedly ask for joint table: Brand; cache it; then in my car read method, only the brand id would be represented, and join the value from my mobile app's brand cache?
which way to go?
Thanks alot!

A: Don't think so much about database schema and joins when designing your API. Instead, think about how your resources should be modeled and accessed via HTTP in a RESTful manner.
Use-case 1 should be served by a GET on a Car URI (say, https://your.api/car/787). That should return all the relevant details about a single Car in the body of the response (that's the "representation" of your Car resource). For example, a JSON response body might be this:
{
  "id" : "123",
  "name" : "Ford Mustang",
  "brand" : "https://your.api/brand/53"
}

If an API client wants details about the brand, they can GET the URI https://your.api/brand/53 to get all the JSON details about it.
For use-case 2, that should be done by having the client PUT a new representation of the Car to the same Car URI as above (https://your.api/car/787). If they wish to change the brand, they will need to have the new brand URI available before calling PUT in order to pass it in the update request. They could get the full list of brands by calling GET on a collection URI such as https://your.api/brands and then passing the desired brand URI within the request body.
Keep in mind that properly-designed RESTful APIs are stateless. Each request/response should be complete and self-contained, and should contain enough data within them to complete an entire read, update or removal operation.


text:
Q: como hacer referencia a un schema en otra carpeta por ejemplo los siguientes esquemas estan las siguientes carpetas
cr/user
lms/content

este es el esquema contenido
user: {
        type: Schema.Types.ObjectId,
        ref: 'cr/user'
    }

como puedo referenciar usuario desde el schema contenido?
porque si lo uso asi me sale un error "Schema hasn't been registered for model"

A: Estás definiendo mal la referencia; ésta no es la ruta del modelo es el nombre que le das al exportarlo mediante mongoose.model.
Ejemplo
Si has exportado el modelo user de la siguiente manera:
module.exports = mongoose.model('User', schema);

Entonces, la referencia debe ser User:
user: {
    type: Schema.Types.ObjectId,
    ref: 'User',
}