text:
Q: specific constraint, instead of a general constraint for a least square problem Let's say that I have a simple problem like this at hand.
import cvxpy as cp
import numpy as np

A = np.array([[ 143, -144, -343, 56]
,[-7632,  77, -277, 63 ]
,[ 55, -75,   74, 744 ]
,[-22 , 177, -28, 12]
,[-848 , -433 , 121, 54]
,[98, 75, 155, 87]])

b = [-114, -734, -270,  577,  676, 122]

n = 4
x = cp.Variable(n)
objective = cp.Minimize(cp.sum_squares(A*x - b))
prob = cp.Problem(objective)
result = prob.solve()

print(" x =", x.value)

The answer of this problem is x = [ 0.04802172 -0.7942824   0.88297924 -0.47109203] where:
 x1 = 0.04802172, x2 = -0.7942824, x3 = 0.88297924, x4 = -0.47109203

I know that I can define a general constriant for this problem, something like this that can be applied on all the resluts :
constraints = [0 <= x, x <= 1]

prob = cp.Problem(objective, constraints)

But I was wondering if I can apply the below constraints to the problem which is more specific:
1) abs(x2)< abs(x1) (and so on and so forth forth ,ie, abs(x4)< abs(x3) , ...)
2) The last two results (in this case x3 and x4) are free to obtain any values.

In other words, I need the second value of each pair of answers to be smaller than the first value, except for the last two answers.
I appreciate any help regarding this problem-defining issue that I have.
Thanks


text:
Q: List VPN connections and properties in command prompt Is there a command, in cmd or PowerShell for Windows VPN like there is for wifi, to list and edit profiles?
Like this is for wifi. (just an example)

netsh wlan show profiles

A: Sure.  VPN connections look like adapters.  Take a look at this question: How to find my VPN client IP in windows

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change line inside shiny::renderText() used in flexdashboard I have the basic flexdashboard below. What I want is to change line after "hello" in order to place "world" below it,inside the renderText(). I have found that I can use htmlOutput() and verbatimTextOutput() but these are not used in flexdashboard.
---
title: "[School Name] Enrollment Projections for Fall 2019"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    runtime: shiny
---
```{r setup, include = FALSE}
library(flexdashboard)
library(shiny)

```
Column {.sidebar }
-------------------------------------
### Menu
```{r}
renderText({
      paste("hello", "world", sep="\n")
    })
```

Row {data-height=400}
-------------------------------------
### Enrollments
```{r}
```


text:
Q: Constructor Item in class Item cannot be applied to given types "constructor Item in class Item cannot be applied to given types;
  required: java.lang.String,java.land.String,int,int,java.lang.String; found; no arguments; reason: actual and formal arguetn lists differ in length"
Is my full error message, I'm trying to get a method to give me a random sword name from an arraylist when called.
For simplicity i pasted the class codes into 2 different pastebins:
Class Swords
Class Item
edit: code...
    import java.util.Random;
    import java.util.ArrayList;
    import java.util.HashMap;
    /**
    * Write a description of class Swords here.
    *
    * @author (your name)
    * @version (a version number or a date)
    */
    public class Swords extends Item
    {
    // instance variables - replace the example below with your own
     private int dmg;
    ArrayList<String> swordNames = new ArrayList();
    HashMap<String,String> swordDesc = new HashMap<String,String>();

    /**
     * Constructor for objects of class Swords
     */
    public Swords()
    {
        generateSwordName();
        super(getRandomSword(), "asd",  40, 40, "Item");
        dmg = generateRandom(2, 50);
    }

    public int generateRandom(int Start, int End)
   {
     int START = Start;
        int END = End;
        Random random = new Random();
        long range = (long)END - (long)START +1;
        long fraction = (long)(range * random.nextDouble());
        int randomNumber = (int)(fraction + START);
        return randomNumber;
    }

   public void generateSwordName()
   {
       swordNames.add("Blade of Slimer");
       swordDesc.put("Blade of Slimer", new String("Blade of Slimer is a sword forged from the waste of Slimer, surprisingly durable."));
       swordNames.add("Thorny Farris");
       swordDesc.put("Thorny Farris", new String("A rose thorn was accidently dropped into a bottle of Farris, and a majestic sword emerged from the bottle"));
       swordNames.add("The Sword of Leah");
       swordDesc.put("The Sword of Leah", new String(" A sword carried by the Leah family for generations, later given the ability to cut through magic."));
       swordNames.add("Grayswandir");
       swordDesc.put("Grayswandir", new String("A sword used by Corwin of Amber. Grayswandir is associated with the moon and the night."));
       swordNames.add("Werewindle");
       swordDesc.put("Werewindle", new String("A sword used by Brand of Amber. Werewindle is associated with the sun and day."));
       swordNames.add("Dull Sword");
       swordDesc.put("Dull Sword", new String("A dull sword"));

    }

   public String getRandomSword()
   {
       int swordSize = swordNames.size()-1;
       String randomSwords = swordNames.get(generateRandom(0,swordSize));
       return randomSwords;
    }

    /**
     * Skriver ut informasjon om itemet.
     */
   public void print()
   {
       int minDmg = dmg - 2;
       int maxDmg = dmg + 2;
       System.out.println("########################");
       System.out.println("# Name of item: " + super.getName());
       System.out.println("# Item description: " + super.getDesc());
       System.out.println("# Sword damage: " + minDmg + "-" + maxDmg);
       System.out.println("# Item value: " + super.getValue() + " coins");
       System.out.println("# Item weight: " + super.getWeight() + "kg");
       System.out.println("########################");
    }
}

Item class:
import java.util.HashSet;
/**
 * Write a description of class Item here.
 *
 * @author Thomas andré G. Petersson
 * @version 29.09.2016 | v0.1
 *
 * Item

 */
public class Item
{

   private String itemName;
   private String desc;
   private int value;
   private int weight;
   private String action;

   public Item(String itemName, String desc, int value, int weight, String action)
   {
       this.itemName = itemName;
       this.desc = desc;
       this.value = value;
       this.weight = weight;
       this.action = action;
   }
   // Getters for bruk av arvings klasser #############################
   public String getName()
   {
       return itemName;
    }

   public String getDesc()
   {
       return desc;
    }

   public int getValue()
   {
       return value;
    }

   public int getWeight()
   {
       return weight;
    }

   public String getAction()
   {
       return action;
    }
   //##################################################################

   /**
     * Skriver ut informasjon om itemet.
     */
   public void print()
   {
       System.out.println("########################");
       System.out.println("# Name of item: " + itemName);
       System.out.println("# Item description: " + desc);
       System.out.println("# Item value: " + value + " coins");
       System.out.println("# Item weight: " + weight + "kg");
       System.out.println("########################");
    }
}

A: Nothing of your code in regard to the different sword names is special to a specific sword instance. So you can move the sword names and descriptions to static fields and initialize them from a static initializer. Then in the constructor you have the data ready:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

/**
 * Write a description of class Swords here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Swords extends Item {
    private static ArrayList<String> swordNames = new ArrayList();
    private static HashMap<String, String> swordDesc = new HashMap<String, String>();

    static {
        generateSwordName();
    }

    // instance variables - replace the example below with your own
    private int dmg;

    /**
     * Constructor for objects of class Swords
     */
    public Swords() {
        super(getRandomSword(), "asd", 40, 40, "Item");
        dmg = generateRandom(2, 50);
    }

    public static String getRandomSword() {
        int swordSize = swordNames.size() - 1;
        String randomSwords = swordNames.get(generateRandom(0, swordSize));
        return randomSwords;
    }

    public static int generateRandom(int Start, int End) {
        int START = Start;
        int END = End;
        Random random = new Random();
        long range = (long) END - (long) START + 1;
        long fraction = (long) (range * random.nextDouble());
        int randomNumber = (int) (fraction + START);
        return randomNumber;
    }

    public static void generateSwordName() {
        swordNames.add("Blade of Slimer");
        swordDesc.put("Blade of Slimer",
                new String("Blade of Slimer is a sword forged from the waste of Slimer, surprisingly durable."));
        swordNames.add("Thorny Farris");
        swordDesc.put("Thorny Farris", new String(
                "A rose thorn was accidently dropped into a bottle of Farris, and a majestic sword emerged from the bottle"));
        swordNames.add("The Sword of Leah");
        swordDesc.put("The Sword of Leah", new String(
                " A sword carried by the Leah family for generations, later given the ability to cut through magic."));
        swordNames.add("Grayswandir");
        swordDesc.put("Grayswandir",
                new String("A sword used by Corwin of Amber. Grayswandir is associated with the moon and the night."));
        swordNames.add("Werewindle");
        swordDesc.put("Werewindle",
                new String("A sword used by Brand of Amber. Werewindle is associated with the sun and day."));
        swordNames.add("Dull Sword");
        swordDesc.put("Dull Sword", new String("A dull sword"));

    }

    /**
     * Skriver ut informasjon om itemet.
     */
    public void print() {
        int minDmg = dmg - 2;
        int maxDmg = dmg + 2;
        System.out.println("########################");
        System.out.println("# Name of item: " + super.getName());
        System.out.println("# Item description: " + super.getDesc());
        System.out.println("# Sword damage: " + minDmg + "-" + maxDmg);
        System.out.println("# Item value: " + super.getValue() + " coins");
        System.out.println("# Item weight: " + super.getWeight() + "kg");
        System.out.println("########################");
    }
}

Edit:
change this line:
private static ArrayList<String> swordNames = new ArrayList();

to
private static ArrayList<String> swordNames = new ArrayList<>();

to get rid of the unchecked compiler warning.

A: The Super() constructor must be the first line that is called from a sub-class constructor. Even if you have it further down. Since the super(...) call is the second method, Java will try to call a no-param Super() automatically for you and sees that there is no Super() available. You'll need to change the call order and call super first.


text:
Q: Python extract PDF data conditionally I have few chapters in pdf file showed in the image below. I want to extract the data (red line) after the bold sentences  My current code able to loop through all the pages and extract all text. But how to extract those after bold sentences?

Sample code:
import PyPDF2

filename = "test.pdf"
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
num_pages = pdfReader.numPages
count = 0
text = ""

while count < num_pages:
    pageObj = pdfReader.getPage(count)
    count += 1
    text += pageObj.extractText()

print(text)

A: Use pdfplumber with char properties.
import pdfplumber

with pdfplumber.open("test.pdf") as pdf:

    for text in pdf.pages:
        normal_text = text.filter(lambda obj: obj["object_type"] == "char" and not "Bold" in obj["fontname"])

        print(normal_text.extract_text())

