text:
Q: How does the Electrical Grid React to Large Changes in Supply or Demand? Background
I'm performing some research for a software project that monitors power generation and consumption for a large fictional spaceship. My rationale is I'd like to first understand how real-world power generation works before starting to make the app feel as authentic as possible when using it.
Basis
My question stems from my current understanding of how the electrical grid works. Energy is generated through whatever mechanism (steam/mechanical, photo-voltaic) and is then stepped up via a HV substation for long distance transmission. Large factories (Steel Mills, Microchip Plants, etc.) may have a substation dedicated to them for their operations. Otherwise, a substation steps HV down to MV for smaller scale distribution (factories, large office buildings, etc.). This is repeated again for LV, for delivery to homes and small businesses. It's a simple model, albeit misleading because it presents a linear chain of flow from source to load, with a single source generator of power. In the real world, there are multiple stations that are running to meet the demand, and they adapt as the demand changes over time.
Question
Suppose a large event such as a generator station unexpectedly shut down. What equipment would be involved in "rerouting" power to minimize the possibility of blackouts? Or, if a rolling blackout was temporarily implemented because of high demand, what equipment or process would be involved?
Related Questions

*

*For coordinating multiple generator stations: How are multiple power sources synchronized in a grid that uses a distribution ring?

*For transient heavy loads: What is the effect of heavy loads on the electrical grid?

*Modelling of Electric Power Grid

A:
What equipment would be involved in "rerouting" power to minimize the
  possibility of blackouts?

Transmission switching stations re-organize things when there are problems with generators or section of grid: -

As you can see, every generator connects to the (national) grid via a TS. This wiki page should help. Pictures taken from here
or here if not a Quora member

A:
Suppose a large event such as a generator station unexpectedly shut down. What equipment would be involved in "rerouting" power to minimize the possibility of blackouts?

Power grids are engineered to withstand the failure of any one component.
For generator failures: There must be enough spare generation running to cover the loss of the largest generator. This is called "spinning reserve". Note that having spare generators sitting still doesn't help you. A cold generator takes minutes to hours to start, but the spare generation must take over from the failed generator in a period of seconds.
Note: This means that generation companies get paid for keeping generators turning over, but producing no power. People wonder why they are getting paid for producing nothing! The generators aren't producing any power, but they are providing an essential service.
It's also important that the spinning reserve generators be able to react quickly to changing load. "Transient response" to "load swings" are the key words to look for. Big coal / nuclear power plants are no good for this, as they respond slowly to control inputs. Gas turbines are much better at taking swings.

For transmission infrastructure failures i.e. transmission lines, substations - I think Andy's answer has that covered.
We do engineer transmission systems to have at least N-1 redundancy, so we can lose any one component and still keep most of the system running.
I don't have any experience with HV transmission systems, so I will refrain from saying anything more.

Or, if a rolling blackout was temporarily implemented because of high demand, what equipment or process would be involved?

There are two ways to manage excessive load.
The traditional system reacts to excessive load by turning off supply to entire load centres, i.e. an entire substation, or an entire feeder. This is a "load shedding system".
Loads would be turned off in priority order. You would turn off a factory before you turned off a hospital. You keep turning things off until the load re-balances with the available generation.
The other way is to pro-actively manage the load, i.e. using ripple control signals. This turns off specific customer equipment, such as air-conditioners, at times of high demand. This won't help in severe power shortages, so a load-shedding system is still required.

A: The actual piece of equipment in a transmisson substation that "switches" electricity around is the Quadrature Booster, otherwise known as the Phase Angle Regulating Transformer. Essentialy, by changing the phase of power with respect to the source, you change the resistance to energy flow, thereby regulating the flow of power through a particular segment of the grid.


text:
Q: I am not able to connect to OPC DA server remotely from client machine I am not able to connect to OPC DA server hosted on a remote server(AZURE VM) from a client machine.
Initially i was getting the "CoCreateIstance excdeption: class not registered" that i resolved by installing the OPC Core Components on the client machine.
Now i am getting the below error while trying to connect to OPCDA server from .NET Service:
Could not connect to server.
Matrikon.OPC.Simulation.1
**************** Exception Details ****************
 Exception occurrred at : 7/21/2020 7:43:47 PM
 Source :  OpcNetApi
 **Message :  E_NETWORK_ERROR**
Could not connect to server.
Matrikon.OPC.Simulation.1
 Type :  Opc.ConnectFailedException
 Inner Exception :
 Stack Trace :     at Opc.Server.Connect(URL url, ConnectData connectData)
   at Opc.Da.Server.Connect(URL url, ConnectData connectData)
   at Opc.Server.Connect()

I tried to modify the DCOM settings at server side but it didn't helped.
Observed one case that when the Matrikon OPC Simulation is installed on client machine  in that case i am able to connect to the remote OPCDA server from client machine.
Can someone guide me with that Why we are able to connect with OPCDA remote server When the server is installed on client machine as well.
Is there any particular settings that happen during the Matrikon server installation that is making the OPCDA remote connection successful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opensea not picking up metadata for ERC-1155 contract I have an ERC-1155 smart contract deployed to the Goerli testnet. My contract inherits from the OpenZeppelin ERC1155 contract and uses its uri function. The URI I initiated the contract with is of the format https://token-cdn-domain/{id}.json as explained here. I have one minted item with id=1 and the metadata file for this item is served from https://token-cdn-domain/0000000000000000000000000000000000000000000000000000000000000001.json.
Opensea does not pick up the metadata.
When I call the opensea validate endpoint I get the following:
{
    "valid": true,
    "token_uri": null,
    "errors": []
}

