Q: Colour newly added bar in bar chart automatically when new data is received Following code basically put a colour in my bar graph based on cell D112 value. Now is there a way to automatically put colour as new data is available and new bar is added to my bar chart? For example, Cell D112 is the value for the month of Jan, now when i get value in cell D113 for the month of Feb, how do i colour the bar of that month automatically? I'm guessing there has to be some kind of a loop here right?
Sub ColorGraphs()

Dim ChrtObj As ChartObject
Dim Ser As Series
Dim SerPoint As Point

Set ChrtObj = ActiveSheet.ChartObjects("Chart 18")

Set Ser = ChrtObj.Chart.SeriesCollection(1)

Set SerPoint = Ser.Points(3)

With SerPoint.Format.Fill
    .Visible = msoTrue
    .Transparency = 0
    .Solid
End With

Select Case Range("D112").Value
    Case Is < 0.96
        SerPoint.Format.Fill.ForeColor.RGB = RGB(204, 0, 51)
        Range("P8").Interior.Color = RGB(204, 0, 51)

    Case 0.96 To 0.98
        SerPoint.Format.Fill.ForeColor.RGB = RGB(255, 102, 0)
        Range("P8").Interior.Color = RGB(255, 102, 0)

    Case Else ' larger than 0.98
        SerPoint.Format.Fill.ForeColor.RGB = RGB(0, 153, 102)
        Range("P8").Interior.Color = RGB(0, 153, 102)

End Select

End Sub

A: Try putting your code in Private Sub Worksheet_Change(ByVal Target as Range).
This Sub runs te code every time a cell is changed.


Q: Is there a data structure for a list ordered by value? I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following:
    // {Position, Name, Score}
Object[][] data = {
    {1, "-", 0},
    {2, "-", 0},
    {3, "-", 0},
    {4, "-", 0},
    {5, "-", 0},
    {6, "-", 0},
    {7, "-", 0},
    {8, "-", 0},
    {9, "-", 0},
    {10, "-", 0}
};

I want to be able to add a new score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table.
I know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best?

A: Use a TreeSet with a custom comparator.
Also, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects

A: Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point.
More info here Collections.binarySearch


Q: How to validate status code in robot framework i about to make a validation status code in robot framework. i create value in json with wrong password and i want to make validation code 400 bad request with this code.
login_negative_user

${json}     Load JSON From File     ${CURDIR}/../json/negativeuser.json
# Set Test Variable   ${JSON_SCHEMA}  ${json}
${resp}=    POST    ${base_url}/horde/v1/auth/login     json=${json}
${data}     Convert To String       ${resp.json()}
Status Should Be    400 ${resp}
Should Be Equal As Strings      ${resp.status_code}     400
${jsondata}     evaluate    ${data}
${poselang}=    Set Variable    ${jsondata['data']['token']}

Set Global Variable     ${poselang}
log to console  Get poselang token

But my log is this
login negativeuser                                                    | FAIL |

HTTPError: 400 Client Error: Bad Request for url: {secret api}
am i wrong to make validation with that code? sorry i cant tell the api because it is secret


Q: Is there a way to rename a similarly named column from two tables when performing a join? I have two tables that I am joining with the following query...
select *
  from Partners p
inner join OrganizationMembers om on p.ParID = om.OrganizationId
where om.EmailAddress = 'my_email@address.com'
  and om.deleted = 0

Which works great but some of the columns from Partners I want to be replaced with similarly named columns from OrganizationMembers.  The number of columns I want to replace in the joined table are very few, shouldn't be more than 3.
It is possible to get the result I want by selectively choosing the columns I want in the resulting join like so...
select om.MemberID,
       p.ParID,
       p.Levelz,
       p.encryptedSecureToken,
       p.PartnerGroupName,
       om.EmailAddress,
       om.FirstName,
       om.LastName
 from Partners p
inner join OrganizationMembers om on p.ParID = om.OrganizationId
     where om.EmailAddress = 'my_email@address.com'
       and om.deleted = 0

But this creates a very long sequence of select p.a, p.b, p.c, p.d, ... etc  ... which I am trying to avoid.
In summary I am trying to get several columns from the Partners table and up to 3 columns from the OrganizationMembers table without having a long column specification sequence at the beginning of the query.  Is it possible or am I just dreaming?

A: select om.MemberID as mem

Use th AS keyword. This is called aliasing.

A: Try this:
p.*,
om.EmailAddress,
om.FirstName,
om.LastName

You should never use * though. Always specifying the columns you actually need makes it easier to find out what happens.

A: You are dreaming in your implementation.
Also, as a best practice, select * is something that is typically frowned upon by DBA's.
If you want to limit the results or change anything you must explicitly name the results, as a potential "stop gap you could do something like this.
SELECT p.*, om.MemberId, etc..

But this ONLY works if you want ALL columns from the first table, and then selected items.

A:
But this creates a very long sequence
  of select p.a, p.b, p.c, p.d, ... etc
  ... which I am trying to avoid.

Don't avoid it. Embrace it!
There are lots of reasons why it's best practice to explicity list the desired columns.

*

*It's easier to do searches for where a particular column is being used.

*The behavior of the query is more obvious to someone who is trying to maintain it.

*Adding a column to the table won't automatically change the behavior of your query.

*Removing a column from the table will break your query earlier, making bugs appear closer to the source, and easier to find and fix.

And anything that uses the query is going to have to list all the columns anyway, so there's no point being lazy about it!


Q: can not read some string from struts.properties I have define variable error in struts.properties as follows:
error=this is an error

Now I can call this error as follows:
ErrorMsg = "<s:property value='getText(\"error\")'/>";

and it works, the result is: ErrorMsg=this is an error
How to get the text of variable instead of string?
I tried the following:
var m="error";
  error1 = "<s:property value='getText(m)'/>";
  error2 = "<s:property value='getText(\"m\")'/>";

I use firebug debugger and error1 and error2 are displyed as follows:
error1=""
error2=""

Any Idea?
thank you in advance

A: You appear to be mixing server side and client side code.
The s:property tags will be evaluated first on the server side, long before any value of m is valid, as that is client side JavaScript code.
If you post what you're trying to achieve then I or someone else may be able to help further.
HTH


Q: 'boost/multi_array.hpp' file not found error while building on Mac I am trying to build using Cmake on macOS Big Sur. Following is the makefile.
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)

#------------------------------------------------------------------------------#
#                             Compiler setup
#------------------------------------------------------------------------------#

IF(CMAKE_SYSTEM_NAME=Windows)
  SET(ADDITIONAL_FLAGS "-DWIN32")
ENDIF(CMAKE_SYSTEM_NAME=Windows)

SET(CMAKE_CXX_COMPILER "g++")
SET(CMAKE_CXX_FLAGS "-std=c++17 -g -Wall -Wno-uninitialized")
SET(CMAKE_CXX_FLAGS_DEBUGALL "${CMAKE_CXX_FLAGS} -fsanitize=address,undefined -pthread" )
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O3 -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -O3 -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS} -O3 -g -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} )

#SET(CMAKE_BUILD_TYPE Debug)
IF(NOT CMAKE_BUILD_TYPE)
  SET(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build: Debug Release RelWithDebInfo" FORCE)
ENDIF(NOT CMAKE_BUILD_TYPE)

#------------------------------------------------------------------------------#
#                             Required libraries
#------------------------------------------------------------------------------#

SET(Boost_DEBUG "ON")
SET(Boost_USE_STATIC_LIBS "ON")
SET(HOME_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "")
SET(CMAKE_MODULE_PATH ${HOME_DIR}/CMake)

FIND_PACKAGE(Boost COMPONENTS filesystem program_options timer chrono REQUIRED)
SET(EXTERNAL_INCLUDES ${Boost_INCLUDES})
SET(EXTERNAL_LIBRARIES ${Boost_LIBRARIES})

FIND_PACKAGE(Eigen3 3.3.4)
INCLUDE_DIRECTORIES(${EIGEN3_INCLUDE_DIRS})

#------------------------------------------------------------------------------#
#                             Directories for compiled libraries
#------------------------------------------------------------------------------#

INCLUDE_DIRECTORIES(src/Mesh)
INCLUDE_DIRECTORIES(src/Quadrature)
INCLUDE_DIRECTORIES(src/Common)
INCLUDE_DIRECTORIES(src/HybridCore)
INCLUDE_DIRECTORIES(src/Plot)
INCLUDE_DIRECTORIES(src/DDRCore)

ADD_SUBDIRECTORY(src/Mesh)
ADD_SUBDIRECTORY(src/Quadrature)
ADD_SUBDIRECTORY(src/Common)
ADD_SUBDIRECTORY(src/HybridCore)
ADD_SUBDIRECTORY(src/Plot)
ADD_SUBDIRECTORY(src/DDRCore)

#------------------------------------------------------------------------------#
#                             Directories for schemes
#------------------------------------------------------------------------------#

INCLUDE_DIRECTORIES(Schemes)
ADD_SUBDIRECTORY(Schemes)

While running make command I am getting
fatal error: 'boost/multi_array.hpp' file not found
#include <boost/multi_array.hpp>

I have boost installed with the help of brew. I also tried this https://stackoverflow.com/a/32929012/8499104 to verify my path is correct. Still not able to figure out why this is not able to find this library.


Q: Redirecting in react-router-dom v6 in a non-JSX context I'm trying to redirect a user from the route they are currently looking at to another route programatically. In my case, I am not in a JSX environment, and cannot use any kind of React hooks. How would I go about this?
I tried to use the code block below to redirect (tried using JSX), only to realize that it wouldn't work as it isn't in the context of the root router.
ReactDOM.render(<div>
    <Navigate to="/" />
</div>, document.getElementById("redirect"));

I also want to try and redirect without using window.location.href = as that would cause the whole page to refresh, something I don't want to happen.
EDIT: As requested, I am trying to redirect to a page from an event that is emitted by Tauri and is handled by some TypeScript code on the front end. Using window.location.href isn't an issue in any case.
Here is an example of what I'm trying to do:
/**
 * Sets up event listeners.
 */
export async function setupListeners() {
    console.log("Setting up link event listeners...");
    await listen("deeplink", onLinked);
}

/**
 * Invoked when a deep link call is received.
 * @param event The event.
 */
async function onLinked(event: Event<string>) {
    const { payload } = event;
    if (payload == "test:")
        // redirect("/testPage");
}

A: See redirect:
import { redirect } from "react-router-dom";

const loader = async () => {
  const user = await getUser();
  if (!user) {
    return redirect("/login");
  }
};

(from the docs)


Q: How does Doctrine generate:entities create getters and setter in symfony I have class User likr this
class user implements UserInterface {

protected id ,
protected username;

Then i have
class student extends user {

protected id ,
protected rollno;

Now when i run this
php app/console doctrine:generate:entities myBundle

Then propery username gets inserted in class student.
I want to know that is this ok or its error. Because then whats the use of extending from base class if my lass is going to be populated with all stuff

A: This isn't an error.
Symfony threats all classes as entities and if you're "mapping" them with doctrine you'll create the corrisponding tables onto database.
Now inheritance have to be taken into account: every "field" (property) into parent classe, will be extended or inherited by child.
So is perfectly clear that the corresponding parent field will be created into database.
To me the best way for solve this is to create a parent class and to migrate all commons (fields,methods and so on...) into it.
Then, you'll extend that new parent calss into user with specific fields (in that case username) aswell into student with student's specific fields.

A: Yeah, that's probably not an error, although I agree it can be annoying.
To see how exactly are they generated you can look into the command class.


Q: Double buffering with C# has negative effect I have written the following simple program, which draws lines on the screen every 100 milliseconds (triggered by timer1). I noticed that the drawing flickers a bit (that is, the window is not always completely blue, but some gray shines through). So my idea was to use double-buffering. But when I did that, it made things even worse. Now the screen was almost always gray, and only occasionally did the blue color come through (demonstrated by timer2, switching the DoubleBuffered property every 2000 milliseconds).
What could be an explanation for this?
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e) {
            Graphics g = CreateGraphics();
            Pen pen = new Pen(Color.Blue, 1.0f);
            Random rnd = new Random();
            for (int i = 0; i < Height; i++)
                g.DrawLine(pen, 0, i, Width, i);
        }

        // every 100 ms
        private void timer1_Tick(object sender, EventArgs e) {
            Invalidate();
        }

        // every 2000 ms
        private void timer2_Tick(object sender, EventArgs e) {
            DoubleBuffered = !DoubleBuffered;
            this.Text = DoubleBuffered ? "yes" : "no";
        }
    }
}

