text:
Q: WebSocket on Heroku ERR_CONNECTION_REFUSED I am trying to run a node js app on Heroku using WebSockets. However, I am not able to resolve this error (As seen in conosle of Chrome browser)

WebSocket connection to 'wss://myappname.herokuapp.com:27225/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I am using 'wss' since Heroku runs on HTTPS.
My client side code is :
$.get("https://myappname.herokuapp.com/port",function(data){
    port = data;
    console.log(data);
    host = 'wss://myappname.herokuapp.com:' + port + '/';
    ws = new WebSocket(host);
  });

My server side code is :
var WebSocketServer = require("ws").Server
var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 5000;
var request = require('request');

var server = http.createServer(app);
var serverOnPort = server.listen(port);

console.log("Server listening on port ",port);

var wss = new WebSocketServer({server: serverOnPort});
console.log("websocket server created");

Any help would be appreciated.
Thank You.

A: So it seems like I was trying to over-do it with the port number. Just using the host as wss://myappname.herokuapp.com/ works well.

A: I also found this problem. It seems Heroku will automatically route port number. It does's allow to specify port number in url. In my chrome,  it show  ERR_CONNECTION_RESET. This also happen with XMLHttpRequest. Port number still need when you test with  localhost or another server which is not Heroku.


text:
Q: Integrate Skype with Jenkins I need to send notification to Skype ( group) from Jenkins about the Build and Deployment status.
Can any one give the step by step process for integrating Jenkins with Skype.
Skype : it is not the business for Skype

redpajama_set_name: RedPajamaStackExchange


text:
Q: TYPO3 v10: rowCount in backend layout seems not to work anymore I have an issue regarding the backend layouts in TYPO3 10 LTS. In v9 I was able to hide rows in the backend by setting the rowCount to a smaller number than there are rows. I used this to hide the irre-elements for the users. In v10 all rows are shown, no matter which number I set the rowCount. Is this a bug by the new version or am I missing something?
Here is my code:
   title = Default
   config {
       backend_layout {
           colCount = 1
           rowCount = 1
           rows {
               1 {
                   columns {
                       1 {
                           name = content
                           colPos = 0
                       }
                   }
               }
               2  {
                   columns {
                       1 {
                           name = elements from elements (should not be visible)
                           colPos = 123
                       }
                   }
               }
           }
       }
   }
}

Thanks in advance

A: If this ever worked, this was a bug, that has been fixed now. Actually the rowCount and colCount parameters were meant to define a specific number of rows for the backend layout wizard, so that you can set things like rowSpan and colSpan.
The number of visible rows should always have been determined by the actual rows defined in the configuration. If you want to remove columns this should be done with colPos_list: https://docs.typo3.org/m/typo3/reference-tsconfig/master/en-us/PageTsconfig/Mod.html


text:
Q: Nested Virtualization I want to deploy openstack with nested virtualization enabled. Here is the scenario, on physical machine (Ubuntu 16.04) I have 2 VMs running,
1. kvm01 and,
2. cmp001
Kvm01: has 7 VMs up and running with different openstack services, with 68 vcpus.
Cmp001: has nova-compute running with 8 vcpus.
I have deployed the openstack successfully on nested VM environment, but VM inside kvm01 slows down after approx. 12 hours and I need to destroy all the vms with virah destroy and destroy kvm01 itself and start again and then everything works fine again.
I don't know what is the problem there and why VMs inside KVM01 are getting slow after some time.
I am using Ubuntu 16.04 OS on physical machine, have 128 GB of RAM and 48 physical cores with 2 NUMA node, I have tried CPU pinning for kvm01 (pinned 42 physical CPUs to the kvm01 vm) but that didn't work for me.
Note: Current CPU model for kmv01 and cmp001 is host-passthrough, I have tried host-model which didn't work for me.
Hope this is clear. Please let me know in comment if XML file of kvm01 or cmp001 is required, or any other information required.
Thanks in advance.


text:
Q: xslt как добавить пробел в начале будущего xml У меня есть файл XML, с помощью файла XSLT я хочу выбрать только те отели, в имени которых есть Hilton, все выводится правильно, но <.Hotels> пишется не с новой строки, а после тега <?xml>
Hilton.xml (результат)
<?xml version="1.0" encoding="UTF-8"?><Hotels>
    <Hotel Price="370 USD per night">
        <Name>DoubleTree by Hilton New York Downtown</Name>
        <Address>
            <AddressLine>8 Stone Street, New York, New York, 10004, United States of America</AddressLine>
            <City>New York</City>
            <Country>United States of America</Country>
            <State>New York</State>
        </Address>
    </Hotel>
    <Hotel Price="255 USD per night">
        <Name>Millennium Hilton New York One UN Plaza</Name>
        <Address>
            <AddressLine>One United Nations Plaza, Midtown East, New York City, NY 10017, USA New York United States</AddressLine>
            <City>New York City</City>
            <Country>United States</Country>
            <State>NY</State>
        </Address>
    </Hotel>
    <Hotel Price="345 USD per night">
        <Name>Homewood Suites by Hilton New York/Midtown Manhattan Times Square-South, NY</Name>
        <Address>
            <AddressLine>312 West 37th Street, New York, NY, 10018, United States of America</AddressLine>
            <City>New York</City>
            <Country>United States of America</Country>
            <State>NY</State>
        </Address>
    </Hotel>
    <Hotel Price="264 USD per night">
        <Name>Martinique New York on Broadway, Curio Collection by Hilton</Name>
        <Address>
            <AddressLine>49 West 32nd Street, New York, NY 10001, United States</AddressLine>
            <City>New York</City>
            <Country>United States</Country>
            <State>NY</State>
        </Address>
    </Hotel>
</Hotels>

Hotels.xsl
<?xml version="1.0" encoding="UTF-8" ?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
        <Hotels>
            <xsl:apply-templates />
        </Hotels>
    </xsl:template>
    <xsl:template match="Hotels/Hotel">
        <xsl:if test="contains(Name, 'Hilton') and (contains(Address/State, 'New York') or contains(Address/State, 'NY'))">
            <Hotel>
                <xsl:attribute name="Price"><xsl:value-of select="@Price"/></xsl:attribute>
                <Name><xsl:value-of select="Name"/></Name>
                <Address>
                    <xsl:apply-templates select="Address"/>
                </Address>
            </Hotel>
        </xsl:if>
    </xsl:template>
    <xsl:template match="Hotels/Hotel/Address">
        <AddressLine><xsl:value-of select="AddressLine"/></AddressLine>
        <City><xsl:value-of select="City"/></City>
        <Country><xsl:value-of select="Country"/></Country>
        <State><xsl:value-of select="State"/></State>
    </xsl:template>

    <xsl:template match="text()" />
</xsl:stylesheet>

A: Это особенность Oracle Java. Вам нужно добавить одну дополнительную строку, как показано ниже.
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");

Java
...
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xslt);
// =============================================================================
// https://stackoverflow.com/questions/18249490/since-moving-to-java-1-7-xml-document-element-does-not-indent
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
// =============================================================================
...