Note : fontname is the name of the character's font face (e.g, Bold).


text:
Q: Declarative Authenication, Unable to register user I'm using declarative authentication but when ever I' click on the link to register a user I am told you are not allow to view that page. I even get this when giving guest omnipotence.
authorization_rules
authorization do

  role :guest do
    has_omnipotence
    #has_permission_on :channels, :to => :read
    #has_permission_on :user_session, :to => [:create, :read]
    #has_permission_on :users, :to => [:manage, :read, :update, :update]
  end

  role :admin do
    has_omnipotence
  end

  role :moderator do
    has_permission_on :channels, :to => :manage
    has_permission_on :users, :to => :read
    has_permission_on :messages , :to => :manage
  end
end

privileges do
  # default privilege hierarchies to facilitate RESTful Rails apps
  privilege :manage, :includes => [:create, :read, :update, :delete]
  privilege :read, :includes => [:index, :show]
  privilege :register, :includes => [:new, :create]
  privilege :update, :includes => :edit
  privilege :delete, :includes => :destroy
end

users controller
class UsersController < ApplicationController

   filter_resource_access

  # GET /users
  # GET /users.xml
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  # GET /users/1
  # GET /users/1.xml
  def show
    #@user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/new
  # GET /users/new.xml
  def new
    #@user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/1/edit
  def edit
    #@user = User.find(params[:id])
  end

  def create
    #@user = User.new(params[:user])
    #@user.roles << 'subscriber'
    @user.channels << Channel.find(1)

    respond_to do |format|
      if @user.save
        format.html { redirect_to(:channels, :notice => 'Registration successfully.') }
        format.xml { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  def profile
    @user = User.find(params[:id])
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
  #@user = current_user

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    @user = User.find(params[:id])
    @user.destroy
    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end

  def delete
    @user = User.find(params[:user_id])
    @user.destroy
    redirect_to :users
  end

  def subs
     @user = User.find(params[:id])
  end

end

layout view
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title><%= h(yield(:title) || "Untitled") %></title>
    <%= stylesheet_link_tag 'application' %>
    <%= yield(:head) %>

      <% if current_user %>
          <%= link_to "Logout: " + current_user.login, :logout %>
      <%else %>
              <%= link_to "Login", :login %>
          <% end %>

<%= link_to "Users", :users %>

<%= link_to "Channels", :channels %>

<%= link_to "My Profile", :profile %>

<%= link_to "My Channels", '#'%>

    <% if current_user %>

        <% else %>

 <%= link_to "Register", new_user_path %>

        <% end %>

      <%- flash.each do |name, msg| -%>
        <%= content_tag :div, msg, :id => "flash_#{name}" %>
      <%- end -%>

      <%- if show_title? -%>

<%=h yield(:title) %>

      <%- end -%>

      <%= yield %>

A: Why don't you try giving explicit authorization for guests to create user?
  role :guest do
    has_permission_on :users, :to => [:register]
  end


text:
Q: How to understand this algebraic contradiction and relate to definition of complex numbers? Using the following identities:
$x^b \cdot x^a = x^{b+a}$  (#1)
Example: $100^1 \cdot 100^{-1} = 100^{1-1} = 1 $
$(yz)^c =y^c \cdot z^c $   (#2)
Example: $16^{3/2} \cdot \sqrt{9}=16^1 \cdot 16^{1/2} \cdot 9^{1/2} = 16 \cdot (16 \cdot 9)^{1/2} = 16 \cdot 144^{1/2} = 16\cdot 12 = 192$
Now taking $\sqrt{-4} \cdot \sqrt{-4} $
We get $(-4)^1 = -4$ by using (#1) but $\sqrt{(-4)(-4)}=\sqrt{16} = \pm4$ by using (#2). How to explain that and relate this "contradiction" to the imaginary number $i$ where $\sqrt{i^2} = i $ and not $\pm i$?

A: There are some limitations built into exponentiation. The base number and exponent cannot be just anything:

*

*If we limit ourselves to $y \in \Bbb N \setminus \{0\}$, then $x^y$ makes sense for any $x \in \Bbb C$.

*If $y \in \Bbb Z$, then $x^y$ makes sense for any $x \in \Bbb C\setminus \{0\}$.

*If $y \in \Bbb R$, then $x^y$ makes sense only for $x \in \Bbb R, x > 0$.

*If $y \in \Bbb C$, then $x^y$ makes sense only for $x = e$.

So you see, the more freely you're allowed to choose $y$, the more restrictive the choices of $x$ becomes. In your case, with the exponent being $y = 1/2$, we are only allowed to use positive reals for base. Otherwise the exponentiation rules (such as $x^{yz} = (x^y)^z$ and $x^{y+z} = x^yx^z$) will get you into exactly the kind of problems that you have discovered.
For instance, $i$ is not defined as $\sqrt{-1}$, really. It's defined by $i^2 = -1$.

A: The square root of a positive real number $x$ is by definition the only positive real number $y$ such as $y^2=x$. Thus there is no $+/-$ to add in front of your last $4$.


text:
Q: How to filter text mark with small values that are overlapping in stack bar chart on vega lite Some of the text overlap with one another because the value is very small, so there isn't enough space for the text mark. I have tried using transform with filter, but the position of the text mark will be incorrect. What could I do, so that I can filter out the value that is less than 5% while maintaining the position of the remaining text mark?
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {
        "value": 0.5026,
        "serie": "bts",
        "category": "facebook",
        "color": "#2ccce4"
      },
      {
        "value": 0.357,
        "serie": "jungkook",
        "category": "facebook",
        "color": "#f47373"
      },
      {
        "value": 0.0967,
        "serie": "jimin",
        "category": "facebook",
        "color": "#37d67a"
      },
      {
        "value": 0.0437,
        "serie": "butter",
        "category": "facebook",
        "color": "#dce775"
      },
      {
        "value": 0.7923,
        "serie": "bts",
        "category": "news",
        "color": "#2ccce4"
      },
      {
        "value": 0,
        "serie": "jungkook",
        "category": "news",
        "color": "#f47373"
      },
      {
        "value": 0.0231,
        "serie": "jimin",
        "category": "news",
        "color": "#37d67a"
      },
      {
        "value": 0.1846,
        "serie": "butter",
        "category": "news",
        "color": "#dce775"
      },
      {
        "value": 0.6569,
        "serie": "bts",
        "category": "twitter",
        "color": "#2ccce4"
      },
      {
        "value": 0.0511,
        "serie": "jungkook",
        "category": "twitter",
        "color": "#f47373"
      },
      {
        "value": 0.0949,
        "serie": "jimin",
        "category": "twitter",
        "color": "#37d67a"
      },
      {
        "value": 0.1971,
        "serie": "butter",
        "category": "twitter",
        "color": "#dce775"
      },
      {
        "value": 1,
        "serie": "bts",
        "category": "blog",
        "color": "#2ccce4"
      },
      {
        "value": 0,
        "serie": "jungkook",
        "category": "blog",
        "color": "#f47373"
      },
      {
        "value": 0,
        "serie": "jimin",
        "category": "blog",
        "color": "#37d67a"
      },
      {
        "value": 0,
        "serie": "butter",
        "category": "blog",
        "color": "#dce775"
      },
      {
        "value": 1,
        "serie": "bts",
        "category": "instagram",
        "color": "#2ccce4"
      },
      {
        "value": 0,
        "serie": "jungkook",
        "category": "instagram",
        "color": "#f47373"
      },
      {
        "value": 0,
        "serie": "jimin",
        "category": "instagram",
        "color": "#37d67a"
      },
      {
        "value": 0,
        "serie": "butter",
        "category": "instagram",
        "color": "#dce775"
      }
    ]
  },
  "title": {},
  "encoding": {
    "y": {
      "field": "category",
      "axis": {
        "title": null
      }
    },
    "x": {
      "aggregate": "sum",
      "stack": "normalize",
      "field": "value",
      "axis": {
        "title": null,
        "grid": false
      }
    }
  },
  "layer": [
    {
      "mark": {
        "type": "bar"
      },
      "encoding": {
        "color": {
          "field": "serie",
          "scale": {
            "range": ["#2ccce4", "#dce775", "#37d67a", "#f47373"]
          },
          "legend": null
        },
        "tooltip": [
          {
            "field": "category",
            "type": "nominal"
          },
          {
            "field": "value",
            "type": "quantitative",
            "aggregate": "sum",
            "format": ".2%"
          },
          {
            "field": "serie",
            "type": "nominal"
          }
        ]
      }
    },
    {
      "mark": {
        "type": "text",
        "dx": -3,
        "align": "right",
        "color": "#000",
        "fontSize": 11
      },
      "encoding": {
        "detail": {
          "field": "serie"
        },
        "text": {
          "condition": {
            "test": "datum.value > 0.05",
            "type": "quantitative",
            "aggregate": "sum",
            "field": "value",
            "format": ".2%"
          },
          "value": ""
        }
      }
    }
  ],
  "config": {
    "view": {
      "stroke": "transparent"
    },
    "axis": {
      "domainWidth": 1
    }
  }
}

A: You can use a condition to show or hide text marks. You didn't provide a full dataset with your example so see below for how to implement with one of the standard examples. Labels less than 55 are hidden by the condition.
Editor

{
  "data": {"url": "data/barley.json"},
  "width": 400,
  "encoding": {
    "x": {
      "type": "quantitative",
      "aggregate": "sum",
      "field": "yield",
      "stack": "zero"
    },
    "y": {"type": "nominal", "field": "variety"}
  },
  "layer": [
    {
      "mark": "bar",
      "encoding": {"color": {"type": "nominal", "field": "site"}}
    },
    {
      "mark": {"type": "text", "color": "white", "dx": -5, "align": "right"},
      "encoding": {
        "detail": {"type": "nominal", "field": "site"},
        "text": {
          "condition": {
            "test": "datum.sum_yield > 55",
            "type": "quantitative",
            "aggregate": "sum",
            "field": "yield",
            "format": ".1f"
          },
          "value": ""
        }
      }
    }
  ]
}


text:
Q: C++ Static and Dynamic Array Initialization Let's have a following code:
#include <iostream>

struct TStruct{
  int x;
  int y;
  int * ptr;

  TStruct( void ) : x( 0 ), y( 0 ), ptr( nullptr ) { }
};

int main(){
  TStruct arr[100];
  TStruct * arr2 = new TStruct[200];

  // some code working with these arrays

  for( int i = 0; i < 100; i ++ )
    if( arr[i] . ptr != nullptr )
      delete [] arr[i] . ptr;
  for( int i = 0; i < 200; i ++ )
    if( arr2[i] . ptr != nullptr )
      delete [] arr2[i] . ptr;
  delete [] arr2;
  return 0;
}

How does initialization of both of these arrays - static and dynamic - works? Are they automatically initialized by TStruct constructor or do I have to initialize them manually by looping both of them and setting values for each TStruct member?

A: The TStruct constructor will be called 300 times with the code you're showing. A hundred times for each element in the array arr, and two hundred times when you allocate memory for arr2.
For the array arr the compiler generates code to call the constructor, and when you use new[] the operator will make sure the constructor is called.

A: The default constructor is being called for every instance of TStruct.
In your code snippet, there are 300 instances and 300 default constructor calls.
There's no difference between an instance created by new, new[] or the "normal" creation on the stack, when it comes to constructor calls.
In your example you created a default constructor, which is called for each instance.
If there wouldn't exist such a self-defined default constructor, the system would create an auto-generated default constructor. The generated one would call the default constructors of each data element.
In case one defines classes with dynamic parts, like in the question (using new to reserve memory and assign the memory adress to the pointer), you need to care about the pointer value: Setting the pointers value to NULL / nullptr at the time of instantiation is very important.
The reason is, that you (or somebody using the class) could suddenly apply delete to the pointers value of his instance. The default value for a pointer is not null, but a random adress in the memory. Deleting the object at this default random adress can lead to unexpected behaviour or crash of the program.

A:
How does initialization of both of these arrays - static and dynamic - works? Are they automatically initialized by TStruct constructor or do I have to initialize them manually by looping both of them and setting values for each TStruct member?

Both statements will call the TStruct default constructor for each element instantiated, you don't need to do anything manually.


text:
Q: Dynamic sitemap by next-sitemap I want to add server-sitemap.xml to my next js App by next-sitemap,
I will be grateful if anyone can explain how can i add dynamic sitemap by next-sitemap in nextjs.
import { GetServerSideProps } from "next"
import { getServerSideSitemap,ISitemapField } from "next-sitemap"
const { all_product_get }  = require("../../src/api/guest")
export const  getServerSideProps =  GetServerSideProps async (ctx) => {
let data = []
await all_product_get().then(res => {
data : res.data.data
})
const fields :ISitemapField[]  = data.map(item => ({loc :`https://sivanland.com/product/detail/${item._id}`,
lastmod: new Date().toISOString()}))
return getServerSideSitemap(ctx, fields);
};
export default function Site(){}

A: I solved it myself.

*

*Add TypeScript to my project: npm i -D typescript

*Add tsconfig.json to project root

*Use TypeScript in NextJS.

tsconfig.json:
{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "jsx": "preserve",
        "lib": [
            "dom",
            "es2017"
        ],
        "module": "esnext",
        "moduleResolution": "node",
        "noEmit": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "preserveConstEnums": true,
        "removeComments": false,
        "skipLibCheck": true,
        "sourceMap": true,
        "strict": true,
        "target": "esnext",
        "forceConsistentCasingInFileNames": true,
        "esModuleInterop": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "incremental": true
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx"
    ]
}