A: I would just draw all of your items to your own buffer, then copy it all in at once.  I've used this for graphics in many applications, and it has always worked very well for me:
    public Form1()
    {
        InitializeComponent();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        Invalidate();// every 100 ms
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        DoubleBuffered = true;
    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Bitmap buffer = new Bitmap(Width, Height);
        Graphics g = Graphics.FromImage(buffer);
        Pen pen = new Pen(Color.Blue, 1.0f);
        //Random rnd = new Random();
        for (int i = 0; i < Height; i++)
            g.DrawLine(pen, 0, i, Width, i);
        BackgroundImage = buffer;
    }

EDIT: After further investigation, it looks like your problem is what you're setting your Graphics object to:
Graphics g = CreateGraphics();

needs to be:
Graphics g = e.Graphics();

So your problem can be solved by either creating a manual buffer like I did above, or simply changing you Graphics object.  I've tested both and they both work.

A: Try setting the double buffered property to true just once in the constructor while you're testing.
You need to make use of the back buffer. Try this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DoubleBufferTest
{
    public partial class Form1 : Form
    {
        private BufferedGraphicsContext context;
        private BufferedGraphics grafx;

        public Form1()
        {
            InitializeComponent();

            this.Resize += new EventHandler(this.OnResize);
            DoubleBuffered = true;

            // Retrieves the BufferedGraphicsContext for the
            // current application domain.
            context = BufferedGraphicsManager.Current;

            UpdateBuffer();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Refresh();

        }

        private void OnResize(object sender, EventArgs e)
        {
            UpdateBuffer();
            this.Refresh();
        }

        private void UpdateBuffer()
        {
            // Sets the maximum size for the primary graphics buffer
            // of the buffered graphics context for the application
            // domain.  Any allocation requests for a buffer larger
            // than this will create a temporary buffered graphics
            // context to host the graphics buffer.
            context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);

            // Allocates a graphics buffer the size of this form
            // using the pixel format of the Graphics created by
            // the Form.CreateGraphics() method, which returns a
            // Graphics object that matches the pixel format of the form.
            grafx = context.Allocate(this.CreateGraphics(),
                 new Rectangle(0, 0, this.Width, this.Height));

            // Draw the first frame to the buffer.
            DrawToBuffer(grafx.Graphics);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            grafx.Render(e.Graphics);
        }

        private void DrawToBuffer(Graphics g)
        {
            //Graphics g = grafx.Graphics;
            Pen pen = new Pen(Color.Blue, 1.0f);
            //Random rnd = new Random();
            for (int i = 0; i < Height; i++)
                g.DrawLine(pen, 0, i, Width, i);
        }
    }
}

It's a slightly hacked around version of a double buffering example on MSDN.

A: No need to use multiple buffers or Bitmap objects or anything.
Why don't you use the Graphics object provided by the Paint event? Like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Pen pen = new Pen(Color.Blue, 1.0f);
    Random rnd = new Random();
    for (int i = 0; i < Height; i++)
        g.DrawLine(pen, 0, i, Width, i);
}


Q: OnNotifyPropertyChanged not firing get I have a class which has an ObservableCollection called Items. That list should fill up a RadGridView. Even though the OC contains data, the list stays empty, and after a bit of debuggingg I noticed it has some odd behavior. I have a breakpoint in the Get and Set of the property. First it hits the Get. Then the Set, but it never hits the Get again. Shouldn't the NotifyChanged also trigger the get after that then, so it updates the list in the view?
Here is the code below of the class I am talking about:
public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged
{
    internal WorkflowEntities Context;
    internal DbSet<TEntity> DbSet;

    private ObservableCollection<TEntity> _items;
    public ObservableCollection<TEntity> Items
    {
        get
        {
            return _items;
        }
        set
        {
            SetField(ref _items, value, nameof(Items));
        }
    }

    public PagedCollection()
    {
        Context = new WorkflowEntities();
        DbSet = Context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
                                            Func<IQueryable<TEntity>, IQueryable<TEntity>> query = null,
                                            string includeProperties = "")
    {
        IQueryable<TEntity> value = DbSet;

        if (filter != null)
        {
            value = value.Where(filter);
        }

        value = includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Aggregate(value, (current, includeProperty) => current.Include(includeProperty));

        return query?.Invoke(value).ToList() != null ? query(value).ToList() : value.ToList();
    }

    // boiler-plate
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

The public virtual IEnumerable<TEntity> Get(...) is being triggered by another class, which fills up the Items. Like this: PagedCollection.Items = PagedCollection.Get();. This in turn fires the get, set, but not a get anymore, so my list stays empty in the view, even though there is data in PagedCollection.Items

A: Your class, PagedCollection, doesn't implement INotifyPropertyChanged.
public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged

What this says is that TEntity must be a class and implement INotifyPropertyChanged.
Try this instead:
public class PagedCollection<TEntity> : INotifyPropertyChanged where TEntity : class, INotifyPropertyChanged

A: You can't call PagedCollection.Get(); like that you have to instantiate something.

A: A change in a property of an object within a regular ObservableCollection does not trigger the CollectionChanged event.
Maybe you could use the TrulyObservableCollection class, derived from the former:
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

A: One thing is the ObservableCollection property itself.
When you run the program, it is get once when the view is loaded, and it is set once when you first initialize that property.
After that, when you populate the list, it's not the PropertyChanged event that is fired, since it would be fired only if you assign the whole OC property to another value (usually via Items = new ObservableCollection<TEntity>());
Thus, the event you should be watching is CollectionChanged, which is fired every time you add, remove, swap or replace elements.


Q: How can I color a graph (vertices and edges) with excel data? I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices.
Can anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it?
THANKS!

A: Try using D3 graph. Visit https://d3js.org/
D3 uses javascript language. You can refer to multiple graphs.
Even you can take input data from excel file to create dynamic graphs.
You can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/

A: If you have the x and y values you can plot them directly on a worksheet.  The following is an example that randomly generates x and y coordinates for 5 points.  A small filled circle is drawn at each point.  A line is drawn between the previous and the next point forming a closed loop.
To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria.
vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray.
Option Explicit

Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long)
  With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = c
  End With
End Sub

Sub drawNode(r As Double, x As Double, y As Double, c As Long)
  With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r)
    .Fill.ForeColor.RGB = c
  End With
End Sub

Sub ConnectedOverLappingLoop()
  Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double
  Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double
  Dim radius As Double
  Dim vbGray As Long, clr As Long

  xMax = 200
  yMax = 200
  radius = 5
  vbGray = RGB(150, 150, 150)

  xFrm = Rnd() * xMax
  yFrm = Rnd() * yMax
  x1 = xFrm
  y1 = yFrm
  clr = vbBlue

  drawNode radius, x1, y1, vbBlue

  Dim i As Integer
  For i = 1 To 5:
    xTo = Rnd() * xMax
    yTo = Rnd() * yMax

    drawNode radius, xTo, yTo, vbBlue
    drawALine xFrm, yFrm, xTo, yTo, clr
    xFrm = xTo
    yFrm = yTo

    If clr = vbBlue Then
       clr = vbGray
    Else
       clr = vbBlue
    End If

  Next
  drawALine xFrm, yFrm, x1, y1, clr