text:
Q: Instant sound notification on new mail? I'm currently helping a food shop with replacing their overbloated Windows installation by Ubuntu. This went pretty well and the owner is quite happy, but there is still one issue: on Windows, he would use Live Messenger and get instant notifications on new emails. This feature is pretty important since the mails are received from the online shop and needs to be processed immediately. Since the personnel are not looking at the screen all of the time, an audio signal is mandatory.
What software and/ or configuration is recommended to get this kind of notification? The default IM software is Empathy, but it does not seems to have a mail notification feature at all. The mail-notification package can only periodically poll for new mail, but I think that the Hotmail servers restrict the number of logins so this is not a real option either.
Finally, I saw Pidgin as recommendation (I haven't tried the mail notification feature), but perhaps there are better alternatives? Pidgin is actually an IM client, which is not really needed in this case.

A: Maybe I am not understanding the question properly but Thunderbird is perfectly capable of sound notifications. Assuming it's notification of email only that you want

Then set Thunderbird to check for new mail every 1 min

A: I see Ryan mentioned Popper already in a comment and that should work for you.
As an alternative you can also try MailNag, which is a non-Ubuntu specific mail notifier. The author describes it this way: "Mailnag is a fork of the Popper mail notifier. What Popper is to Ubuntu's Unity, Mailnag is to GNOME-Shell."

A: Guifications for Pidgin, mentioned here
Placed here for your convenience.

Install Guifications via Synaptic Package Manager,

Once Installed go to "Tools/Plugins and choose "Guifications",activate
  it and click on "Configure Plugin" in order to set your preferences.
  You can set the position, stack, and other display options, the same
  as Mouse behavior.

Additionally you can set which notifications you want to be notified
  about and get themes to enhance your GUI notifications.
Note: You might need to disable current notification popups in order not to receive duplicated notifications.

As you can see, you can define The Position, Stack, if you wish to show it while away (really useful!), animation, how long must a message last on screen defined by "Display time" (in order not to lose any purchase order for your clients) and the mouse behavior, among other useful configurable things which includes but not limits to:
Notifications, will let you select which events you wish to be notified about.

Advanced options, including the maximum visible guifications and if you are using dual view monitors, choose where will the guifications be placed.

Good Luck!


text:
Q: Where can I find out more on Collatz-conjecture like sequences? I'm interested in Collatz-conjecture (the 3n+1 problem) like sequences.  I'm interested in any literature that contains information about problems that are divided into similar cases.
I'm particularly interested in studies of sequences that have 3 or more cases, but information on 2 case problems is interesting as well.
I'm just trying to get a feel of what is known.  Anything will be helpful.
So, where can we find lots of information on these types of problems/sequences?

A: Anyone wanting to study the $3n+1$ problem and related sequences should check Jeffrey Lagarias' annotated bibliographies on the arXiv, posted here and here. It contains some hundreds of papers, with for each paper a short summary of what it is about.

A: A natural generalization of the Collatz problem is recursively undecidable.
You may be interested in this paper.

A: This arXiv paper deals with the $7x\pm1$ problem, having three (technically four) branches:
$$ f(n) = \begin{cases}
  7n+1 & \text{if $n\equiv+1\pmod{4}$,} \\
  7n-1 & \text{if $n\equiv-1\pmod{4}$,} \\
  n/2  & \text{if $n\equiv\phantom+0\pmod{2}$.} \\
\end{cases} $$
The conjecture is that the orbit of arbitrary positive integer
always returns to 1, exactly as in the case of $3x+1$ problem.


text:
Q: How to make tabs scrollable in compose I want to add dynamic tab items. in a scrollable way, not fixed tabs
I followed this example here
But after I implement the same, still the tabs fixed, what I want is to show the whote text of the tab (Not fixed size tab), and the tabs must be scrollable like the following image

I tried to make the TabRaw scrollable as the following:
 TabRow(
    selectedTabIndex = pagerState.currentPage,
    backgroundColor = Color.Transparent,
    modifier = Modifier
        .fillMaxWidth()
        .padding(MaterialTheme.spacing._20sdp)
        .horizontalScroll(scrollableState)
        .height(32.dp),
    contentColor = colorResource(id = R.color.primary)
)

But it throws IllegalArgumentException, Because I'm including it in a ConstraintLayout

A: I only used ScrollableTabRow instead of TabRow


text:
Q: How do I notify a TreeModel that its underlying model has changed? I am developing a simulation of the world, where the World is represented by:
public class World {
    Turtle turtle;
    // .. basic constructors, getters, setters
}

and a Turtle is represented by:
public class Turtle {
    List<Turtle> turtles;
    // .. basic constructors, getters, setters
}

where a Turtle stands on the backs of its turtles and the World rests on one, main Turtle (who may have turtles underneath it). I want to represent this, in Swing, as a JTree.
So I code up a JTree and a TreeModel:
JTree tree = new JTree(new WorldModel(world.getTurtle());

public class WorldModel implements TreeModel {

    private Turtle = null;

    public WorldModel(Turtle turtle) {
        this.turtle = turtle;
    }

    @Override
    int getChildCount(Object object) {
        return ((Turtle) object).getNumTurtles();
    }

    @Override
    Object getChild(Object parent, int index) {
        return ((Turtle) object).getTurtle(index);
    }

    // etc., you get the overbearing point

}

This works splendidly up until the point at which I change the Turtle I initially passed in to the TreeModel's constructor:
world.getTurtle().removeAllTurtleChildren();

How do I update my JList to reflect this change? Do I have to create a new TreeModel and set it again?
(I would like to stay away from DefaultTreeModel, if possible.)

A: add api that supports modifying the structure to the model:
public class WorldModel implements TreeModel {

     ...

     public void removeAllChildren(Turtle parent) {
         if (parent.getChildCount() == 0) return;
         Turtle[] children = parent.getChildren();
         int[] locations = new int[children.length());
         for(int loc = 0; loc < locations.length; loc++) {
            locations[i] = i;
         }
         parent.removeAllChildren();
         List<Turtle> path = new ArrayList<>();
         while (parent != null) {
             path.add(0, parent);
             parent = parent.getParent();
         }

         TreeModelEvent event = new TreeModelEvent(this, path, locations, children);
         // for each listener
              listener.treeNodesRemoved(event);
     }
}

As you see, it's quite some work - you might reconsider not using DefaultTreeModel :-)


text:
Q: SQL Server : how to delete based on another table I have a USERS table with active and inactive users and I also have another table called Leaders where team leaders are stored (so a list of users).
I want to delete those users in table Leaders that are inactive in table users.
Edit based on comments:

*

*Users table: ID and Active

*Leaders table: ID

A: You could use an in condition:
DELETE
FROM   leaders
WHERE  id IN (SELECT id
              FROM   users
              WHERE  active = 0 -- Or however you mark inactive users
             )

A: You can make joins in delete, similar to select:
delete ld
from leaders ld
join users us on ld.idUser = us.idUser
where us.active = 0


text:
Q: Learning probability from Zero level How do i develop a very good conception in probability theory to do advanced theoretical research in communication theory?Which book do i follow to gain a solid conception about the subject.I have the original manuscript of A N Kolmogorov but do not have the mathematical background to understand it. Any suggestions will be much appreciated.

A: For a basic working knowledge of probability, there are many good books such as An Introduction to Probability. They will introduce you to the main terminology and to most basic applications of probability.
However, if you want to see the full story, that is, proofs of most theorems and a real understanding of why things work the way they do, you would have to study a field of mathematics called Measure Theory, which deals with the problem of assigning a 'size' to sets.
It is common to consider a basic knowledge of real analysis, such as the one given in the incredible Understanding Analysis to be a prerequisite for studying measure theory, but you might have a go at Measure, Integral and Probability and see how you do. Kolmogorov is usually very mathematically intense, so I'd recommend you to save him for when you're better acquainted with the basics.


text:
Q: ArcGIS Server REST API: at which URL can I acquire a token? I'm working with the ArcGIS Server REST API in a python script. In order to access my server, I need to generate a token and put it into the https://myserverurl.com/arcgis/rest/login page, however, I'm unable to find the URL where a token is generated. This page says "To acquire this token, go to https://myserverurl.com/arcgis and enter https://myserverurl.com/arcgis/rest' for the 'Webapp URL' parameter." This link redirects me to https://myserverurl.com/arcgis/sharing/rest/generatetoken, but it is an empty page.
Some URLs I've tried include: https://myserverurl.com/arcgis/rest/generatetoken and https://myserverurl.com/arcgis/rest/authentication, among others. ESRI's documentation asks for http://gisserver.domain.com:6080/arcgis/tokens, but this is not working either.
Am I missing something?

A: two things: make sure get requests are enabled server.arcgis.com/en/server/latest/administer/linux/… and then you will have to include the username and password in the url like this: http://domain.net:6080/arcgis/tokens/generateToken?username=theusername&password=thepassword&client=requestip

A: It sounds like you have your answer to enable GET requests, but I just wanted to mention to get the url you can always make a request to the info resource to obtain the tokenServicesUrl.  For example, if your domain is gis.your-domain.com, you can make a call like this:
http://<your-domain>/arcgis/<instance>/info?f=pjson
This will return JSON similar to this:
{
 "currentVersion": 10.31,
 "fullVersion": "10.3.1",
 "soapUrl": "http://gis.your-domain.com/arcgis/services",
 "secureSoapUrl": "https://gis.your-domain.com/arcgis/services",
 "authInfo": {
  "isTokenBasedSecurity": true,
  "tokenServicesUrl": "https://gis.your-domain.com/arcgis/tokens/",
  "shortLivedTokenValidity": 480
 }
}

Then to actually obtain the token, hit the tokenServicesUrl with your credentials.


text:
Q: Android: Multiple editText in recycle view. The values keeps cloning from one to another I am creating a program for my company, where I need a part where is consignation for money. The money types are in database what I get from an api. So I use recycleView with elements. My problem is that when I am changing the value of the first 7 element it'c copying itselfe to the next 7.
Does someone have a clue why?
My Activity:

package eu.obsys.staffkeeper.ui.dayclose;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.ParcelFormatException;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.util.ArrayList;

import eu.obsys.staffkeeper.FirstPageActivity;
import eu.obsys.staffkeeper.R;
import eu.obsys.staffkeeper.adapter.ConsignLocalRecycleAdapter;
import eu.obsys.staffkeeper.adapter.DeliveryOrderRecycleAdapter;
import eu.obsys.staffkeeper.data.ConsignLocalAsyncResponse;
import eu.obsys.staffkeeper.data.JsonObjectAsyncResponse;
import eu.obsys.staffkeeper.data.Repository;
import eu.obsys.staffkeeper.model.LocalConsignRow;
import eu.obsys.staffkeeper.ui.deliveryorder.DeliveryOrderFragment;

public class LocalConsignActivity extends AppCompatActivity {

    private RecyclerView localConsignRecycleView;
    private ConsignLocalRecycleAdapter consignLocalRecycleAdapter;
    private Button nextToEuroConsign;
    private JSONArray _jsonArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_consign);
        initVariable();
        initLocalConsign();
        initListener();
    }

    public void initVariable() {
        localConsignRecycleView = findViewById(R.id.localConsignRecycleView);
        nextToEuroConsign       = findViewById(R.id.nextToEuroConsign);
        _jsonArray              = new JSONArray();
    }

    public void initLocalConsign() {

        localConsignRecycleView.setHasFixedSize(true);
        localConsignRecycleView.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<LocalConsignRow> localConsigns = new Repository().getLocalConsignRows( this, new ConsignLocalAsyncResponse() {
            @Override
            public void processFinished(ArrayList<LocalConsignRow> localConsignRows) {
                try {
                    if(localConsignRows.size() > 0 ) {
                        consignLocalRecycleAdapter = new ConsignLocalRecycleAdapter(localConsignRows, getApplicationContext());
                        localConsignRecycleView.setAdapter(consignLocalRecycleAdapter);
                        localConsignRecycleView.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void initListener() {
        nextToEuroConsign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                printAllEditTextValues();
                /* int totalLocal   = 0;
                JSONObject jsonObject = new JSONObject();
                int arrayLength = consignLocalRecycleAdapter.getItemCount();
                for (int i = 0; i < arrayLength; i++) {
                    View view = localConsignRecycleView.getChildAt(i);
                    //View view = localConsignRecycleView.getLayoutManager().findViewByPosition(i);
                    try {

                        EditText valueEditText = view.findViewById(R.id.localConsignRowEditText);
                        String valueText = valueEditText.getText().toString();

                        Log.d("SUBTOTAL", valueText);
                        if (valueText.length() > 0 && !valueText.equals("0")) {
                            try {
                                int valueOfEditText = Integer.parseInt(valueText);
                                LocalConsignRow localConsignRow = consignLocalRecycleAdapter.getItem(i);
                                totalLocal += (valueOfEditText * localConsignRow.getValue_local());
                                try {
                                    jsonObject.put(localConsignRow.getId() + "", valueOfEditText);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                            //Repository
                        }
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                } */
                //Log.d("TOTAL", totalLocal + "");
            }
        });
    }

    public void printAllEditTextValues() {
        int childCount = localConsignRecycleView.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view       = localConsignRecycleView.getChildAt(i);
            EditText nameEditText = (EditText) view.findViewById(R.id.localConsignRowEditText);
            String name     = nameEditText.getText().toString();
            Log.d("EditText", name);
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(LocalConsignActivity.this, FirstPageActivity.class);
        startActivity(intent);
        finish();
    }

}

my Adapter:

package eu.obsys.staffkeeper.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

import eu.obsys.staffkeeper.R;
import eu.obsys.staffkeeper.model.LocalConsignRow;

public class ConsignLocalRecycleAdapter extends RecyclerView.Adapter<ConsignLocalRecycleAdapter.ViewHolder> {

    private ArrayList<LocalConsignRow> localConsigns;
    private Context context;

    public ConsignLocalRecycleAdapter(ArrayList<LocalConsignRow> localConsigns, Context context) {
        this.localConsigns  = localConsigns;
        this.context        = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.local_consign_row, parent, false);

        return new ViewHolder(view, new LocalConsignEditTextListener());
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        LocalConsignRow localConsignRow = localConsigns.get(position);
        holder.textInputLayout.setText(localConsignRow.getLabel());
        holder.textInputEditText.setHint("0");
    }

    @Override
    public int getItemCount() {
        return Objects.requireNonNull(localConsigns.size());
    }

    public LocalConsignRow getItem(int position) {
        return localConsigns.get(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public EditText textInputEditText;
        public TextView textInputLayout;
        public LocalConsignEditTextListener localConsignEditTextListener;

        public ViewHolder(@NonNull View itemView, LocalConsignEditTextListener _localConsignEditTextListener) {
            super(itemView);
            textInputEditText                 = itemView.findViewById(R.id.localConsignRowEditText);
            localConsignEditTextListener      = _localConsignEditTextListener;
            textInputEditText.addTextChangedListener(localConsignEditTextListener);
            textInputLayout                   = itemView.findViewById(R.id.localConsignRowLabel);
        }
    }

    private class LocalConsignEditTextListener implements TextWatcher {
        private int position;
        public void updatePosition(int position) {
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            // no op
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            int amount = 0;
            try {
                amount = Integer.parseInt(charSequence.toString());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            localConsigns.get(position).setAmount(amount);
        }

        @Override
        public void afterTextChanged(Editable editable) {
            // no op
        }

    }
}


text:
Q: Coordinar barra lateral y navegador co bootstrap Buenas!
Lo primero de todo soy un supernoob con páginas web y he tomado la mala decisión de usar bootstrap en mi primer proyecto de la universidad, así que agradecería todo consejo que podáis darme :3
Estoy haciendo una plantilla de la barra de navegación y la barra lateral y quiero que estén un poco coordinadas.
Primero he creado una fila donde esta colocada la barra de navegación y la he dividido en dos columnas, una de tamaño md-2 y otra de md-10, en la pequeña he puesto el header de la barra y en la grande los botones.
Para el resto de la página he hecho otra fila y la he dividido de la misma forma que la anterior. En la pequeña esta situada la barra lateral y en la grande el contenido principal de las páginas.
Haciendo esto he conseguido que parezca que las dos barras se unen en el header y le da un aspecto bastante estético a mi parecer.
El problema es que estoy corriegiendo la posición de algunos elementos de bootstrap cambiando los elementos margin y padding de algunos divs para conseguir que todo cuadre como quiero, pero claro según el navegador y tamaño de pantalla la posición que he puesto no es la misma y se descuadra.

Como puedo hacer para que algunos divs donde pongo botones, contenido o lo que sea se quede siempre en la misma posición? (pegado a un lateral o top). He probado varias formas que he encontrado por internet pero siempre se descuadra algo y es un poco frustrante porque pierdo más tiempo colocando cosas que pensando y haciendo la página.
Aquí dejo el código: CodePen
Utilizo bootstrap 3.3.7.

A: Puedes utilizar los siguientes códigos en css.
position: absolute;
z-index: 100;

Uno hace que sea absoluto como dice, e independiente de lo que haya, siempre se quedara allí. z-index define en que "capa" esta, o sea, si quieres que este por encima de todo coloca 9999, si algo estará por sobre este, ese elemento debe tener un z-index superior.
Espero que te ayuden estos códigos y éxito con tu proyecto :D

A: Amigo recuerda que siempre los row de boostrap siempre tienen 12 celdas es decir.
en un

maximo de 12 celdas si quieres tener mas de 12 crea otros row .
aparte de eso te recomiendo que leas la documentacion de boostrap.
http://getbootstrap.com/css/#grid
recuerda que tambien en un
  puedes colocar la diferente diferencias de un pantalla.
en tu codigo ya lo modifique :
https://codepen.io/anon/pen/mWoRPg
HTML

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link href="general.css" type="text/css" rel="stylesheet" />
    <link href="inicio.css" type="text/css" rel="stylesheet" />
    <title>Inicio</title>

                            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

                          </button>
                            Brand

Inicio

¿Quiénes somos?

Contacto

                                    Registrarse

Registro

                                            <form>

                                                    <input type="text" class="form-control" placeholder="Usuario">

                                                    <input type="email" class="form-control" placeholder="Email">

                                                    <input type="password" class="form-control" placeholder="Contraseña">

                                                    <input type="password" class="form-control" placeholder="Confirmar contraseña">

                                                            <input type="submit" class="form-control btn btn-info" value="Registrarse">

                                            </form>

                                    Iniciar sesión

Inicio de sesión

                                            <form>

                                                    Usuario
                                                    <input type="text" class="form-control">

                                                    Contraseña
                                                    <input type="password" class="form-control">

                                                            <input type="checkbox">
                                                            Recordarme

                                                            <input type="submit" class="form-control btn btn-success" value="Log In">

                                                                Olvidaste la contraseña?

                                                <input type="hidden" class="hide" name="token" id="token" value="a465a2791ae0bae853cf4bf485dbe1b6">
                                            </form>

User

                                 Perfil

                                 Estadísticas

                                 Trofeos

                                 Ayuda

CSS
body {
    font-family: sans-serif;
    background-color: rgb(239, 244, 246);
}

.navbar {
    margin-bottom: 0 !important;
}

.mar-left {
    margin-left: -13px !important;
}

ul.navbar-right {
    /*margin-right: -15.45vw !important;*/
    margin-right: -8.5vw !important;
}

.navbar-nav>li>a {

}

.row {

}

.margin-left-nav {
    margin-left: 0 !important;
}

ul.dropdown-width {
    width: 300px;
}

.navbar .nav>li.dropdown.open.active>a:hover,
.navbar .nav>li.dropdown.open>a,
li a:hover,
li.active>a {
    color: #fff !important;
    background-color: rgb(10, 66, 117) !important;
}

li a:hover {
    background-color: rgb(10, 66, 117) !important;
    color: #ffffff !important;
}

li.active>a {
    background-color: rgb(10, 66, 117) !important;
    color: #ffffff !important;
}

.navbar-brand:hover {
    color: #5b9bd1 !important;
}

ul.horizontal li {
    border-left: 1px solid black;
}

ul.horizontal li:last-child {
    border-right: 1px solid black;
}

/*.center {
    margin: 0 auto !important;
}*/

/*.vertical-center {
    display: flex;
    align-items: center;
}*/

.border {
    border: 1px solid black;
}

/*----- Sidebar -----*/

.profile-sidebar {
    background-color: rgb(35, 35, 35);
    height: 92.5vh;
    border-right: 1px solid black;
    margin-top: 0 !important;
}

.profile-userpic {
    padding-top: 40px;
}

.profile-userpic img {
    margin: 0 auto;
    width: 70%;
    height: 70%;
}

.profile-user {
    text-align: center;
    margin-top: 20px;
}

.profile-name {
    color: #93a3b5;
    font-size: 16px;
    font-weight: 600;
    padding-bottom: 10px;
}

.profile-menu {
    margin-top: 30px;
}

.profile-menu ul li a {
    color: #93a3b5;
    font-size: 14px;
    font-weight: 400;
    padding-left: 40px;
    border-bottom: 1px solid black;
}

ul.vertical li:first-child {
    border-top: 1px solid black;
}

.profile-menu ul li a i {
    margin-right: 9px;
    font-size: 14px;
}

/*----- End Sidebar -----*/

#full-page {
    background-color: rgb(239, 244, 246);
    width: 100vw;
}

#header-content {
    height: 43.5vh;
}

.lma-content {
    height: 50vh;
}

A: Sí, se lo que me habéis respondido y he probado varias veces, (Como estoy aún por la primera entraga aún no tengo que adapatar la página a dispositivos móviles y demás) a lo que me refiero es a que  bootstrap tiene margin y padding por defecto en algunos de sus elementos, y los estoy contrarrestado para colocarlos justo donde quiero.
La solución ideal para mí sería decirle a un elemento ponte a la derecha del todo sin importar el padding y margin por defecto, pero no consigo que se quede en su lugar porque tengo que corregir esos campos constantemente.


text:
Q: Plot bar chart with facet wrap I'm very new to R and struggling in plotting geom_bar with facet_wrap. I need to manually adding colors to the chart but I can't be able to. I can only add "fill = percentage" to be able to add colors but it's scaled from low to high which I don't want to. I want to manually set two colors
"#554F66", "#C2D1A4" on the chart. The chart only has 2 cols that represent 2 years.
I tried to use scale_fill_manual and scale_color_manual as well but it didn't work. :(
Below are my codes,can you please help? Thank you and much appreciate
ggplot(newdata2,aes(x=as.factor(CODE), y=percentage)) +
  geom_bar(stat = "identity", fill = "#554F66")+
  facet_wrap(~variable) +
  theme_bw() +
  xlab("")

A: it would be very helpful if you could post a reproducible example, with a data set that resembles yours, to help us understand what exactly the problem is.
See some code below that might help you:
ggplot(newdata2,aes(x=as.factor(CODE), y=percentage, fill = percentage)) +
  geom_bar(stat = "identity")+
  facet_wrap(~variable) +
  scale_fill_manual(values = c("#554F66", "#C2D1A4")) +
  theme_bw() +
  xlab("")

Make sure that you use scale_fill_manual() when using the fill aesthetic.


text:
Q: How to use projection of vectors in order to compute length of a cross product? This is the question. The vectors u and v are such that $\|u\|= 4$, $\|v\|= 5$ and $(u|v) =−12$.  Compute the length of the vector $(2u+ 3v)\times(5v−4u)$.
I broke it down into $2u \times (5v-4u) + 3v(5v-4u)$ and then further broke it down into $(2u \times 5v) -(2u \times 4u) + (3v \times 5v) -(3v \times 4u)$.
But what I don't get is, how do I use $(u|v) =−12$ here in order to compute the answer? Is it connected to the formula $u \times v = \|v\| T(u')$?

A: The cross-product of a vector by itself is always $0$, and $v\times u=-u\times v$. So,$$(2u+3v)\times(5v-4u)=(10+12)(u\times v)=22u\times v.$$On the other hand$$-12=(u|v)=\|u\|\|v\|\cos\theta=20\cos\theta,$$where $\theta$ is the angle between $u$ and $v$. So, $\cos\theta=-\frac35$, and therefore $\sin\theta=\frac45$. Now, use the fact that $\|u\times v\|=|\sin\theta|\|u\|\|v\|$.


text:
Q: How to set require field to company in billing address in magento2? How to set require the field to a company in billing address in magento2?

A: You should as well add it in your attribute on the server side.
If you're using Magento Entreprise Edition, you can simply edit the company attribute through back end, and set it to "required".
If you're working with a Community Edition, you'll have to manually change this value with SQL. It's in eav_attribute table, the attribute_code is company and you just need to set is_required to 1.


text:
Q: Add a derived attribute to existing table in SQL Developer Is there any way to add a derived date/time column (to an existing table) to hold calculated running time from a race.
The values are in hours, round to 2 decimals. There are 2 columns for start time and end time in the table. Below is the last I've tried got a missing expression error.
ALTER TABLE race
ADD race_time AS (SELECT ROUND(DATEDIFF (endtime, starttime),2)FROM race);

A: There is no datediff() function in Oracle and you also don't need a SELECT statement to create a computed column:
ALTER TABLE race
  ADD race_time AS (endtime - starttime);

If endtime and starttime are defined as timestamp the race_time column will be of the type interval.
If those two columns are date columns, the result will be a number representing the number of days between the two days

A: It's been a while since I used this functionality but I think it would look more like:
ALTER TABLE race
ADD race_time AS (ROUND(DATEDIFF (endtime, starttime),2))

Note that I'm not aware of a DATEDIFF function in Oracle - if you haven't written this yourself and are looking to get the number of hours between two dates it would be more like:
ALTER TABLE race
ADD race_time AS (ROUND((endtime - starttime)*24.0,2))

If your columns are timestamps, it would probably be easier to convert them to dates when doing the math
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=3ac1f46f8d7296754d14a3de6191dbe8


text:
Q: Unable to configure the PyDev interpreter in Eclipse We have the newest version of Eclipse IDE, and specifically the Java EE Developer package. We also have 64-bit Python 3.7 installed at-
C:\Program Files\Python37

I can install PyDev and continue like so
Windows--> Prefrences--> PyDev-->Interpeters-->Python Interpeters-->New

But when I name the Interpeter and select our Python.exe file at C:\Program Files\Python37 I get the following error-
See error log for details.
Can't find relative path:pysrc/interpreterInfo.py
within:org.python.pydev.core_6.5.0.201809011628 [1001]

Snip of the error code and resulting window for new
If I attempt to add an interpreter using either the Advanced Auto-Config or Quick Auto-Config buttons I get the following error for both options-
Errors getting info on discovered interpreter(s).
See error log for details.

java.lang.RuntimeException: Can't find relative
path:pysrc/interpreterInfo.py within:org.python.pydev.core_6.5.0.201809011628 [1001]

Snip of error code and resulting window for auto-configure
I have tried reinstalling Python in several locations but haven't had any luck. Thanks for reading any ideas are appreciated.


text:
Q: How to use '! operator' with 'in operator' in TypeScript? I do programming with strikNullCheks option.
When I use ! operator with in operator, I got a following error.
(This is exactly what happens when I use a payload of Redux's Action.)
Is there any way to solve the problem?
Thanks you for reading :)
interface Interface {
    AB?: {
        a: number;
    } | {
        b: number[];
    }
}

function test(ab: Interface['AB']) {
    const ab2 = ('a' in ab!) ? [ab!.a] : ab!.b;
    => error: Property 'a' does not exist on type '{ a: number; } | { b: number[]; }'.
              Property 'a' does not exist on type '{ b: number[]; }'.
    => error: Property 'b' does not exist on type '{ a: number; } | { b: number[]; }'.
              Property 'b' does not exist on type '{ a: number; }'
}

example

A: The in type-guard (and generally type-guards) will not work on expressions. So the expression ab! will not result in the narrowing of ab. For the type-guard to work, the guarded expression must be a simple parameter/variable/field. The simplest solution is to guard against null explicitly. This is probably a good idea since the field is optional anyway:
function test(ab: Interface['AB']) {
    const ab2 = !ab ? null : ('a' in ab) ? [ab.a] : ab.b;
}


text:
Q: Checking empty request uri with .htaccess I need to redirect the request from
www.mysite.com/?querystring=data

to
www.mysite.com/dir/phpfile.php/?querystring=data

It means that it should be translated only the url with empty request_uri ( for example
www.mysite.com/css/style.css

should not be translated), and with not empty query string ( for example the main page
www.mysite.com/

should not be translated).
I wrote this code
RewriteCond %{HTTP_HOST} ^www.mysite.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/?(.*)$ www.mysite.com/$1 [QSA]

But it doesn't work. Any suggestion?

A: The rule that you have has the domain name in it without a protocol, it's going to look like a URI or file pathname to mod_rewrite. Additionally, you're rewriting it nothing, since $1 backreferences the grouping (.*) in your match, which must be nothing since your condition says the URI can only be /. You probably want something like:
RewriteCond %{HTTP_HOST} ^www.mysite.com$ [NC]
RewriteRule ^/?$ /dir/phpfile.php/ [L,R]

The query string will automatically get appended to the end. Remove the R if you don't want to externally redirect the browser (thus changing the URL in the location bar), or replace it with R=301 if you want a permanent redirect.

A: Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^(.+)$ [NC]
RewriteRule ^$ /dir/phpfile.php/ [L,QSA,R=302]

Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.


text:
Q: Do I need to declare a class for using HQL? I am migrating some of the application logic from JDBC to Hibernate. Using JDBC there are many simple insert, update and select statements and I am trying to use HQL for this purpose.
As an example, using JDBC, following is the query
select * from tab where property =<given value>

I used the HQL like this
session.createQuery(query).setString("property", "some prop value");

When I am running the code, I keep getting the error saying

"org.hibernate.hql.internal.ast.QuerySyntaxException: tab is
  not mapped"

Do I need to declare a POJO class for each of the query that I am planning to execute using hql?

A: Using of Hibernate:
To use a table in HQL query in clause FROM you must map your table as a bean
Example 1:
String hql = "SELECT e FROM " + MyEntity.class.getName() + " e ";

MyEntity class must map a real table to access on your DB (you can use JPA notation or XML notation, I prefer the second)
You can not have a real table but redirect your query result in a bean not mapped using a costructor of your bean.
Example 2:
String hql = "SELECT new " + MyNotMappedEntity.class.getName() +
"(e.field1, e.field2)" +
" FROM " + MyEntity.class.getName() + " e ";

In Example 2 your class MyNotMappedEntity must have a properly constructor with two parameter of the same type of two fields passed.
Tell me it's ok or you want more info.


text:
Q: FoxPro Unique Random Number Could some one help, Looking for Unique random generated number.
Currently have 4 pubs, If data have more than 4 pubs, need randomly select the pubs and place the value to Pub1 Pub2 Pub3 and Pub4 fields. Can't find solution by using FoxPro.
SELE A
USE TEST
REPL PUB1 WITH "" ALL
REPL PUB2 WITH "" ALL
REPL PUB3 WITH "" ALL
REPL PUB4 WITH "" ALL
REPL RANDOM1 WITH "" ALL
REPL RANDOM2 WITH "" ALL
REPL RANDOM3 WITH "" ALL
REPL RANDOM4 WITH "" ALL
REPL RANDOMLOG WITH "" ALL

SELE B
USE WHATPUB

SELE A
GO TOP
DO WHILE !EOF()
    cBRANCH=BRANCH
    SELE B
    SET FILTER TO BRANCH=cBRANCH
    COUN TO nBRANCHQTY

    IF nBRANCHQTY<=4
        FOR loop=1 TO nBRANCHQTY
            SELE B
            LOCA FOR loop=FT_URN
            IF FOUND()
                cPUBID=PUBID
                SELE A
                cFLD1="PUB"+LTRIM(STR(loop))
                REPL (cFLD1) WITH cPUBID
            ENDIF
        NEXT loop

    ELSE

        SELE A

        FOR loop=1 TO 4
            SELE A

            DO WHILE nRANDOMPUB>nBRANCHQTY
                nRANDOMPUB=INT(RAND()*10)+1
            ENDDO

            SELE B
            LOCATE FOR nRANDOMPUB=FT_URN

            IF FOUND()
                cPUBID=PUBID
                SELE A
                cFLD1="PUB"+LTRIM(STR(loop))
                cFLD2="RANDOM"+LTRIM(STR(loop))

                REPL (cFLD1) WITH cPUBID
                REPL (cFLD2) WITH LTRIM(STR(nRANDOMPUB))
            ENDIF

            nRANDOMPUB=9999999

        NEXT loop

    ENDIF

    SELE A
    SKIP

ENDDO

GO TOP
BROW FIELDS BRANCH,RANDOMLOG,RANDOM1,PUB1,RANDOM2,PUB2,RANDOM3,PUB3,RANDOM4,PUB4

If something is not understandable, just let me know.

A: You are using int(rand() * 10) + 1. Be it VFP or any other language your intent is to select a random number between 1 and 10. There is nothing in your code that says it should be unique Pub1, Pub2, ... It is normal that repeated calls to rand may return same value when you are choosing 4 values out of max 10. Instead you could do something like this (untested off the top of my head):
Create Cursor crsRand (pubVal i)
Local ix
For ix = 1 To 10
    Insert Into crsRand Values (m.ix)
Endfor

Rand(-1)

Select 0
Use TEST
Replace PUB1 With "", ;
    PUB2 With "", ;
    PUB3 With "", ;
    PUB4 With "", ;
    RANDOM1 With "", ;
    RANDOM2 With "", ;
    RANDOM3 With "", ;
    RANDOM4 With "", ;
    RANDOMLOG With "" All

Use WHATPUB In 0

Local cBRANCH, nBranch, nBRANCHQTY, Loop, cPubId, cFld1
Local Array laRandPub[1]

Select TEST
Scan
    cBRANCH=BRANCH
    Select WHATPUB
    Count For BRANCH=m.cBRANCH To nBRANCHQTY

    If m.nBRANCHQTY<=4
        Select WHATPUB
        For Loop=1 To m.nBRANCHQTY
            Locate For FT_URN=m.loop
            If Found()
                cPubId=PUBID
                Select TEST
                cFld1="PUB"+Ltrim(Str(m.loop))
                Replace (m.cFld1) With m.cPubId
            Endif
        Endfor
    Else
        Select pubVal From ;
            (Select Top 4 pubVal, Rand() From crsRand Where pubVal <= m.nBRANCHQTY Order By 2) tmp ;
            into Array laRandPub

        For Loop=1 To 4
            Select WHATPUB
            Locate For FT_URN=laRandPub[m.loop]
            If Found()
                select Test
                cPubId=PUBID
                cFld1="PUB"+Ltrim(Str(m.loop))
                cFLD2="RANDOM"+Ltrim(Str(m.loop))

                Repl (m.cFld1) With m.cPubId, (m.cFLD2) With Ltrim(Str(laRandPub[m.loop]))
            Endif
        Endfor
    Endif
Endscan

Locate
Brow Fields BRANCH,RANDOMLOG,RANDOM1, ;
            PUB1,RANDOM2,PUB2,RANDOM3,PUB3,RANDOM4,PUB4

Note that Select A, Select B style coding is dangerous. Use aliases instead.


text:
Q: Why does the second order delta method approximation to the variance of Bernoulli r.v. result in a negative chi-square? Let $Y_1, \ldots, Y_n$ be iid Bernoulli random variables with parameter $p$. Suppose we estimate the variance $Var(Y_1) = p(1-p)$ using $\hat{p}(1-\hat{p})$ where $\hat{p}=\bar{Y}_n$. I am trying to obtain the asymptotic distribution for this estimator specifically in the case where $p=\frac{1}{2}$. In the $p = \frac{1}{2}$ case, the first derivative is zero, hence we use the second order delta method:
Suppose that $\sqrt{n}(T_n-\theta_0) \to_D Z$ and that we are interested in $g(T_n)$ where $g'(\theta_0) = 0$ but $g''$ is continuous and nonzero in a neighborhood of $\theta_0$. Then $\sqrt{n}(g(T_n)-g(\theta_0))$ has a degenerate limiting distribution, but:
$$
$\sqrt{n}(g(T_n)-g(\theta_0)) \to_D \frac{g''(\theta_0)}{2}Z^2
$$
So, using this I have that for $p =\frac{1}{2}$, $g'(p) = 0$, but $g''(p) = -2 \neq 0$, so:
$$
n\left(\hat{p}(1-\hat{p})-\frac{1}{4}\right) \to_D -\frac{1}{4}\chi^2_1
$$
I am wondering why this negative limit makes sense. I read in a footnote somewhere that this makes sense since $p(1-p)$ is maximized at $p=\frac{1}{2}$, but this doesn't really register with me. Can anyone help me here? thanks.

A: You have $p(1 - p) \le \frac{1}{4}$ for all $p \in \mathbb{R}$, so you always have $p(1-p) - \frac{1}{4} \le 0$. This is where the negative sign comes from.
Now for large $n$, $\hat p(1 - \hat p)$ will be close to $\frac{1}{4}$ by the law of large numbers. But in a typical case, you don't have an exact equality $\hat p = \frac{1}{2}$, but only $\hat p \approx \frac{1}{2}$. This means that in a typical case we have strict inequality $\hat p (1 - \hat p) - \frac{1}{4} < 0$.
Now how "strong" is this strict inequality? Well, if we rescale this difference by a factor of $n$, we get a nondegenerate limiting distribution, i.e. $n(\hat p(1 - \hat p) - \tfrac{1}{4}) \to -\frac{1}{4} \chi^2_1$.


text:
Q: How to make your website https only? I've got a working SSL certificate, but the only way for a person to visit my https website is by typing "https://" in the search bar. I've got a .htacces file that contains the following code:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

And I also tried this line of code:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

But neither of them seem to work.
I've also read that there is a meta tag that sends all users to your https no matter what. But still have yet to find what the meta tag looks like.
Any help is appreciated. Thank you for your time

A: The basic idea is correct - you will need rewrite rules on your webserver for to make the site HTTPS only
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Please take a look at the following documentation: https://wiki.apache.org/httpd/RewriteHTTPToHTTPS
Regarding why your rules are not working - you need to know the context of .htaccess file, from documentation:

.htaccess files (or "distributed configuration files") provide a way
  to make configuration changes on a per-directory basis. A file,
  containing one or more configuration directives, is placed in a
  particular document directory, and the directives apply to that
  directory, and all subdirectories thereof.

it is however better not to use .htaccess at all if possible since it has negative performance implications and the same thing can be achieved with <Directory> blocks. All of that is in here: https://httpd.apache.org/docs/current/howto/htaccess.html
Regarding the meta tag - all you need to do is add something like this:
<meta http-equiv="refresh" content="0; url=https://yoursite.com/">

The meta tag is definitely not the best practice of HTTP-2-HTTPS redirection due to the fact that it is easy to circumvent and outside of webmasters control since it's a client side redirect.


text:
Q: Can't use require() method that receives a prop in React As part of a personal project, I have to create an image gallery. For every image (miniature) that is clicked in the gallery, I want the chosen image to appear in a larger size on the page. I have been trying to do this by passing the desired image's address as a prop to my ImageOnView component, like so:
<ImageOnView imgSrc = {this.state.imageLarge}/>

Inside my ImageOnView component, however, I'm having trouble displaying the image using the require() method. Right now it looks like this:
class ImageOnView extends Component {
  render() {
    //This alert displays the image source as expected
    alert(this.props.imgSrc);
    return (

    );
  }
}

I get the following error on my webpage: "Error: Cannot find module ".""
How do I go about resolving this issue? Thanks in advance.

A: Just try
src={require('' + this.props.imgSrc)}

A: Since you are using Webpack as a bundler in runtime, require can't use a variable name like this. It should accept a resolvable path, ie a string here. So, you can require the image in the parent instead of the child and use the resolved path:
class App extends Component {
  state = {
    imageLarge: require( "./somedir/some.jpg" ),
  };

  render() {
    return (

        <ImageOnView imgSrc={this.state.imageLarge} />

    );
  }
}

class ImageOnView extends React.Component {
  render() {
    // This alert displays the image source as expected
    alert( this.props.imgSrc );
    return (

    );
  }
}

A: Can also do like this:-
import React from 'react';

function index({title, image, rating}) {
   return

;
}

export default index;

A: require() is used to import a module or file. So to get an imageLarge from another file you might want to
const imageLarge = require(path)

or es6 version:
import imageLarge from 'path'

in the img tag you just need to provide a src attribute with imageLarge in component it would look something like:
const imageLarge = require(path)

<ImageOnView imgSrc = {imageLarge}/>

class ImageOnView extends Component {
  render() {

    return (

    );

  }
}


text:
Q: Removing ' » ' from a String using jQuery I have a

 and I am trying to display breadcrumbs where one of the string contains Tab3 ».
Its like Tab1 > Tab2 > Tab3 » > Tab4 except that > is an arrow-right.png image.
I want to remove &raquo or » from Tab3 ».
I want to search if the selected tab has » or &raquo in it and if it does then I want to replace it with "" so that Tab3 » becomes Tab3.
I've tried the following but it doesn't seem to work.
$("document").ready(function() {
    var crumbs = $("a.selected");

    jQuery.each(crumbs, function() {

        if(this != crumbs.get([0])) {
            $("#bread").append(" ");
        }
        $("#bread").append("<img src='<c:url value="/resources/images/arrow-right.png" />' />" + " ");

            var crumb = $(this).html();
            var slicedCrumb;
            if(crumb.indexOf(' » ') != -1) {
                slicedCrumb = $(this).html().replace(' » ', '');
                $("#bread").append(slicedCrumb);
            }
            else {
                $("#bread").append(crumb);
            }

     });
});

I also tried to use » at the place of » but that din't seem to work either.
$("document").ready(function() {
    var crumbs = $("a.selected");

    jQuery.each(crumbs, function() {

        if(this != crumbs.get([0])) {
            $("#bread").append(" ");
        }
        $("#bread").append("<img src='<c:url value="/resources/images/arrow-right.png" />' />" + " ");

            var crumb = $(this).html();
            var slicedCrumb;
            if(crumb.indexOf(' » ') != -1) {
                slicedCrumb = $(this).html().replace(' » ', '');
                $("#bread").append(slicedCrumb);
            }
            else {
                $("#bread").append(crumb);
            }

     });
});

I've spent quite sometime reading other posts on the given subject but somehow I am not able to get it working. Could someone help me understand what am I missing here? I am using jquery-1.5.js to run this code. Do I need to use the newer version of jquery or any other library as well to get it working?

A: slicedCrumb = $(this).html().replace(/\»/g, '');

The important part is escaping the » character. Also I added the global (g) flag so that if there are multiple instances that match the regex, they will all be removed.
Here is a demo: http://jsfiddle.net/YXXZs/1/
UPDATE
If you want to check if a character exists before trying to replace it then you can use .match():
var text = $(this).html();
if (text.search(/\»/) > -1) {
    slicedCrumb = text.replace(/\»/g, '');
}

Here is a demo: http://jsfiddle.net/YXXZs/4/
Docs for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match

A: Try using
slicedCrumb = $(this).html().replace('/[&]raquo[;]/ ', '');


text:
Q: Default built-in editors for the PropertyGrid control I can't seem to find the answer to this anywhere. What default editors/converters are building into 3.5 Framework PropertyGrid control. Otherwise what object types can I throw at it and it be able to reliably show and edit? I've found a lot of tutorials on using custom editors (which I may do at some point). But right now in my program I'm allowing the user to create their own custom properties and I want to know what object types I should allow assuming they will be editing them in a PropertyGrid.

A: Bear in mind that there some non-public classes.
System.Object
  System.Drawing.Design.UITypeEditor
    System.ComponentModel.Design.CollectionEditor
      System.ComponentModel.Design.ArrayEditor
      System.Web.UI.Design.CollectionEditorBase
      System.Web.UI.Design.WebControls.WizardStepCollectionEditor
      System.Web.UI.Design.WebControls.EmbeddedMailObjectCollectionEditor
      System.Web.UI.Design.WebControls.HotSpotCollectionEditor
      System.Web.UI.Design.WebControls.ListItemsCollectionEditor
      System.Web.UI.Design.WebControls.MenuItemStyleCollectionEditor
      System.Web.UI.Design.WebControls.RoleGroupCollectionEditor
      System.Web.UI.Design.WebControls.StyleCollectionEditor
      System.Web.UI.Design.WebControls.SubMenuStyleCollectionEditor
      System.Web.UI.Design.WebControls.TableCellsCollectionEditor
      System.Web.UI.Design.WebControls.TableRowsCollectionEditor
    System.ComponentModel.Design.BinaryEditor
    System.ComponentModel.Design.DateTimeEditor
    System.ComponentModel.Design.MultilineStringEditor
    System.ComponentModel.Design.ObjectSelectorEditor
    System.Windows.Forms.Design.AnchorEditor
    System.Windows.Forms.Design.BorderSidesEditor
    System.Windows.Forms.Design.DockEditor
    System.Windows.Forms.Design.FileNameEditor
    System.Windows.Forms.Design.FolderNameEditor
    System.Windows.Forms.Design.ShortcutKeysEditor
    System.Web.UI.Design.ConnectionStringEditor
    System.Web.UI.Design.DataBindingCollectionEditor
    System.Web.UI.Design.ExpressionsCollectionEditor
    System.Web.UI.Design.UrlEditor
    System.Web.UI.Design.XmlFileEditor
    System.Web.UI.Design.WebControls.DataGridColumnCollectionEditor
    System.Web.UI.Design.WebControls.DataControlFieldTypeEditor
    System.Web.UI.Design.WebControls.MenuBindingsEditor
    System.Web.UI.Design.WebControls.MenuItemCollectionEditor
    System.Web.UI.Design.WebControls.ParameterCollectionEditor
    System.Web.UI.Design.WebControls.RegexTypeEditor
    System.Web.UI.Design.WebControls.TreeNodeCollectionEditor
    System.Web.UI.Design.WebControls.TreeViewBindingsEditor
    System.Web.UI.Design.WebControls.DataPagerFieldTypeEditor
    System.Messaging.Design.QueuePathEditor
    System.Drawing.Design.ImageEditor
    System.Drawing.Design.ColorEditor
    System.Drawing.Design.ContentAlignmentEditor
    System.Drawing.Design.CursorEditor
    System.Drawing.Design.FontEditor
    System.Drawing.Design.FontNameEditor
    System.Drawing.Design.IconEditor
    System.Workflow.ComponentModel.Design.TypeBrowserEditor
    System.Workflow.ComponentModel.Design.BindUITypeEditor

A: You might want to take a look at classes that derive from UITypeEditor (in the System.Drawing.Design namespace).  These types will be passed as parameters to the EditorAttribute (in the System.ComponentModel namespace).
You can also look at the metadata for the type to see where the EditorAttribute is applied.  However, do not use reflection here, as that is not what the PropertyGrid class uses.
Rather use the TypeDescriptor class to get property descriptors for the properties on the type (call the static GetProperties method).  Then, with the PropertyDescriptor instance, call the GetEditor method to get an instance of the editor for that property.

A: You can actually throw any object at the PropertyGrid. It will do a lot of things automatically. You only need to create custom UI type editors if you want to have a special edit experience, which is not natively provided. And even in that case you do it per property and not for a whole object.

A: The PropertyGrid uses TypeConverters and there are TypeConverters for every primitive type (as well as collections of primitive types).
As long as you're using one of the primitive types or a collection of primitive types the property grid should be able to take care of providing an editing UI.

A: Besides UITypeEditors, the PropertyGrid is able to display any object with a TypeConverter that returns true for CanConvertFrom(String).  You can implement your own TypeConverters for specific object types in order to accomplish this.


text:
Q: The basis for the set of 2 x 2 real, symmetric matrices Let $A$ be the set of $2 \times 2$ real, symmetric matrices.
Consider the set of matrices
$\{\begin{bmatrix} 1 & 0 \\ 0 & 0\end{bmatrix}, \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix}, \begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix} \}$. I am curious for an explanation for why this is not the basis for $A$.
I know that the dimension of $A$ is 3, and the basis that is more consistent with this dimension is $\{\begin{bmatrix} 1 & 0 \\ 0 & 0\end{bmatrix}, \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, \begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix} \}$. This basis satisfies the definition of a basis.
However, it is not clear to me why the first set does not satisfy the definition of a basis (i.e. it spans $A$ and is linearly independent). The set spans the space of all $2 \times 2$ matrices, so it certainly spans $A$. So, I am guessing there is some reason why the set is no linearly independent.