*Then I used the above code with dynamic data from the database:

import { getServerSideSitemap, ISitemapField } from 'next-sitemap'
import { GetServerSideProps } from 'next'

 export const getServerSideProps: GetServerSideProps = async (ctx) => {
// Method to source urls from cms
const response = await fetch('https://newapi.example.com/api/guest/search   /product/all');
let items: any = {}
items = await response.json();

const fields: ISitemapField[] = items.data.map((item: any) => ({
    loc: `https://www.example.com/product/detail/${item._id}`,
    lastmod: new Date().toISOString(),
    changefreq: 'daily',
    priority: '0.7'
}));
return getServerSideSitemap(ctx, fields)
}

export default function Site() { }

*Add folder: pages/server-sitemap.xml/index.tsx

*and paste the above code to index.tsx

*Add site map address to next-sitemap.gonfig.js
additionalSitemaps: [
  'https://example.com/sitemap.xml',
  'https://example.com/server-sitemap.xml'
]


text:
Q: Existe uma especificação REST para upload de arquivos? Estou com uma dúvida a quase um mês sobre o assunto. Em determinada para do meu aplicativo, o usuário pode enviar um upload para uma biblioteca de arquivos.
Esse upload precisa ser registrando numa tabela chamada midias, onde, além do caminho do arquivo, preciso também de dados extras, como nome, descrição, a permissão do arquivo, além das informações de metadados como tamanho e extensão do arquivo.
A dúvida que me surge nesse caso é a seguinte: Para o registro no banco de dados referente a esse arquivo, preciso também das outras informações. E, como as requisições geralmente usam o content-type JSON, fico me perguntando como seria feito então o envio do arquivo, já que o JSON possuim certa limitação quanto aos carateres que podem ser incluidos no mesmo.
Exemplo hipotético:
POST /api/midias/
Content-Type: application/json

{
    "nome" : "Flor",
    "descricao" : "A flor azul encontrada na
    "tipo_acesso" : 1,
    "extensao" : "jpg",
    "tamanho"  : 5225,
    "arquivo"  : ???????
}

Ou seja, de acordo com exemplo acima, para criação do recurso na minha API, além das informações da mídia, precisava também de envia o binário do arquivo, para fazer o upload.
Agora vamos aos problemas:
1) A primeira forma que tentei foi enviar o binário de um arquivo via JSON mesmo, convertendo o binário do arquivo para base64.
O problema do base64 é que ele aumenta (e muito) o tamanho do arquivo, tornando inviável no meu caso, já que vamos permitir upload de vídeos.
2) Usar o multipart/form-data, enviando o arquivo normalmente, como se faz em requisições de formulário, e anexando os outros dados citados anteriormente num campo "json", enviando esses dados como uma string JSON (serializado).
Exemplo:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="json"

{"nome" : "Flor", "descricao" : "..."}
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Ao meu ver, isso foge do padrão que já está sendo usado em toda as outras requisições, que é o content-type: application/json, além de ser uma gambiarra das bem porcas.
3) Separar a lógica de upload do arquivo do envio dos dados da midia.
Essa me pareceu a mais agradável e, pelo pouco que li e conversei sobre, me pareceu mais organizado. Porém eu nunca fiz nada parecido, não tendo experiência de implementação, e também não sei se isso se trata de um padrão em REST.
Um das dicas que vi, por exemplo, foi fazer o upload do arquivo, retornar o ID desse upload, para ser utilizado no envio dos "dados extras" para criação do recurso no servidor referente a esse arquivo.
A minha dúvida é:

*

*Das opções acima, qual delas seria mais próxima do REST?

*Se caso seja viável implementar a terceira opção, existe algum padrão, para definir o content-type do arquivo e que tipo de status de resposta eu poderia devolver?
Gostaria de uns exemplos a respeito da terceira opção, já que de todas essas, foi a única que não implementei, e não tenho a mínima ideia de como fazer algo parecido.

A:
Existe uma especificação REST para upload de arquivos?

Mais ou menos, WebDAV, que pode ser considerado proto-REST.

*

*Das opções acima, qual delas seria mais próxima do REST?

Prefiro a opção 3, pois facilita a vida do programador em certos aspectos. Apesar de ser a opção mais trabalhosa.
Nesse caso específico, que a API tem o papel de gerenciar o arquivo. Poderia ser feito desta maneira:

*

*Requisição POST /api/midias para adicionar o metadado, inicializando com conteúdo de arquivo vazio. Sendo request Content-Type: application/json, response Content-Type: application/json.

*Requisição POST /api/midias/1/conteudo para adicionar o conteúdo do arquivo. Sendo request Content-Type: ver resposta abaixo, response Content-Type: application/json. O número 1 significa o ID da mídia.

Assim, o download do arquivo em si, seria através de GET /api/midias/1/conteudo, e GET /api/midias/1 para consultar metadados.

*

*Se caso seja viável implementar a terceira opção, existe algum padrão,
  para definir o content-type do arquivo e que tipo de status de
  resposta eu poderia devolver?

Para /api/midias/1/conteudo usaria multipart/form-data ou/e application/octet-stream(que é mais simples). Mas se o arquivo tem o próprio tipo MIME, vale a tentativa (pode complicar a configuração do CORS depois). Retorne o status do mesmo jeito que as suas outras APIs. Se é 200 para sucesso, e 400 para erro, por que seria diferente neste caso?

A: Resposta resumida: não.
O HTTP suporta upload direto, e o REST especifica URLs - isso é o que vai ficar mais perto.
Quanto as suas opções,talvez o mais interessante aí seja algo que fica parecido com sua terceira opção, mas na ordem inversa:
você faz um POST JSON com os metadados do arquivo - nome, e tamanho, inclusive - e recebe, na resposta, uma URL que pode ser usada para upload do arquivo completo.
O Upload, por sua vez, você faz como um post de HTTP do arquivo - não precisa ser multi-part encoded - você pode simplesmente enviar os cabeçalhos de http normais -
Content-Type: image/jpeg
Content-Length: XXXX

seguido do seu arquivo - todo o "corpo" da mensagem HTTP vai ser o conteúdo do arquivo. Esse método ainda tem outra vantagen - faz tempo que não visito as especificações do HTTP, mas acredito que seja possível colocar no cabeçalho que você está "continuando um request anterior" e um "offset" - e portanto, mandar um arquivo grande, como um arquivo de vídeo, em vário requests separados - retransmitindo os que falharem.
Você não mencionou qual linguagem/framework está usando do lado do servidor, mas acredito que a grande maioria permita que você possa ter uma view mais "baixo nível" que interprete os cabeçalhos e o copo do HTTP elas mesmas. A URL em si já vai incluir um token que você relaciona no banco com a postagem JSON anterior - então sabe: a que o arquivo está relacionado, e se a pessoa usando esse endereço tem autorização pra isso (basta que seja um token randomizado na URL- ele vai servir ao mesmo tempo de identificador e autorização para o arquivo).
Eu tinha começado a escrever esta resposta - fui fazer uma busca rápida pra confirmar se posts HTTP com um arquivo puro são permitidos, e acabei chegando num artigo sobre uploads com REST - e o autor fez mais ou menos as mesmas considerações que fiz aqui - ou seja, parece ser um caminho sensato. (E que ainda permite upgrades futuros tipo - a feature de quebrar o arquivo em partes e fazer uploads de segmentos não precisa ser implementada num primeiro momento).
O artigo: https://philsturgeon.uk/api/2016/01/04/http-rest-api-file-uploads/