End Sub


Q: PHP sanitization question I was wondering how would you sanitize the $_SERVER['REQUEST_URI'], $_POST['email'] and $url code in the code snippets below using PHP.
I'm using PHP Version 5.2.14
Code Snippets.
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
</form>

$email = $_POST['email']; //Grabs the email address

$page_url = $url; //Grabs the pages url address.

A: Use filter_var functions.
 // url
 filter_var($url, FILTER_VALIDATE_URL)
 // email
 filter_var('me@example.com', FILTER_VALIDATE_EMAIL)

A: Except in some very particular cases you should never 'sanitize' input - only ever validate it. (Except in the very particular cases) the only time you change the representation of data is where it leaves your PHP - and the method should be appropriate to where the data is going (e.g. htmlentities(), urlencode(), mysql_real_escape_string()....).
(the filter functions referenced in other posts validate input - they don't change its representation)


Q: How does Nutch's plug-in system work? I am new to Nutch, but I know Nutch uses Lucene for indexing, which only understands text format.
Nutch has many plug-ins that are used for crawling documents with a particular format.
My doubt is: how does actually the Nutch plug-in system?
I seen the Team wiki page for nutch
I'd like some information like how actually Nutch works with Lucene.

A: All Lucene does is provide a way for "Documents" to be added into a structured index and for queries to be executed against that index.
The Nutch crawler (I assume that's what you mean by nutch) just provides an easy way to get unstructured data (ie a website) to get pushed into the index. Just like you can use Solr to easily push xml data into a lucene index.
Nutch plugins simply provide a hook were you can put customer logic. For instance the "parse-pdf" can convert a binary PDF file into one of these "lucene Documents". Basically all it does is use an API that can read PDF documents (pdfbox) to extract the text (this is similar to what "parse-html" does since html has a lot of parts that isn't text, for example all html tags).
So regarding your concern about binary formats, its not difficult to parse, just difficult to get something useful. For instance we can write a "parse-image" plugin that could extract a lot of info about the image (ie name, format, size), it's just that parsing the "face" or the "dog" in the picture is difficult.


Q: Convert Raw png data to a usable img src in javascipt Getting raw png data from an api I am using, from the docs it is supposedly base64 png but it does not look like it to me. The data comes back in either of 2 forms
PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00�%00%00%00�%08%06%00%00%00=�%062%00%00%00%09pHYs%00%00%0E�%00%00%0E�%01�+%0E%1B%00%00 %00IDATx%01%00��q~%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00

or like
PNG   IHDR��=�2 pHYs���+ IDATx��q~J@7J@7�ɭ� IDATJ@72.*D2.*D������'$ �2-($J@7����.)&j��������6 6��n����J@7����(%!R���M���H� ���$�������N�����>�0����J����M+(���������J@7����/*&���< ���"������ �����������  ��� ����"�D#!-����2-

could someone help me identify what this is being returned, and how can I decode it to be used as a img src?


Q: How to delete file and its folder if there is one, in shell? I have a shell script that is copying some files for a S3 bucket (aws) on local, then it is copying it to another place (it cannot do it directly, because of some authorization), but the idea is that the image may be in some folder and the shell is creating it locally, but it is deleting just the image and I found that after execution I have some empty folders. So my question is how to delete the folder too, if it is present in the name?
My shell part that copies and deletes:
aws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE
# copy to other place
rm $PHOTO_NAME # here PHOTO_NAME may have the parent folder in it (a.jpg,
               # or b/a.jpg) and I would like to delete the b folder too

I have updated my code, based on the answer below, but it seems not to do what expected: the temporary directory is created, but all is done outside of it... My code looks like this:
dir="$(mktemp aws-sync-XXXXX)"
pushd "$dir"
COUNT=1
until [ $COUNT -gt $MAX_COUNT ]; do
        aws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE
        # copy to other place
        rm $PHOTO_NAME

        (( MESSAGES_COUNT+=1 ))
    fi
done
popd
rm -rf "$dir"

A: fundamentally, you're setting yourself up for some race conditions (what if the folder already existed, &c). A better way to do this is creating a fresh folder before you run this script, then run it inside there. So:
dir="$(mktemp aws-sync-XXXXX)"
pushd "$dir"

# do stuff

popd
rm -rf "$dir"

That will ensure you delete everything your temporary command created, and nothing more.


Q: How do I authenticate using MSXML2.XMLHTTP and VBA? I need to authenticate on the endpoint https://graph.microsoft.com/v1.0/me/drive/root/children using MSXML2.XMLHTTP and VBA.
I have the access token already but I am struggling to find out the string to be used on:
setRequestHeader method.
Thank you,

A: After searching I found the solution:
setRequestHeader "Authorization", "Bearer " + accessToken


Q: Rapid json, c++, json, modify empty json array I have a json file, which contains two object. The first object is an array of objects. Each of these objects has an element "key" and empty array. I need to fill the array with 4 numbers and I need to save back the json. I am checking the tutorial, but probably I am missing something. May somebody help me please?
Here is my code, that doesn't work:
void BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen)
{
    Value& projections = md_FilesJsonDocument["ProjectionImages"];
    for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator)
    {
        rapidjson::Value& projectionJson = *projectionsIterator;
        string name = projectionJson["Name"].GetString();
        if (projectionName == name)
        {
            Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator();
            rapidjson::Value& viewBox = (*projectionsIterator)["BB"];

            viewBox.PushBack((int)minX, allocator);
            viewBox.PushBack((int)minY, allocator);
            viewBox.PushBack((int)Xlen, allocator);
            viewBox.PushBack((int)Ylen, allocator);

            rapidjson::StringBuffer strbuf;
            rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
            md_FilesJsonDocument.Accept(writer);
            break;
        }
    }
}

The json looks like this:
{
    "ProjectionImages": [
        {
            "Id": "33c75d31-7ccd-4daf-814a-56250cdee42f",
            "Name": "Projection_Image_Architectural_First Floor_Zone 1.png",
            "Discipline": "Architectural",
            "LevelName": "First Floor",
            "BB": [],
            "SheetFileName": null,
            "ProjectionLineFileId": "36bb6683-c6d3-43c2-bbdc-aedf3203ea86",
            "ProjectionLineFileName": "Projection_Image_Architectural_First Floor_Zone 1.pdf",
            "ZoneName": "Zone 1"
        },
...

Even if I try to add new array member, this code doesn't work. Is it because of my writing approch?
void BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen)
{
    Value& projections = md_FilesJsonDocument["ProjectionImages"];
    for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator)
    {
        rapidjson::Value& projectionJson = *projectionsIterator;
        string name = projectionJson["Name"].GetString();
        if (projectionName == name)
        {
            Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator();

            Value a(kArrayType);
            a.PushBack((int)minX, allocator);
            a.PushBack((int)minY, allocator);
            a.PushBack((int)Xlen, allocator);
            a.PushBack((int)Ylen, allocator);
            (*projectionsIterator).AddMember("AA", a, allocator);

            rapidjson::StringBuffer strbuf;
            rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
            md_FilesJsonDocument.Accept(writer);
            break;
        }
    }
}

A: This part of the code doesn't do anything:
rapidjson::StringBuffer strbuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
md_FilesJsonDocument.Accept(writer);

strbuf contains the json string but it is discarded. I would move this into a separate function and print the conents with std::cout << strbuf;.
To write directly to a file:
std::ofstream ofs("out.json", std::ios::out);
if (ofs.is_open()) {
    rapidjson::OStreamWrapper osw(ofs);
    rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw);
    md_FilesJsonDocument.Accept(writer);
}


Q: jpegoptim: error creating temp file: mkstemps() failed jpegoptim gives me this error: error creating temp file: mkstemps() failed
jpegoptim -o *.jpg
image1.jpg 2000x1333 24bit P JFIF  [OK] 442829 --> 451511 bytes (-1.96%), skipped.
image2.jpg 1500x1124 24bit P Exif XMP IPTC ICC JFIF  [OK] 582748 --> 583528 bytes (-0.13%), skipped.
image3.jpg 2000x1501 24bit P Exif XMP IPTC ICC JFIF  [OK] 630262 --> 634146 bytes (-0.62%), skipped.
image4.jpg 1620x846 24bit P JFIF  [OK] 316664 --> 319702 bytes (-0.96%), skipped.
image5.jpg 1280x855 24bit N Exif XMP Adobe  [OK] 66306 --> 66279 bytes (0.04%), optimized.
jpegoptim: error creating temp file: mkstemps() failed

A: If you haven't figured out the issue yet, it's likely that you don't have write permissions to the directory the image is in.


Q: speeding up (rewriting?) a not in sub select query From a table I'm trying to get
a) users who fulfil certain criteria which is held in a key/value combination in a table
OR
b) users who do not have that key/value combination at all
So, for example, to try and find users who live in France or who have not yet added their location, I'm using this (simplified) query:
SELECT *
FROM
    current_users
    JOIN current_users um_location ON current_users.id = um_location.id
WHERE
    (
        ( um_location.meta_key = 'location' AND um_location.meta_value = 'France' )
    OR
        ( current_users.id NOT IN
            (SELECT current_users.id FROM current_users WHERE current_users.meta_key = 'location' )
        )
    )

The problem is, of course, that running the OR sub-select query (if that's what it's called) is slowing down the query hugely. And since the full query has about 5 or 6 of these sub-selects, it's slowing things down far too much.
Is there another way of doing this perhaps? A faster way?

A: Change your OR condition as a UNION query instead of OR
SELECT * FROM
    current_users
    JOIN current_users um_location ON current_users.id = um_location.id
WHERE
    um_location.meta_key = 'location' AND um_location.meta_value = 'France'
UNION
SELECT * FROM
    current_users
    JOIN current_users um_location ON current_users.id = um_location.id