A: Note that not all the matrices in the first basis are elements of $A$, as they are not symmetric. You can't have basis elements that are not even part of the space they supposedly span. That set is certainly a basis. It's just not a basis for $A$, but rather for the whole space of $2\times 2$ matrices.


text:
Q: Why do I have to make my own drivers? Why does *NIX require me to make (i.e. build) my own drivers to install them?
Couldn't they just be pre-built by the author and so long as they target the right CPU architecture I could install the binaries which would save me having to have all the right dependencies to build them.
I ask because I am currently faced with this problem: https://unix.stackexchange.com/questions/154188/make-asus-pce-n15-driver-errors-on-steamos.
It has been suggested to me in another forum the the issue maybe they target an old version of the kernel - so what am I suppose to do in this instance? Are you telling me drivers target specific versions of the kernel and are tied to it - that sounds like a nightmare!

A: This isn't necessarily a *NIX thing and is more of a Linux thing, IMO, and what you're considering as a annoyance is actually a good thing! That the drivers are made available in source form, rather than only in binary form.
There are many reasons why you want drivers to be avail. like this. Different architectures + kernel versions being 2 of them.
I completely understand your frustration but this is how Open Source generally works. I would pursue any building of drivers with the original authors or the distro that you're trying to build them on.

A:
on Windows I go to the manufactures website download the driver and install it