A: The problem was apparently using an Infura URL for my metadata (https://...infura.io/ipfs/...). When I changed my metadata to have the ipfs link directly (https://ipfs.io/ipfs/...) it solved the problem.
I'm guessing the reason it wasn't working was the Infura URL redirects the request and Opensea apparently doesn't know how to handle this redirect.


text:
Q: ng hide image if the brackes is populated I have this bit of code, Basically when the image is uploaded the logoFileUrl will be populated, I'm wanting the placeholder to be removed if its populated.
Heres my bit of code

Whats actually happening is the placeholder image stays and the second uploaded image is shown also
Heres the changes i made
i placed this in my controller
eventModule.config(function ($stateProvider, $urlRouterProvider, flowFactoryProvider) {

    //$locationProvider.html5Mode(true).hashPrefix('!');
 logoFileUrl = '';
    $stateProvider

and i placed this in my html

A: Try this:
At the beginning of your controller, explicitly set logoFileUrl to empty:
 yourApp.controller('yourController', function...){
    logoFileUrl = '';
    ...
 }

Then, populate it after uploading.
In your html, use ng-if:


text:
Q: Models/View in Different Files I just tried to adopt backbone.js to my project with the todo example. In my app.js file I try to instantiate my views/models/collections etc. but I try to I get the error msg: app is not defined in TodoList.
HTML:
<head>

<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js/backbone-min.js"></script>
<script type="text/javascript" src="js/backbone-localstorage.js"></script>

<script type="text/javascript" src="js/models/models.js"></script>
<script type="text/javascript" src="js/collections/collections.js"></script>
<script type="text/javascript" src="js/views/views.js"></script>
<script type="text/javascript" src="js/views/app.js"></script>

<script type="text/javascript" src="js/app.js"></script>

app.js(root for my application):
    var app = {
    models:{},
    collections:{},
    views:{}
};

    jQuery(function($) {

        var Todos = new app.collections.TodoList;
        var test = new Todo;
        var test2 = new TodoView;
        var appView = new AppView({});

    });

collections.js:
app.collections.TodoList = Backbone.Collection.extend({

model: Todo,

localStorage: new Store("todos"),

done: function() {
    return this.filter(function(todo) {
        return todo.get('done');
    });
},

remaining: function() {
    return this.without.apply(this, this.done());
},
nextOrder: function() {
    if (!this.length) return 1;
    return this.last().get('order') + 1;
},

comparator: function(todo) {
    return todo.get('order');
}

});

A: You're trying to use a namespace before it's ready. Two options. First, have 'app.js' first but take out initialization code and put that into a 'bootstrap.js' that's loaded absolute last. Second option, and the one that I generally lothe, define your namespaces that you need in the file if they aren't already there. For example
var app = app || {};
app.collection = app.collection || {};

Basically, the code is loading in one by one. When you say namespace.subspace, the code expects that namespace has already been defined as something - generally an object in most cases that I've seen. Without that base piece the code will just flatline - it'll assume you're trying to do the equivalent of building a castle starting with the roof.


text:
Q: Tablesorter plugin not working on loading html code for table When I try to use the tablesorter plugin with direct HTML it works.
For direct I mean:
 echo '

                first name
                last name
                age
                total
                discount
                date

                peter
                parker
                28
                $9.99
                20%
                jul 6, 2006 8:14 am

                john
                hood
                33
                $19.99
                25%
                dec 10, 2002 5:14 am

                clark
                kent
                18
                $15.89
                44%
                jan 12, 2003 11:14 am

                bruce
                almighty
                45
                $153.19
                44%
                jan 18, 2001 9:12 am

                bruce
                evans
                22
                $13.19
                11%
                jan 18, 2007 9:12 am

';

But when this code is loaded with JavaScript from a navigation code:
$(".menu_user").live('click', function() {
    $('.menu_user_sel').removeClass('menu_user_sel').addClass('menu_user');
    $(this).removeClass('menu_user').addClass('menu_user_sel');
    var goPage = $(this).attr('id');
    $('#content').load(goPage + ".php");

});

Which loads this php code:
echo '
';
echo '
';
echo '<input type="text" name="cerca" id="cerca"/>   ';
echo '
';
echo '
';
echo '<input id="nuovoUtente" type="button" value="">';
echo '
';
echo '
';

echo '
';
stampaTabellaProgetto();
echo '
';

Where can I change stampaTabellaProgetto() for the HTML of the table it do nothing. I have the table with the right style etc but no arrow for sorting and no error in console.
the $(".tablesorter").tablesorter({
        theme : 'blue'
    });
Is just after the document ready.


text:
Q: Failed to execute 'fetch' on 'WorkerGlobalScope' I trying to fetch data from the server inside of a web worker. But in dev tools every time I got the same error.
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Failed to parse URL from /api/books

I saw  this answer about service workers, but it's not working for me.
WebWorker file code!
// data-handling.web-worker.js

const workercode = () => {
  onmessage = async e => {
    const res = await fetch('/api/books');

    postMessage(res);
  }
};

let code = workercode.toString();
code = code.substring(code.indexOf('{')+1, code.lastIndexOf('}'));

const blob = new Blob([code], {type: 'application/javascript'});
const worker_script = URL.createObjectURL(blob);

export default worker_script;

Imported in React component.
import data_handling_worker from "./data-handling.web-worker";
const dataHandlingWorker = new Worker(data_handling_worker);

Running and posting messages inside of the hooks!
const [searchQuery, setSearchQuery] = useState('');
const [booksList, setBooksList] = useState([]);

useEffect(() => {
  dataHandlingWorker.postMessage(searchQuery);
}, [searchQuery]);

useEffect(() => {
  dataHandlingWorker.onmessage = (m) => {
    setBooksList(m.data);
  };
}, []);

A: Workers created from a blob:// URI have their baseURI set to set to that blob:// URI.
To fetch a relative URL the browser first has to build an absolute URI from the current realm's baseURI.
So in your case, the browser will try to generate an absolute URL from /api/books using blob:[origin]/[UUID] as the base. This is what throws:

const worker_script = `
  postMessage( { baseURI: self.location.href } );
  try {
    const absolute = new URL( "api/books", self.location.href );
  }
  catch( err ) {
    postMessage( { err: err.toString() } );
  }
`;
const worker_url = URL.createObjectURL( new Blob( [ worker_script ] ) );
const worker = new Worker( worker_url );
worker.onmessage = (evt) => console.log( evt.data );

To workaround that issue you have two options:

*

*Use an absolute URL. This way you won't face that problem.

*Pass the baseURI from your main thread to your Worker's script. This way you will be able to create the absolute URL yourself using the URL constructor.
The first option is really simple, so I guess you don't need an example.
For the second, since we can't host relative files in StackSnippets, I had to host it in this plunker.
Here is the code:
const worker_script = `
  onmessage = (evt) => {
    const base = evt.data;
    const absolute = new URL( "api/books", base );
    fetch( absolute )
      .then( (resp) => resp.text() )
      .then( (txt) => postMessage( txt ) )
      .catch( console.error );
  };
`;
const worker_url = URL.createObjectURL( new Blob( [ worker_script ] ) );
const worker = new Worker( worker_url );
worker.onmessage = (evt) => document.body.append( evt.data );
// pass the main thread's baseURI
worker.postMessage( document.baseURI );

A: My problem was that I wanted to make a conditional response depending on the cache.

I was using the request object and paying attention to this post and using the absolute url solved the problem.
const respuesta = caches.match('codeGalery/cat.jpg')
.then((response) =>
{
  if (response !== undefined)
  {
    return response;
  }
  //wrong
  //return fetch(FetchEvent.request, {credentials:"same-origin"});
  //correct
  return fetch(FetchEvent.request.url, {credentials:"same-origin"});

});

A:

const worker_script = `
  postMessage( { baseURI: self.location.href } );
  try {
    const absolute = new URL( "api/books", self.location.href );
  }
  catch( err ) {
    postMessage( { err: err.toString() } );
  }
`;
const worker_url = URL.createObjectURL( new Blob( [ worker_script ] ) );
const worker = new Worker( worker_url );
worker.onmessage = (evt) => console.log( evt.data );


text:
Q: Run a script after maven install I have a Maven project and after I install the project I need to run a script. I want to automize this process. My guess is that by adding something in the pom file I could automize this, but so far i haven't found how to run a script after installation. I only found how to run a script before the maven project has finised installing.
So, how can I run a script after a Maven project as finished installing?

A: Use the http://www.mojohaus.org/exec-maven-plugin/ exec-maven-plugin, in conjunction with an "executions" configuration block that specifies the installation phase. Make sure it is after your maven-install-plugin as plugins are ran in order (within the same phase)
(in build/plugins)
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
  </plugin>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
      <execution>
        <phase>install</phase>
        <goals>
           <goal>exec</goal>
        </goals>
        <configuration>
          <executable>do-something.sh</executable>
          <workingDirectory>/some/dir</workingDirectory>
          <arguments>
             <argument>--debug</argument>
             <argument>with_great_effect</argument>
          </arguments>
        </configuration>
      </execution>
    </executions>
  </plugin>

A: For a purely maven-driven approach, the answer you're looking for is the exec goal of exec-maven-plugin, and this answer applies: https://stackoverflow.com/a/2008258/3403663
EDIT: OP indicates the above doesn't work for him.
Alternative approach: I just tried the following in my own project, and it executes ls at the very end of the install phase, after artifacts have been deployed.
mvn clean install exec:exec -Dexec.executable="/bin/ls" -Dexec.args="/etc"
Otherwise, you could always just wrap the whole thing in a script:
#!/bin/bash

set -o errexit

mvn clean install
<your other commands here>

A: Why can't you do something like this? This will go after the normal maven install phase.
EDIT: If you add the maven-install-plugin before it, maven will run each in the order they are in the pom.
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
  </plugin>
  <plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
      <execution>
        <phase>install</phase>
        <configuration>
          <tasks>
            <exec
              dir="${project.basedir}"
              executable="${project.basedir}/src/main/sh/do-something.sh"
              failonerror="true">
              <arg line="arg1 arg2 arg3 arg4" />
            </exec>
          </tasks>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Source: maven-antrun-plugin

A: You can chain the commands
$ mvn clean install && myscript.sh || echo "error."


text:
Q: python Force git hook server side output on same line in realtime git hooks server side output only transmits on a newline. I want to configure a custom task and print real-time output on the same line. How can I achieve that? I tried sys.stdout.flush but it transmits everything once complete. It does work in real-time if I add a newline.
I want something like

Step A)Started......Completed

with each '.' appended after a given time.
My current code looks like the following and it outputs only when the method is completed.
import sys, time, os

def print_realtime():
    sys.stdout.write('Started.')
    sys.stdout.flush()
    time.sleep(1)
    for i in range(1, 15):
        sys.stdout.write('.')
        sys.stdout.flush()
        time.sleep(0.5)

if __name__ == "__main__":
    print_realtime()

However, it works in realtime if I append '\n' like:
sys.stdout.write('.\n')

A: The problem comes down to the fact that Git itself does not print accumulated remote: text until the remote sends either a newline or carriage return.
Hence, if we change your inner loop to read:
for i in range(1, 15):
    sys.stdout.write('.' * i + '\r')
    sys.stdout.flush()
    time.sleep(0.5)

you will see the effect you desire.
Note that the \r moves the print position back to just after the word remote:, so we must repeat what we have printed so far (hence the need to print first one ., then two .s, then three, and so on).


text:
Q: Iseka/tensei manga with boy prince and elf assassin maid MC is a baby boy prince and has a girl guide telling him he will be assassinated on his nth bday. The girl guide teaches him magic etc. and his maid as he grows. His mom and him live off royalty grounds and he finds a secret room where it has records of assassinations. His elf maid is the one who will kill him. Also, he ran into a forest and met a wolf.

A: I believe this is Fuguushoku to Baka ni Saremashita ga, Jissai wa Sorehodo Waruku Arimasen?, also known as People Looked Down on Me for Having a Crummy Job but It Really Isn't All That Bad?
The main character is reincarnated as the son of a king, and is immediately banished to an estate in the middle of a dangerous forest with his mother.  They are placed there since the job/class he was assigned at birth was considered useless. The angel/guide who helped him reincarnate teaches him the basics of the world, including some magic. There are a few servants at the estate, including an elf maid.
After a few years, he uses his skills to sneak into a locked room.  Inside is a single bookshelf of books, which contain records of people who have been assassinated.  At the end of one of the books, he finds his name, along with his mother's.  The date and method of assassination were left blank.  Talking with the guide, he decides to escape around his 10th birthday, which is when another son will be born to the king.
A day or so before his 10th birthday, he overhears the elf maid being given the order to kill the target. So, he runs off into the forest, where he befriends a wolf.


text:
Q: Methods .endswith/.removesuffix) not removing suffixes I am trying to remove suffixes but for some reason, it is not working.
Code is:
# Stemming
    suffix_list = ['-ed', '-ing', '-s']

    for word in range(len(output)):  # loop
        # range returns the sequence, len checks the lenght
        for suffix in range(len(suffix_list)):
            # .endswith checks x in both
            if output[word].endswith(suffix_list[suffix]):
                # .removesuffix removes from output if in suffix_list
                print(output[word].removesuffix(suffix_list[suffix]))

    return output

print(textPreprocessing("I'm gathering herbs."))
print(textPreprocessing("When life gives you lemons, make lemonade"))

Outcome is:
gather
herb
['im', 'gathering', 'herbs']
give
lemon
['life', 'gives', 'you', 'lemons', 'make', 'lemonade']

Where it should be:
['im', 'gather', 'herbs']
['life', 'give', 'you', 'lemon', 'make', 'lemonade']

Any help?
I feel like I am missing something obvious...

A: output[word] = output[word].removesuffix(suffix_list[suffix])

A: This will work:-
str_sample = "When life gives you lemons make lemonade"
suffixes, words = ["s"], str_sample.split()

for i in range(len(suffixes)):
    for j in range(len(words)):
        if words[j].endswith(suffixes[i]):
            words[j] = words[j].replace(f"{suffixes[i]}", "")

print(words)

It can be compressed to a List Comprehension as :-
str_sample = "When life gives you lemons make lemonade"
suffixes, words = ["s"], str_sample.split()

res = [words[j].replace(f"{suffixes[i]}", "") if words[j].endswith(suffixes[i]) else words[j] for j in range(len(words)) for i in range(len(suffixes))]

print(words)


text:
Q: Can I use lighten css property in ngStyle? I'm trying to use lighten property in ngStyle but it doesn't work.
I have color variable in component and I want to use it like this:

Can someone gives some idea?

A: thre're no "lighten" function in css -it is about less or Sass-. In internet there are javascripts function to make it, eg. this in css.trick
UPDATE Important! (change the function)
  /**Credits to: https://css-tricks.com/snippets/javascript/lighten-darken-color/ */
  //amt from 0 to 100
  lightenDarkenColor(col, amt) {

    amt=256-Math.floor(amt*5.12)
    const  usePound = col[0]=="#";
    if (usePound)
        col = col.slice(1);

    const num = parseInt(col,16);

    const rr=(num >> 16) + amt;
    const  bb = ((num >> 8) & 0x00FF) + amt;
    const  gg = (num & 0x0000FF) + amt;

    const r=rr>255?255:rr<0?0:rr;
    const b=bb>255?255:bb<0?0:bb;
    const g=gg>255?255:gg<0?0:gg;

    if ((g | (b << 8) | (r << 16))==0)
        return "#000000";

    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

  }

Use

hello word

hello word

see demo in stackblitz

A: The above (answered) function sometimes return white and then I found that solution:
hexToRgbNew(hex: any, opacity: any): string {
    let h = hex.replace('#', '');
    h =  h.match(new RegExp('(.{' + h.length / 3 + '})', 'g'));

    for (let i = 0;  i < h.length; i++) {
        h[i] = parseInt(h[i].length === 1 ? h[i] + h[i] : h[i], 16);
    }

    if (typeof opacity !== 'undefined') { h.push(opacity); }

    return 'rgba(' + h.join(',') + ')';
}


text:
Q: Changing 9x9 matrix to sudoku-like cubes I have 9x9 matrix in numpy. I need fast method to change it into sudoku-like 9x9 array with cubes (also I need method to reverse this operation). I attach conceptual drawing.
conceptual drawing

A: Reshape, permute axes and reshape -
In [43]: a
Out[43]:
array([[0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8]])

In [44]: a.reshape(3,3,3,3).swapaxes(1,2).reshape(9,9)
Out[44]:
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8]])