WHERE
    current_users.id NOT IN
    (SELECT current_users.id FROM current_users WHERE
    current_users.meta_key='location' )

A: This should be the most succinct possible:
SELECT *
FROM current_users
LEFT JOIN current_users AS um_location
   ON current_users.id = um_location.id
   AND um_location.meta_key = 'location'
WHERE um_location.meta_value = 'France'
   OR um_location.meta_value IS NULL
;

...but as isaace answer hints, MySQL does not handle OR conditions ideally.
So, this might perform better.
SELECT *
FROM current_users
LEFT JOIN current_users AS um_location
   ON current_users.id = um_location.id
   AND um_location.meta_key = 'location'
WHERE um_location.meta_value = 'France'
UNION
SELECT *
FROM current_users
LEFT JOIN current_users AS um_location
   ON current_users.id = um_location.id
   AND um_location.meta_key = 'location'
WHERE um_location.meta_value IS NULL
;

..but it will probably only make a difference if you have meta_value indexed; as the issue is that MySQL tends to ignore indexes when presented with OR.

Edit: Due to the type of schema design begin used, there might be some weird issues with these queries using "location" entries as rows on the left side of the join; try this instead.
SELECT *
FROM current_users AS non_location
LEFT JOIN current_users AS um_location
   ON current_users.id = um_location.id
   AND um_location.meta_key = 'location'
WHERE non_location.meta_key != 'location'
   AND (um_location.meta_value = 'France'
        OR um_location.meta_value IS NULL
       )
;

A: First off, thank you both for your suggestions. Unfortunately I couldn't get them to work as the join
LEFT JOIN current_users AS um_location
ON current_users.id = um_location.id
AND um_location.meta_key = 'location'

did not return the records of those users who hadn't yet entered their location.
However, after a lot of work I managed to solve the issue. It's not elegant but it works:

*

*Create a temporary table with a subset of the users who fulfil some basic criteria.

*Do a simple INSERT IGNORE INTO ... SELECT DISTINCT ... FROM current_users adding in the missing 'location' with dummy information.

Then the final query includes this:
um_location.meta_value = 'France'
or
um_location.meta_value = 'dummyinfo'

It's not blisteringly fast but since this is a process which acts in the back end for admin users only they can afford to wait... ;)
Again, thanks for your help!


Q: How to generate a QR code and a downloadable link in php I would like to create a program that generates a QR code based on a URL (data from a database).
The QR code will not be stored or saved, but only downloadable via a link on the page displaying the QR code.
All in PHP :)
Could someone help me ?
I haven't found my answer for the downloadable link :)

A: This works for me in creating the QR code use API:-
https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl={data}
In place of data use the data which you want to convert into a QR code.

Code:-

<?php
echo '';
?>

<button id="downloadid" class="btn btn-small btn-primary">Download</button>

Script For the Downloading the QR code image:-

`enter code here`


Q: How do I create a circuit based on this truth table? So this is the truth table
   In_1  In_2  In_3  Out
    0      0    0      0
    0      0    1      1
    0      1    0      1
    0      1    1      1
    1      0    0      1
    1      0    1      1
    1      1    0      1
    1      1    1      0

I would like to create a circuit based on this truth table.
This is what I have tried, but failed

A: A Karnaugh map as suggested by paddy, will give you a set of minterms which fulfil the expression. That is the classical way to tackle such problems.
By inspection of the truth-table you can convince yourself, that the output is true whenever In_1 is unequal In_3 or In_1 is unequal In_2:
f = (In_1 xor In_2) or (In_1 xor In_3)


Q: Woocommerce - Remove Only one Unit of a product from cart I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal.
In each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time. I managed to make the add to cart button work but can't seem to find a good solution to remove just one single unit from cart instead of all of them at once.

I have tried this:
function remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 282;
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}

but it removes all products with that ID at once.
I want to be able to remove unit by unit in case there are items in cart with that ID.
This is the code I have right now for the remove from cart button:
add_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart');
add_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart');

// handle the ajax request
function search_remove_from_cart()
{
    $product_id = $_REQUEST['product_id'];
    WC()->cart->remove_cart_item($product_id);

    $products_in_cart = WC()->cart->get_cart_item_quantities($product_id);
    $updated_qty = $products_in_cart[$product_id];

    // in the end, returns success json data
    wp_send_json_success(["Product removed from cart Successfuly!", $updated_qty]);

    // or, on error, return error json data
    wp_send_json_error(["Could not remove the product from cart"]);
}

Is there any function to remove only one unit of a certain product from cart?
Thank you all !

A: You have to change the quantity instead of removing the product. Number of product units in the cart = quantity.
Try something like this:
function remove_from_cart(){
    $product_id = 47;
    $cart = WC()->cart;
    $product_cart_id = $cart->generate_cart_id( $product_id );
    $cart_item_key = $cart->find_product_in_cart( $product_cart_id );
    if ( $cart_item_key ){
        $quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1;
        $cart->set_quantity($cart_item_key, $quantity);
    }
}