Correct, and those exact same manufacturers have the option of providing linux drivers.  While it does require some effort to maintain them in relation to kernel versions, in most cases this maintenance effort would not be all that significant for the manufacturer.
But they don't. Why is somewhat conjecture, but: This statistical survey regarding desktop systems (using net applications) puts the linux "market share" at < 2%.  That sounds like it should be enough to make it worthwhile, but there are some things to consider in context:

*

*While gaming has provided a historical impetus the evolution of consumer hardware, most of the desktop market is still not gamers.  This is significant because games make specific demands of hardware -- but while desktop users whose focus is not gaming may (or may not) have special needs, they are not the same needs.

*Desktop users who are gamers and are frustrated by this situation will mostly be willing to fall back on MS Windows.
If you add these two factors together, the significance of that 2% market share becomes crippled.  Most of that 2% aren't gamers, and most of the ones that are will be perfectly willing to use Windows for their gaming needs.  This means that the real $$ loss to manufacturers from consumers who won't buy their product because they don't provide linux drivers is negligible.
Hence, they don't bother.  Would it cost them much? No. But would they have much to gain from it? No.  If the manufacturer won't bother, then it is mostly left up to volunteers to do the work.   Now consider, you are a software developer with some free time...

*

*If you like games and want to contribute, you almost certainly won't be starting with linux as a platform, because it isn't oriented that way.