On a generic shaped array, it would be -
m,n = a.shape
H,W = (3,3) # block size on sudoku
out = a.reshape(m//H,H,n//W,W).swapaxes(1,2).reshape(m,n)

More info on intuition behind nd-to-nd array transformation.

If you want to start from scratch, use kron on a ranged-array -
In [65]: np.kron(np.ones((3,3),dtype=int),np.arange(9).reshape(3,3))
Out[65]:
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8]])


text:
Q: How to get axios to work with expo (react native) I am trying to call the local weather from openweathermap in my react native app. I have tested the url in both the browser and the code in a plain react project and it works. However in react native it does not.
Here is my code:
function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{...apikey...}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = useCallback(async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(2)}&appid=${API_KEY}`;

        console.log("my provided url is set to:", url);

        const response = await axios.get(url);
        if (response.data) {
            setTemperature(response.data.main.temp);
        }
    }, [latitude, longitude])

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {
        getTemperature()
            .catch(console.error);

    }, [getTemperature])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"}/>
                <OverviewContainer title="Time on app" value={secondsToHms(count)}/>
            </View>
        </View>
    );
}

Originally I thought it may be an issue with my code but corrected it to make sure it worked. I have read in other questions that in expo you need to add your ip and port to the url. However upon trying this I still couldnt get it to work. Any help would be great!


text:
Q: Different metrics for GridSearch and Keras: which one is actually returned During GridSearchCV/RandomizedSearchCV we have different options to use for scoring, 'accuracy' being the most popular. However, in the case of unbalanced classes, such metrics as "f1_macro" are more appropriate. When we work with Keras, we can choose any metric in the compile line, however, no "f1_macro" or "f1_micro" is available. In case of using, let's say, "f1_macro" in GridSearch and "accuracy" in .compile, what score is actually returned after .best_score_ is typed? Do we have to use the same metrics in both create_model and GridSearch or we can safely omit metrics in compile?
Thank you.


text:
Q: Does Dapper have a limit to the size of the Query's SELECT statement? I'm using Dapper to do a dynamic Query on a SQL string that is quite large.  If I paste it into Word, I get the following stats:

*

*Words: 15,433

*Characters (with spaces): 103,366

*Lines:  1,637

The problem is that when it executes nothing fails but I get an empty IEnumerable result.
So the question is does Dapper have a limit on this size?  Or is it failing quietly?

A: OK, there is no problem with Dapper, just me!  I have two versions of the database and one has data, the other doesn't.  I was running against the dataless version.


text:
Q: How do I create a method that capitalizes the first letter of a string in java? what I'm trying to do is write a method that has one argument and returns a new string that capitalises that string and returns in its parameter.
this is my code so far:
 public void input(){

    this.printmessage("Dillon", "Francis", "chimes", "chimes from hudson mohawke", "2",             "$69.00", "$420.00", "$1337.00");
}

public void printmessage(String firstName, String lastname, String product, String company, String number, String retail, String price, String saving){

    UI.println("text " + firstName + ",");

    UI.println(text + " " + product + "s text, text text text text -");

    UI.println(" ");
}

What I want to do is capitalise the product parameter (chimes) and then return into into the printMessage capitalized if it is used at the beginning of a sentence.
Will something like this work?
 public String capitalise(String product){

    return Character.toUpperCase(product.charAt(0)) + product.substring(1);

}

I'm really stuck and would love some help.
Thanks.
I've tried this
 String pls = (product + " example");
    if ( pls.startsWith(product) ) {
        product = capitalise(product);
   }
   UI.println(pls);

but it doesnt print out the capitalised version.

A: change this line :
UI.println(text + " " + product + "s text, text text text text -");
to:
UI.println(text + " " + capitalize(product) + "s text, text text text text -");
But your code needs a bit more structuring. Focus on even indentation. And if you need the capitalized product later on, you'd better save it before you use it, like
...
product = capitalize(product);
UI.println(text + " " + product + "s text, text text text text -");
...

EDIT:
For this I'm assuming the line is contained in a String called line.
First check if the line begins with product. Then capitalize it.
...
String line = text + " " + product + "s text, text text text text -";
line = line.trim(); // removes whitespaces.
if ( line.startsWith( product ) ) {
    product = capitalize ( product ); //or whatever.
}
UI.println(line);
...


text:
Q: How do I decode HTML entities in Swift? I am pulling a JSON file from a site and one of the strings received is:
The Weeknd 'King Of The Fall' [Video Premiere] | @TheWeeknd | #SoPhi

How can I convert things like &#8216 into the correct characters?
I've made a Xcode Playground to demonstrate it:
import UIKit

var error: NSError?
let blogUrl: NSURL = NSURL.URLWithString("http://sophisticatedignorance.net/api/get_recent_summary/")
let jsonData = NSData(contentsOfURL: blogUrl)

let dataDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

var a = dataDictionary["posts"] as NSArray

println(a[0]["title"])

A: Swift 4 Version
extension String {

    init(htmlEncodedString: String) {
        self.init()
        guard let encodedData = htmlEncodedString.data(using: .utf8) else {
            self = htmlEncodedString
            return
        }

        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            self = attributedString.string
        }
        catch {
            print("Error: \(error)")
            self = htmlEncodedString
        }
    }
}

A: extension String{
    func decodeEnt() -> String{
        let encodedData = self.dataUsingEncoding(NSUTF8StringEncoding)!
        let attributedOptions : [String: AnyObject] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
            NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
        ]
        let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!

        return attributedString.string
    }
}

let encodedString = "The Weeknd 'King Of The Fall'"

let foo = encodedString.decodeEnt() /* The Weeknd 'King Of The Fall' */

A: Swift 4:
The total solution that finally worked for me with HTML code and newline characters and single quotes
extension String {
    var htmlDecoded: String {
        let decoded = try? NSAttributedString(data: Data(utf8), options: [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
            ], documentAttributes: nil).string

        return decoded ?? self
    }
}

Usage:
let yourStringEncoded = yourStringWithHtmlcode.htmlDecoded

I then had to apply some more filters to get rid of single quotes (for example, don't, hasn't, It's, etc.), and new line characters like \n:
var yourNewString = String(yourStringEncoded.filter { !"\n\t\r".contains($0) })
yourNewString = yourNewString.replacingOccurrences(of: "\'", with: "", options: NSString.CompareOptions.literal, range: nil)

A: This would be my approach. You could add the entities dictionary from https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555 Michael Waterfall mentions.
extension String {
    func htmlDecoded()->String {

        guard (self != "") else { return self }

        var newStr = self

        let entities = [
            """    : "\"",
            "&"     : "&",
            "'"    : "'",
            "<"      : "<",
            ">"      : ">",
        ]

        for (name,value) in entities {
            newStr = newStr.stringByReplacingOccurrencesOfString(name, withString: value)
        }
        return newStr
    }
}

Examples used:
let encoded = "this is so "good""
let decoded = encoded.htmlDecoded() // "this is so "good""

OR
let encoded = "this is so "good"".htmlDecoded() // "this is so "good""

A: Elegant Swift 4 Solution
If you want a string,
myString = String(htmlString: encodedString)

add this extension to your project:
extension String {

    init(htmlString: String) {
        self.init()
        guard let encodedData = htmlString.data(using: .utf8) else {
            self = htmlString
            return
        }

        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
           .documentType: NSAttributedString.DocumentType.html,
           .characterEncoding: String.Encoding.utf8.rawValue
        ]

        do {
            let attributedString = try NSAttributedString(data: encodedData,
                                                          options: attributedOptions,
                                                          documentAttributes: nil)
            self = attributedString.string
        } catch {
            print("Error: \(error.localizedDescription)")
            self = htmlString
        }
    }
}

If you want an NSAttributedString with bold, italic, links, etc.,
textField.attributedText = try? NSAttributedString(htmlString: encodedString)

add this extension to your project:
extension NSAttributedString {

    convenience init(htmlString html: String) throws {
        try self.init(data: Data(html.utf8), options: [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
            ], documentAttributes: nil)
    }

}

A: Swift 4

*

*String extension computed variable

*Without extra guard, do, catch, etc...

*Returns the original strings if decoding fails

extension String {
    var htmlDecoded: String {
        let decoded = try? NSAttributedString(data: Data(utf8), options: [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ], documentAttributes: nil).string

        return decoded ?? self
    }
}

A: Swift 5.1 Version
import UIKit

extension String {

    init(htmlEncodedString: String) {
        self.init()
        guard let encodedData = htmlEncodedString.data(using: .utf8) else {
            self = htmlEncodedString
            return
        }

        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            self = attributedString.string
        }
        catch {
            print("Error: \(error)")
            self = htmlEncodedString
        }
    }
}

Also, if you want to extract date, images, metadata, title and description, you can use my pod named:
.
Readability kit

A: Swift 3 version of @akashivskyy's extension,
extension String {
    init(htmlEncodedString: String) {
        self.init()
        guard let encodedData = htmlEncodedString.data(using: .utf8) else {
            self = htmlEncodedString
            return
        }

        let attributedOptions: [String : Any] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
        ]

        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            self = attributedString.string
        } catch {
            print("Error: \(error)")
            self = htmlEncodedString
        }
    }
}

A: Computed var version of @yishus' answer
public extension String {
    /// Decodes string with HTML encoding.
    var htmlDecoded: String {
        guard let encodedData = self.data(using: .utf8) else { return self }

        let attributedOptions: [String : Any] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]

        do {
            let attributedString = try NSAttributedString(data: encodedData,
                                                          options: attributedOptions,
                                                          documentAttributes: nil)
            return attributedString.string
        } catch {
            print("Error: \(error)")
            return self
        }
    }
}

A: Swift 4
I really like the solution using documentAttributes. However, it is may too slow for parsing files and/or usage in table view cells. I can't believe that Apple does not provide a decent solution for this.
As a workaround, I found this String Extension on GitHub which works perfectly and is fast for decoding.
So for situations in which the given answer is to slow, see the solution suggest in this link:
https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555
Note: it does not parse HTML tags.

A: This answer was last revised for Swift 5.2 and iOS 13.4 SDK.

There's no straightforward way to do that, but you can use NSAttributedString magic to make this process as painless as possible (be warned that this method will strip all HTML tags as well).
Remember to initialize NSAttributedString from main thread only. It uses WebKit to parse HTML underneath, thus the requirement.
// This is a[0]["title"] in your case
let htmlEncodedString = "The Weeknd ‘King Of The Fall’"

guard let data = htmlEncodedString.data(using: .utf8) else {
    return
}

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
]

guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
    return
}

// The Weeknd 'King Of The Fall'
let decodedString = attributedString.string

extension String {

    init?(htmlEncodedString: String) {

        guard let data = htmlEncodedString.data(using: .utf8) else {
            return nil
        }

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
            return nil
        }

        self.init(attributedString.string)

    }

}

let encodedString = "The Weeknd ‘King Of The Fall’"
let decodedString = String(htmlEncodedString: encodedString)

A: Swift 2 version of  @akashivskyy's extension,
 extension String {
     init(htmlEncodedString: String) {
         if let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding){
             let attributedOptions : [String: AnyObject] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
            NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
        ]

             do{
                 if let attributedString:NSAttributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil){
                     self.init(attributedString.string)
                 }else{
                     print("error")
                     self.init(htmlEncodedString)     //Returning actual string if there is an error
                 }
             }catch{
                 print("error: \(error)")
                 self.init(htmlEncodedString)     //Returning actual string if there is an error
             }

         }else{
             self.init(htmlEncodedString)     //Returning actual string if there is an error
         }
     }
 }

A: @akashivskyy's answer is great and demonstrates how to utilize NSAttributedString to decode HTML entities. One possible disadvantage
 (as he stated) is that all HTML markup is removed as well, so
 4 < 5 & 3 > 2

becomes
4 < 5 & 3 > 2

On OS X there is CFXMLCreateStringByUnescapingEntities() which does the job:
let encoded = " 4 < 5 & 3 > 2 . Price: 12 €.  @ "
let decoded = CFXMLCreateStringByUnescapingEntities(nil, encoded, nil) as String
println(decoded)
//  4 < 5 & 3 > 2 . Price: 12 €.  @

but this is not available on iOS.
Here is a pure Swift implementation. It decodes character entities
references like < using a dictionary, and all numeric character
entities like &#64 or &#x20ac. (Note that I did not list all
252 HTML entities explicitly.)
Swift 4:
// Mapping from XML/HTML character entity reference to character
// From http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
private let characterEntities : [ Substring : Character ] = [
    // XML predefined entities:
    """    : "\"",
    "&"     : "&",
    "'"    : "'",
    "<"      : "<",
    ">"      : ">",

    // HTML character entity references:
    " "    : "\u{00a0}",
    // ...
    "♦"   : "♦",
]

extension String {

    /// Returns a new string made by replacing in the `String`
    /// all HTML character entity references with the corresponding
    /// character.
    var stringByDecodingHTMLEntities : String {

        // ===== Utility functions =====

        // Convert the number in the string to the corresponding
        // Unicode character, e.g.
        //    decodeNumeric("64", 10)   --> "@"
        //    decodeNumeric("20ac", 16) --> "€"
        func decodeNumeric(_ string : Substring, base : Int) -> Character? {
            guard let code = UInt32(string, radix: base),
                let uniScalar = UnicodeScalar(code) else { return nil }
            return Character(uniScalar)
        }

        // Decode the HTML character entity to the corresponding
        // Unicode character, return `nil` for invalid input.
        //     decode("@")    --> "@"
        //     decode("€") --> "€"
        //     decode("<")     --> "<"
        //     decode("&foo;")    --> nil
        func decode(_ entity : Substring) -> Character? {

            if entity.hasPrefix("&#x") || entity.hasPrefix("&#X") {
                return decodeNumeric(entity.dropFirst(3).dropLast(), base: 16)
            } else if entity.hasPrefix("&#") {
                return decodeNumeric(entity.dropFirst(2).dropLast(), base: 10)
            } else {
                return characterEntities[entity]
            }
        }

        // ===== Method starts here =====

        var result = ""
        var position = startIndex

        // Find the next '&' and copy the characters preceding it to `result`:
        while let ampRange = self[position...].range(of: "&") {
            result.append(contentsOf: self[position ..< ampRange.lowerBound])
            position = ampRange.lowerBound

            // Find the next ';' and copy everything from '&' to ';' into `entity`
            guard let semiRange = self[position...].range(of: ";") else {
                // No matching ';'.
                break
            }
            let entity = self[position ..< semiRange.upperBound]
            position = semiRange.upperBound

            if let decoded = decode(entity) {
                // Replace by decoded character:
                result.append(decoded)
            } else {
                // Invalid entity, copy verbatim:
                result.append(contentsOf: entity)
            }
        }
        // Copy remaining characters to `result`:
        result.append(contentsOf: self[position...])
        return result
    }
}

Example:
let encoded = " 4 < 5 & 3 > 2 . Price: 12 €.  @ "
let decoded = encoded.stringByDecodingHTMLEntities
print(decoded)
//  4 < 5 & 3 > 2 . Price: 12 €.  @

Swift 3:
// Mapping from XML/HTML character entity reference to character
// From http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
private let characterEntities : [ String : Character ] = [
    // XML predefined entities:
    """    : "\"",
    "&"     : "&",
    "'"    : "'",
    "<"      : "<",
    ">"      : ">",

    // HTML character entity references:
    " "    : "\u{00a0}",
    // ...
    "♦"   : "♦",
]

extension String {

    /// Returns a new string made by replacing in the `String`
    /// all HTML character entity references with the corresponding
    /// character.
    var stringByDecodingHTMLEntities : String {

        // ===== Utility functions =====

        // Convert the number in the string to the corresponding
        // Unicode character, e.g.
        //    decodeNumeric("64", 10)   --> "@"
        //    decodeNumeric("20ac", 16) --> "€"
        func decodeNumeric(_ string : String, base : Int) -> Character? {
            guard let code = UInt32(string, radix: base),
                let uniScalar = UnicodeScalar(code) else { return nil }
            return Character(uniScalar)
        }

        // Decode the HTML character entity to the corresponding
        // Unicode character, return `nil` for invalid input.
        //     decode("@")    --> "@"
        //     decode("€") --> "€"
        //     decode("<")     --> "<"
        //     decode("&foo;")    --> nil
        func decode(_ entity : String) -> Character? {

            if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
                return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 16)
            } else if entity.hasPrefix("&#") {
                return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 2) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 10)
            } else {
                return characterEntities[entity]
            }
        }

        // ===== Method starts here =====

        var result = ""
        var position = startIndex

        // Find the next '&' and copy the characters preceding it to `result`:
        while let ampRange = self.range(of: "&", range: position ..< endIndex) {
            result.append(self[position ..< ampRange.lowerBound])
            position = ampRange.lowerBound

            // Find the next ';' and copy everything from '&' to ';' into `entity`
            if let semiRange = self.range(of: ";", range: position ..< endIndex) {
                let entity = self[position ..< semiRange.upperBound]
                position = semiRange.upperBound

                if let decoded = decode(entity) {
                    // Replace by decoded character:
                    result.append(decoded)
                } else {
                    // Invalid entity, copy verbatim:
                    result.append(entity)
                }
            } else {
                // No matching ';'.
                break
            }
        }
        // Copy remaining characters to `result`:
        result.append(self[position ..< endIndex])
        return result
    }
}

Swift 2:
// Mapping from XML/HTML character entity reference to character
// From http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
private let characterEntities : [ String : Character ] = [
    // XML predefined entities:
    """    : "\"",
    "&"     : "&",
    "'"    : "'",
    "<"      : "<",
    ">"      : ">",

    // HTML character entity references:
    " "    : "\u{00a0}",
    // ...
    "♦"   : "♦",
]

extension String {

    /// Returns a new string made by replacing in the `String`
    /// all HTML character entity references with the corresponding
    /// character.
    var stringByDecodingHTMLEntities : String {

        // ===== Utility functions =====

        // Convert the number in the string to the corresponding
        // Unicode character, e.g.
        //    decodeNumeric("64", 10)   --> "@"
        //    decodeNumeric("20ac", 16) --> "€"
        func decodeNumeric(string : String, base : Int32) -> Character? {
            let code = UInt32(strtoul(string, nil, base))
            return Character(UnicodeScalar(code))
        }

        // Decode the HTML character entity to the corresponding
        // Unicode character, return `nil` for invalid input.
        //     decode("@")    --> "@"
        //     decode("€") --> "€"
        //     decode("<")     --> "<"
        //     decode("&foo;")    --> nil
        func decode(entity : String) -> Character? {

            if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
                return decodeNumeric(entity.substringFromIndex(entity.startIndex.advancedBy(3)), base: 16)
            } else if entity.hasPrefix("&#") {
                return decodeNumeric(entity.substringFromIndex(entity.startIndex.advancedBy(2)), base: 10)
            } else {
                return characterEntities[entity]
            }
        }

        // ===== Method starts here =====

        var result = ""
        var position = startIndex

        // Find the next '&' and copy the characters preceding it to `result`:
        while let ampRange = self.rangeOfString("&", range: position ..< endIndex) {
            result.appendContentsOf(self[position ..< ampRange.startIndex])
            position = ampRange.startIndex

            // Find the next ';' and copy everything from '&' to ';' into `entity`
            if let semiRange = self.rangeOfString(";", range: position ..< endIndex) {
                let entity = self[position ..< semiRange.endIndex]
                position = semiRange.endIndex

                if let decoded = decode(entity) {
                    // Replace by decoded character:
                    result.append(decoded)
                } else {
                    // Invalid entity, copy verbatim:
                    result.appendContentsOf(entity)
                }
            } else {
                // No matching ';'.
                break
            }
        }
        // Copy remaining characters to `result`:
        result.appendContentsOf(self[position ..< endIndex])
        return result
    }
}

A: I was looking for a pure Swift 3.0 utility to escape to/unescape from HTML character references (i.e. for server-side Swift apps on both macOS and Linux) but didn't find any comprehensive solutions, so I wrote my own implementation: https://github.com/IBM-Swift/swift-html-entities
The package, HTMLEntities, works with HTML4 named character references as well as hex/dec numeric character references, and it will recognize special numeric character references per the W3 HTML5 spec (i.e. € should be unescaped as the Euro sign (unicode U+20AC) and NOT as the unicode character for U+0080, and certain ranges of numeric character references should be replaced with the replacement character U+FFFD when unescaping).
Usage example:
import HTMLEntities

// encode example
let html = ""

print(html.htmlEscape())
// Prints "<script>alert("abc")</script>"

// decode example
let htmlencoded = "<script>alert("abc")</script>"

print(htmlencoded.htmlUnescape())
// Prints ""

And for OP's example:
print("The Weeknd ‘King Of The Fall’ [Video Premiere] | @TheWeeknd | #SoPhi ".htmlUnescape())
// prints "The Weeknd 'King Of The Fall' [Video Premiere] | @TheWeeknd | #SoPhi "

Edit: HTMLEntities now supports HTML5 named character references as of version 2.0.0. Spec-compliant parsing is also implemented.

A: Updated answer working on Swift 3
extension String {
    init?(htmlEncodedString: String) {
        let encodedData = htmlEncodedString.data(using: String.Encoding.utf8)!
        let attributedOptions = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

        guard let attributedString = try? NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString.string)
   }

A: Swift 4
extension String {
    var replacingHTMLEntities: String? {
        do {
            return try NSAttributedString(data: Data(utf8), options: [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ], documentAttributes: nil).string
        } catch {
            return nil
        }
    }
}

Simple Usage
let clean = "Weeknd ‘King Of The Fall&#8217".replacingHTMLEntities ?? "default value"

A: Have a look at HTMLString - a library written in Swift that allows your program to add and remove HTML entities in Strings
For completeness, I copied the main features from the site:

*

*Adds entities for ASCII and UTF-8/UTF-16 encodings

*Removes more than 2100 named entities (like &)

*Supports removing decimal and hexadecimal entities

*Designed to support Swift Extended Grapheme Clusters (→ 100% emoji-proof)

*Fully unit tested

*Fast

*Documented

*Compatible with Objective-C

A: Swift 4
func decodeHTML(string: String) -> String? {

    var decodedString: String?

    if let encodedData = string.data(using: .utf8) {
        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        do {
            decodedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil).string
        } catch {
            print("\(error.localizedDescription)")
        }
    }

    return decodedString
}

A:
Swift 4.1 +

var htmlDecoded: String {

    let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [

        NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,
        NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue
    ]

    let decoded = try? NSAttributedString(data: Data(utf8), options: attributedOptions
        , documentAttributes: nil).string

    return decoded ?? self
}

A: Swift 3.0 version with actual font size conversion
Normally, if you directly convert HTML content to an attributed string, the font size is increased. You can try to convert an HTML string to an attributed string and back again to see the difference.
Instead, here is the actual size conversion that makes sure the font size does not change, by applying the 0.75 ratio on all fonts:
extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let attriStr = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        attriStr.beginEditing()
        attriStr.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, attriStr.length), options: .init(rawValue: 0)) {
            (value, range, stop) in
            if let font = value as? UIFont {
                let resizedFont = font.withSize(font.pointSize * 0.75)
                attriStr.addAttribute(NSFontAttributeName,
                                         value: resizedFont,
                                         range: range)
            }
        }
        attriStr.endEditing()
        return attriStr
    }
}

A: Swift 4
extension String {

    mutating func toHtmlEncodedString() {
        guard let encodedData = self.data(using: .utf8) else {
            return
        }

        let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            NSAttributedString.DocumentReadingOptionKey(rawValue: NSAttributedString.DocumentAttributeKey.documentType.rawValue): NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey(rawValue: NSAttributedString.DocumentAttributeKey.characterEncoding.rawValue): String.Encoding.utf8.rawValue
        ]

        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            self = attributedString.string
        }
        catch {
            print("Error: \(error)")
        }
    }

A: Objective-C
+(NSString *) decodeHTMLEnocdedString:(NSString *)htmlEncodedString {
    if (!htmlEncodedString) {
        return nil;
    }

    NSData *data = [htmlEncodedString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *attributes = @{NSDocumentTypeDocumentAttribute:     NSHTMLTextDocumentType,
                             NSCharacterEncodingDocumentAttribute:     @(NSUTF8StringEncoding)};
    NSAttributedString *attributedString = [[NSAttributedString alloc]     initWithData:data options:attributes documentAttributes:nil error:nil];
    return [attributedString string];
}

A: Use:
NSData dataRes = (nsdata value )

var resString = NSString(data: dataRes, encoding: NSUTF8StringEncoding)


text:
Q: There exists a constant arc length parametrization I heard that for any curve in the plane that can be given parametrically by $\vec{r}(t)=\langle x(t),y(t)\rangle$ for $a\leq t\leq b$ that there exists a constant arc length parametrization, i.e. another parametrization $\hat{\vec{r}}(t)=\langle \hat{x}(t),\hat{y}(t)\rangle$ that satisfies $\hat{x}'(t)^2+\hat{y}'(t)^2=1$ and $\hat{\vec{r}}\big((a,b)\big)=\vec{r}\big((a,b)\big)$.
What is the name of this theorem and who proved it?  I've been looking around the internet and it seems like the Gauss-Bonnet Theorem comes up a lot, but I don't see the connection between that and this?  Maybe I just don't understand it as well as I need to.

A: The earliest use is due to Leonard Euler in 1775: Methodus facilis omnia Symptomata linearum Curvarum non in eodem Plano sitarum Investigandi, Acta. Acad. Scient. Petropolitanse 1782 I, 1786, 19--57.


text:
Q: Word for "When two (or more) people are chasing after the same thing"? In baseball when two people are running toward the same pop fly, one will often yell "I got it!" or "mine"!
But in life there are all kinds of situations where two people are going for the same parking spot, or chasing after the same love interest, etc.
Is there a general term in English that describes these collisions? Is there a more formal term for when one person calls "shotgun" for these collisions (i.e. calls dibs, or claims ownership)?

A: Such people are called rivals. The word is ultimately from Latin rīvālis, "one who uses a stream in common with another" (rivus is stream, whence English river).

A:
Is there a more formal term for when one person calls "shotgun" for these collisions (i.e. calls dibs, or claims ownership)?

In formal language, it's to stake a claim.

[Merriam-Webster, from stake]
stake a claim
: to assert a title or right to something by or as if by placing stakes usually to satisfy a legal requirement

In other words, you are staking the claim that the baseball, parking spot, or love interest belongs to you and nobody else. You are asserting your right to it.

A: When two or more people eagerly chase after the same thing in a competitive manner, they're scrambling for it.
Definition: * to struggle eagerly or unceremoniously for possession of something*
Source: Merriam-Webster

A: I am going to assume you are looking for a noun that refers to the situation you describe, and another noun for the action of claiming priority in that situation.
I am going to say that there is no such noun in general English. In parallel computing the analogous thing can happen with different processes, and then it is called a race condition. Occasionally that term will be used metaphorically for the kind of "who claims the ticket" scenario you describe in your comment, but most people wouldn't be familiar with the concept. And also it wouldn't feel natural at all to use it with either a love interest or a parking space (two concepts I don't usually lump together).
I think if the contest really just goes to whoever gets there first, you can say that it is a race for X. In the case of a love interest, I imagine getting there first isn't enough, and you could say a competition for X's affections (although that sounds a little old-fashioned).
I think the English term for calling dibs is calling dibs, or just calling something. You can also say that someone "lays a claim", "stakes a claim", or just "claims" something.

A: It looks like you're asking for competitions where people are after the same thing, where they cannot all have it.
To describe a competition where two (or more) people cannot all successfully claim the prize, we could use zero-sum game

a situation in which one person or group can win something only by causing another person or group to lose it

(Merriam Webster)

A: I'd say they're vying.

Vie: Compete eagerly with someone in order to do or achieve something.
Example: the athletes were vying for a place in the British team. [Lexico]

Or they're contesting.

Contest: Engage in competition to attain (a position of power)
Example: she declared her intention to contest the presidency. [Lexico]

The competition could also be referred to as cut-throat or dog-eat-dog.

A:
Is there a general term in English that describes these collisions?

Contention
Example: There is much contention for parking spaces.

Is there a more formal term for when one person calls "shotgun" for
these collisions (i.e. calls dibs, or claims ownership)?

Win
Example: The blue car won the space.


text:
Q: Gatling sbt assembly- jar file cannot created? I am using gatling tool for performance testing.My gatling code is running perfectly. i am using intellij IDEA for my project. I am trying to create a jar file. It cannot created. i think this is sbt problem.please someone correct my sb My build.sbt file is here:
import io.gatling.sbt.GatlingPlugin
import sbtassembly.MergeStrategy

parallelExecution in Test := false
enablePlugins(GatlingPlugin, AssemblyPlugin)
lazy val root = (project in file("."))
 .configs(IntegrationTest)
 .settings(Defaults.itSettings: _*)

Project.inConfig(IntegrationTest)(baseAssemblySettings)
mainClass in assembly := Some("gatling.GatlingMain")
assemblyMergeStrategy in assembly := {
case x =>
val oldStrategy = (assemblyMergeStrategy in assembly).value
oldStrategy(x)
}
libraryDependencies ++= Seq(
"com.typesafe.play" % "play-json_2.11" % "2.6.2" % IntegrationTest,
"org.scalacheck" % "scalacheck_2.11" % "1.13.5"  % IntegrationTest,
"com.typesafe" % "config" % "1.3.1" % IntegrationTest,
"io.gatling.highcharts" % "gatling-charts-highcharts" % "2.2.5" %
IntegrationTest,
 "io.gatling" %  "gatling-test-framework" % "2.2.5" % IntegrationTest,
"com.google.code.gson" % "gson" % "2.8.0" % IntegrationTest
)
resourceDirectory in Compile := baseDirectory.value /"resources"
assemblyJarName in (IntegrationTest, assembly):=s"${name.value}-${version.value}.jar"

when i am trying to create a jar file using sbt command sbt "it:assembly"
It shows the following error
  [error] 1 error was encountered during merge
  java.lang.RuntimeException: deduplicate: different file contents found in the following:
  /Users/james/.ivy2/cache/io.netty/netty-buffer/jars/netty-buffer-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  /Users/james/.ivy2/cache/io.netty/netty-common/jars/netty-common-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  /Users/james/.ivy2/cache/io.netty/netty-codec-http/jars/netty-codec-http-4.0.44.Final.jar:META-INF/io.netty.versions.properties
 /Users/james/.ivy2/cache/io.netty/netty-codec/jars/netty-codec-4.0.44.Final.jar:META-INF/io.netty.versions.properties
 /Users/james/.ivy2/cache/io.netty/netty-transport/jars/netty-transport-4.0.44.Final.jar:META-INF/io.netty.versions.properties
 /Users/james/.ivy2/cache/io.netty/netty-handler/jars/netty-handler-4.0.44.Final.jar:META-INF/io.netty.versions.properties
/Users/james/.ivy2/cache/io.netty/netty-transport-native-epoll/jars/netty-transport-native-epoll-4.0.44.Final-linux-x86_64.jar:META-INF/io.netty.versions.properties
    at sbtassembly.Assembly$.applyStrategies(Assembly.scala:140)
    at sbtassembly.Assembly$.x$1$lzycompute$1(Assembly.scala:25)
    at sbtassembly.Assembly$.x$1$1(Assembly.scala:23)
    at sbtassembly.Assembly$.stratMapping$lzycompute$1(Assembly.scala:23)
    at sbtassembly.Assembly$.stratMapping$1(Assembly.scala:23)
    at sbtassembly.Assembly$.inputs$lzycompute$1(Assembly.scala:67)
    at sbtassembly.Assembly$.inputs$1(Assembly.scala:57)
    at sbtassembly.Assembly$.apply(Assembly.scala:83)
    at sbtassembly.Assembly$$anonfun$assemblyTask$1.apply(Assembly.scala:245)
    at sbtassembly.Assembly$$anonfun$assemblyTask$1.apply(Assembly.scala:242)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
    at sbt.std.Transform$$anon$4.work(System.scala:63)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
    at sbt.Execute.work(Execute.scala:237)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
  [error] (it:assembly) deduplicate: different file contents found in the following:
  [error] /Users/james/.ivy2/cache/io.netty/netty-buffer/jars/netty-buffer-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  [error] /Users/james/.ivy2/cache/io.netty/netty-common/jars/netty-common-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  [error] /Users/james/.ivy2/cache/io.netty/netty-codec-http/jars/netty-codec-http-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  [error] /Users/james/.ivy2/cache/io.netty/netty-codec/jars/netty-codec-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  [error] /Users/james/.ivy2/cache/io.netty/netty-transport/jars/netty-transport-4.0.44.Final.jar:META-INF/io.netty.versions.properties
  [error] /Users/james/.ivy2/cache/io.netty/netty-handler/jars/netty-handler-4.0.44.Final.jar:META-INF/io.netty.versions.properties

My sbt version is 0.13.16 and my scala version is 2.11.8. please someone help me to resolve this error. Thanks in advance

A: Most likely you don't need io.netty.versions.properties from all the io.netty libraries, one may be enough. I think something like this should work:
assemblyMergeStrategy in assembly := {
 case p if p.endsWith("io.netty.versions.properties") =>
   MergeStrategy.first
 case x =>
   val oldStrategy = (assemblyMergeStrategy in assembly).value
   oldStrategy(x)
}


text:
Q: extending captions for A3 pages Im writing my Thesis in A4 format and sometimes I need to use A3 pages for bigger images.
I managed to create a single A3 page within the A4 document and I extended the header up to the right margin. However, the text justification for the caption is still set up as an A4 document.
Does anyone know how to adjust the caption to the size of the image (in an A3 image)? this is the last bit I need to correct before submitting =)
Here you have what I'm doing...(--EDITED-- to have a complete document. I'm working with a preamble so I copied all the packages I'm using in order to have the setting up as I have...)
    \documentclass[a4paper,12pt, oneside]{book}

\usepackage{float}
\usepackage{afterpage}
\usepackage[usenames,dvipsnames]{color}

\usepackage{etex}
\reserveinserts{18}
\usepackage{morefloats}
\usepackage{lscape}

\usepackage[portuges,brazilian,english]{babel}
\usepackage[T1]{fontenc}

\usepackage[T1]{fontenc}

\usepackage{textcomp}

\usepackage{setspace}
\usepackage[authoryear]{natbib}
\usepackage{graphicx}
\usepackage{float}
\usepackage{fancyhdr}
\usepackage{eso-pic}
\usepackage{color}
\usepackage{fixltx2e}  %gives \textsubscript
\usepackage{pdfpages}
\usepackage{sidecap}

\renewcommand{\sfdefault}{phv}

\usepackage{microtype}

\usepackage{multirow}

\usepackage{indentfirst}

\usepackage{array}

\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{3}

%Sets margins...
\usepackage[cm]{fullpage}
\usepackage[top=1.5cm, bottom=4cm, left=4cm, right=2cm]{geometry}

%Customises figure captions...
\usepackage[small,justification=justified,format=plain,labelsep=space,indention=0cm,margin={0cm,0cm},labelfont={rm,bf},up,textfont={rm,it}]{caption}
\usepackage{wrapfig}
\usepackage{sidecap}
\usepackage{rotating}

\usepackage{booktabs}

\usepackage{pdfpages}

\newcommand{\degree}{\ensuremath{^\circ}}

%customises header...
\usepackage{fancyhdr}
\setlength{\headheight}{15pt}
\setlength{\headsep}{30pt}
 \pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1}{}}
 \fancyhf{}
\fancyhead[LE,RO]{\textrm{\normalsize{\thepage}}}
\fancyhead[RE]{\textrm{\normalsize{{{\leftmark}}}}}
\fancyhead[LO]{\textrm{\large{{{\rightmark}}}}}

\begin{document}

\clearpage{
\pdfpagewidth=2\pdfpagewidth
\fancyheadoffset[R]{20cm}

\begin{figure}[H]
    \centering
    \includegraphics[height=1.3\textwidth]{LATEX/C8/IMAGES/SCENARIOB}
    \caption[Results of Burial scenario B  - maturity window]{ResultsB - Burial scenario B contemplating transient heat flow (B-transient) and rifting heat flow (B-rifting). B-transient-I is contemplating a geothermal gradient of 30$^\circ$C/km for the overburden calculation; B-transient-II is contemplating a geothermal gradient of 20$^\circ$C/km for the overburden calculation; B-transient-III is contemplating a geothermal gradient of 15$^\circ$C/km for the overburden calculation. B-rifting is contemplating a $\beta$=1.3. }
    \label{SCENARIO B}
\end{figure}
\clearpage
}

\pdfpagewidth=1\pdfpagewidth

\end{document}

Here how it looks...( in this particular case, the image is not covering the whole page, but that is just because of the size of the image, it's not an error):


text:
Q: Fix the "-e" is deprecated warning with gnome-terminal I have the below script.
#!/bin/bash

# Run abc-app services
cd abc-app/packages/auth-service

tab=" --tab"
options_1=()
options_2=()

cmd_1[1]="yarn start"
cmd_1[2]="cd ../../api/shipper; yarn start:shipper"
cmd_1[3]="cd ../../frontend/shipper; yarn dev"

cmd_2[1]="yarn start:procure-app"
cmd_2[2]="yarn start:procure-worker"
cmd_2[3]="yarn start:mail-worker"
cmd_2[4]="yarn start:transporter"
cmd_2[5]="cd ../frontend/shipper; yarn dev"
cmd_2[6]="cd ../frontend/transporter; yarn dev"

for i in 1 2 3; do
options_1+=($tab -e "bash -c '${cmd_1[i]} ; bash'" )
done

for j in 1 2 3 4 5 6; do
options_2+=($tab -e "bash -c '${cmd_2[j]} ; bash'" )
done

gnome-terminal "${options_1[@]}"

cd
cd Documents/Code/abc-procure

gnome-terminal "${options_2[@]}"

When I run the script using ./startServices.sh, its runs as expected but with the below warnings
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.
# Option "-e" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.

I see that's just a syntax change I need to do, but not sure how to apply and make it work.

A: As the message says, you should use -- to separate the options from the command to execute:
for i in 1 2 3; do
    options_1+=("$tab" -- bash -c "${cmd_1[i]} ; bash" )
done

Also, you shouldn't put a space at the beginning of the value of $tab. Use
tab="--tab"

A: You need something like
for i in 1 2 3; do
    gnome-terminal $tab -- bash -c "${cmd_1[i]} ; bash"
done


text:
Q: why I unable to generate the rspec files while scaffold with rails 2.3.* version? I have tried to generate spec related files also while doing scaffold.
As normally, it will generate spec files along with all other CRUD related files while doing
scaffold.
But here, I trying with Rails 2.3.18 version + rspec, rspec-rails 1.3.2,1.3.4
Its not creating the spec files in spec folder but creating in test folder.
How I can achieve it?
Any Ideas? Please share your thoughts.

A: Got it, script/generate rspec_scaffold Model_Name


text:
Q: Google charts error:Cannot read property 'length' of undefined; Debugging error in Google Charts The following code works fine as a independant page as itself. But if incorporated into my PHP web app, it throws error. How to debug if the error happens in the google chart JS?
Any suggestions will be helpful
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>

        My Column Chart

Error in Chrome: It displays "Cannot read property 'length' of undefined", With a red background in the container
Error in Firefox: Throws error in Firebug console as:
b[c] is undefined
http://www.google.com/uds/api/visualization/1.0/97e6275dc5c50efe5944ddda289e59d2/format+en,default,corechart.I.js
Line 785

A: This answer will apply if you are using the Prototype JS framework. (I don't see it here, but it might have been excluded).
There is a ticket open for this issue on the Google Visualization API here.
One potential issue is that there might be a conflicting version of prototype or some other library being included.
Alternately, the reduce function may need to be redefined:

[Note: I had this issue in the past, and this led to the solution.  I am experiencing this issue a second time, but the original solution is not working for this new issue. Your mileage may vary.]

A: In my web app, I had included 'prototype-1.6.0.2.js', which created this error !
If I exclude 'prototype-1.6.0.2.js', everything runs great !

A: I had a similar issue where Google chart tools and Prototype library conflicted. I upgraded Prototype from version 1.6.1 to 1.7.1 and the problem was gone.


text:
Q: custom html button code for a form ttI know this is a lame question but in order to do it right i need your help.
this is my html code
<form name="form1" class="form1">
<fieldset>
    <legend>Subscription</legend>
    Name
    <input type="text" name="subname" />
    Your Email
    <input type="text" name="subemail" />
</fieldset>
</form>

Click here to subscribe

and here is the fiddle
http://jsfiddle.net/V8RB2/
how can i associate the "Click here to subscribe" text and the button with this form?

A: If i understood you correctly, you want to submit the form when the link is clicked. To do this, you'll have to use JavaScript.
A quick way of doing it is by telling the form to submit itself in the onclick attribute of the link.
Click here to subscribe

What happens is, that when the link is clicked, you trap its onclick event and then you tell form1 to submit itself.

A: The easiest way would make this a button within the form and use CSS to style it however you want.
<input type="submit" id="button1" class="button1" name="subscribe" value="Click here to subscribe!" />

Then to style:
form input.button1 {
   style here
}

A: The below will work.
<form name="form1" class="form1">
<fieldset>
<legend>Subscription</legend>
Name
<input type="text" name="subname" />
Your Email
<input type="text" name="subemail" />
</fieldset>
Click here to subscribe

</form>

A: Change your link's href to:
href="javascript:document.forms['form1'].submit()"

Or add that as an onClick attribute.
Updating with a technique to route around disabled javascript.
<input type="submit" value="submit">


text:
Q: C# / Outlook Interop Pickfolder window is not modal I have a question about an Outlook Pickfolder window.
When I call it directly from the Outlook it works fine and let me choose a folder that I want, acting as a modal window (so it prevents an Outlook window from being clicked on).
But when I call it from my custom WPF Window in the Outlook it behaves as a  non-modal window (not disabling my WPF window and not preventing it from being selected).
So the question is, how do I make it behave as a modal window or how can I disable my WPF window to prevent user input (and even prevent the window from being chosen like when you have a modal window opened)?
I tried to invoke it by a Dispatcher, but it didn't help.
Thanks!
UPD: I use the Outlook API method that calls a Pickfolder window inside.
var folder = NetOffice.OutlookApi.Application.Session.PickFolder();

And it works fine when I use it directly from Outlook window, but doesn't work from my custom window.
UPD2: For showing my custom window there's something like this:
var view = new SettingsPageView();
...
var window = new MyMessageBoxWindow(new MyMessageBoxViewModel());
window.DataContext = view.ViewModel;
window.Content = view;
window.ShowDialog(); // that calls System.Windows.Window.ShowDialog() deeper inside

A: Use IOleWindow and WindowInteropHelper to show your form as a child of the main Outlook window.
using System.Runtime.InteropServices;
...
IntPtr wnd = new IntPtr(0);
object window = _application.ActiveWindow();
if (window != null)
{
    IOleWindow oleWindow = window as IOleWindow;
    if (oleWindow != null)
    {
        oleWindow.GetWindow(out wnd);
    }
}
...

if (wnd != IntPtr.Zero)
{
    WindowInteropHelper helper = new WindowInteropHelper(archiveSettingWindow);
    window.Owner = wnd;
}


text:
Q: How can I check the SQL syntax in a .sql file? How can I check the SQL syntax in a .sql file?

A: SELECT STATEMENT_DIGEST_TEXT in MySQL 8.0 can be used for MySQL query syntax validation.
8.0.4>SELECT STATEMENT_DIGEST_TEXT('FLUSH TABLES')\G
STATEMENT_DIGEST_TEXT('FLUSH TABLES'): FLUSH TABLES

8.0.4>SELECT STATEMENT_DIGEST_TEXT("SET GLOBAL second_cache.key_buffer_size=128*1024;")\G
STATEMENT_DIGEST_TEXT("SET GLOBAL second_cache.key_buffer_size=128*1024;"): SET GLOBAL `second_cache` . `key_buffer_size` = ? * ? ;

8.0.4>SELECT STATEMENT_DIGEST_TEXT("create TABLE t1 ( a2 int unsigned not null, b2 int unsigned not null, c2 int unsigned not null, primary key (a2), index b2x (b2), index c2x (c2) ) ENGINE=MEMORY;")\G
STATEMENT_DIGEST_TEXT("create TABLE t1 ( a2 int unsigned not null, b2 int unsigned not null, c2 int unsigned not null, primary key (a2), index b2x (b2), index c2x (c2) ) ENGINE=MEMORY;"): CREATE TABLE `t1` ( `a2` INTEGER UNSIGNED NOT NULL , `b2` INTEGER UNSIGNED NOT NULL , `c2` INTEGER UNSIGNED NOT NULL , PRIMARY KEY ( `a2` ) , INDEX `b2x` ( `b2` ) , INDEX `c2x` ( `c2` ) ) ENGINE = MEMORY ;

If the SQL is not supported, you'll get an error. Like the next one, but there is something special about this response;
8.0.4>SELECT STATEMENT_DIGEST_TEXT('HELP SELECT')\G
ERROR 3676 (HY000): Could not parse argument to digest function: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT' at line 1".

Did you see what was special? It is the fact that 'HELP' is a valid, but client-side only keyword - i.e. not a server keyword. In any case, an invalid SQL statement will produce a similar situation; an ERROR.
Thus, you can check based on ERROR vs NO ERROR to know whether the passed SQL syntax is valid or not (excluding the very limited set of client-side-only commands, but those would not be of interest to most people).
Summary; SELECT STATEMENT_DIGEST_TEXT is a comprehensive SQL parser (while that may not be it's direct/intended function) which can be used in all cases to check the validity of statements quickly and without actually executing them. This is huge progress as far as SQL validity validation is concerned.
Note that you need to have a MySQL server up and running for this. You can pass queries using the mysql -e client, or use a pipe to mysql etc.

A: The basic lexer seems to be implemented in sql/sql_lex.cc. You could use/salvage this to build your own test parser.
But this would only check for syntax but not any runtime errors.
edit: For MySQL 8.0+ see How can I check the SQL syntax in a .sql file?

A: TLDR:
>awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"

Strangely, mysql does not have a built-in switch for this, but you can check syntax by adding the EXPLAIN statement in front of your queries.
If you have a statements.sql file with each statement on one line, prepend EXPLAIN in front of all lines with:
>awk '{print "EXPLAIN " $0}' statements.sql > check.sql

You can then run the statements with the mysql command-line tool and use --force to have it continue on error. It will print an error for any statements with incorrect syntax.
>mysql --force -u user -p database < check.sql

Or to only view the lines with errors:
>mysql --force -u user -p database < check.sql | grep "ERROR"

You can do all of this on one line without creating an intermediate file:
>awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"

A: There are a few free/try-ware products out there that will allow you to connect to a MySQL database or just paste in the script to validate it.  Google is your friend here.
Mimer will check ANSI-Standard syntax validation but probably not handle any MySQL specifics.

A: You could paste it into a query browser like the MySQL Query Browser (part of the GUI Tools package) and visually inspect how the keywords and string literals are colored to more easily see if you've made any syntax errors.
http://dev.mysql.com/downloads/gui-tools/5.0.html

A: There are a couple of possiblities.  If you are using InnoDB tables that support transactions, you can simply execute a start transaction; at the beginning of your .sql file and a rollback; at the end.  MySQL will output any syntax errors.
If you are testiing UPDATE or DELETE statements, you could add LIMIT 0 to the end to prevent these queries from making any database changes, and still have MySQL check the syntax.

A: just run it....
begin transaction
run it
rollback


text:
Q: How to initialize a table with tables in Lua? A friend and I try to write a mine sweeper program in Lua using the Löve framework. So far the code needs to see if a box (a cell) is checked and then draw it. We are new to Lua, the program now has the flaw that it only works on the lower right box.
UPDATE: Looking at it now I see that the values of the initialized GameBoard all have the same value (i.e., GameBoard[1] till GameBoard[150] are all identical cells).
Here's the code:
conf.lua has some global variables defined:
function love.conf(t)

    -- Global variables.
    CELL_SIZE = 40
    NUM_ROWS = 15
    NUM_COLS = 10
    STATS_HEIGHT = 100
    AMOUNT_OF_CELLS = NUM_ROWS * NUM_COLS
    GRID_WIDTH = 400
    GRID_HEIGHT = 700

end

Here's the relevant failing code in main.lua (it goes wrong in the load method where the GameBoard is filled with Cells.
--  The Cell table is used for every individual square on
--  the gameboard
Cell = {}

-- The Gameboard (150 Cell objects)
GameBoard = {}

--  The function new belongs to Cell and spawns a new object (a table)
--  with the same attributes as Cell.
function Cell:new(i, j)

--  each cell knows:
    --  its x- and y-coordinates.
    self.x_min = (i-1) * CELL_SIZE
    self.x_max = (CELL_SIZE-1) + (i-1) * CELL_SIZE
    self.y_min = STATS_HEIGHT + (j-1) * CELL_SIZE
    self.y_max = STATS_HEIGHT + (CELL_SIZE-1) + (j-1) * CELL_SIZE

    --  if it is a mine (determined with random number generator)
    isMine =  (math.random(1, 8) % 8 == 0) -- Roughly 0.15 (1/7) times true (is a mine)
    self.isMine = isMine

    --  do not check the mine initially
    self.checked = false

    --  return the cell object
    return self;

end

--  love.load is a love-function that is called once when the game
--  starts.
function love.load()

    -- The index of the cell on the GameBoard (ranging from 1 to 150)
    local index = 1

    --  Build a two dimensional table of Cell-objects
    for i = 1, NUM_COLS, 1 do
        for j = 1, NUM_ROWS, 1 do
            GameBoard[ index ] = Cell:new( i, j )
            index = index + 1
        end
    end
end

The result is that all boxes have the values of the lower box with index 150 (the latest since NUM_ROWS * NUM_COLS = 150). All elements (Cells) of the table (Gameboard) have the same the x and y values set in the Cell:new method.
It would be appreciated if someone could tell us how to properly initialize and access a table of tables.

A: In the function Cell:new, self is the table Cell itself, so you are returning the same table every time.
A simple fix is to create a new table instead:
function Cell:new(i, j)
    local t = {}

    t.x_min = (i-1) * CELL_SIZE
    --omit the rest

    return t;
end

For future improvement, you may be interested in another way, which implements prototype:
function Cell:new(i, j)
    local o = {}
    setmetatable(o, self)
    self.__index = self

    self.x_min = (i-1) * CELL_SIZE
    --omits rest

    return o;
end

Read PiL: Object-Oriented Programming for further information.


text:
Q: Read Only file system error My system often goes into Read-Only mode.
System details:
Linux amrav 3.19.0-78-generic #86~14.04.1-Ubuntu SMP Tue Dec 6 17:58:35 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Output of some of the commands which I tried from other answers on stackoverflow.
$ dmesg | grep "error"
[   25.457633] EXT4-fs (sda5): re-mounted. Opts: errors=remount-ro
[   27.346559] [drm:intel_uncore_check_errors [i915]] *ERROR* Unclaimed register before interrupt

I even get the following error while trying to access (copy a file) from a certain directory in the hard disk:
There was an error copying the file into /home/amrav.
Error opening file '/home/amrav/train_iter_.txt': Read-only file system

And whenever I start the terminal, I get the following error:
mktemp: failed to create file via template '/tmp/setup.sh.XXXXXXXXXX': Read-only file system
Could not create temporary file:
mktemp: failed to create file via template '/tmp/setup.sh.XXXXXXXXXX': Read-only file system
Could not create temporary file:
zsh: locking failed for /home/amrav/.zsh_history: read-only file system: reading anyway


text:
Q: How to improve fit of Poisson Mixture Model in PyMC3? I have some data that looks like this:

I want to try to model this data using a Poisson Mixture Model with 2 components. As I am new to PyMC3, I used the links here: PyMC3 GMM tutorial and here: PyMC3 Mixture API to try to do this. My code is here:
with pm.Model() as model:
    lam1 = pm.Exponential('lam1', lam=1)
    lam2 = pm.Exponential('lam2', lam=1)
    pois1 = pm.Poisson.dist(mu=lam1)
    pois2 = pm.Poisson.dist(mu=lam2)
    w = pm.Dirichlet('w', a=np.array([1, 1]))
    like = pm.Mixture('like', w=w, comp_dists=[pois1, pois2], observed=data)
with model:
    trace = pm.sample(5000, n_init=10000, tune=10000, random_seed=SEED)[1000:]
with model:
    ppc_trace = pm.sample_ppc(trace, 5000, random_seed=SEED)
fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(data, bins=30, normed=True,
        histtype='step', lw=2,
        label='Observed data')
ax.hist(ppc_trace['like'], bins=30, normed=True,
        histtype='step', lw=2,
        label='Posterior predictive distribution')
ax.legend(loc=1)
plt.show()

But the result is this:
How do I improve the fit? I have tried fiddling with the lambdas to no avail.

A: It looks like you are plotting the posterior of the parameters. Don't confuse this with the distribution of random samples based on the model. That said, it should be clear that the orange line is not a "fit" of the blue one but rather indicates where the parameters of your components are. I am not familiar with pymc but there should also be a way to really sample from the model instead of sampling the model. One alternative option would be to read out the maxima of the posterior (the MAP solution) and with that use numpy.random functions to sample.


text:
Q: Service invoked too many times for one day: email with only 19 emails sent on a Time Trigger I have looked over all the MailApp limitations over at:
https://developers.google.com/apps-script/guides/services/quotas
The company I work for has their own Google domain and should qualify for over 1,500 emails a day. I am getting this error no where near that number.
Upon writing this code and debugging at the start of the day:
var y  = MailApp.getRemainingDailyQuota();

It appears to say I have a maximum of 100 emails a day from the MailApp command. If my company is using Google's services, why do I qualify for only 100 emails instead of 1,500?
Furthermore, why is the service being blocked if I send significantly under 100 emails?

A: You question can be answered with the following information

*

*Description of the getRemainingDailyQuota():

*

*Returns the number of remaining emails a user can send for the rest of the day. Quotas are based on the number of email recipients.

*Email recipients per day:

This means that if your company's Google Domain is new, you might be
  temporary limited to 100 email recipients per day, which can result in less than 100 emails per day.


text:
Q: New Rmd document: knitr: Error in library("rstudio") : there is no package called 'rstudio' firing up "RStudio" V1.0.136 on my Mac, just as usual, creating a new file, a Rmd, and trying--as I've done countless time before--knitr it just as is, but this time a strange error message occurs:
Error in library("rstudio") : there is no package called 'rstudio'

Never ever have seen this before, and I haven't got the faintest clue as why this has popped into existence, and how to remedy it.

A: Funny enough, after wiping my whole RStudio and R installation, with a subsequent re-installation thereof, all is working fine again.


text:
Q: How to inform the kernel with increased disk space? I was running out of storage space on my wm-ware ubuntu virtual machine and I used Gparted ISO to increased storage space for boot partition. Everything went well until I got a msg saying that Gparted unable to inform kernel of changes.
Is there a command that would make kernel run like an update check? Im am using Ubuntu 14.04 TLS.


text:
Q: How can I change a lot of parameters to Real? Because of some formulas with Conjugate in a notebook, I have to tell mathematica to change a lot of parameters to Real!
I know that I can use Refine with Element or Assumptions:
Refine[k + x + g, Element[x | k | g, Reals]]

or
Refine[%, Assumptions -> {x, k, g} \[Element] Reals]

, But it's useful for a few parameters not a lot!
For Example I'd like to define:
Ki,j & i{1 to 20} , j{1 to 20}

in Reals. Is there any function to define it without telling mathematica one by one?

A: I'm not sure what you mean by Ki,j but perhaps this
vars = ToExpression@
   Flatten@Table["K" <> ToString[i] <> "$" <> ToString[j], {i, 20}, {j, 20}];

or this
vars = Flatten@Table[k[i, j], {i, 20}, {j, 20}];

Then one can use it thus:
Assuming[vars ∈ Reals,
 Refine[
   Apply[
    Times,
    Sqrt[vars ^ RandomInteger[4, Length[vars]]]
    ]] /. p_Power :> Simplify[p]
 ]
(* large expression with Sqrt[x^2] simplified to Abs[x] etc. *)


text:
Q: asynchronous decorator for tornado fails I am using tornado 3.2 on python 2.7 and the asynchronous decorator is throwing errors. The error is :
[~code]$ python server.py
Traceback (most recent call last):
File  "server.py", line 15, in <module>
class UploadHandler(tornado.web.RequestHandler):
File "server.py", line 16, in UploadHandler
@asynchronous
NameError: name 'asynchronous' is not defined

And this is my code that uses decorator:
class UploadHandler(tornado.web.RequestHandler):
    @asynchronous
    def post(self):
      print "In post"
      self.redirect("/upload.html")

Any advice would be great

A: You need to use the fully qualified name:
class UploadHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        print("In post")
        self.redirect("/upload.html")

Alternatively, you could import all of tornado.web to use the single name:
from tornado.web import *


text:
Q: How to download (export) an apps script add-on project? How will I download an apps-script Google Docs add-on project, which was  opened from Tools > Script editor of Google Docs.
File > make a copy of the project do not seem to be any use. since it makes online copy itself. Any alternative ways to achieve?

A: Google launched clasp last year, an official tool to import and export apps scripts projects. It works great!

A: You should not develop you add-on directly in a document (I made this mistake too). Instead you need to have an independant script that you bound to a document with the options to test it as an addon (this way).
Doing so you'll have the capacity to export (and import) your script with the Google Drive rest api.To my knowledge there is two tools that you can use:
gapps writen in node
python-gas-cli, a python tool (never tested it)
You should also have a look at this post that explain quite well how it work