Q: Implementing a C++ calling convention in ASM x86 I've written a simple program that obfuscates a string using ASM x86. User must input their desired string, and then choose a key (Ekey) for the string to be obfuscated. (I know you can emulate left and right bit rotations with shift operators or table lookups, I'm just trying to familiarize myself with ASM)
I'm trying to alter the program so that it adopts an accepted C++ standard calling procedure such as Cdecl for passing parameters (EKey & tempChar) into the sub-routine obfuscate.
Despite numerous hours of research I've been unsuccessful so I have come here in hope that somebody with a little more experience would be kind enough to offer some guidance.
Here's the relevant function:
void obfusc_chars (int length, char EKey)
{   char tempChar;                      // char temporary store

    for (int i = 0; i < length; i++)    // encrypt characters one at a time
    {
        tempChar = OChars [i];          //
        __asm {                         //
            push   eax                  // save register values on stack to be safe
            push   ecx                  // pushes first string on stack
                                        //
            movzx  ecx,tempChar         // set up registers (Nb this isn't StdCall or Cdecl)
            lea    eax,EKey             //
            call   obfuscate            // obfuscate the character
            mov    tempChar,al          //
                                        //
            pop    ecx                  // restore original register values from stack
            pop    eax                  //
        }
        EChars [i] = tempChar;          // Store encrypted char in the encrypted chars array
    }
   return;

And the obfuscate subroutine:
// Inputs: register EAX = 32-bit address of Ekey,
//                  ECX = the character to be encrypted (in the low 8-bit field, CL).

// Output: register EAX = the encrypted value of the source character (in the low 8-bit field, AL).

       __asm {

     obfuscate: push    esi
                push    ecx
                mov     esi, eax
      and dword ptr     [esi], 0xFF
      ror byte ptr      [esi], 1
      ror byte ptr      [esi], 1
      add byte ptr      [esi], 0x01
                mov     ecx, [esi]
                pop     edx
            x17:ror     dl, 1
                dec     ecx
                jnz     x17
                mov     eax, edx
                add eax, 0x20
                xor eax, 0xAA
                pop esi
                ret
        }

Thanks in advance for taking the time to read.


Q: not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class? Not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class?
In this case a=a1.get() is not taking value from command (of sub1 button) in ques1() function.
from tkinter import *
global root
root=Tk()
root.geometry("500x500")
a1=StringVar()
ans1=StringVar()

def ans1():
    a=a1.get()  #not getting it from ques1()
    print(a)

def ques1():
    root.destroy()
    global window1
    window1=Tk()
    window1.geometry("500x500")
    question1=Label(window1, text="How many Planets are there in Solar System").grid()
    q1r1=Radiobutton(window1, text='op 1', variable=a1, value="correct").grid()
    q1r2=Radiobutton(window1, text='op 2', variable=a1, value="incorrect").grid()
    sub1=Button(window1, text="Submit", command=ans1).grid()
    next1But=Button(window1, text="Next Question", command=ques2).grid()

def ques2():
    window1.destroy()
    window2=Tk()
    window2.geometry("500x500")
    question2=Label(window2, text="How many Planets are there in Solar System").grid()
    next2But=Button(window2, text="Next Question")

button=Button(root,text="Start Test", command=ques1).grid()

A: This is a side effect from using Tk more than once in a program. Basically, "a1" is tied to the "root" window, and when you destroy "root", "a1" will no longer work.
You have a couple options:

*

*Keep the same window open all the time, and swap out the Frames instead.

*Use Toplevel() to make new windows instead of Tk.

Option 1 seems the best for you. Here it is:
from tkinter import *

root=Tk()
root.geometry("500x500")
a1=StringVar(value='hippidy')
ans1=StringVar()

def ans1():
    a=a1.get()  #not getting it from ques1()
    print(repr(a))

def ques1():
    global frame
    frame.destroy() # destroy old frame
    frame = Frame(root) # make a new frame
    frame.pack()

    question1=Label(frame, text="How many Planets are there in Solar System").grid()
    q1r1=Radiobutton(frame, text='op 1', variable=a1, value="correct").grid()
    q1r2=Radiobutton(frame, text='op 2', variable=a1, value="incorrect").grid()
    sub1=Button(frame, text="Submit", command=ans1).grid()
    next1But=Button(frame, text="Next Question", command=ques2).grid()

def ques2():
    global frame
    frame.destroy() # destroy old frame
    frame = Frame(root) # make a new frame
    frame.pack()

    question2=Label(frame, text="How many Planets are there in Solar System").grid()
    next2But=Button(frame, text="Next Question")

frame = Frame(root) # make a new frame
frame.pack()
button=Button(frame,text="Start Test", command=ques1).grid()

root.mainloop()

Also, don't be scared of classes. They are great.
Also, the way you have a widget initialization and layout on the same line is known to cause bugs. Use 2 lines always. So instead of this
button=Button(frame,text="Start Test", command=ques1).grid()

Use this:
button=Button(frame,text="Start Test", command=ques1)
button.grid()

A: You need to use a single instance of Tk. Variables and widgets created in one cannot be accessed from another.

A: Your code has some common mistakes. You are creating a new window on each question. It is not a good idea. You can use Toplevel but I will suggest you to use the root. You can destroy all of your previous widgets and place new ones. When the first question, both radiobuttons are unchecked and return 0 when none is selected. You are creating the buttons in Window1 so you will have to tie it with your var.
from tkinter import *
global root
root=Tk()
root.geometry("500x500")
a1=StringVar(root)
a1.set(0)  #unchecking all radiobuttons
ans1=StringVar()

def ans1():
    a=a1.get()
    print(a)

def ques1():
    for widget in root.winfo_children():
        widget.destroy() #destroying all widgets
    question1=Label(root, text="How many Planets are there in Solar System").grid()
    q1r1=Radiobutton(root, text='op 1', variable=a1, value="correct").grid()
    q1r2=Radiobutton(root, text='op 2', variable=a1, value="incorrect").grid()
    sub1=Button(root, text="Submit", command=ans1).grid()
    next1But=Button(root, text="Next Question", command=ques2).grid()
def ques2():
    for widget in root.winfo_children():
        widget.destroy()
    question2=Label(root, text="How many Planets are there in Solar System").grid()
    next2But=Button(root, text="Next Question")

button=Button(root,text="Start Test", command=ques1)
button.grid()


Q: Nhibernate entity with multiple Many-To-Many lists of the same type? Does anybody know how I would map an entity with two many-to-many collections of the same child type.
My database structure is this....
The "normal" relationship will be....
tbl_Parent
  col_Parent_ID

tbl_Parent_Child_Xref
   col_Parent_ID
   col_Child_ID

tbl_Child
   col_Child_ID

The alternative relationship is...
tbl_Parent
  col_Parent_ID

tbl_Include_ParentChild_Xref
   col_Parent_ID
   col_Child_ID

tbl_Child
   col_Child_ID

The entity and mapping look like this...
public partial class ParentEntity : AuditableDataEntity<ParentEntity>
{
  public virtual IList<ChildEntity> Children { get; set; }
  public virtual IList<ChildEntity> IncludedChildren { get; set; }
}

public partial class ParentMap : IAutoMappingOverride<ParentEntity>
{
    public void Override(AutoMapping<ParentEntity> mapping)
    {
        mapping.Table("tbl_Parent");

        mapping.HasManyToMany(x => x.Children)
        .Table("tbl_Parent_Child_Xref")
        .ParentKeyColumn("col_Parent_ID")
        .ChildKeyColumn("col_Child_ID")
        .Inverse()
        .Cascade.All();

        mapping.HasManyToMany(x => x.IncludedChildren)
        .Table("tbl_Include_ParentChild_Xref")
        .ParentKeyColumn("col_Parent_ID")
        .ChildKeyColumn("col_Child_ID")
        .Inverse()
        .Cascade.All();
    }
}

The error that I'm getting is
"System.NotSupportedException: Can't figure out what the other side of the many-to-many property 'Children' should be."
I'm using NHibernate 2.1.2, FluentNhibernate 1.0.

A: It seems FNH is confused because you seem to map the same object (ChildEntity) to two different tables, if I'm not mistaken.
If you don't really need the two lists to get separated, perhaps using a discriminating value for each of your lists would solve the problem. Your first ChildEntity list would bind to the discriminationg value A, and you sesond to the discriminating value B, for instance.
Otherwise, I would perhaps opt for a derived class of your ChildEntity, just not to have the same name of ChildEntity.
IList<ChildEntity> ChildEntities
IList<IncludedChildEntity> IncludedChildEntities

And both your objects classes would be identitical.
If you say it works with NH, then it might be a bug as already stated. However, you may mix both XML mappings and AutoMapping with FNH. So, if it does work in NH, this would perhaps be my preference. But think this workaround should do it.

A: You know I'm just shooting in the dark here, but it almost sounds like your ChildEntity class isn't known by Hibernate .. that's typically where I've seen that sort of message.  Hibernate inspects your class and sees this referenced class (ChildEntity in this case) that id doesn't know about.
Maybe you've moved on and found the issue at this point, but thought I'd see anyway.

A: Fluent is confused because you are referencing the same parent column twice. That is a no-no. And as far as I can tell from the activity i have seen, a fix is not coming any time soon.
You would have to write some custom extensions to get that working, if it is possible.

A: To my great pity, NHibernate cannot do that. Consider using another ORM.


Q: Wrap input with submit tag in one div Let's say I have these fields generated by simple_form_for:
= f.input :amount, label: false, required: true
= f.submit "✓", class: "btn btn-primary"

I want to wrap them in one div and none of them should be nested inside any other div.
(it should look like this):
<form>

     <input name="amount">
     <input name="commit">

</form>

now it looks like this:
<form>

     <input name="amount">

  <input name="commit">
</form>

How to achieve this?

A: According to the Simple Form documentation, you can skip use of the wrapper html tags by using input_field instead of input. So, if this is just a one-off case then you could define your own wrapper div tag and turn off the auto-generated wrapper:
.inputFields
  = f.input_field :amount, label: false, required: true
  = f.submit "✓", class: "btn btn-primary"

Or, if this is not a one-off case and is a common thing, you could create your own wrapper... See the custom wrapper documentation for help.


Q: cordova websocket plugin showing error code 1006 and angular websocket plugin showing isTrusted true error Angular websocket plugin is working in the browser. But after generating apk in the mobile it is not working, it is showing error. Cordova websocket plugin also not working, it is showing error code 1006. Can any one help me. I am new to ionic.
 document.addEventListener('deviceready', function () {
 var ws = new WebSocket('ws://197.164.1.12:8080/example/2');

 ws.onopen = function () {
    alert('open');
    this.send('hello');
 };

 ws.onmessage = function (event) {
    alert(event.data);
    this.close();
 };

 ws.onerror = function (event) {
    alert('error occurred!'+JSON.stringify(event));
 };

 ws.onclose = function (event) {
    alert('onclose code=' + event.code);
 };
 ws.close = function (event) {
    alert('close code=' + JSON.stringify(event));
    alert('onclose code=' + event.code);
 };
}, false);

A: Your browser is not allow CORS Origin api access. So you can add the plugin
CORS Plugin for chrome


Q: PHP / JpGraph - Memory not freed on completion of function My application needs to generate a pdf file with a bunch of graphs in it.
The situation: I'm using FPDF for pdf generation and JpGraph for the graphs. My code gets the graph data from a database and iterates through, calling a function for each graph that contains all the JpGraph code for setting up, styling the graph and caching it as a png file in a cache folder on the server. FPDF then places these images in the pdf, which is served to browser.
The problem: I'm getting PHP out of memory errors when the number of graphs exceeds a certain number. AFAICT this is not an FPDF problem: in trying to diagnose the problem I have generated much larger documents with many more (pre-generated) graphs and images of equivalent size. The problem seems to be that the memory used to render the graph in the graph rendering function is not freed when the function is completed. This is based on the fact that if I call memory_get_peak_usage in the function I get a bunch of increasing numbers, one from each time the function is called, up to the limit of 64MB where it stops.
My graph generation script looks something like this:
function barChart($filename, $ydata, $xdata){

// Create the graph. These two calls are always required
$graph = new Graph(900,500);
$graph->SetScale('textlin');

//(bunch of styling stuff)

// Create the bar plot
$bplot=new BarPlot($ydata);

// Add the plot to the graph
$graph->Add($bplot);

//(more styling stuff)

// Display the graph
$graph->Stroke($filename);

$graph = null;
$bplot = null;

unset($graph);
unset($bplot);

echo "

".(memory_get_peak_usage(true)/1048576)."

";
}

As you can see, I've tried unsetting and nullifying the graph and bplot objects, although my understanding is that this shouldn't be necessary. Shouldn't all the memory used by the Graph and Bplot instances be freed up when the function finishes? Or is this perhaps a JpGraph memory leak? (I've searched high and low and can't find anyone else complaining about this). This is my first remotely resource-heavy PHP project, so I could be missing something obvious.

A: I had the same problem and found the solution after just an hour or so.
The issue is that jpgraph loads a default set of font files each time a Graph is created. I couldn't find a way to unload a font, so I made a slight change so that it only loads the fonts one time.
To make the fix for your installation, edit "gd_image.inc.php" as follows:
Add the following somewhere near the beginning of the file (just before the CLASS Image):
// load fonts only once, and define a constant for them
define("GD_FF_FONT0", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT0.gdf"));
define("GD_FF_FONT1", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1.gdf"));
define("GD_FF_FONT2", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2.gdf"));
define("GD_FF_FONT1_BOLD", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1-Bold.gdf"));
define("GD_FF_FONT2_BOLD", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2-Bold.gdf"));

then at the end of the Image class constructor (lines 91-95), replace this:
$this->ff_font0 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT0.gdf");
$this->ff_font1 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1.gdf");
$this->ff_font2 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2.gdf");
$this->ff_font1_bold =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1-Bold.gdf");
$this->ff_font2_bold =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2-Bold.gdf");

with this:
$this->ff_font0 =  GD_FF_FONT0;
$this->ff_font1 =  GD_FF_FONT1;
$this->ff_font2 =  GD_FF_FONT2;
$this->ff_font1_bold =  GD_FF_FONT1_BOLD;
$this->ff_font2_bold =  GD_FF_FONT2_BOLD;

I didn't test this with multiple versions of php or jpgraph, but it should work fine. ymmv.

A: You could try using PHP >= 5.3 Garbage collection
gc_enable() + gc_collect_cycles()
http://php.net/manual/en/features.gc.php

A: @bobD's answer is right on the money and helped solved my same question.
However there is also one other potential memory leak source for those still looking for an answer to this very old problem.
If you are creating multiple charts with the same background image, each load of the background image causes an increase in memory with each chart creation.
Similar to bobD's answer to the font loading issue, this can be solved by making the background image(s) global variables instead of loading them each time.
EDIT: It looks like there is a very small memory leak when using MGraph() as well.
Specifically the function Add(). Perhaps it also loads a font library or something similar with each recursive call.


Q: In bash/sed, how do you match on a lowercase letter followed by the SAME letter in uppercase? I want to delete all instances of "aA", "bB" ... "zZ" from an input string.
e.g.
echo "foObar" |
sed -Ee 's/([a-z])\U\1//'

should output "fbar"
But the \U syntax works in the latter half (replacement part) of the sed expression - it fails to resolve in the matching clause.
I'm having difficulty converting the matched character to upper case to reuse in the matching clause.

If anyone could suggest a working regex which can be used in sed (or awk) that would be great.
Scripting solutions in pure shell are ok too (I'm trying to think of solving the problem this way).
Working PCRE (Perl-compatible regular expressions) are ok too but I have no idea how they work so it might be nice if you could provide an explanation to go with your answer.
Unfortunately, I don't have perl or python installed on the machine that I am working with.

A: You may use the following perl solution:
echo "foObar" | perl -pe 's/([a-z])(?!\1)(?i:\1)//g'

See the online demo.
Details

*

*([a-z]) - Group 1: a lowercase ASCII letter

*(?!\1) - a  negative lookahead that fails the match if the next char is the same as captured with Group 1

*(?i:\1) - the same char as captured with Group 1 but in the different case (due to the lookahead before it).

The -e option allows you to define Perl code to be executed by the compiler and the -p option always prints the contents of $_ each time around the loop.  See more here.

A: This might work for you (GNU sed):
sed -r 's/aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ//g' file

A programmatic solution:
sed 's/[[:lower:]][[:upper:]]/\n&/g;s/\n\(.\)\1//ig;s/\n//g' file

This marks all pairs of lower-case characters followed by an upper-case character with a preceding newline. Then remove altogether such marker and pairs that match by a back reference irrespective of case. Any other newlines are removed thus leaving pairs untouched that are not the same.

A: Here is a verbose awk solution as OP doesn't have perl or python available:
echo "foObar" |
awk -v ORS= -v FS='' '{
   for (i=2; i<=NF; i++) {
      if ($(i-1) == tolower($i) && $i ~ /[A-Z]/ && $(i-1) ~ /[a-z]/) {
         i++
         continue
      }
      print $(i-1)
   }
   print $(i-1)
}'

fbar

A: Note: This solution is (unsurprisingly) slow, based on OP's feedback:
"Unfortunately, due to the multiple passes - it makes it rather slow. "

If there is a character sequence¹ that you know won't ever appear in the input,you could use a 3-stage replacement to accomplish this with sed:

echo 'foObar foobAr' | sed -E -e 's/([a-z])([A-Z])/KEYWORD\1\l\2/g' -e 's/KEYWORD(.)\1//g' -e 's/KEYWORD(.)(.)/\1\u\2/g'

gives you: fbar foobAr
Replacement stages explained:

*

*Look for lowercase letters followed by ANY uppercase letter and replace them with both letters as lowercase with the KEYWORD in front of them foObar foobAr -> fKEYWORDoobar fooKEYWORDbar

*Remove KEYWORD followed by two identical characters (both are lowercase now, so the back-reference works) fKEYWORDoobar fooKEYWORDbar -> fbar fooKEYWORDbar

*Strip remaining² KEYWORD from the output and convert the second character after it back to it's original, uppercase version fbar fooKEYWORDbar -> fbar foobAr
¹ In this example I used KEYWORD for demonstration purposes. A single character or at least shorter character sequence would be better/faster. Just make sure to pick something that cannot possibly ever be in the input.
² The remaining occurances are those where the lowercase-versions of the letters were not identical, so we have to revert them back to their original state

A: There's an easy lex for this,
%option main 8bit
    #include <ctype.h>
%%
[[:lower:]][[:upper:]] if ( toupper(yytext[0]) != yytext[1] ) ECHO;

(that's a tab before the #include, markdown loses those).  Just put that in e.g. that.l and then make that.  Easy-peasy lex's are a nice addition to your toolkit.


Q: EPPlus next row I am using Epplus to write out a collection into an excel file. Currently I am incrementing rows by manually manipulating the cell number.(ws is an instance of ExcelWorkSheet)
  int i = 1;
  foreach (var item in items)
   {
      ws.Cells["A"+i.ToString()].Value =item.Text;
      i++;
    }

Instead of adding number to cell name is there a better way to handle this? Something like
 int i = 1;
      foreach (var item in items)
       {
          ws.Row[i].Cells[0]=item.Text;
          i++;
        }

A: There's an [int Row, int Col] indexer on Cells (type ExcelRange), so you can use ws.Cells[i, 0].
  int i = 1;
  foreach (var item in items)
   {
      ws.Cells[i, 0].Value =item.Text;
      i++;
    }


Q: How to determine current status of web video (playing | stopped) How can I determine when a user starts or stops playing a video on a web page?  For instance, the video on this page:
http://www.novamov.com/video/exm71hcwt1aly
I need to be able to determine this from a separate .NET application running on the client.


Q: How to create HTML in angular? I have been working on React for a year. Now, I am writing angular. How can I create a piece of html code in ts.file?
In react, I do it that way:
const example = (item: string): React.ReactNode => {
  return
 something.... {item}

}

I want to do same thing in Angular8+
I know some way to do it. For example:
const example2= (name: string): string => {
  return `

heyyy ${name}

  `;
};

Are there any other ways to do it?

A: In Angular, there are a couple of ways to do this. If you need to generate HTML in the typescript and then interpolate it into the template, you can use a combination of the DomSanitizer and the innerHTML attribute into other elements (for example a span).
Below would be an example of what I suggested above:
hello-world.component.ts:
@Component({
    selector: "hello-world",
    templateUrl: "./hello-world.component.html",
    styleUrls: ["./hello-world.component.scss"]
})
export class HelloWorld {
   innerHTML: string = `<p>Hello, world!</p>`;
}

sanitze.pipe.ts:
@Pipe({
   name='sanitize'
})
export class SanitizePipe {
   constructor(private sanitizer: DomSanitizer) { }
   transform(value: string): SafeHtml {
      return this.sanitizer.bypassSecurityTrustHtml(value);
   }
}

hello-world.component.html:
<div [innerHTML]="innerHTML | sanitize"


Q: Javassist - How to add line number to method I am a newbie to java bytecode and javassist. I created a new class file with using javassist. Although I added fields and methods, I couldn't achieve to add line number to method. Result of my research, I understand that I need to add linenumberattribute to codeattribute of method info. Moreover, linenumberattribute consists of linenumbertable. I don't know how can I create a new linenumberattribute with javassist.

A: I am writing a compiler that produces JVM code. I need line numbers in the output. I do it this way.
I build up a list of objects similar to this:
public class MyLineNum {
    public final short pc;
    public final short lineNum;
}

Then I add the line number table:
final ClassFile  classFile = ...;
final ConstPool  constPool = classFile.getConstPool();
final MethodInfo minfo     = new MethodInfo( ... );
final Bytecode   code      = new Bytecode( constPool );
... code that writes to 'code'

final List<MyLineNum> lineNums = new ArrayList<>();
... code that adds to 'lineNums'

final CodeAttribute codeAttr = code.toCodeAttribute();
if ( !lineNums.isEmpty() ) {
    // JVM spec describes method line number table thus:
    //    u2 line_number_table_length;
    //    { u2 start_pc;
    //      u2 line_number;
    //    } line_number_table[ line_number_table_length ];
    final int    numLineNums = lineNums.size();
    final byte[] lineNumTbl  = new byte[ ( numLineNums * 4 ) + 2 ];

    // Write line_number_table_length.
    int byteIx = 0;
    ByteArray.write16bit( numLineNums, lineNumTbl, byteIx );
    byteIx += 2;

    // Write the individual line number entries.
    for ( final MyLineNum ln : lineNums) {
        // start_pc
        ByteArray.write16bit( ln.pc, lineNumTbl, byteIx );
        byteIx += 2;
        // line_number
        ByteArray.write16bit( ln.lineNum, lineNumTbl, byteIx );
        byteIx += 2;
    }

    // Add the line number table to the CodeAttribute.
    @SuppressWarnings("unchecked")
    final List<AttributeInfo> codeAttrAttrs = codeAttr.getAttributes();
    codeAttrAttrs.removeIf( ( ai ) -> ai.getName().equals( "LineNumberTable" ) );       // remove if already present
    codeAttrAttrs.add( new AttributeInfo( constPool, "LineNumberTable", lineNumTbl ) );
}

// Attach the CodeAttribute to the MethodInfo.
minfo.setCodeAttribute( codeAttr );

// Attach the MethodInfo to the ClassFile.
try {
    classFile.addMethod( minfo );
}
catch ( final DuplicateMemberException ex ) {
    throw new AssertionError( "Caught " + ex, ex );
}


Q: Is a function return necessary to be called a Closure Hey i came across this video on youtube http://www.youtube.com/watch?v=KRm-h6vcpxs
which basically explains IIFEs and closures. But what I am not understanding is whether i need to return a function in order to call it a closure.
E.x.
function a() {
    var i = 10;
    function b() {
       alert(i);
    }
}

in this case can i call it a closure as it is accessing the 'i' variable from the outer function's scope or do i need to return the function like this
return function b(){alert(i);}

A: A closure is simply a function which holds its lexical environment and doesn't let it go until it itself dies.
Think of a closure as Uncle Scrooge:

Uncle Scrooge is a miser. He will never let go of his money.
Similarly a closure is also a miser. It will not let go of its variables until it dies itself.
For example:
function getCounter() {
    var count = 0;

    return function counter() {
        return ++count;
    };
}

var counter = getCounter();

See that function counter? The one returned by the getCounter function? That function is a miser. It will not let go of the count variable even though the count variable belongs to the getCounter function call and that function call has ended. Hence we call counter a closure.
See every function call may create variables. For example a call to the getCounter function creates a variable count. Now this variable count usually dies when the getCounter function ends.
However the counter function (which can access the count variable) doesn't allow it to die when the call to getCounter ends. This is because the counter function needs count. Hence it will only allow count to die after it dies itself.
Now the really interesting thing to notice here is that counter is born inside the call to getCounter. Hence even counter should die when the call to getCounter ends - but it doesn't. It lives on even after the call to getCounter ends because it escapes the scope (lifetime) of getCounter.
There are many ways in which counter can escape the scope of getCounter. The most common way is for getCounter to simply return counter. However there are many more ways. For example:
var counter;

function setCounter() {
    var count = 0;

    counter = function counter() {
        return ++count;
    };
}

setCounter();

Here the sister function of getCounter (which is aptly called setCounter) assigns a new counter function to the global counter variable. Hence the inner counter function escapes the scope of setCounter to become a closure.
Actually in JavaScript every function is a closure. However we don't realize this until we deal with functions which escape the scope of a parent function and keep some variable belonging to the parent function alive even after the call to the parent function ends.
For more information read this answer: https://stackoverflow.com/a/12931785/783743

A: Returning the function changes nothing, what's important is creating it and calling it. That makes the closure, that is a link from the internal function to the scope where it was created (you can see it, in practice, as a pointer. It has the same effect of preventing the garbaging of the outer scope, for example).

A: By definition of closure, the link from the function to its containing scope is enough. So basically creating the function makes it a closure, since that is where the link is created in JavaScript :-)
Yet, for utilizing this feature we do call the function from a different scope than what it was defined in - that's what the term "use a closure" in practise refers to. This can both be a lower or a higher scope - and the function does not necessarily need to be returned from the function where it was defined in.
Some examples:
var x = null;

function a() {
    var i = "from a";
    function b() {
        alert(i); // reference to variable from a's scope
    }
    function c() {
        var i = "c";
        // use from lower scope
        b(); // "from a" - not "c"
    }
    c();

    // export by argument passing
    [0].forEach(b); // "from a";
    // export by assigning to variable in higher scope
    x = b;
    // export by returning
    return b;
}
var y = a();
x(); // "from a"
y(); // "from a"

A: The actual closure is a container for variables, so that a function can use variables from the scope where it is created.
Returning a function is one way of using it in a different scope from where it is created, but a more common use is when it's a callback from an asynchronous call.
Any situation where a function uses variables from one scope, and the function is used in a different scope uses a closure. Example:
var globalF; // a global variable

function x() { // just to have a local scope

  var local; // a local variable in the scope

  var f = function(){
    alert(local); // use the variable from the scope
  };

  globalF = f; // copy a reference to the function to the global variable

}

x(); // create the function
globalF(); // call the function

(This is only a demonstration of a closure, having a function set a global variable which is then used is not a good way to write actual code.)

A: a collection of explanations of closure below. to me, the one from "tiger book" satisfies me most...metaphoric ones also help a lot, but only after encounterred this one...

*

*closure: in set theory, a closure is a (smallest) set, on which some operations yields results also belongs to the set, so it's sort of "smallest closed society under certain operations".

a) sicp: in abstract algebra, where a set of elements is said to be closed under an operation if applying the operation to elements in the set produces an element that is again an element of the set. The Lisp community also (unfortunately) uses the word "closure" to describe a totally unrelated concept: a closure is an implementation technique for representing procedures with free variables.
b) wiki: a closure is a first class function which captures the lexical bindings of free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it "closes over" those variables.”
c) tiger book: a data structure on heap (instead of on stack) that contains both function pointer (MC) and environment pointer (EP), representing a function variable;
d) on lisp: a combination of a function and a set of variable bindings is called a closure; closures are functions with local state;
e) google i/o video: similar to a instance of a class, in which the data (instance obj) encapsulates code (vtab), where in case of closure, the code (function variable) encapsulates data.
f) the encapsulated data is private to the function variable, implying closure can be used for data hiding.
g) closure in non-functional programming languages: callback with cookie in C is a similar construct, also the glib "closure": a glib closure is a data structure encapsulating similar things: a signal callback pointer, a cookie the private data, and a destructor of the closure (as there is no GC in C).
h) tiger book: "higher-order function" and "nested function scope" together require a solution to the case that a dad function returns a kid function which refers to variables in the scope of its dad implying that even dad returns the variables in its scope cannot be "popup" from the stack...the solution is to allocate closures in heap.
i) Greg Michaelson ($10.15): (in lisp implementation), closure is a way to identify the relationship betw free variables and lexical bound variables, when it's necessary (as often needed) to return a function value with free variables frozen to values from the defining scope.
j) histroy and etymology: Peter J. Landin defined the term closure in 1964 as having an environment part and a control part as used by his SECD machine for evaluating expressions. Joel Moses credits Landin with introducing the term closure to refer to a lambda expression whose open bindings (free variables) have been closed by (or bound in) the lexical environment, resulting in a closed expression, or closure. This usage was subsequently adopted by Sussman and Steele when they defined Scheme in 1975, and became widespread.