text:
Q: Get Buyer Email from Omnipay Paypal Express I integrated the Omnipay PayPal express.
After the completePurchase() I need the PayPal buyer email adress.
I can access the Transaction ID with $data['PAYMENTINFO_0_TRANSACTIONID'] and also the Payer ID through $_GET['PayerID'].
Any ideas how to get the buyers email?

A: After completePurchase(), you need to fetch the checkout datas:
$response = $gateway->fetchCheckout($parameters)->send();
$data = $response->getData();

// you can check the full received data
print "<pre>";
var_dump($data);

And in this array, you've got a $data["EMAIL"] variable, wich stores the payer's e-mail address.
Regards!
P.s.: For more information and a TL;DR disquisition, check this.


text:
Q: Wrong message showing in Laravel validation for multidimensional array I have this validation rules and i appended some custom messages for those validations.
 $this->validate($request, [
            'name'=>'required',
            'departments.*.name'=>'required',
            'departments.*.sections.*.name'=>'required',
        ],[
            'name.required'=>'The division name field is required.',
            'departments.*.name.required'=>'The department name field is required.',
            'departments.*.sections.*.name.required'=>'The section name field is required.',
        ]);

Screenshot of my view:

Here you can see, the empty section input field showing error message

"The department name field is required."

But it should be show

"The section name field is required."

What am i missing?
Note:  i am printing the first index of all fields error messages

A: Its replacing the error messages from departments.*.sections.*.name.required
You should add child dimension errors before parent fields
try to use this:
 $this->validate($request, [
            'name'=>'required',
            'departments.*.name'=>'required',
            'departments.*.sections.*.name'=>'required',
        ],[
            'name.required'=>'The division name field is required.',
            'departments.*.sections.*.name.required'=>'The section name field is required.',
            'departments.*.name.required'=>'The department name field is required.',
        ]);


text:
Q: How to self host a UDP Policy server for Silverlight? I am trying to see how viable UDP is for development of a web based game.
Andrea Boschin has a good example of a UDP solution. This solution works fine when run from the VS2010 debugged. This solution comprises of three projects

*

*A console application which hosts the MulticastPolicyServer

*A Silverlight client which talks to a UdpAnySourceMulticastClient

*A web project to host the Silverlight client

My question: What do I need to do to host this on the internet? Do I need to deploy the policy server to IIS? Construct a windows service ? or is this a intranet only solution?

A: IIS is not meant for this purpose. You have to write a windows service to host your UDP program. And of course there restriction exposing UDP over the Internet. Just keep in mind that UDP is not reliable protocol and it can miss a packet. So your logic should be capable of handling this.

A: use an RPC protocol over TCP to setup a subscription/authentication service (it may be useful to read up on XMPP) - do a one time authentication (your best bet is probably X509 [SSL, HTTPS] via WCF) which would work like a passive FTP...connect to me (server) then I'll give you a new port to connect to where I'll (as in me, the server) will be broadcasting media - then use UDP as your transport mechanism for your video/audio assuming that's what you're trying to do


text:
Q: A canonical form for this equivalence relation on matrices This question is inspired by https://cs.stackexchange.com/q/19250/755.
Define the equivalence relation $\sim$ as follows: If $M,N$ are two $8\times 8$ (or $n\times n$ if you prefer generality) $(0,1)$ matrices (all elements are $0$ or $1$), say that
$$M \sim N \text{ iff there is a permutation matrix P such that }M=PNP,$$
ie if you can transform $M$ into $N$ by a sequence of moves, where each move picks some pair $(i,j)$ and swaps rows $i$ and $j$ and then swaps columns $i$ and $j$.  For example,
\begin{equation}
\left( \begin{array}{ccc}
0 & 0 & 0 \\
0 & 1 & 1 \\
1 & 0 & 0 \end{array} \right) \sim
\left( \begin{array}{ccc}
1 & 0 & 1 \\
0 & 0 & 0 \\
0 & 1 & 0 \end{array} \right).
\end{equation}
This equivalence relation induces a set of equivalence classes.
Is there a way to define a canonical representative for each equivalence class, so that given any matrix $M$, we can efficiently compute the canonical representative $M^*$ corresponding to the equivalence class containing $M$?  I'm hoping for a simple and efficient algorithm to compute the canonical representative.
For instance, one way to define a canonical representative for matrix $M$ would be as follows: among all matrices $N$ that are equivalent to $M$, choose the one that is lexicographically first.  However, I don't know of any fast way to compute the canonical representative corresponding to a given matrix $M$.  (One could enumerate all matrices that are equivalent to $M$ by trying all $8!$ possible permutations, and then check which one is lexicographically first, but this is inefficient: it requires $8! \approx 2^{15.3}$ steps of computation, which is too much.) Is there a better approach? In particular, can we construct the canonical form of a given matrix without constructing every other matrix in its conjugacy class?
A good answer to this question might help solve https://cs.stackexchange.com/q/19250/755.

A: This is at least as hard as graph isomorphism,(which is your problem for $M$ adjacency matrix of a graph) which is not known to be in $P,$ so I would not hold my breath for anything too speedy.


text:
Q: why does this equation capture the assumption that the probabilities of $x$ and $y$ are independent? From Jaynes' probability theory: the logic of science, I found this:

$p$ here is the joint probability distribution of $x,$ and $y$. I'm assuming the $\times$ denotes the cartesian product, but I don't really understand what this equation means, nor why it captures the assumption that $x$ and $y$ are independent.
Why does this equation capture the assumption that $x$ and $y$ are independent?

A: $\times$ means the regular multiplication between two real numbers, not the cartesian product.
The definition of independent is
$$P(X=x, Y=y) = P(X=x)P(Y=y)$$
You might want to understand the equation as
$$\int \int \rho(x,y) dxdy = \int f_X(x) dx \int f_Y(y) dy$$
Credit: Hagen for pointing out we should not use the same $f$ for both variables.

A: I think it means that the probability density function $\rho(x, y)$ is given by $$\rho(x, y) = f(x) \cdot g(y).$$
This implies independence, because if $A \subseteq X$ and $B \subseteq Y$, then $$\begin{align*} \Pr(x \in A \wedge y \in B) & = \int \limits_{A \times B} \rho(x, y) \, \mbox{d} x \mbox{d} y = \int \limits_{A \times B} f(x) \cdot g(y) \, \mbox{d} x \mbox{d} y \\ & = \int \limits_{A} f(x) \mbox{d} x \cdot \int \limits_{B} g(y) \mbox{d} y \\ & = \Pr(x \in A) \cdot \Pr(y \in B) \end{align*}$$


text:
Q: Remove space on bar ZingChart I'm making a chart here and I have a little problem with removing the distance between the boxes

 var myConfig = {
            type: 'bar',
            legend: {
                layout: "x4",
                overflow : "page",
                shadow : false,
                align : "left",
                alpha :0.05,
                "adjust-layout": true,
                marker : {
                    type : "circle",
                    size : "7px",
                    "border-color" :"none"
                }
            },
            scaleX: {
                // convert text on scale indices
                labels: ['Automotive', 'Retail', 'Wholesale']
            },
            plot: {
                barWidth:"50%",
                animation: {
                    effect: 'ANIMATION_EXPAND_BOTTOM',
                    method: 'ANIMATION_STRONG_EASE_OUT',
                    sequence: 'ANIMATION_BY_NODE',
                    speed: 275,
                }
            },
            series: [
                {
                    // plot 1 values, linear data
                    values: [23, 20, 27],
                    text: 'Sum of target Premi',
                    backgroundColor: '#fa6383',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [35, 42, 33],
                    text: 'Sum of premi Leads',
                    backgroundColor: '#fb9f40',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [15, 22, 13],
                    text: 'Sum of premi Activity',
                    backgroundColor: '#fdcd55',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [15, 22, 13],
                    text: 'Sum of premi Booking',
                    backgroundColor: '#4bc0c1',
                    borderRadius: 5,
                }
            ]
        };

for my settings like this. there are suggestions so there can be no space ?
i have try documentation but does not work.
https://www.zingchart.com/docs/chart-types/bar

A: I'm not sure that I correctly understood your problem but probably you can try to use "barsOverlap" in "plot" configuration to achieve the desired result.

 var myConfig = {
            type: 'bar',
            legend: {
                layout: "x4",
                overflow : "page",
                shadow : false,
                align : "left",
                alpha :0.05,
                "adjust-layout": true,
                marker : {
                    type : "circle",
                    size : "7px",
                    "border-color" :"none"
                }
            },
            scaleX: {
                // convert text on scale indices
                labels: ['Automotive', 'Retail', 'Wholesale']
            },
            plot: {
                barWidth:"50%",
                barsOverlap: '50%',
                animation: {
                    effect: 'ANIMATION_EXPAND_BOTTOM',
                    method: 'ANIMATION_STRONG_EASE_OUT',
                    sequence: 'ANIMATION_BY_NODE',
                    speed: 275,
                }
            },
            series: [
                {
                    // plot 1 values, linear data
                    values: [23, 20, 27],
                    text: 'Sum of target Premi',
                    backgroundColor: '#fa6383',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [35, 42, 33],
                    text: 'Sum of premi Leads',
                    backgroundColor: '#fb9f40',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [15, 22, 13],
                    text: 'Sum of premi Activity',
                    backgroundColor: '#fdcd55',
                    borderRadius: 5,
                },
                {
                    // plot 2 values, linear data
                    values: [15, 22, 13],
                    text: 'Sum of premi Booking',
                    backgroundColor: '#4bc0c1',
                    borderRadius: 5,
                }
            ]
        };


text:
Q: Postgre SQL incorrect syntaxt near If I'm trying to create function but it's having error at If statement don't know what's the problem with it.
CREATE FUNCTION uspgetcountrylistwithpagenumber(IN "PageNumber" integer, IN "PageSize"         integer, IN "WhereClause" text, IN "OrderBy" text) RETURNS SETOF getcountrylistitem AS
$BODY$declare
RowData "getcountrylistitem"%rowtype;

    IF $1 <> -1 and $2 <> -1  then
        for RowData in
        loop
            execute 'Select "CountryId","CountryName"' ||
                    'from "MasterCountry"' ||
                    $3 ||
                    $4 ||
                    'limit' || $2 ||
                    'offset' || ($1-1)*$2
            RETURN NEXT RowData;
        END LOOP;
        RETURN;
    else
        for RowData in
        loop
            execute 'Select "CountryId","CountryName"' ||
                    'from "MasterCountry"' ||
                    'order by "CountryName" asc'
            RETURN NEXT RowData;
            END LOOP;
            RETURN;
    end IF;