*If you aren't interested in games, you are unlikely to want to spend time developing drivers that the actual equipment manufacturers didn't even want to bother with.  You want to contribute to things that you find interesting and useful -- which linux may be very suitable for, but that's not much help to end consumers of video games.
To draw a really crass analogy, complaining that a sailboat is more awkward than a pickup truck begs the question, for what?  People who build sailboats aren't trying to create pickup trucks.


text:
Q: Datatables remove all rows I use DataTables and Bootstrap gentelella. Datatables work fine when they have some records. When I open page with empty data in table and go to Create page and go back I see that DataTables do not work ok.

I use this code for init Datatable:
$('#table-programm-station')
  .DataTable({
    "language": {
      "url": "/js/datatables/Russian.json"
    },
    dom: 'T<"clear">lfrtip',
    tableTools: {
      "sRowSelect": "multi",
      //"aButtons": ["select_all", "select_none"]
    }
  });

If I remove language option it all work fine. Also I at first load language json and successfully parse it then assign it to language option and have the same result.
I don't get any errors in the console. How to fix it?

A: You can use this cdn '//cdn.datatables.net/plug-ins/1.10.15/i18n/Russian.json'.
It works here
var table = $('#example').DataTable({
   language : {
      url: '//cdn.datatables.net/plug-ins/1.10.15/i18n/Russian.json'
   }
});