Q: C# change the first 32bit Int of a GUID I have a GUID which I created with GUID.NewGUID(). Now I want to replace the first 32 bit of it with a specific 32-bit Integer while keeping the rest as they are.
Is there a function to do this?

A: You can use ToByteArray() function and then the Guid constructor.
byte[] buffer = Guid.NewGuid().ToByteArray();
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 0;

Guid guid = new Guid(buffer);

A: Since the Guid struct has a constructor that takes a byte array and can return its current bytes, it's actually quite easy:
//Create a random, new guid
Guid guid = Guid.NewGuid();
Console.WriteLine(guid);

//The original bytes
byte[] guidBytes = guid.ToByteArray();
//Your custom bytes
byte[] first4Bytes = BitConverter.GetBytes((UInt32) 0815);

//Overwrite the first 4 Bytes
Array.Copy(first4Bytes, guidBytes, 4);

//Create new guid based on current values
Guid guid2 = new Guid(guidBytes);
Console.WriteLine(guid2);

Fiddle

Keep in mind however, that the order of bytes returned from BitConverter depends on your processor architecture (BitConverter.IsLittleEndian) and that your Guid's entropy decreases by 232 if you use the same number every time (which, depending on your application might not be as bad as it sounds, since you have 2128 to begin with).

A: The question is about replacing bits, but if someone wants to replace first characters of guid directly, this can be done by converting it to string, replacing characters in string and converting back. Note that replaced characters should be valid in hex, i.e. numbers 0 - 9 or letters a - f.
var uniqueGuid = Guid.NewGuid();
var uniqueGuidStr = "1234" + uniqueGuid.ToString().Substring(4);
var modifiedUniqueGuid = Guid.Parse(uniqueGuidStr);