end;
$BODY$
LANGUAGE plpgsql IMMUTABLE;
ALTER FUNCTION public.uspgetcountrylistwithpagenumber(IN integer, IN integer, IN text, IN text)
OWNER TO postgres;

What i want to achieve is custom paging ..
I want to have a function that can take PageNumber,PageSize,WhereClause,and OrderByClause
PageNumber=1
PageSize=10
WhereClause=Where 1=1 and CountryName='INDIA'
OrderByClause=order by CountryName desc

above are the parameter values that can be helpful for solving my problem
Let me know if more information is required. Thank you in advance..:P

A: You need a BEGIN before the first IF.


text:
Q: Website doesn't reflect Stripe customer/subscription changes I have a website built with the Laravel framework that uses Stripe to process subscription payments. When a user subscribes to a plan through my website, this row appears in the "subscriptions" database table:

When a subscription is canceled through my website, the ends_at column is populated with a date the current subscription period ends and will not be renewed:

This is the desired behavior, however, when a payment method is invalid, Stripe automatically cancels the subscription outside of the website. Since the subscription was canceled automatically on Stripe's end, my website doesn't reflect the changes and the ends_at database column will indefinitely have a value of NULL, allowing the user to continue using premium features of the website for free.
This is how I currently check if a user has an active subscription plan on my website:
public function index()
{
    $user = auth()->user();

    if (!$user->subscribed('plan') && $user->posts->count() > 0) {
        foreach ($user->posts as $post) {
            $post->update(['status' => 'unpublished']);
        }
    }

    return view('dashboard');
}

This is how a user cancels their subscription on my website:
public function cancel()
{
    $user = auth()->user();

    $user->subscription('plan')->cancel();

    return redirect()->back()->with("success", "Subscription canceled.");
}

How do I fix this issue so my website will automatically check Stripe for a customer's subscription status?


text:
Q: MongoDb search on date field I have a Mongo collection with 'DateAdded' in ISODate format
{
"_id" : 4098199,
"DateAdded" : ISODate("2018-08-31T05:06:13.150Z")
}

so it is 1hour off then local datetime
LocalDatetime is 2018-08-31 06:06:13 +01:00
UTC is 2018-08-31T05:06:13.150Z

Using following query when i try to get records added after 2018-08-31 06:00:00 i m not getting this records as it is in UTC
 db.getCollection('User').find({"DateAdded":{$gte: new ISODate('2018-08-31T6:00:00Z')}})

How to convert UTC date while doing search on date field in MongoDB?

A: First of all ISODate('2018-08-31T6:00:00Z') has a typo - it should be 06:00:00Z. Without leading 0 ISODate helper returns '2018-08-31T00:00:00Z' 0am UTC and the query actually returns the document.
Secondly, there is nothing about local time. ISODate is in UTC, so
ISODate("2018-08-31T05:06:13.150Z") is 5am UTC and ISODate("2018-08-31T06:06:13.150Z") is 6am UTC. 5 < 6, so the $gte condition doesn't meet and the document is not returned.
Lastly, if you want to use local time - use Date instead:
db.getCollection('User').find({"DateAdded":{$gte: new Date('2018-08-31T6:00:00')}})

Will return all documents created after 5am UTC, 6am local time. Note, there is no Z at the end, which specifies UTC timezone.
As a recommendation - don't mess up with local time. Convert it to UTC as soon as possible and always work with UTC.


text:
Q: How increase the vertical space between two labels from the table of contents? I need to increase the vertical space between two labels, specifically the vertical space in between any label (section or subsection) and the next Part.
The code that I using for the table of contents is the following:
\documentclass[11pt,fleqn,x11names,table]{book}

\usepackage{xcolor, tcolorbox, multicol}
\usepackage{tikz,tkz-tab}
\usepackage{kpfonts}
\usepackage{titletoc}

\titlecontents{part}
[8em]{\centering\Large\sc\bfseries\contentslabel{3em}}{}{}
{}{}

\titlecontents{chapter}[0pc]
{\addvspace{30pt}
    \begin{tikzpicture}[remember picture, overlay]
    \draw[fill=orange,draw=orange] (-4,-.1) rectangle (0.0,0.5);
    \pgftext[left,x=-1.5 cm,y=0.2cm]{\color{white}\Huge\sc\bfseries \ \thecontentslabel};%
    \end{tikzpicture}\color{orange}\large\sc\bfseries}
{}{}
{\;\titlerule\;\large\sc\bfseries Página \thecontentspage
    \begin{tikzpicture}[remember picture, overlay]
    \draw[fill=orange,draw=orange] (2pt,0) rectangle (6,0.1pt);
    \end{tikzpicture}}

\titlecontents{section}[2.4pc]
{\addvspace{1pt}}
{\contentslabel[\color{blue}\thecontentslabel]{2.4pc}}
{}
{\hfill\small \color{blue}\thecontentspage}
[]

\titlecontents*{subsection}[4pc]
{\addvspace{-1pt}\small}
{}
{}
{\hfill\small \color{blue}\thecontentspage}
[\\][]
\makeatletter

\renewcommand{\tableofcontents}{

    \chapter*{
        \vspace*{-20\p@}%
        \begin{tikzpicture}[remember picture, overlay]%
        \pgftext[right,x=15cm,y=0.2cm]{\color{black}\Huge\sc\bfseries \contentsname};%
        \draw[fill=orange,draw=orange] (13,-.75) rectangle (20,1);%
        \clip (13,-.75) rectangle (20,1);
        \pgftext[right,x=15cm,y=0.2cm]{\color{black}\Huge\sc\bfseries \contentsname};%
        \end{tikzpicture}}
    \@starttoc{toc}}
\makeatother

\begin{document}
\tableofcontents
\thispagestyle{empty}
    \part{Part I}
      \chapter{Chapter 1}
       \section{section 1}
         \subsection{subsection 1}
          \subsection{subsection 2}

\part{Part 2}
        \chapter{Chapter 2}
         \section{section 1}
           \subsection{subsection 1}
            \subsection{subsection 2}

\part{Part 3}
         \chapter{Chapter 3}
         \section{section 1}
         \subsection{subsection 1}
         \subsection{subsection 2}

\end{document}

Finally, this generates the following table:

But, what I really need to generate is the following:

Is there any way to make it work?
Thanks!!!

A: It was only necessary to add the following line of code:
\titlecontents{part} [8em]{\addvspace{some length}\centering\Large\sc\bfseries\contentslabel{3em}}{}{}{}


text:
Q: Como validar pelo menos um campo obrigatório? Tenho dois campos CPF e CNPJ, o usuário deve digitar apenas um, mas nunca deixar os dois campos vazios. Desta forma ele deixa obrigatório os dois campos:
 [
   'Cpf' => array('required'),
   'Cnpj' => array('required'),
 ]

Existe alguma maneira no Laravel de validar apenas um campo obrigatório quando um estiver preenchido?

A: Pode-se usar o  required_without ou required_without_all.
[
    'Cpf'  => 'required_without:Cnpj',
    'Cnpj' => 'required_without:Cpf',
]


text:
Q: Why does the HTML in my JSON response get encoded? I'm using this blog post as a guide, detailing how to use jQuery with jTemplates to stuff a JSON response into a template.
My problem is, one of the returned fields (named Description) contains HTML, but the HTML brackets are getting encoded to \u003C and \u003e.
Here's the HTML (in the Description field) the server returns:
Chad updated their ad, Validation Test Ad Again, @Yokota

Here's what the JSON response looks like:
[{"TypeOfActivity":"0","Description":"\u003ca href=\"/en/Yokota/User/Show/YokotaTour\"\u003eYokotaTour\u003c/a\u003e posted \u003ca href=\"/en/Yokota/Ad/Show/166\"\u003eOne of the best for sure\u003c/a\u003e for sale @\u003ca href=\"/en/Yokota\"\u003eYokota\u003c/a\u003e","DateHappened":"6/23/2010 12:26:55 AM"}]

Notice the "\u003c", or "\u003e". Those look like unicode escapes, but why is that happening? Here's the jQuery making the call for JSON response:
$.getJSON("<%= Url.Action("List", "Activity") %>",
    function(data){
        $("#aLog").setTemplate($("#templateHolder").html());
        $("#aLog").processTemplate(data);
    });

UPDATE
And this is what the source looks like when the page has loaded complete (View > Page Source in Firefox):
<a href="/en/Yokota/User/Show/Chad">Chad</a> updated their ad, <a href="/en/Yokota/Ad/Show/100">Validation Test Ad Again</a>, @<a href="/en/Yokota">Yokota</a>

Maybe it's because it's nearing 3am, but I'm stumped... any help is greatly appreciated - thank you!
Update 2
public JsonResult List()
{
    IList<ActivityContract> contracts = new List<ActivityContract>();
    var activityList = _db.Activity.ByBaseID(CurrentBase.BaseID).OrderByDescending(a => a.DateHappened);
    foreach (var a in activityList) {
        contracts.Add(new ActivityContract { TypeOfActivity = a.TypeOfActivity.ToString(), Description = a.Description, DateHappened = a.DateHappened.ToString() });
    }
    return Json(contracts, JsonRequestBehavior.AllowGet);
}

A: Turns out, the problem was with a setting in jTemplates. The setTemplate line needed to be this:
$("#aLog").setTemplate($("#templateHolder").html(), [], {filter_data: false});

Particularly, filter_data had to be set to false. By default jTemplates html encodes. ;(

A: make checks like this in the example with the "contentType" in utf8
your example
       $.ajax({
                type:"GET",
                url: "<%= Url.Action("List", "Activity") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#aLog").setTemplate($("#templateHolder").html());
                    $("#aLog").processTemplate(data);
                }
            });
        });

A: The JSONSerializer automatically escapes the "<" and ">" characters with unicode escape sequences.
jQuery should be able to parse these normally.  You are using the $.getJSON method, which I thought would automatically evaluate the response as json and unescape it, so I'm a little stumped as to why the final output still contains the escape codes.
If you do:
$("#aLog").processTemplate(eval("(" + data+ ")"));