text:
Q: Can I use regex capturing groups in SQL Server 2014? I have some text data in an SQL Server 2014 table in which I want to detect complex patterns and extract certain portions of the text if the text matches the pattern. Because of this, I need capturing groups.
E.g.
From the text
"Some title, Some Journal name, vol. 5, p. 20-22"

I want to grab the volume number
, vol\. ([0-9]+), p\. [0-9]+

Mind that I have simplified this use-case to improve readability. The above use-case could be solved without capturing groups. The actual use-case handles a lot more exceptions, like:

*

*The journal/title containing "vol.".

*Volume numbers/pages containing letters

*"vol" being followed by ":" or ";" instead of "."

*...

The actual regex I use is the following (yet, this is not a question on regex structure, just elaborating on why I need capturing groups).
(^|§|[^a-z0-9])vol[^a-z0-9]*([a-z]?[0-9]+[a-z]?)

As far as I know, there are two ways of getting Regex functionality into SQL Server.

*

*Through CLR: https://www.simple-talk.com/sql/t-sql-programming/clr-assembly-regex-functions-for-sql-server-by-example/ . Yet, this example (from 2009) does not support groups. Are there any commonly used solutions out there that do?

*By installing Master Data Services

Since installing and setting up the entire Master Data Services package felt like overkill to get some Regex functionality, I was hoping there'd be an easy, common way out...

A: I have found a CLR implementation that is super easy to install, and includes Regex capturing group functions.
http://www.sqlsharp.com/
I have installed this in a separate database called 'SQL#' (simply by using the provided installation .sql script), and the functions are located inside a schema with the same name. As a result I can use the function as follows:
select SQL#.SQL#.RegEx_CaptureGroup( 'test (2005) test', '\((20[012][0-9]|19[5-9][0-9])\)', 1, NULL, 1, -1, '');

Would be nice if this was included by default in SQL Server...


text:
Q: Accessing internally hosted server inside Docker container from docker host So my question is a bit different, I've looked at the existing answers but couldn't find a solution.
So I have a simple express.js application which looks like:
var express = require("express");
var app = express();
const PORT = 8080;
const HOST = '0.0.0.0';