Q: BeautifulSoup doesn't seem to parse anything I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this :
<html>
 <head>
 </head>
 <body>
  <bound 0x7f977c9121d0="" <http.client.httpresponse="" at="" httpresponse.read="" method="" object="" of="">
>
  </bound>
 </body>
</html>

I have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ?
from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req).read
        soup = BeautifulSoup(str(content), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())

A: You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you.
A better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you.
from bs4 import BeautifulSoup
import urllib
import html5lib

class Websites:

    def __init__(self):
        self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}

    def free_proxy_list(self):
        print("Connecting to free-proxy-list.net ...")

        url = "https://free-proxy-list.net"
        req = urllib.request.Request(url, None, self.header)
        content = urllib.request.urlopen(req)
        html = content.read()
        soup = BeautifulSoup(str(html), "html5lib")

        print("Connected. Loading the page ...")

        print("Print page")
        print("")
        print(soup.prettify())
        content.close()  # Important to close the connection

For more info see: https://docs.python.org/3.0/library/urllib.request.html#examples


Q: Is there a way to import a react component without using 'import' statement I'm new to React. Just trying out things.
So far I have been using CDNs for React, React-DOM, and React-Bootstrap. I had no trouble using components of React-Bootstrap using the example code below:
var Alert = ReactBootstrap.Alert;

Now my problem is I want to use a component that is not provided by React-Bootstrap so I tried to look for components available in Github. I found a lot of the components that I am looking for but all of them are available for installation via npm which I am avoiding since I'm using React thru CDN. I know it is recommended to use npm or create-react app, but that's not how I started my application.
So is there a way to import components like how I did in React-Bootstrap components? For example:
var Select = React.Select; // import Select from 'react-select';


Q: Android: Send Longitude and Latitude after 60 seconds to the localhost server(WAMP) I want to send the Longitude, Latitude, TimeStamp and the stonest wifi access point as JSON format to the server (WAMP- localhost) after every 60 seconds what is the best approach to do that? I would use AsyncTask but AsyncTasks should ideally be used for short operations (a few seconds at the most.) can someone give short example for sending this data with another approach than AsyncTask?

A: start with these tutorials
http://www.tutorialspoint.com/android/android_php_mysql.htm
http://www.tutorialspoint.com/android/android_php_mysql.htm
after that here is how to repeate every 60 seconds
    boolean run=true;
   Handler mHandler = new Handler();//sorry forgot to add this
...
...
      public void timer() {
            new Thread(new Runnable() {
            @Override
            public void run() {
                while (run) {
                    try {
                        Thread.sleep(60000);//60000 milliseconds  which is 60 seconds
                        mHandler.post(new Runnable() {

                            @Override
                            public void run() {
                                 //here you send data to server
                            }
                        });
                    } catch (Exception e) {
                    }
                }
            }
        }).start();}

call it like this to start it
  timer()

and to stop it just do
run=false;