does that solve the issue?


text:
Q: MATLAB: How to make a property whose name is same as a keyword? In this article (https://blogs.mathworks.com/loren/2012/07/16/who-what-why-but-not-this/) near the bottom Loren says that class properties can be the same as keywords. However, how is this possible? If you write a classdef script any attempt to use a keyword (including class keywords like "events") in the properties block gets a red syntax error. Was she mistaken? I'm asking because I really want a property name to be a keyword for a particular application.

A: Its possible by the use of dynamic properties, for example:
classdef test < dynamicprops
  methods
    function obj = test()
    end
  end
end

var = test();
var.addprop ( 'events' );
var.events = 123;

It can make code harder to maintain and its a bit overkill if you only want to name a single property the same as a keyword, in that instance why dont you do something like capitilizing the var name, or prepending it with something - so it still reads like what you want but it doesn't cause the name clash:
classdef test
  properties
    Events
    myIf
    % etc...
  end
  methods
    function obj = test()
    end
  end

end


text:
Q: How to show custom product pricing display and filter only I have required to display only product price in frontend all place like pdp, plp,cart, mini cart, checkout.
For example
If price=100 and special price =90 and product unit(custom attribute value) =6
Then
Result expected
Price=600 special price=540
Just display price multiply by unit value
Thanks in advance


text:
Q: Error cannot open tty-output Linux I have installed one paravirtualized image, Debian 8, in XenServer, and I'm adding a script to create a template that come. Added in the startup script with the command systemctl enable script. Scritp I use in the dialog that is already installed.
When I come to convert the template and create a new VM, the syslog log me the following error appears as if the script had starting at the wrong time of boot:
initial-conf[407]: Error opening terminal: unknown.
initial-conf[407]: cannot open tty-output
initial-conf[407]: Error opening terminal: unknown.


text:
Q: Apache PHP mod_rewrite not working I'm trying to test out the mod_rewrite meaning:
I have two files: level1.php and warpzone.php.
In my .htaccess I have the following code:
RewriteEngine On
RewriteRule ^warp-zone.php$ level-1.php

Yet when I go to warpzone.php, nothing happens :/ (the url doesn't change)
Any suggestions? I really don't know what I'm doing wrong.

A: First of all you have dashes in php file names at your .htaccess file, while your files does not have them.
Rewrite conditions - this changes the content to new one, but URL stays as it was:
RewriteEngine On
RewriteRule    ^warpzone\.php$  level1.php  [L]

Redirect conditions - this changes both content and URL to new one:
RewriteEngine On
RewriteRule    ^warpzone\.php$  /level1.php  [R]

Also you can use Redirect condition instead of mod_rewrite:
Redirect 301 /warpzone.php /level1.php

In case if it does not work for you, you can use headers() method at the top of your warpzone.php file:
<?php
header("Location: " . $_SERVER['SERVER_NAME'] . "/level1.php");
?>

A: *

*check whether warpzone.php or warp-zone.php is the correct filename, you are mixing them in your example.

*check the apache error.log file if mod_rewrite is available, if not then enable it (this can be done either with "LoadModule ..." or it is wrapped by your Linux distribution)

*check the apache error.log if you are allowed to use mod_rewrite, if not consider setting "AllowOverride All" in global config files httpd.conf/apache2.conf

*change your rewrite rule to "RewriteRule ^warp-zone.php$ level-1.php [L]" to issue an http redirect; without L flag, is is handled internally in the web sever; see https://httpd.apache.org/docs/2.4/rewrite/flags.html for all flags

regards


text:
Q: How to manage application data for functional tests? We are currently improving the test coverage of a set of database-backed applications (or 'services') we are running by introducing functional tests. For me, functional tests treat the system under test (SUT) as a black box and test it through its public interface (be it a Web interface, REST, or our potential adventure into the messaging realm using AMQP).
For that, the test cases either A) bootstrap an instance of the application or B) use an instance that is already running.
The A version allows for test cases to easily test the current version of the system through the test phase of a build tool or inside a CI job. That is what e.g. the Grails functional test phase is for. Or Maven could be set up to do this.
The B version requires the system to already run but the system could be inside (or at least closer to) a production environment. Grails can do this through the -baseUrl option when executing functional tests.
What now puzzles me is how to achieve a required state of the service prior to the execution of every test case?
If I e.g. want to test a REST interface that does basic CRUD, how do I create an entity in the database so that I can test the HTTP GET for it?
I see different possibilities:

*

*Using the same API (e.g. HTTP POST) to create the entity. Downside: Changing the creation method breaks two test cases. Furthermore, there might not be a creation method for all APIs.

*Adding an additional CRUD API for testing and only activating that in non-production environments. That API is then used for testing. Downside: adds additional code to the production system, API logic might not be trivial, e.g. creation of complex entity graphs (through aggregation/composition), and we need to make sure the API is not activated for production.

*Basically the same approach is followed by the Grails Remote Control plugin. It allows you to "grab into your application" and invoke arbitrary code through serialisation. Downside: Feels "brittle". There might be similar mechanisms for different languages/frameworks (this question is not Grails specific).

*Directly accessing the relational database and creating/deleting content, e.g. using DbUnit or just manually creating entities through JDBC. Downside: you duplicate creation/deletion logic and/or ORM inside the test case. Refactoring the DB breaks the test case though the SUT still works.

Besides these possibilities, Grails when using the (-inline) option for functional tests allows accessing Spring services (since the application instance is run inside the same JVM as the test case). Same applies for Spring Boot "integration tests". But I cannot run the tests against an already running application version (as described as option B above).
So how do you do that? Did I miss any option for that?
Also, how do you guarantee that each test case cleans up after itself properly so that the next test case sees the SUT in the same state?

A: *

*as with unit testing you want to have a "clean" database before you run a functional test. You will need some setup/teardown functionality to bring the database into a defined state.

*easiest/fastest solution to clean the database is to delete all content with an sql script. (For debugging it is also useful to run this in the test setup to keep the state of the database after a test failure.) This can be maintained manually (it just contains delete <table> statements). If your database changes often you could try to generate the clean script (disable foreign keys (to avoid ordering problem), delete tables).

*to generate test data you can use an sql script too but that will be hard to maintain, or create it by code. The code can be placed in ordinary Services. If you don't need real production data the build-test-data plugin is a great help at simplifying test data creation. If you are on the code side it also makes sense to re-use the production code to create test data to avoid duplication.

*to call the test data setup simply use remote-control. I don't think it is more brittle than all the http & ajax stuff ;-). Since we now have all the creation code in a service the only thing you need to call with remote control is the Service that does create the data. It does not have to get more complicated than remote { ctx.testDataService.setupDataForXyz() }. If it is that simple you can even drop remote-control and use a controller/action to run it.

*do not test too much detail with functional tests to make it not more complicated as it already is. :)


text:
Q: Return a value given an index as input for the Fibonacci sequence So given this.
//Fibonacci Series using Recursion
class fibonacci
{
    static int fib(int n)
    {
    if (n <= 1)
    return n;
    return fib(n-1) + fib(n-2);
    }

    public static void main (String args[])
    {
    int n = 10;
    System.out.println(fib(n));
    }
}

How could I transform it so it takes an index as a parameter and returns the given Fibonacci number at that index? So say I put in index = 5 and it should return 8.

A: static int fib(int index)
{
       int counter = 0;
       int current = 0;
       int previous = 0;
       int temp = 0;
       while(counter < index)
       {
              temp = previous;
              previous = current;
              current += temp;
              counter++;
       }
       return current;
}

If it does not have to be recursive, then I think this might work. Haven't tested it but tried to answer your question

A: int main(){
int index, temp1 = 0, temp2 = 1, value_at_index = 0;
    printf("Enter index: ");
    scanf("%d",&index);
    if(index==1){
       printf("Fib value at index 1 = 1");
    }
    else{
        for (int i = 2; i <= index; ++i){
              value_at_index = temp1 + temp2;
              temp1 = temp2;
              temp2 = value_at_index;
        }
       printf("Fib value at index %d = ", index);
       printf("%d\n", value_at_index);
       return 0;
    }
}


text:
Q: Angular - Uncaught ReferenceError: global is not defined with firebase Imagem do erro

Uncaught ReferenceError: global is not defined at
  Object../node_modules/firebase/auth.js (auth.js:255) at
  webpack_require (bootstrap:81) at Object../node_modules/angularfire2/auth/auth.js (vendor.js:123513) at
  webpack_require (bootstrap:81) at Object../node_modules/angularfire2/auth.js (vendor.js:123479) at
  webpack_require (bootstrap:81) at Object../src/app/services/login-service.ts (http-util-service.ts:7) at
  webpack_require (bootstrap:81) at Object../src/app/pages/login/login.component.ts (main.js:1021) at
  webpack_require (bootstrap:81)

package.json
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "1.0.0-beta.2",
    "@angular/animations": "6.0.2",
    "@angular/cdk": "6.1.0",
    "@angular/common": "6.0.2",
    "@angular/compiler": "6.0.2",
    "@angular/core": "6.0.2",
    "@angular/forms": "6.0.2",
    "@angular/http": "6.0.2",
    "@angular/material": "6.1.0",
    "@angular/platform-browser": "6.0.2",
    "@angular/platform-browser-dynamic": "6.0.2",
    "@angular/platform-server": "6.0.2",
    "@angular/router": "6.0.2",
    "ajv": "6.3.0",
    "angular-calendar": "0.23.1",
    "angularfire2": "^4.0.0-rc.2",
    "animate.css": "3.5.2",
    "arrive": "2.3.1",
    "bootstrap": "4.1.0",
    "bootstrap-material-design": "4.1.1",
    "bootstrap-notify": "3.1.3",
    "bootstrap-rtl": "3.3.4",
    "bootstrap-select": "1.12.2",
    "bootstrap-tagsinput": "0.7.1",
    "chartist": "0.9.4",
    "chartist-plugin-zoom": "0.4.0",
    "core-js": "2.4.1",
    "datatables": "1.10.13",
    "datatables.net-bs": "1.10.16",
    "datatables.net-responsive": "2.1.1",
    "firebase": "^3.9.*",
    "fullcalendar": "3.4.0",
    "googleapis": "19.0.0",
    "hammerjs": "2.0.8",
    "intl": "^1.2.5",
    "jasny-bootstrap": "3.1.3",
    "jquery": "3.2.1",
    "jquery-validation": "1.17.0",
    "jqvmap": "1.5.1",
    "moment": "^2.18.1",
    "moment-timezone": "0.4.0",
    "ng2-nouislider": "1.7.11",
    "ng2-select": "2.0.0",
    "ngx-chips": "1.9.2",
    "nouislider": "9.2.0",
    "perfect-scrollbar": "1.1.0",
    "popper.js": "1.14.1",
    "rxjs": "6.1.0",
    "rxjs-compat": "6.1.0",
    "sweetalert2": "7.22.0",
    "twitter-bootstrap-wizard": "1.2.0",
    "uglify-js": "^3.3.26",
    "validate": "3.0.1",
    "web-animations-js": "2.3.1",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "0.6.3",
    "@angular/cli": "6.0.3",
    "@angular/compiler-cli": "6.0.2",
    "@types/bootstrap": "3.3.32",
    "@types/chartist": "0.9.34",
    "@types/jasmine": "2.5.38",
    "@types/jquery": "1.10.31",
    "@types/node": "6.0.73",
    "codelyzer": "4.3.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "2.0.2",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "0.2.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "protractor": "^5.3.2",
    "ts-node": "2.0.0",
    "tslint": "5.9.1",
    "typescript": "~2.7.0"
  }
}