app.get("/", function (req, res) {
  var params = req.params;
  var url = req.query["url"];
  res.send('
Hello ' + url + '
');
});
app.listen(PORT, HOST, () => console.log(`App running on ${PORT}`));

If I dockerize this application and expose and bind my port then I am able to access the application but within the docker container apart from this app, I want to parallel run a Python HTTPServer using the command python -m SimpleHTTPServer 1337 and I want that it should only be accessible through my container only http://dockerip:8080/?url= but it fails to connect to port 1337. If I expose 1337, then obviously it will be accessible via http://dockerip:1337 which I don't want.
What can I do to make it accessible ONLY from within the docker container.


text:
Q: Add value to field by URL ?name=data You know passing value to field by URL could be done by :
?name=data

For example :
Google.com/?q=stackoverflow

And then when you open this link you have "stackoverflow" written in the field.
But I can't do this with some websites.
For example : ( GitHub search bar name is also "q" )
github.com/?q=stackoverflow

If you open this link there is no text in the search field.
I want to know why and how to make this method work for these websites?

A: The site has to parse the data out of the URL and use it to set the value attribute of the input when they generate the HTML to send to the browser.


text:
Q: Razorpay cordova plugin not working for iOS stuck on splash screen I'm trying to implement Razorpay checkout in my ionic application using Razorpay-cordova. After installing this plugin, ios application gets stuck on its splash screen and then gets close. Although this plugin works perfectly on Android platforms.
I have done following basic steps:
Added razorpay plugin - cordova plugin add com.razorpay.cordova --save
After this I emulate this basic app just in ios simulator - ionic cordova emulate ios
I have embedded swift libraries in Xcode the razorpay.framework.
Then imported the <razorpay-swift.h> in main.m.
Result: The app gets stuck on the splash screen for few secs and then gets close. (Only on IOS. Also tested on IOS device, results in same!).
I don't know what I'm missing here?


text:
Q: Heap Storage Limit exception while creating attachment I have a custom object Call2_vod__c which is detail to Account.
It has a Signature_vod__c field that is in encoded base64 format.
Now for one Account, I can create an attachment from any of the calls associated with it (Account:Call2_vod__c=1:many).
I am getting a limit exception with my below code. Can someone please help me?
Apex Class:`
    global class Account_chk {
  WebService static void method1(Id i) {
  List a= new List();
  List p=new List ();
    List exist=new List ();
exist=[select ParentId,id from Attachment];
Map existMap = new Map();
Map signMap = new Map();
for (Attachment att : exist) {
    existMap.put(att.ParentId, att);
}
for (Call2_vod__c call: [select Name,Id,Signature_vod__c,Signature_Date_vod__c,Account_vod__c from Call2_vod__c where Signature_Date_vod__c !=Null and Account_vod__c not in :existMap.keySet()])
{

  Attachment record = new Attachment(Name = Call.Id ,ParentId = call.Account_vod__c , Body = EncodingUtil.base64Decode(call.Signature_vod__c), ContentType = 'image/jpeg');
   if (record.parentId !=Null && existMap.get(record.ParentId).Id == null) {
    p.add(record);

}
}
try { insert(p);
} catch(System.DMLException e){
  System.debug('The following exception has occurred: ' + e.getMessage());
  }

}
}`
Please find the error currently I am facing with the code:
Failed to execute 'send' on 'XMLHttpRequest':Failed to load 'https://cs18.salesforce.com/services/Soap/package/Account_chk'

A: You are querying too many unneeded records and creating Attachments for them which is why you are hitting the heap limit. Try make the 2 changes listed below
1: Restrict your query
Changing the SOQL to have extra where conditions will mean you are querying less records which means less fields that are base64 encoded. The SOQL below is looking at the Account_vod__c fields which will mean you query less records.
[select Name,Id,Signature_vod__c,Signature_Date_vod__c,Account_vod__c
    from  Call2_vod__c
    where Signature_Date_vod__c !=Null and Account_vod__c in :existMap.keySet()]

The extra check for Account_vod__c in :existMap.keySet() will stop you querying the records you are not interested in.
2: Change the for loop
Because you do your SOQL and store the results in a it means that ALL records will be on the heap. Try changing your for loop to the format shown below. This will avoid the heap issues are you are not storing all the results to a list:
for (Call2_vod__c call : [select ... from ... where ...]) {
    //
}

Doing number 2 will probably fix your issue but having the SOQL returning so many records is wrong and will cause problems as the number of Call2_vod__c records grow. For example: you will hit another limit if that query returns more than 10,000 records

A: You cannot catch or handle LIMIT exception.
Depending on actual LIMITs being violated, you could try to check if some value is close to limit and stop any functionality if it is approaching the limit. Check https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_limits.htm Limits class which has some helpful methods to get current limits usage.


text:
Q: Como fazer para que esse código possa a ser usado mais de seis vezes <!DOCTYPE HTML>
<head>
 <Title>Api de som</title>
</head>
<body>
<button onclick="play()">play</button>

<Script>
let context = new AudioContext();
oscillator = context.createOscillator();
oscillator.type="sine";
oscillator.connect(context.destination);
oscillator.frequency.value=2000;

function play(){
oscillator.start(0);
oscillator.stop(0.5);
}
</Script>
</body>
</html>

A: Lendo o log de o erros está sendo informado:

"message": "Uncaught InvalidStateError: Failed to execute 'start' on
'AudioScheduledSourceNode': cannot call start more than once."

Ou seja houve falha ao executar o método OscillatorNode.start() pois o método não pode ser chamado mais de uma vez por oscilador.
Então migre para o corpo da função play() os métodos de criação e configuração da oscilador.

function play() {
  let context = new AudioContext();
  oscillator = context.createOscillator();

  oscillator.type = "sine";
  oscillator.connect(context.destination);
  oscillator.frequency.value = 2000;

  oscillator.start(0);
  oscillator.stop(0.5);
}
<!DOCTYPE HTML>

<head>
  <Title>Api de som</title>
</head>

<body>
  <button onclick="play()">play</button>
</body>

</html>


text:
Q: SQL Server How to UPDATE with SELECT and GROUP BY clause Our team uses SQL Server and I wanted to use aggregate function to update one of the columns for the NEW values that are being inserted existing table.
Below is the existing table and values in it.
CREATE TABLE CARS
(
   ID INT NOT NULL,
   carCompany VARCHAR(100) NOT NULL,
   feature VARCHAR(100) NOT NULL,
   sequence INT NOT NULL
);

INSERT INTO CARS VALUES (1, 'Toyota', 'Auto transmission', 1);
INSERT INTO CARS VALUES (2, 'BMW', 'Keyless Entry system', 1);
INSERT INTO CARS VALUES (3, 'Toyota', 'Power Steering', 2);
INSERT INTO CARS VALUES (4, 'Tesla', 'Auto transmission', 1);
INSERT INTO CARS VALUES (5, 'BMW', 'Auto transmission', 2);
INSERT INTO CARS VALUES (6, 'Tesla', 'Keyless Entry system', 2);
INSERT INTO CARS VALUES (7, 'BMW', 'Power Steering', 3);

Requirement came in to 'Auto Pilot' for BMW and Tesla only with sequence column incremented in the same carCompany group. Since, Insert statement was easier, I just inserted records and struggling to get the Update statement right.
INSERT INTO CARS VALUES (8, 'Tesla', 'Auto Pilot', 0);
INSERT INTO CARS VALUES (9, 'BMW', 'Auto Pilot', 0);

Below UPDATE statement is INCORRECT. Kindly help here.
UPDATE c1
SET c1.sequence = d.sq
FROM
    (SELECT MAX(c2.sequence) + 1 AS sq
     FROM CARS c2
     WHERE c2.carCompany = c1.carCompany
     GROUP BY c2.carCompany) d
WHERE c1.sequence = 0

A: You're close, just move the correlated subquery into the SET statement:
UPDATE c1
    SET c1.sequence = (SELECT max(fc2.sequence) + 1 as sq FROM CARS c2 WHERE c2.carCompany = c1.carCompany GROUP BY c2.carCompany)
FROM CARS c1
WHERE c1.sequence = 0

But note that this only works if there's only one new record for that car company. I.e., if you had two new Tesla features they'd both be set to 2. You can use a CTE with the RANK function to allow for any number of new values:
WITH NewSequences
AS (
SELECT id, RANK()OVER(PARTITION BY c1.carCompany ORDER BY id) + (SELECT max(fc2.sequence) + 1 as sq FROM CARS c2 WHERE c2.carCompany = c1.carCompany GROUP BY c2.carCompany) AS NewSeq
FROM CARS
WHERE c1.[sequence] = 0
)
UPDATE c1
    SET c1.sequence = n.NewSeq
FROM CARS c1
    INNER JOIN NewSequences n
        ON c1.id = NewSequences.id

A: If you just want the next sequence number, you are very close with your query:
UPDATE cars
    SET sequence = d.sq
FROM (SELECT max(c2.sequence) + 1 as sq
      FROM CARS c2
      GROUP BY c2.carCompany
     ) c2
     ON c2.carCompany = c1.carCompany
WHERE sequence = 0;

Note:  I don't think this does what you want if you have inserted multiple rows with the same company.  Presumably, you want them to have different values, so you would use:
with toupdate as (
      select c.*,
             max(c.sequence) over (partition by carcompany) as max_sequence,
             row_number() over (partition by carcompany order by id) as seqnum
      from cars c
     )
update toupdate
    set sequence = max_sequence + seqnum
    where sequence = 0;

However, pre-calculating this value seems quite unnecessary when you can just use:
select c.*,
       row_number() over (partition by carCompany order by id) as seq
from cars c;

I don't see a reason to store this value.


text:
Q: Creating an Exe file With only 1's and 0's: Machine Code I want to type a couple of 1's and 0's into notepad, save as something.exe, and get a program. Obviously, it will not be very complex. Even just saying hi would work. How do I output text? How do I pause it so it doesn't close immediately? Is there a resource anybody has where it says all this?

A: I think you would have a better experience if you used a text editor, typed either binary (ones and zeros) or hex into a text file then write a small program that reads that ascii file and saves it as the binary bits or bytes you intended.  Basically making a machine code assembler.
You should specify the processor and operating system you are interested in before taking this further.  You not only have to know the opcodes/machine code for the instruction set but need to know the binary file formats for the operating system (coff, elf, exe, etc) and would need to hand code all of that information (much better suited to have your machine code assembler create that header for you if needed).
As an example take http://github.com/dwelch67/lsasim an educational instruction set with simulator and tools that I created.  The "binary file format" is an ascii file with the machine code in readable hex.  The simulator reads that and executes it, and if desired (which is how I tested it at first), you can hand code the machine code instead of assembly language.  I dont have an operating system, etc, the parser that reads the machine code file turns it into a buffer of binary ones and zeros, which is the simulated memory for the processor.
In the old days of dos and windows the debug command line program made this kind of thing easy, hand code either assembly or machine code bytes, and when you save you can easily save to a .com executable file.  I am certain I am not the only one that learned x86 assembly language using debug as I couldnt afford to buy software tools like masm, and didnt have a modem to get whatever the popular free assembler was asm86 or some such thing (until years later when I could afford one of those).  if debug is still part of the windows command line you can probably still do this today with that tool.

A: You would need to first identify a specific processor it would run on, and also an environment (raw CPU, some operating system, something else). From the environment you would need to determine the correct binary format. From the CPU you would need to determine the actual machine language. There are several other things you would need to determine as well.
Your question may as well be "where does life come from?" -- yes, it can be answered, but not with any useful result through a simple Q&A forum. If you want to pursue this further, you might consider taking a course (or just reading a book) in Computer Organization, concentrating on the assembly language details. From there, it's not a far stretch to learn to convert your assembly into machine code (though there will still be quite a bit to learn).


text:
Q: How can I change cols of textarea in twitter-bootstrap? If I change the value of :rows, it works. But it stays at the default cols whatever value I set with ':cols =>'. Column width won't change.
I viewed the html source and it reflected the change. I wonder that bootstrap's CSS might be the suspect...
HTML (there is a "cols=" in the final HTML, but column width stays at the default value, which is 30. I can't believe my eyes!)
<textarea cols="100" id="comment_body" name="comment[body]" rows="5"></textarea>

Rails:
<%= form_for([@post, @post.comments.build]) do |f| %>

    <%= f.text_field :commenter %>

    <%= f.text_area :body, :rows => 5, :cols => 100 %>

    <%= f.submit %>

<% end %>

A: The other answers didn't work for me. This did:

Document

        <textarea class="field span12" id="textarea" rows="6" placeholder="Enter a short synopsis"></textarea>
        <button class="btn">Upload</button>

Note the span12 in a div with span6.

A: I don't know if this is the correct way however I did this:

  Label:

    <textarea id="id1" class="textareawidth" rows="10" name="anyname">value</textarea>

and put this in my bootstrapcustom.css file:
@media (min-width: 768px) {
    .textareawidth {
        width:500px;
    }
}
@media (max-width: 767px) {
    .textareawidth {

    }
}

This way it resizes based on the viewport. Seems to line everything up nicely on a big browser and on a small mobile device.

A: UPDATE: As of Bootstrap 3.0, the input-* classes described below for setting the width of input elements were removed. Instead use the col-* classes to set the width of input elements. Examples are provided in the documentation.

In Bootstrap 2.3, you'd use the input classes for setting the width.
<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>
<textarea class="input-block-level"></textarea>

Do a find for "Control sizing" for examples in the documentation.
But for height I think you'd still use the rows attribute.

A: This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row

     <%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>

A: Simply add the bootstrap "row-fluid" class to the textarea. It will stretch to 100% width;
Update:
For bootstrap 3.x use "col-xs-12" class for textarea;
Update II:
Also if you want to extend the container to full width use: container-fluid class.

A: I found the following in the site.css generated by VS2013
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

To override this behavior in a specific element, add the following...
 style="max-width: none;"

For example:

      <textarea style="max-width: none;"
                class="form-control"
                placeholder="a col-md-6 multiline input box" />

A: Another option is to split off the textarea in the Site.css as follows:
/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:
@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me


text:
Q: jQuery html() not working for string $("Hello").html()
Returns undefined. Of course, my situation is a little more complex than this, but this line of code shows the issue. How can I fix this?
This gives an idea of what I'm trying to do:
var $theSite = $(myHTMLString);//myHTMLString is an external web site (string)
$theSite.filter('input').remove();
alert($myHTMLString.html());

A: That's because there's no renderable HTML
Note that .text() returns a value
$("Hello").text();

And if we add some HTML in the body tag we get a result too!
$("
Hello
").html();

Update based on OP comments
No need to use JQuery to resolve your problem. Treat the HTML as a string and then use a regular expression to remove input tags:
var x = '<input type="text" />Hello<input type="button" />
p
';

alert(x);

var regX = /(<input([^>]+)>)/ig;

alert(x.replace(regX, ""));

A: You could use a DOMParser - something like this:
var pageStr = "
Hello
YO";
var dp = new DOMParser();
var doc = dp.parseFromString(pageStr,'text/html');
alert(doc.documentElement.outerHTML);//"
Hello
YO"
$(doc).find("span").remove();
alert($(doc).get(0).documentElement.outerHTML);//"
Hello
"

JSFiddle
Update: answer now implements a DOMParser polyfill
/*
 * DOMParser HTML extension
 * 2012-09-04
 *
 * By Eli Grey, http://eligrey.com
 * Public domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*! @source https://gist.github.com/1129031 */
/*global document, DOMParser*/

(function(DOMParser) {
    "use strict";

    var
      DOMParser_proto = DOMParser.prototype
    , real_parseFromString = DOMParser_proto.parseFromString
    ;

    // Firefox/Opera/IE throw errors on unsupported types
    try {
        // WebKit returns null on unsupported types
        if ((new DOMParser).parseFromString("", "text/html")) {
            // text/html parsing is natively supported
            return;
        }
    } catch (ex) {}

    DOMParser_proto.parseFromString = function(markup, type) {
        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
            var
              doc = document.implementation.createHTMLDocument("")
            ;
                if (markup.toLowerCase().indexOf('<!doctype') > -1) {
                    doc.documentElement.innerHTML = markup;
                }
                else {
                    doc.body.innerHTML = markup;
                }
            return doc;
        } else {
            return real_parseFromString.apply(this, arguments);
        }
    };
}(DOMParser));

A: There are restrictions on the HTML that you can create with jQuery(htmlString). As explained in the documentation:

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new
 element and sets the innerHTML property of the element to the HTML snippet that was passed in.
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as ,  <title>, or   elements. As a result, the elements inserted may not be representative of the original string passed.

This is what's happening in your case. You can't use jQuery(htmlString) to parse a complete web page, because it has to be something that can be put inside a DIV. You should use the DOMParser API instead.

A: var $html=$("
             <input type='text' value='hello'>
hi
");
$("div").html($html.filter('*:not("input")'));

http://jsfiddle.net/tSUFc/1/

A: You are using this wrong. The first part is a selector, you select one or more elements with it, like this:
$('html,body') // selects both html and body
$('body div') // selects all 'divs' in 'body' (just like css)

The .html() works like this:
// a setter
$('#someElement').html('This is the new html in #someElement</strong');
// or, as getter:
console.log( $('#someElement').html() ); // returns " 'This is the new html in #someElement</strong' "


text:
Q: Numpy eigenvectors I am trying to use the numpy's linalg.eig() function to get eigenvectors and eigenvalues.
import numpy as np
M = np.array([[168.04570515, 1.38100609, -48.60662242],
              [1.38100609, 16.49647382, 9.18370965],
              [-48.60662242, 9.18370965, 38.37842496]])
eigenvalue, eigenvector = np.linalg.eig(M)

>>>eigenvalue
array([184.25812834,  28.91371368,   9.74876191])

>>>eigenvector
array([[-0.94849917, -0.26039343, -0.18040119],
   [ 0.0095255 , -0.59267178,  0.80538775],
   [ 0.31663637, -0.7621912 , -0.56462906]])

However, when I input the same M values into WolframAlpha, I get the following:

Why do I get different eigenvectors?

A: So you are actually getting the same eigenvectors. It's just that Wolfram Alpha scales the eigenvectors so the last element is 1 (if you recall, eigenvectors are scale invariant). Let's look at the first column of your result. If you run,
np.array([-0.94849917, 0.0095255, 0.31663637])/0.31663637

You will get
array([-2.99554713,  0.0300834 ,  1.        ])

Which if you notice is what Wolfram Alpha reports. You can check the other two as well.


text:
Q: Create a dictionary with input in python I'm trying to create a dictionary from user input, with the ability to add nested dictionaries as well.
The code I have now can create a dictionary, with one level nesting, but I think there's a better way to do this and also make the nesting levels be unlimited, does anyone know how to achieve this?
def input_to_dict():
    def str_or_list(value):
        # return list if values are separated by comma, else return string
        if "," in value:
            value = value.split(",")
            value = [i.strip() for i in value]
            return value
        else:
            return value.strip()

    temp_dict = {}
    while True:
        key = input('Key: ').title()
        if not key:
            break
        value = input('Value: ')
        # if value is key-value pair, nest dict
        if ":" in value:
            value = value.split(":")
            value_k = value[0].strip().title()
            value_v = value[1].strip()
            temp_dict[key] = {value_k: str_or_list(value_v)}

        else:
            temp_dict[key] = str_or_list(value)

    return temp_dict

A: If you want the nested dictionaries to be able to include arbitrary entries, including more nested dictionaries, you probably want a recursive function, e.g.:
def input_to_dict():
    d = {}
    while True:
        k = input('Key: ').title()
        if not k:
            break
        v = input('Value: ')
        if v == ":":
            d[k] = input_to_dict()
        elif "," in v:
            d[k] = [i.strip() for i in v]
        else:
            d[k] = v
    return d

Key: foo
Value: bar
Key: moar
Value: :
Key: foo
Value: bar
Key: moar
Value: :
Key: foo
Value: bar
Key:
Key:
Key:
{'Foo': 'bar', 'Moar': {'Foo': 'bar', 'Moar': {'Foo': 'bar'}}}

A: This is the code I ended up using thanks to @Samwise answer
I added indentation and cleaned console text a little for clarity, and I also added an option to only use keys from a ref dict.
def input_to_dict(nest=0, ref=None):
    # indentation for nested dictionaries
    indent = "    " * nest if nest > 0 else ""

    # return list if values are separated by comma, else return string
    def islist(value):
        if "," in value:
            value = value.split(",")
            value = [i.strip() for i in value]
            return value
        else:
            return value.strip()

    def clear_line():
        print("\033[F", end="") # Move up one line
        print("\033[K", end="") # Clear line

    d = {}
    while True:
        k = input(f'{indent}Key: ').title()
        clear_line()
        if not k:
            break
        if ref and k not in ref.keys():
            clear_line()
            print("Invalid key! choose from:", ", ".join(ref))
            continue

        v = input(f'{indent}{k}: ')
        if v == ":" or v == "\t":
            clear_line()
            print(f'{indent}{k}:')
            if ref:
                d[k] = input_to_dict(nest + 1, ref[k])
            else:
                d[k] = input_to_dict(nest + 1)
        else:
            d[k] = islist(v)
    return d


text:
Q: Font Panel to change Text Field Font I Setup a Push Button to open up a Font Panel like they did shown in this question:
Make NSButton open fonts panel
I did all of these through the Interface Builder by dragging buttons and Labels onto the MainMenu View and i have nothing inside my AppDelegate.h and .m
Im really new to objective c and cocoa so i was wondering if anyone could give me an in depth explanation on how to use that font panel to edit the font in a Label or a Text Field.


text:
Q: Having an error with python and can't figure it out : TypeError: can't multiply sequence by non-int of type 'float' line 28, in calculateSalesTax
    salesTax = totalPrices * 0.07;
TypeError: can't multiply sequence by non-int of type 'float'
def calculateSalesTax(salesTax, totalPrices):
    salesTax = totalPrices * 0.07;
    return salesTax, totalPrices;

totalPrices is the sum of many prices:
def getPrices(price1, price2, price3, price4, price5):
    price1 = float(input("<ENTER THE PRICECE FOR ITEM # 01> "));
    price2 = float(input("<ENTER THE PRICE FOR ITEM # 02> "));
    price3 = float(input("<ENTER THE PRICE FOR ITEM # 03> "));
    price4 = float(input("<ENTER THE PRICE FOR ITEM # 04> "));
    price5 = float(input("<ENTER THE PRICE FOR ITEM # 05> "));
    return price1, price2, price3, price4, price5;

def calculateTotalPrices(totalPrices, price1, price2, price3, price4, price5):
    totalPrices =(price1 + price2 + price3 + price4 + price5);
    return totalPrices, price1, price2, price3, price4, price5;

I am new with python and it gives me this error please help me.

A: Perhaps this is what you meant
>>> prices=(1.35, 34.57, 49.89)
>>> taxes = [p * 0.07 for p in prices]
>>> taxes
[0.094500000000000015, 2.4199000000000002, 3.4923000000000002]


text:
Q: Showing the contents of a cell array in MATLAB I am trying to extract an array in MATLAB such as below:

Before this i used regular expressions to split particular delimiters among the columns.
Code : datasplitnew = regexp(replacefinal, '\,', 'split');
In the end, i would like to show the contents of that cell array accordingly among its respective columns in that same cell array. I know that i can just click the cell array that i would like to view and see the contents, but i don't want that.
Some people have been telling me to use, {:} to split the cell array, but it only seems to split the first row in the column instead of all of them.
Please advise.

A: You can't simply concat them as rows have different number of cells.
The ones that have the same number you could join with vertcat.
But in the end the only solution I can think of is to construct the table cell by cell. but that's not hard to do yourself.

A: You could use char(datasplitnew) to get one big character array.