Q: "error_description": "Invalid Value" for token google sign in every time using flutter I am new in flutter trying to access auth token from google for my backend server but every time token is invalid.
i am using FirebaseUser user await user.getIdToken() I give me a token but when I am trying to validate that token using my backend server as well as https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken and https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken this link it gives me "error_description": "Invalid Value".
I am not sure await user.getIdToken() this method is right for getting token.
Other think everything ok I am getting all user information except right token.
please let me know if any other way.
Below is my code:
class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => new _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final FirebaseAuth auth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = new GoogleSignIn();
  Future<http.Response> socailLogin(String authToken) async {
    var url = "http://api.ourdomain.com/user/social/login/google";
    final response = await http.post(url,
    body: json.encode({"auth_token": authToken}),
    headers: {HttpHeaders.CONTENT_TYPE: "application/json"});
    return response;
  }

  Future<FirebaseUser> googleSignin() async {
  final GoogleSignInAccount googleSignInAccount = await
  googleSignIn.signIn();

  final GoogleSignInAuthentication googleSignInAuthentication =
    await googleSignInAccount.authentication;

  final FirebaseUser firebaseUser = await auth.signInWithGoogle(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken);
   return firebaseUser;
 }

@override
Widget build(BuildContext context) {
final logo = Hero(
  tag: 'hero',
  child: CircleAvatar(
    backgroundColor: Colors.transparent,
    radius: 48.0,
    child: Image.asset('assets/logo.png'),
  ),
);

final googleloginButton = Padding(
  padding: EdgeInsets.symmetric(vertical: 5.0),
  child: Material(
    borderRadius: BorderRadius.circular(30.0),
    //  shadowColor: Colors.lightBlueAccent.shade100,
    // elevation: 5.0,
    child: MaterialButton(
      minWidth: 200.0,
      height: 42.0,
      onPressed: () async {
        FirebaseUser user = await googleSignin();
         String idToken = await user.getIdToken();
        if (idToken != null) {

          final http.Response response = await socailLogin(idToken);
          if (response.statusCode == 200) {
            var authToken = json.decode(response.body)['token'];
            if (authToken != null) {
              storedToken(authToken);
            }
          } else {
            print("Response status: " + response.statusCode.toString());
            print("Response body: " + response.body);
            print("errror while request");
          }
        } else {
          print("in else part not get token id from google");
        }
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => HomeScreen(),
          ),
        );
      },
      color: Colors.red,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Icon(
            Icons.bug_report,
            color: Colors.white,
          ),
          Text('Connect with Google',
              style: TextStyle(color: Colors.white)),
        ],
      ),
    ),
  ),
);

 return Scaffold(
   backgroundColor: Colors.white,
   appBar: new AppBar(
     centerTitle: true,
     title: new Text("Login"),
   ),
   body: Center(
    child: ListView(
      shrinkWrap: true,
      padding: EdgeInsets.only(left: 24.0, right: 24.0),
      children: <Widget>[
        // logo,
        googleloginButton,
        facebookloginButton,
      ],
     ),
   ),
  );
 }
}

Pleases help me.

A: For backend server-side validation, you must use verifiable ID tokens to securely get the user IDs of signed-in users on the server side.
ref. : https://developers.google.com/identity/sign-in/web/backend-auth
Seems that the current flutter google sign in plugin does not support getting AuthCode for backend server-side OAuth validation.
ref. : https://github.com/flutter/flutter/issues/16613
I think the firebaseUser.getIdToken() cannot be used for Google API.
For https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken
, you may need to pass the googleSignInAuthentication.idToken
For https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken
, you may need to pass the googleSignInAuthentication.accessToken
Getting user information like user id and pass it to backend server-side is vulnerable to hackers. You should verify the idToken in backend server-side by Google API Client Libraries.

A: I recently had a similar problem.
this was my code:
Future<void> googleLogin() async {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) {
  print('no google user??');
  return;
}
_user = googleUser;

final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken);

try {
  await FirebaseAuth.instance.signInWithCredential(credential);

} catch (e) {
  print('could not sign in with goodle creds, and heres why: \n $e');
}

}
I was not providing all the information in the credential variable. So all I had to do was to add the accessTokenId there. So replace the:
final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken);

with:
final credential = GoogleAuthProvider.credential(
    idToken: googleAuth.idToken, accessToken:    googleAuth.accessToken);

and when that got passed to FirebaseAuth.instance, it worked! How this helps.


Q: Using SmtpAppender to only send emails when logging an error or fatal I'm using log4net to log different types of messages.
I have added the SmtpAppender to email specific user when logging messages.
However, what I would like to achieve is to be able to only send emails if an error or fatal is logged.
Accroding to my current configuration in the web.config file, I get two emails, one for the error and another one for the rest of the logs.
Global.asax.cs:
logger.Info("Info");
logger.Warn("Warning");
logger.Fatal("Fatal");
logger.Error("exception");

web.config:
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
    <to value="bla@bla.com" />
    <from value="bla@bla.com" />
    <subject value="test logging message" />
    <smtpHost value="*******" />
    <bufferSize value="512" />
    <lossy value="true" />
    <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="WARN"/>
    </evaluator>
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger- %message%newline%newline%newline" />
    </layout>
</appender>

A: I have found the solution, I should just add this tag to the SmtpAppender:
<filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="ERROR" />
    <levelMax value="FATAL" />
</filter>

A: Try using:
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
    ...
    <threshold value="WARN"/>
    ...
</appender>

(or threshold value="ERROR" since you say you want to limit to Error and Fatallevels) rather than:
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
    ...
    <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="WARN"/>
    </evaluator>
    ...
</appender>

The log4net documentation or this message in the log4net user mailing list explains the difference.


Q: Android make a dialog scrollable I'm showing a dialog when the user clicks a button. When the dialog appears and you click an EditText to enter some text, you can't see the bottom buttons (and the lowest EditText) anymore. So you have to click the keyboard down, then select the button or EditText. I searched for the answer for a while now, but i can't find it.
So: How do i make my dialog scrollable? Apparently my code doesnt do the trick:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical"
    android:scrollbars="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true">

<EditText
   android:id="@+id/addKlantNaam"
   android:textSize="20sp"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="@string/klantNaam"
   />

<EditText
   android:id="@+id/addKlantLocatie"
   android:textSize="20sp"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="@string/klantLocatie"
   />

<TextView
    android:id="@+id/scheidenDoorKomma"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:text="@string/scheidenDoorKomma"/>

<EditText
   android:id="@+id/addFabrieken"
   android:textSize="20sp"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="@string/fabrieken"
   />

 <EditText
   android:id="@+id/addMachines"
   android:textSize="20sp"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="@string/machines"
   />

 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" >

    <Button
        android:id="@+id/dialogAnnuleren"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/annuleren"
        android:textSize="22sp" />

    <Button
        android:id="@+id/dialogToevoegen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/dialogAnnuleren"
        android:textSize="22sp"
        android:text="@string/toevoegen"/>
  </RelativeLayout>

</LinearLayout>

This is how i call for the dialog:
btnAdd.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {

            // custom dialog
            dialog = new Dialog(context);
            dialog.setContentView(R.layout.addklant_layout);
            dialog.setTitle("Klant toevoegen");

            Button BTNannuleren = (Button) dialog.findViewById(R.id.dialogAnnuleren);
            // if button is clicked, close the custom dialog
            BTNannuleren.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            Button BTNtoevoegen = (Button) dialog.findViewById(R.id.dialogToevoegen);
            // if button is clicked, close the custom dialog
            BTNtoevoegen.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    StoreKlantInDatabase task = new StoreKlantInDatabase();
                        task.execute(urlInsertKlant);
                        dialog.dismiss();
                    }
            });
            dialog.show();
      }
    });

anyone can help me out here?

A: GeertG... now im emotionally involved :) try the link i found... it might do the trick as far as using a scrollview with more than a single child...I dont know if it solves your issue but...
If ScrollView only supports one direct child, how am I supposed to make a whole layout scrollable?
or
how to add multiple child in horizontal scroll view in android
Those solutions should work as creating a scrollview with more than 1 child... will it solve your problem? IDK...
also look in to
How to hide soft keyboard on android after clicking outside EditText?
but having the keyboard closed and re-opened seems kinda reasonable to me... dont linger on it for too long:)

A: The guidelines for what you are asking are can be found here. As you can see. there are a number of ways to achieve what you are asking.
Further to this, you could consider changing default action of the 'Enter' button on the keyboard to select the next EditText and finally to submit the form when you are done (read up about it here):
android:imeOptions="actionDone"

A: Use LinearLayout Height match_parent. And try if its working or not.
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical"
    android:scrollbars="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true">


Q: Hbase Pagination Filter returning more keys I am using Hbase pagination Filter to iterate over all the rows in table using following code
Scan scan=new Scan(Bytes.toBytes(key))
Filter filter=new PageFilter(10000);
scan.setFilter(pageFilter);
scan.setCaching(100000);// 1lakh i know  it should be 10K but this should not be the reson for scanner to return more keys as i commented out the line still getting more keys
ResultScanner resultScanner=htable.getScanner(scan);

But i am getting more than 10000 value for a specific key in most of the cases it is working fine and returning 10000 keys that is equal to pagination factor but in a specific case it returns more than 10000 key.
Any point in the direction to understand this behavior will be of a great help

A: OK,It is clear from HBase Api Pagination doc that the pagination filter does not guarantee to give rows <= pagination factor since the filter is applied for each region server


Q: how to overwrite User model I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User

class ShugeUser(User)
    username = EmailField(uniqute=True, verbose_name='EMail as your
username', ...)
    email = CharField(verbose_name='Nickname, ...)

User = ShugeUser

A: That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).
If you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).

A: The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.
You access the profile by utilizing the get_profile() method of a User object.
Related documentation is available here.