A: You can refer the issue,
As temporary workaround for any that reach this page you can add
(window as any).global = window;


text:
Q: Generate X random integers between Y and Z? Is there a function in Python (I'm working with SageMath) to get 10 random integers between 0 and 30, for instance, without repeating them?

A: import random
random.sample(range(31), 10)

A: >>> n=[]
>>> while len(n)<=10:
    x=randint(0,30)
    if x not in n:
        n.append(x)

do not forget to clear list every time you run this code


text:
Q: Are there statements more easily shown to be provable than proved? For specificity, fix ZFC as our axiom system, and assume it's consistent.
If we can prove some proposition $P$, then we can also prove $\square P$, "P is provable (in ZFC)", with some constant-factor additional work to turn each step of the proof into a demonstration that that step can be carried out in (some encoding of) the axioms.
However, this naive approach to conversion inevitably lengthens the proof in question. Are there easy-to-construct examples where the proof of $\square P$ is much shorter than the proof of $P$? Intuitively, this seems like it ought to be the case, as one frequently encounters situations where one can easily see that whatever the answer to a problem, it straightforwardly exists by computation, and this realization takes far less work than the computation itself.
If so, can the difference in length be made huge, in the sense that the shortest proof of $\square P$ is of length $n$, while the shortest proof of $P$ is on the order of $BB(n)$? (This is as good as could be hoped for, since a proof of $\square P$ must be at least as long as the length $k$ of the statement $P$, and we can make a Turing Machine of size $O(k)$ searching for proofs of $P$.)

A: Let's write "$\Diamond_n P$" for "there is no proof of $\neg P$ of length $<n$." Just as $\Diamond\top$ is shorthand for "ZFC is consistent," the sentence $\Diamond_n\top$ is shorthand for "There is no contradiction in ZFC of length $<n$."
Each sentence of the form $\Box\Diamond_n\top$ is then almost trivially ZFC-provable. We argue (within ZFC) by cases:

*

*If $\Diamond_n\top$ is false, then ZFC proves everything (being inconsistent) and so in particular proves $\Diamond_n\top$.

*If $\Diamond_n\top$ is true, then ZFC can prove $\Diamond_n\top$ by simply checking all possible ZFC-proofs of length $<n$.
(This second bulletpoint relies on the fact that ZFC proves its own $\Sigma^0_1$-completeness - see e.g. here.)
Now we go a bit further. For each $e$ which ZFC proves is an index for a total computable function, each appropriately-formulated sentence $$\theta^e_n\equiv\Diamond_{\varphi_e(n)}\top$$ have "provability proofs" not too dependent on $e$ (it only takes constant overhead to describe $\varphi_e$). Specifically:

There is a (ZFC-provably-)total computable function $h$ such that for all $e$, if $e$ is an index for a ZFC-provably-total computable function then for all but finitely many $n$ there is a ZFC-proof of $\Box\theta^e_n$ of length $<h(n)$.

But we can now whip up an $e$ which is sufficiently fast-growing that for no $n$ is there a ZFC-proof of $\theta_n^e$ of length $<h(n)$.

*

*(HINT: $\varphi_e(x)$ should be the least $k$ such that there is no proof of ...).

If you want a bigger gulf, just replace the $h$ above with a needlessly-bigger function $\hat{h}$; the corresponding $\hat{e}$ for $\hat{h}$ will then have the property that no $\theta^\hat{e}_n$ has a ZFC-proof of length $<\hat{h}(n)$, but still for all but finitely many $n$ the sentence $$\Box\theta^\hat{e}_n$$ has a ZFC-proof of length $<h(n)$. The bigger the gulf between $h$ and $\hat{h}$, the bigger the "eventual slowdown" we see.

Meanwhile, there is a sort of computable bound on the slowdown we can see here. Assuming ZFC is $\Sigma_1$-sound, there is a total computable $j$ such that for every sentence $\varphi$, if $\Box\varphi$ has a proof of length $<n$ then $\varphi$ has a proof of length $<j(n)$. This $j$ is simple to describe: first enumerate each of the finitely many sentences with provability proofs of length $<n$, and now search for actual proofs of each such sentence and record the longest such. The second half of this algorithm works if ZFC is $\Sigma_1$-sound.
So there is in fact a computable bound to the slowdown we can have, as long as ZFC is $\Sigma_1$-sound. Meanwhile, if ZFC is not $\Sigma_1$-sound then there is a sentence $\psi$ such that ZFC proves $\Box \psi$ but ZFC does not prove $\psi$, so the question doesn't even make sense without that hypothesis.


text:
Q: The mapping cylinder of CW complex If $X,Y$ are CW  complexes and $f$ a cellular map from $X$ to $Y$, is it true that $M_f$ is a CW complex?

A: Yes this is true. The proof can be found on Akhil Mathew's blog under 'The Loose End' at the bottom of the linked page.
To repeat what Akhil has on that page (If he reads this I hope he doesn't mind!)

First, it is a general and well-known fact that the product of two CW complexes is a CW complex. So $X \times I$ is a CW complex. And, from the construction, $X = X \times \left\{0\right\}$ is a subcomplex.
Let $X$ be a CW complex and $A \subset X$ a subcomplex. Suppose $f: A \rightarrow Y$ is a cellular map (for $Y$ another CW complex). Then the space $X \cup_f Y$ is a CW complex.
Proof: We take as the cells the cells of $X$ not in $A$ and the cells of $Y$. This is kosher, because $X-A$ is the union of various cells, $A$ being a subcomplex. The reason we have to require $f: A \rightarrow Y$ to be cellular, though, is that the boundary of each $n$-cell has to be contained in a union of $n-1$-cells.


text:
Q: Classic ASP (VBScript) convert HTML codes to plain text I'm trying to convert HTML Codes like the &#XXXX; (where XXXX is a number) to plain text using classic ASP (VBScript).
I'm adding the text to an email which is in plain text format and if I add them as HTML Codes, it just displays the code and doesn't convert them.
One fix would be to change the email to be HTML which does fix that problem but then causes other problems for my email which I won't go into.
Is there a built in function or a custom function I can use to convert these HTML Codes to plain text?

A: A more exausted decoder epanding C. Ross response
Function HTMLDecode(sText)
    Dim regEx
    Dim matches
    Dim match
    sText = Replace(sText, """, Chr(34))
    sText = Replace(sText, "<"  , Chr(60))
    sText = Replace(sText, ">"  , Chr(62))
    sText = Replace(sText, "&" , Chr(38))
    sText = Replace(sText, " ", Chr(32))

    sText = Replace(sText, "¡", Chr(161))
    sText = Replace(sText, "£", Chr(163))
    sText = Replace(sText, "¥", Chr(165))
    sText = Replace(sText, "©", Chr(168))
    sText = Replace(sText, "«", Chr(171))
    sText = Replace(sText, "»", Chr(187))
    sText = Replace(sText, "¿", Chr(191))
    sText = Replace(sText, "À", Chr(192))
    sText = Replace(sText, "Á", Chr(193))
    sText = Replace(sText, "Â", Chr(194))
    sText = Replace(sText, "Ã", Chr(195))
    sText = Replace(sText, "Ä", Chr(196))
    sText = Replace(sText, "Å", Chr(197))
    sText = Replace(sText, "Æ", Chr(198))
    sText = Replace(sText, "Ç", Chr(199))
    sText = Replace(sText, "È", Chr(200))
    sText = Replace(sText, "É", Chr(201))
    sText = Replace(sText, "Ê", Chr(202))
    sText = Replace(sText, "Ë", Chr(203))
    sText = Replace(sText, "Ì", Chr(204))
    sText = Replace(sText, "Í", Chr(205))
    sText = Replace(sText, "Î", Chr(206))
    sText = Replace(sText, "Ï", Chr(207))
    sText = Replace(sText, "Ñ", Chr(209))
    sText = Replace(sText, "Ò", Chr(210))
    sText = Replace(sText, "Ó", Chr(211))
    sText = Replace(sText, "Ô", Chr(212))
    sText = Replace(sText, "Õ", Chr(213))
    sText = Replace(sText, "Ö", Chr(214))
    sText = Replace(sText, "×", Chr(215))
    sText = Replace(sText, "Ø", Chr(216))
    sText = Replace(sText, "Ù", Chr(217))
    sText = Replace(sText, "Ú", Chr(218))
    sText = Replace(sText, "Û", Chr(219))
    sText = Replace(sText, "Ü", Chr(220))
    sText = Replace(sText, "Ý", Chr(221))
    sText = Replace(sText, "Þ", Chr(222))
    sText = Replace(sText, "ß", Chr(223))
    sText = Replace(sText, "à", Chr(224))
    sText = Replace(sText, "á", Chr(225))
    sText = Replace(sText, "â", Chr(226))
    sText = Replace(sText, "ã", Chr(227))
    sText = Replace(sText, "ä", Chr(228))
    sText = Replace(sText, "å", Chr(229))
    sText = Replace(sText, "æ", Chr(230))
    sText = Replace(sText, "ç", Chr(231))
    sText = Replace(sText, "è", Chr(232))
    sText = Replace(sText, "é", Chr(233))
    sText = Replace(sText, "ê", Chr(234))
    sText = Replace(sText, "ë", Chr(235))
    sText = Replace(sText, "ì", Chr(236))
    sText = Replace(sText, "í", Chr(237))
    sText = Replace(sText, "î", Chr(238))
    sText = Replace(sText, "ï", Chr(239))
    sText = Replace(sText, "ð", Chr(240))
    sText = Replace(sText, "ñ", Chr(241))
    sText = Replace(sText, "ò", Chr(242))
    sText = Replace(sText, "ó", Chr(243))
    sText = Replace(sText, "ô", Chr(244))
    sText = Replace(sText, "õ", Chr(245))
    sText = Replace(sText, "ö", Chr(246))
    sText = Replace(sText, "÷", Chr(247))
    sText = Replace(sText, "ø", Chr(248))
    sText = Replace(sText, "ù", Chr(249))
    sText = Replace(sText, "ú", Chr(250))
    sText = Replace(sText, "û", Chr(251))
    sText = Replace(sText, "ü", Chr(252))
    sText = Replace(sText, "ý", Chr(253))
    sText = Replace(sText, "þ", Chr(254))
    sText = Replace(sText, "ÿ", Chr(255))

    Set regEx= New RegExp

    With regEx
     .Pattern = "&#(\d+);" 'Match html unicode escapes
     .Global = True
    End With

    Set matches = regEx.Execute(sText)

    'Iterate over matches
    For Each match in matches
        'For each unicode match, replace the whole match, with the ChrW of the digits.

        sText = Replace(sText, match.Value, ChrW(match.SubMatches(0)))
    Next

    HTMLDecode = sText
End Function

A: What you need is HTML Decode, though unfortunately ASP doesn't include one.
This function, found on ASP Nut, and modified heavily by me, should do what you need.  I tested it as vbscript running on my local computer and it seemed to work well, even with Unicode symbols in the 1000+ range.
Function HTMLDecode(sText)
    Dim regEx
    Dim matches
    Dim match
    sText = Replace(sText, """, Chr(34))
    sText = Replace(sText, "<"  , Chr(60))
    sText = Replace(sText, ">"  , Chr(62))
    sText = Replace(sText, "&" , Chr(38))
    sText = Replace(sText, " ", Chr(32))

    Set regEx= New RegExp

    With regEx
     .Pattern = "&#(\d+);" 'Match html unicode escapes
     .Global = True
    End With

    Set matches = regEx.Execute(sText)

    'Iterate over matches
    For Each match in matches
        'For each unicode match, replace the whole match, with the ChrW of the digits.

        sText = Replace(sText, match.Value, ChrW(match.SubMatches(0)))
    Next

    HTMLDecode = sText
End Function

Note: You'll need script version 5.0 installed on your server to use the RegExp object.

A: I made this based on C.Ross's answer above and some code from a fb_app.inc someone else made. It should do the trick.
    <%
    Option Explicit

    Dim objHelper
    Set objHelper = New HtmlEntityToUnicode

    Response.Write(objHelper.HtmlDecode("

hi  💚 green heart! purple heart 💜 ! "))

    Set objHelper = Nothing

    Class HtmlEntityToUnicode
    dim BITS_TO_A_BYTE
    dim BYTES_TO_A_WORD
    dim BITS_TO_A_WORD
    Dim m_lOnBits(30)
    Dim m_l2Power(30)

    Sub Class_Initialize()

        BITS_TO_A_BYTE = 8
        BYTES_TO_A_WORD = 4
        BITS_TO_A_WORD = 32

        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)

    End Sub

    Public Function HTMLDecode(sText)
        Dim regEx
        Dim matches
        Dim match
        sText = Replace(sText, """, Chr(34))
        sText = Replace(sText, "<"  , Chr(60))
        sText = Replace(sText, ">"  , Chr(62))
        sText = Replace(sText, "&" , Chr(38))
        sText = Replace(sText, " ", Chr(32))

        Set regEx= New RegExp

        With regEx
         .Pattern = "&#(\d+);" 'Match html unicode escapes
         .Global = True
        End With

        Set matches = regEx.Execute(sText)

        'Iterate over matches
        For Each match in matches
        'For each unicode match, replace the whole match, with the ChrW of the digits.
            sText = Replace(sText, match.Value, "\U"&WordToHex(match.SubMatches(0)))
        Next

        HTMLDecode = sText
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
             WordToHex = Right("0" & Hex(lByte), 2) & WordToHex
        Next
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    End Class

    %>


text: Q: How can I connect to RabbitMQ using Sockjs and Stomp in React? I'm trying to connect to RabbitMQ using Stomp and Sockjs. I have Stomp.js and Sock.js files. I have already tried 'react-load-script' module to load the scripts but they seem to run into scope issues. Is there any other way to do this? I tried using 'react-stomp' as well and it runs into CORS issue and when that resolves, application refuses to connect to Stomp url. Is there any other way to do this?


text:
Q: Why does using "=" result in no updated reference, while using "+=" updates the reference? Why does using = result in no updated reference while using += updates the reference?
x = [5,6,7]
y = []
y.append(x)
x += [8, 9]

t = [3,6]
v = []
v.append(t)
t = t + [4,5]

A: With += you are updating the variable.
With t = t + [4,5] you are assigning a new variable.
So when you append something with x, and then update x, it will also update the appended variable. But when you assign another value to x, it won't


text:
Q: Automatically copy text from a web page There is a vpn that keeps changing their password. I have an autologin, but obviously the vpn connection drops every time that they change the password, and I have to manually copy and paste the new password into the credentials file.
http://www.vpnbook.com/freevpn
This is annoying. I realise that the vpn probably wants people not to be able to do this, but it's not against the ToS and not illegal, so work with me here!
I need a way to automatically generate a file which has nothing in it except
username
password
on separate lines, just like the one above. Downloading the entire page as a text file automatically (I can do that) will therefore not work. OpenVPN will not understand the credentials file unless it is purely and simply
username
password
and nothing more.
So, any ideas?

A: This kind of thing is done ideally via an API that vpnbook provides. Then a script can much more easily access the information and store it in a text file.
Barring that, and looks like vpnbook doesn't have an API, you'll have to use a technique called Web Scraping.
To automate this via "Web Scraping", you'll need to write a script that does the following:

*

*First, login to vpnbook.com with your credentials

*Then navigate to the page that has the credentials

*Then traverse the structure of the page (called the DOM) to find the info you want

*Finally, save out this info to a text file.

I typically do web scraping with Ruby and the mechanize library. The first example in the Mechanize examples page shows how to visit the google homepage, perform a search for "Hello World", and then grab the links in the results one at time printing it out.  This is similar to what you are trying to do except instead of printing it out you would want to write it to a text file. (Google for writing a text file with Ruby)":
require 'rubygems'
require 'mechanize'

a = Mechanize.new { |agent|
  agent.user_agent_alias = 'Mac Safari'
}

a.get('http://google.com/') do |page|
  search_result = page.form_with(:id => 'gbqf') do |search|
    search.q = 'Hello world'
  end.submit

  search_result.links.each do |link|
    puts link.text
  end
end

To run this on your computer you would need to:
a. Install ruby
b. Save this in a file called scrape.rb
c. call it by using the command line "ruby scrape.rb"
OSX comes with an older ruby that would work for this. Check out the ruby site for instructions on how to install it or get it working for your OS.
Before using a gem like mechanize you need to install it:
gem install mechanize

(this depends on Rubygems being installed, which I think typically comes with Ruby).
If you're new to programming this might sound like a big project, but you'll have an amazing tool in your toolbox for the future, where you'll feel like you can pretty much "do anything" you need to, and not rely on other developers to have happened to have built the software you need.
Note: for sites that rely on javascript, mechanize wont work - you can use Capybara+PhantomJS to run an actual browser that can run javascript from Ruby.
Note 2: Its possible that you don't actually have to go through the motions of (a) going to the login page (2) "filling in your info", (3) clicking on "Login", etc. Depending how their authentication works, you may be able to go directly to the page that displays info you need and just provide your credentials directly to that page using either basic auth or other means. You'll have to look at how their auth system works and do some trial and error for this. The most straightforward, most likely to work approach is to just to what a real user would do...login through the login page.
Update
After writing all this, I came across the vpnbook-utils library (during a search for "vpnbook api") which I think does what you need:

...With this little tool you can generate OpenVPN config files for the free VPN provider vpnbook.com...
  ...it also extracts the ever changing credentials from the vpnbook.com website...

looks like with one command line:
vpnbook config

you can automatically grab the credentials and write them into a config file.
Good luck! I still recommend you learn ruby :)

A: You don't even need to parse the content. Just string search for the second occurrence of Username:, cut everything before that, use sed to find the content between the next two occurrences of <strong> and </strong>. You can use curl or wget -qO- to get the website's content.


text:
Q: How to check in C# if user account is active How can I check from C# if a local user account (namely the local Administrator account) is active?
What I actually want is a C# replacement for the "Account Active" = "Yes" (or "No") output from the "net user Administrator" command.
I'm afraid this question looks like a duplicate to this one, but I don't know what to pass in for the parameter for the root DirectoryEntry object. Tried different things like "ldap://" + Environment.MachineName, "ldap://127.0.0.1", "WinNT://" + Environment.MachineName, but none of them worked. I get an exception thrown by the searcher.FindAll() call in all three cases.

A: class Program
{
    static void Main(string[] args)
    {

        // Create the context for the principal object.
        PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "Administrator");
        Console.WriteLine(String.Format("Administrator is enable: {0}", u.Enabled));

    }
}

A: You can query WMI's Win32_UserAccount
This is boilerplate what MS's wmi code creator spits out as a reference;
using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Disabled FROM Win32_UserAccount WHERE name = 'alexk'");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_UserAccount instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Disabled: {0}", queryObj["Disabled"]);
                    Console.ReadKey();
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

(I'd link the tool but as usual the msdn links are dead)

A: Try this.
 var server = "YOURMACHINENAME";
 var username = "Guest";
 var de = new DirectoryEntry {Path = "WinNT://" + server + ",computer"};
 var result = de.Children
     .Cast<DirectoryEntry>()
     .First<DirectoryEntry>(d => d.SchemaClassName == "User" && d.Properties["Name"].Value.ToString() == username);

 var flags = (int)result.Properties["UserFlags"].Value;
 var disabled = (flags & 2) == 2;

A: This isn't quite the same but they use DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));  Would that help?

A: Considering it's a local user, you need to call the win32 api funcion NetGetUserInfo to get what you need.
The example in pinvoke.net is almost what you need, however you need to change the level parameter to 2 to get the neccesary info