text:
Q: RexExp in javascript dont match a number inside a string Im learning Regular Expresions in Javascript and there is a thing that i dont understand.
The following regexp should match any string from a to z but if I add a number it says that is correct
var patron = /[a-zA-Z]/;
var regex = new RegExp(patron);
        var v= "hello word 512";

        if(v.match(regex))
        {
            //should not match but it does
        }else
        {
            objInput.style.color = "red";
        }

And them i tried this:
 var patron = /[a-zA-Z\D]/;
var regex = new RegExp(patron);
        var v= "hello word 512";

        if(v.match(regex))
        {
            //should not match but still dont work
        }else
        {
            objInput.style.color = "red";
        }

And also, parentheses are not being match
 var patron = /[a-zA-Z\"\']/;
    var regex = new RegExp(patron);
            var v= "hello word 512";

        if(v.match(regex))
        {
            //it match whenever the double quoute it followed by the single quoute'
        }else
        {
            objInput.style.color = "red";
        }

A: About the first example you provided, your regex /[a-zA-Z]/ checks for any character in the input string. Since it finds h in your input string, it returns true.
What you need to do is place start and end anchors, ^ and $ in your regex. New regex would look like this:
/^[a-zA-Z]+$/

You can make changes to all you regex accordingly.

To match parentheses, you need to escape them with a backslash. \( would match (, and \) would match ).

A: You should match the whole string, using the ^ (matches the beginning of the string) and $ (matches the end of the string) operators, for example:
/^[a-zA-Z\s]+$/.test("any string followed by numbers! 555") // will return false

This will not allow anything else than a-z chars and spaces in your string.

A: the match function seeks for at least ONE match in your case this is 1st symbol which is a char.
if you want ONLY chars then use /[a-zA-Z]/.test("your string")


text:
Q: UnhandledPromiseRejectionWarning: Unhandled promise rejection. When using Pusher for real time mongoDb I'm trying to make my mongodb realtime using pusher in my node-express app and react frontend app. After googling forours I couldn't find anything that solved my problem but I did get to know some things like when I don't attach an image in my Post when submitting my form, it listens and updates correctly but when I do attach an image in my Post then it gives my server error:
(node:1344) UnhandledPromiseRejectionWarning: Error
    at new RequestError (E:\Web Development\Simple Social Media App using MERN stack\backend\node_modules\pusher\lib\errors.js:13:16)
    at E:\Web Development\Simple Social Media App using MERN stack\backend\node_modules\pusher\lib\requests.js:61:17
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:1344) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a
catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)

This is my node-express code to listen to changes:
mongoose.connection.once("open", () => {
    console.log("DB Connected !");

    const changeStream = mongoose.connection.collection("users").watch();

    changeStream.on("change", (change) => {

        if(change.operationType === "insert"){
            console.log("Triggering pusher **POST CREATED**");
            const postDetails = change.fullDocument;
            pusher.trigger("users", "inserted", {
                author: postDetails.author,
                message: postDetails.message,
                imageFile: postDetails.imageFile
            })
        } else if(change.operationType === "delete"){
            console.log("Triggering pusher **POST DELETED**");
            pusher.trigger("users", "deleted")
        }
        else {
            console.log("Unknown trigger from pusher !");
        }
    })
})

This is my react app code:
const getData = async () => {
        const allPosts = await getAllPosts();
        setPosts(allPosts);
    }
useEffect(() => {
        const pusher = new Pusher('this is my id', {
            cluster: 'ap2'
          });
          const channel = pusher.subscribe("users");
          channel.bind('inserted', () => {
            getData();
          });
    }, [])

These are my middlewares:
app.use(express.json({limit:'50mb'}));
app.use(cors());

As said earlier, the problem only occurs when there is an image in my Post (I think maybe because of image size), otherwise if i do not include image, it will happily fetch newly posted data from server and refresh without reloading the whole app !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom select function with copy to clipboard pure JS The current code appends a button to quickly select some code in a
 tag. What I want to add is the ability to copy that content to the clipboard and change the button text to "copied".
How can I achieve it by modifying the current working code below? I wouldn't mind using clipboard.js, jQuery bits or just native JS support as it was introduced since Chrome 43. I just dont know how to go on from here on adding what I need.
function selectPre(e) {
    if (window.getSelection) {
        var s = window.getSelection();
        if (s.setBaseAndExtent) {
            s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
        }
        else {
            var r = document.createRange();
            r.setStart(e.firstChild, 0);
            r.setEnd(e.lastChild, e.lastChild.textContent.length);
            s.removeAllRanges();
            s.addRange(r);
        }
    }
    else if (document.getSelection) {
        var s = document.getSelection();
        var r = document.createRange();
        r.selectNodeContents(e);
        s.removeAllRanges();
        s.addRange(r);
    }
    else if (document.selection) {
        var r = document.body.createTextRange();
        r.moveToElementText(e);
        r.select();
    }
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
    var newdiff = diff[i].childNodes[1];
    if (newdiff.className && (newdiff.className == 'added' || newdiff.className == 'modified')) {
        newdiff.className += ' diff-select';
        newdiff.innerHTML = '
<button class="btn btn-default btn-xs" onclick="selectPre(this.parentNode.nextSibling)">Select</button>
' + newdiff.innerHTML;
    }
}

A: For some reason indeed your selectPre function is not found when reproducing the case on jsfiddle. Jsfiddle may get rid of what it thinks is dead code or rename it for the sake of minification.
But if what it does is selecting the content of a
 tag, the clipboard.js library (that you are ready to use) can do that already on its own.
So you end up by requiring a correct configuration of the Clipboard object. Using that one:
new Clipboard('.btn', {
    // The targeting to the correct content is done here.
    target: function(trigger) {
        return trigger.parentNode.nextSibling;
    }
    // clipboard.js will take the entire inner content of the
,
    // I think this is what you are trying to do in your "selectPre"
    // function, but I am not sure.
});

it mimics your selectPre(this.parentNode.nextSibling) that you no longer need to attach to the onclick attribute of your button.
Demo: http://jsfiddle.net/5k60nm1y/
Note that I had to guess what your table structure is. It might differ from your actual table so you may need to fine-tune how newdiff is assigned to the correct cell.
If you need something more complicated than just the inner content of the
 tag, you could fine-tune the behaviour of the Clipboard object by passing a custom function to the text property of the Clipboard constructor option, instead of using the target property. Check the clipboard homepage, it is quite self-explanatory.
As mentioned by Zac, you would have made people's task easier (and you would probably have received a solution much faster) if you could have shared your HTML table. I would not have needed to guess and create a fake one. Furthermore, the code I would have provided you with would have been directly applicable to your real table, whereas now it may still need customization. Hopefully I guessed it right enough and my table is close to yours.

A: I applied a piece of code from this resource,  How do I copy to the clipboard in JavaScript?, to your code, for you to easily see how it can be done.
I also modified your onclick="selectPre(...)" to this onclick="selectPre(this)" and added a couple of variables in the "selectPre" function.
Here is also a Fiddle demo
function selectPre(b) {
    var s;                               // added - selection variable
    var e = b.parentNode.nextSibling;    // added - parent sibling element
    if (window.getSelection) {
        var s = window.getSelection();
        if (s.setBaseAndExtent) {
            s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
        }
        else {
            var r = document.createRange();
            r.setStart(e.firstChild, 0);
            r.setEnd(e.lastChild, e.lastChild.textContent.length);
            s.removeAllRanges();
            s.addRange(r);
        }
    }
    else if (document.getSelection) {
        var s = document.getSelection();
        var r = document.createRange();
        r.selectNodeContents(e);
        s.removeAllRanges();
        s.addRange(r);
    }
    else if (document.selection) {
        var s = document.body.createTextRange();
        s.moveToElementText(e);
        s.select();
    }

    // added - copy and change button text
    if (s) {
        try {
            var successful = document.execCommand('copy');
            // var msg = successful ? 'successful' : 'unsuccessful';
            // console.log('Copying text command was ' + msg);
            if (successful) {
                b.innerHTML = "Copied";
            }
        } catch (err) {
            // console.log('Oops, unable to copy');
        }
    }
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
    var newdiff = diff[i].childNodes[1];
    if (newdiff.className && (newdiff.className == 'added' || newdiff.className == 'modified')) {
        newdiff.className += ' diff-select';

        // altered - onclick handler
        newdiff.innerHTML = '
<button class="btn btn-default btn-xs" onclick="selectPre(this)">Select</button>
' + newdiff.innerHTML;
    }
}


text:
Q: Download Java x64 and Microsoft Edge with PowerShell I found this script to download Javax64 and it really works, but I had some problems.
The first is that the command I would put would be inside an XML file that a powershell script calls it, so putting it directly like this, it gave some errors because where it shows "<a" the XML understood that this was part of it and not of something that only PowerShell would make use of.
The second is "New-Object -ComObject "InternetExplorer.Application" where this is not working on my Windows Server and it is recommended not to use it for ie it is being discontinued soon. It still works on Windows 10 normally but on Windows Server it gets stuck in a loop and won't get out.
How would I convert this script to an Invoke-WebRequest, is this possible? Because then I would just need to put the complete string of the Invoke-WebResquest in my XML file and PowerShell would read it normally, I think.
$ie = New-Object -ComObject "InternetExplorer.Application"
# Navigate to the requested page
$ie.Navigate2("https://www.java.com/en/download/manual.jsp")

$anchor = $null
while($anchor -eq $null -or $anchor -eq "")
{
     #wait 1 second for the page to load
     start-sleep -m 1000
     #get the html of the page
     $html = $ie.document.body.innerHTML
     #apply your regex to identify the anchar with the download link
     $anchor = [regex]::Match($html, '(?:<a title="Download Java software for Windows \(64-bit\)" href=")(.*)(?:">)').Groups[1] .Value
}

#regex doesn't return the link correctly, that's why I made the substring to get the link
$url_download = $anchor.Substring(0,$anchor.IndexOf(""""))
$url_download

Edit: There is the same situation but to download Edge?

A:
Note: Neither Invoke-WebRequest or the built-in .NET clients for obtaining files over HTTP seem to support rendering the full DOM, and so JavaScript cannot be executed. JavaScript is required to access those downloads links and use the site in general. You have two choices:

*

*Use static links as I have outlined in my original answer below; or

*Automate Edge using WebDriver, which is how Microsoft recommends you automate MS Edge. There is no COM functionality for controlling the Edge browser.

Unfortunately, I cannot help with the latter as I have no experience using WebDriver.

Looking at the oraclejdk Chocolatey package installation script, the URL is
https://download.oracle.com/java/17/archive/jdk-17.0.2_windows-x64_bin.msi. Since you're already familiar with Chocolatey from another environment, I would figure the version you need, see if there is a Chocolatey package for it, and get the direct URL from that package version's installation script.
You could also attempt to templatize the URL like so:
https://download.oracle.com/java/MAJOR_VERSION/archive/jdk-MAJOR_VERSION.MINOR_VERSION.PATCH_windows-x64_bin.msi
where MAJOR_VERSION, MINOR_VERSION, and PATCH are pieces of the Java version. However, I have not tested that all Java MSI URLs follow this pattern.

Regardless, once you have the URL, it's as simple as:
# Work around performance issue with iwr and the progress bar
$ProgressPreference = 'SilentlyContinue'

$MSI_URL = 'https://download.oracle.com/java/17/archive/jdk-17.0.2_windows-x64_bin.msi'
Invoke-WebRequest -UseBasicParsing $MSI_URL -Outfile 'jdk-17.0.2_windows-x64_bin.msi'


text:
Q: What to do with static method overrides? For example,
public class A {
    public static int f() { return 1; }
}

public class B extends A {
    public static long f() { return 100L; }
}

Unfortunately B.f() couldn't be compiled because B.f() tries to override A.f(), and so the name clashes because the return types aren't compatible.
I'm weired what's purpose to override a static method? Any use case? Can I just hide away A.f() in class B?
Actual usage:
class EntityDTO {

    public static List<EntityDTO> marshal(Collection<? extends Entity> entities) {
        ...
    }

}

class BookDTO extends EntityDTO {

    public static List<BookDTO> marshal(Collection<? extends Book> books) {
        ...
    }

}

A: Strictly speaking, static methods can not be overridden. Method overriding is exclusively a feature of object polymorphism, and static methods doesn't belong to any object but the class itself.
Having clarified that, you should not make any of your methods static. That would solve your problem in hand, at least. As the method arguments are different, it will not be considered as overriding, but overloading.

A: static method can not be overridden.
Notice: your B.f() should return int rather than long to pass compile.

A: static methods are not overriden...But it is called method hiding. The benefits of using the same method name and parameters are just like any other method overriding benefits

A: I can't think of a use case where overriding static functions (in Java) can be useful, but if you ever absolutely must achieve it, here's how:
import java.lang.reflect.Method;

class A {

    public static void callOut() {

        System.out.println("A.callOut");
    }

}

public class B extends A {

    public static void callOut() {

        System.out.println("B.callOut");
    }

    public static void main(String[] args) throws Exception
    {
        A a = new A();
        A b = new B();

        Method aM = a.getClass().getMethod("callOut");
        Method bM = b.getClass().getMethod("callOut");

        aM.invoke(null); // prints A.callOut
        bM.invoke(null); // prints B.callOut
    }
}

A: Maybe you need to rethink you design, if you have a need to override the marshal method, then it shouldn't be static in the first place.


text:
Q: Interesting behavior of preview If you compile this code (note that \begin{document} is commented):
% arara: pdflatex
\documentclass{article}
\usepackage{tikz}
\usepackage[active,tightpage]{preview}
%\begin{document}
\PreviewEnvironment{tikzpicture}
\begin{tikzpicture}
    \node  {a node};
\end{tikzpicture}
\end{document}

You got this error:
! I can't find file `preview.aux'.

but if you uncomment \begin{document}, compile it again creating preview.aux:
\relax
\gdef \@abspage@last{1}

comment again \begin{document}, and eventually re-compile it, it works!
Why does it happen?

A: The error
 ! LaTeX Error: Missing \begin{document}.

has a rather simple implementation: it has been added to \everypar in the format:
 \everypar{\@nodocument}

So if something starts a paragraph in the preamble it is triggered.
It is easy to suppress the error, simply empty \everpar:
\documentclass{article}
\everypar{}
zzz

\begin{document}
aaa
\end{document}

Another way is to call \@arrayparboxrestore which contains an \everypar{}:
\documentclass{article}
\makeatletter \@arrayparboxrestore \makeatletter
zzz

\begin{document}
aaa
\end{document}

The preview code contains at the begin a \@arrayparboxrestore and so it suppresses the error, but naturally if there is no \begin{document} important code is missing and so at the end you get an error that the aux-file is missing. Proving an aux helps here, but naturally that doesn't mean that you have a sane document.


text:
Q: Are the algebraic numbers dense everywhere on the boundary of the Mandelbrot set? Let $\mathcal{B}$ denote the boundary of the Mandelbrot set, and let
$\overline{\mathbb{Q}}$ denote the algebraic closure of the rationals.
Further put $\mathcal{B}_{\overline{\mathbb{Q}}} := \mathcal{B} \cap
\overline{\mathbb{Q}}$.
Questions:

*

*Is $\mathcal{B}_{\overline{\mathbb{Q}}}$ dense in $\mathcal{B}$
in the sense that for every $z \in \mathcal{B}$ and every
$\varepsilon > 0$, the $\varepsilon$-neighborhood of $z$ has nontrivial
intersection with $\mathcal{B}_{\overline{\mathbb{Q}}}$?

*Given $z \in \mathbb{C}$, let
$\mathcal{B} + z := \{b + z \ | \ b \in \mathcal{B}\}$
denote the translate of $\mathcal{B}$ by $z$.
Is there a $z \in \mathbb{C}$ such that
$(\mathcal{B} + z) \cap \overline{\mathbb{Q}} = \emptyset$?

*What are the answers to (1.) and (2.) if we replace
$\overline{\mathbb{Q}}$ by the Gaussian rationals $\mathbb{Q}[i]$
or by the cyclotomic integers $\mathbb{Z}[e^{\frac{2\pi i}{5}}]$?

A: Post-critically pre-periodic quadratic polynomials, i.e. those for which the orbit of the critical point $0$ is pre-periodic, are well-known to be dense in the boundary of the Mandelbrot set. (This is essentially a normality argument.)
Each of these is determined by an algebraic equation. This answers your first question (the question in the title).
EDIT. As pointed out by Malik, post-critically pre-periodic parameters are also called Misiurewicz points. (Unfortunately, the term Misiurewicz is sometime also used, particularly in real dynamics I think, to refer to a larger class of systems.)


text:
Q: How to do Transfer Learning without ImageNet weights? This is a description of my project:
Dataset1: The bigger dataset, contains binary classes of images.
Dataset2: Contains 2 classes that are very similar in appearance to Dataset1. I want to make a model that is using transfer learning by learning from Dataset1 and apply the weights with less learning rate in Dataset2.
Therefore I'm looking to train the entire VGG16 on dataset1, then using transfer learning to finetune the last layers for dataset2. I do not want to use the pre-trained imagenet database. This is the code I am using, and I have saved the wights from it:

from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
import numpy as np
from glob import glob
import matplotlib.pyplot as plt

vgg = VGG16(input_shape=(244, 244, 3), weights=None, include_top=False)

# don't train existing weights
for layer in vgg.layers:
    layer.trainable = False

x = Flatten()(vgg.output)

import tensorflow.keras
prediction = tensorflow.keras.layers.Dense(2, activation='softmax')(x)

model = Model(inputs=vgg.input, outputs=prediction)

model.compile(
  loss='categorical_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('chest_xray/train',
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')

test_set = train_datagen.flow_from_directory('chest_xray/test',
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')

# fit the model
r = model.fit_generator(
  training_set,
  validation_data=test_set,
  epochs=5,
  steps_per_epoch=len(training_set),
  validation_steps=len(test_set)
)

model.save_weights('first_try.h5')

A: Update
Based on your query, it seems that the class number won't be different in Dataset2. At the same time, you also don't want to use image net weight. So, in that case, you don't need to map or store the weight (as described below). Just load the model and weight and train on Dataset2. Freeze the all trained layer from Dataset1 and train the last layer on Dataset2; really straight forward.

In my below response, though you're not needed the full information, I am keeping that anyway for future reference.

Here is a small demonstration of what you probably need. Hope it gives you some insight. Here we will train the CIRFAR data set which has 10 classes and try to use it for transfer learning with on different data set which probably has different input sizes and a different number of classes.
Preparing the CIFAR (10 Classes)
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

# train set / data
x_train = x_train.astype('float32') / 255

# validation set / data
x_test = x_test.astype('float32') / 255

# train set / target
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
# validation set / target
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)

print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
'''
(50000, 32, 32, 3) (50000, 10)
(10000, 32, 32, 3) (10000, 10)
'''

Model
# declare input shape
input = tf.keras.Input(shape=(32,32,3))
# Block 1
x = tf.keras.layers.Conv2D(32, 3, strides=2, activation="relu")(input)
x = tf.keras.layers.MaxPooling2D(3)(x)

# Now that we apply global max pooling.
gap = tf.keras.layers.GlobalMaxPooling2D()(x)

# Finally, we add a classification layer.
output = tf.keras.layers.Dense(10, activation='softmax')(gap)

# bind all
func_model = tf.keras.Model(input, output)

'''
Model: "functional_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_2 (InputLayer)         [(None, 32, 32, 3)]       0
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 15, 15, 32)        896
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 5, 5, 32)          0
_________________________________________________________________
global_max_pooling2d_1 (Glob (None, 32)                0
_________________________________________________________________
dense_1 (Dense)              (None, 10)                330
=================================================================
Total params: 1,226
Trainable params: 1,226
Non-trainable params: 0
'''

Run the model to get some weight matrices as follows:
# compile
print('\nFunctional API')
func_model.compile(
          loss      = tf.keras.losses.CategoricalCrossentropy(),
          metrics   = tf.keras.metrics.CategoricalAccuracy(),
          optimizer = tf.keras.optimizers.Adam())
# fit
func_model.fit(x_train, y_train, batch_size=128, epochs=1)

Transfer Learning
Let's use it for MNIST. It also has 10 classes but for sake of need a different number of classes, we will make even and odd categories from it (2 classes). Below how we will prepare these data sets
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

# train set / data
x_train = np.expand_dims(x_train, axis=-1)
x_train = np.repeat(x_train, 3, axis=-1)
x_train = x_train.astype('float32') / 255
# train set / target
y_train = tf.keras.utils.to_categorical((y_train % 2 == 0).astype(int),
                                        num_classes=2)

# validation set / data
x_test = np.expand_dims(x_test, axis=-1)
x_test = np.repeat(x_test, 3, axis=-1)
x_test = x_test.astype('float32') / 255
# validation set / target

y_test = tf.keras.utils.to_categorical((y_test % 2 == 0).astype(int),
                                       num_classes=2)

print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
'''
(60000, 28, 28, 3) (60000, 2)
(10000, 28, 28, 3) (10000, 2)
'''

If you're familiar with the usage of ImageNet pretrained weight in the keras model, you probably use include_top. By setting it False we can easily load a weight file that has no top information of the pretrained models. So here we need to manually (kinda) do that. We need to grab the weight matrices until the last activation layer (in our case which is Dense(10, softmax)). And put it in the new instance of the base model, and + we add a new classifier layer (in our case that will be Dense(2, softmax).
for i, layer in enumerate(func_model.layers):
    print(i,'\t',layer.trainable,'\t  :',layer.name)

'''
  Train_Bool  : Layer Names
0    True     : input_1
1    True     : conv2d
2    True     : max_pooling2d
3    True     : global_max_pooling2d # < we go till here to grab the weight and biases
4    True     : dense  # 10 classes (from previous model)
'''

Get Weights
sparsified_weights = []
for w in func_model.get_layer(name='global_max_pooling2d').get_weights():
    sparsified_weights.append(w)

By that, we map the weight from the old model except for the classifier layers (Dense). Please note, here we grab the weight until the GAP layer, which is there right before the classifier.
Now, we will create a new model, the same as the old model except for the last layer (10 Dense), and at the same time add a new Dense with 2 unit.
predictions    = Dense(2, activation='softmax')(func_model.layers[-2].output)
new_func_model = Model(inputs=func_model.inputs, outputs = predictions)

And now we can set weight as follows to the new model:
new_func_model.get_layer(name='global_max_pooling2d').set_weights(sparsified_weights)

You can check to verify as follows; all will be the same except the last layer.
func_model.get_weights()      # last layer, Dense (10)
new_func_model.get_weights()  # last layer, Dense (2)

Now you can train the model with new data set, in our case which was MNIST
new_func_model.compile(optimizer='adam', loss='categorical_crossentropy')
new_func_model.summary()

'''
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         [(None, 32, 32, 3)]       0
_________________________________________________________________
conv2d (Conv2D)              (None, 15, 15, 32)        896
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 5, 5, 32)          0
_________________________________________________________________
global_max_pooling2d (Global (None, 32)                0
_________________________________________________________________
dense_6 (Dense)              (None, 2)                 66
=================================================================
Total params: 962
Trainable params: 962
Non-trainable params: 0
'''

# compile
print('\nFunctional API')
new_func_model.compile(
          loss      = tf.keras.losses.CategoricalCrossentropy(),
          metrics   = tf.keras.metrics.CategoricalAccuracy(),
          optimizer = tf.keras.optimizers.Adam())
# fit
new_func_model.fit(x_train, y_train, batch_size=128, epochs=1)

WARNING:tensorflow:Model was constructed with shape (None, 32, 32, 3) for input Tensor("input_1:0", shape=(None, 32, 32, 3), dtype=float32), but it was called on an input with incompatible shape (None, 28, 28, 3).
WARNING:tensorflow:Model was constructed with shape (None, 32, 32, 3) for input Tensor("input_1:0", shape=(None, 32, 32, 3), dtype=float32), but it was called on an input with incompatible shape (None, 28, 28, 3).
469/469 [==============================] - 1s 3ms/step - loss: 0.6453 - categorical_accuracy: 0.6447
<tensorflow.python.keras.callbacks.History at 0x7f7af016feb8>

A: couple of issues. You are not using the imagenet weights (can't  imagine why not ) then you set all the layer of the VGG network as untrainable. So you will start out with random weights and stay will stay random. Then you add the Flatten and prediction layers and try to train. All you will be training is a single dense layer. Doubt that will work very well but I guess it will learn something. I would use the imagenet weights as a minimum, I also prefer to train the entire model to get the best results.
Then next issue is the code
test_set = train_datagen.flow_from_directory('chest_xray/test',
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')
#where
train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

You do not want to perform image augmentation on a test set which is what you will be doing so use
test_set =  ImageDataGenerator(rescale = 1./255).flow_from_directory('chest_xray/test',
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'categorical'
                                                 shuffle=False)

Next you are using model.fit_generator, that will work for now but is being depreciated in future versions of tensorflow. Use model.fit it now works with generators I think starting with tensorflow 1.5. What you call the test set is normally called the validation set so that's OK. You have specified a batch_size=32.However you have the code in model.fit
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
# what you want is
steps_per epoch=len(training_set)//32
validation_steps=len(test_set)//32

Once you train your model it has the weights you desire to use for dataset2. Just create new generators for datset2 and retrain it with model.fit


text:
Q: Connect multiple clients using single thread with synchronous or asynchronous? a few months ago,i had asked some relative questions about qt tcp network programming for my project. And finally the software  came out. But after learned more detail about qt event mechans and signals -slots  realization. I have some worry about my program performance and stability.
The key problem is that server using a single thread for handle multiple tcpsockets. the brief introduction code for realization:

*

*incomingConnection function  is writen as following: two QSignalMapper are used for map each socket SlotReadyRead and SlotDisconnected
void ServerModule::incomingConnection(qintptr socketDescriptor)
 {
    m_tcpSocket = new QTcpSocket(this);
    if (!m_tcpSocket->setSocketDescriptor(socketDescriptor)) {
        return;
    }
    connect(m_tcpSocket, SIGNAL(readyRead()), m_readyReadSignalMapper, SLOT(map()));
     m_readyReadSignalMapper->setMapping(m_tcpSocket, m_tcpSocket);
     connect(m_tcpSocket, SIGNAL(disconnected()), m_disconnectedSignalMapper, SLOT(map()));
     m_disconnectedSignalMapper->setMapping(m_tcpSocket, m_tcpSocket);
     }

*the sever construct function:

ServerModule::ServerModule(QObject * parent) : QTcpServer(parent),m_readyReadSignalMapper(new QSignalMapper(this)),m_disconnectedSignalMapper(new QSignalMapper(this))
{

    connect(m_readyReadSignalMapper, SIGNAL(mapped(QObject *)), this, SLOT(SlotReadyRead(QObject *)));
    connect(m_disconnectedSignalMapper, SIGNAL(mapped(QObject *)), this, SLOT(SlotDisconnected(QObject*)));
       ......other code
}

*SlotReadyRead and  SlotDisconnected functions are every normal,it convertsQObject* socketObject to QTcpSocket *socket and then do some work.

So i have learned that if write like aboving connect function  with specific connect  mode

Qt::DirectConnection
  Qt::QueuedConnection
  Qt::BlockingQueuedConnection

if using single thread,only first mode and second mode can be used . And use first mode, it's  synchronous  ,if second, it's asynchronous. My program default  using first mode, so the signals -slots are connected  synchronous.
So here is my worry:
1. How about the single thread performance  for handling  multiple sockets?can it reach 500 connection /per second concurrency?what's  the max connected can be handled?
2. if at the same time,multiple sockets are ready to read then called qt core to send readyRead signals, the QSignalMapper can handle it properly?
3. should I connect socket and QSignalMapper using QueuedConnection  mode, because this connecting  is not connected immediately, it's using event queue and postEvent to connect. so its asynchronous. Is in this situation,the concurrency request  can be handled?

A: First a few issues with your code:

*

*QSignalMapper just adds complexity to your code

*Don't use a member variable for QTcpSocket, you will be overwriting it every time and chances are that you might use an invalid pointer

*If you are not doing something complex or using QSslSocket don't subclass QTcpServer, just connect to the newConnection() signal and call nextPendingConnection()

Now to the connect part of your questioning you should read https://woboq.com/blog/how-qt-signals-slots-work.html in short:

*

*Qt::DirectConnection - means once the signal is emitted the slot will called immediately, if the object that has the slot lives in another thread it will be called in the caller thread. This is used if Qt::AutoConnection is used and both objects live in the same thread.

*Qt::QueuedConnection - means that when the signal is emitted it will create an event and be put on the event loop to be dispatched once you return to the event loop, this is useful for different threads as the slot will called on the thread that the object lives in. This is NOT what you want here, nor how QTcpSocket should be used (read the docs).

*Qt::BlockingQueuedConnection - is very rare to use this one, this like the above puts the event on the event loop of the other thread, but it blocks until the slot was called.

The only "Sync" method is the blocking one, because it would block, but that doesn't mean it's a problem, you can have a non-gui thread that blocks waiting for the reply of the gui thread while asking the user for a password for example.
To the questions now:
UPDATED 1 and 3 for more clarification

*

*Performance really depends on what these sockets will do, how long each will take to process the request and send a reply, in Cutelyst Web Framework a single thread on an i5 can process up to 100K req/s (returning a 'Hello Wolrd!' string HTTP response), the maximum number depends of concurrent connections will be limited by max ports available, memory available to allocate memory and of course if it's CPU intensive the clients will have a long time waiting.

The most common way is to call sender() on your slot, due a small hit on performance (due sender() call) it's faster to use a lambda:
void Parser::readyRead() {
     auto socket = qobject_cast<QTcpSocket*>(sender());
     ...
}

Or with a lambda:
connect(sock, &QTcpSocket::readyRead, [sock] () {
    // use sock obj here
});

*Again QSignalMapper is not what you want, you should call sender() to get the QTcpSocket or use a lambda capturing the socket object (this is a little faster)

*No shouldn't used QueuedConnection connection on your QSignalMapper, because that will cause an unneeded overhead due the fact that it will put the event on the event loop queue and it will be processed later, it might also cause weird bugs due the way QTcpSockets handle data (you must consume all the bytesAvailable() on readyReady since if no extra data arrives readyRead() signal is not emitted again.


text:
Q: Detecting the users browser with the User Agent String I want to detect the browser using the UAS however it seems that the general consensus is that it is a terrible idea. My problem is that by using say, JS or JQuery it would detect it to late, I need the server to be told what browser and send back browser specific information.
This is for a mobile part of the site, if a mobile browser is detected, the server sends content B otherwise it is content A.
I like to keep to what the community generally approves of however I can only see one method to achieve what I want, but it feels like I am breaking a rule.

A: You may try to check this Browser detection using the user agent

The most common reason to perform user agent sniffing is to determine
  which type of device the browser runs on.

A: you could just check if the browser is on mobile using javascript:
var isTouch = ("ontouchstart" in document.documentElement);
if(isTouch){
      // is on mobile device
} else {
      // is NOT on mobile device
}

or you could use a js library like Moderizer:
http://modernizr.com/download/#-touch-shiv-cssclasses-teststyles-prefixes-load
using PHP you could try this:
http://mobiledetect.net/
http://code.google.com/p/php-mobile-detect/
http://detectmobilebrowsers.com/  - download the script you need
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)));
header('Location: http://detectmobilebrowser.com/mobile');
?>

A: The server cannot know what you are using to access it by itself; a javascript library would work best for this purpose.
My solution:
Load page A which detects the browser (Modernizr works for this) then use a javascript redirect to page B with posted variables of what browser is being used.


text:
Q: Conectar mysql no Android Studio Tenho um sistema web-based onde a base de dados dele é com Mysql. Estou começando agora a desenvolver a aplicação no Android usando o Android Studio. Gostaria de saber se tem como criar conexão Mysql no Android Studio, aproveitando as tabelas desse sistema que já encontram-se prontas e populadas. Tenho visto alguns modelos usando o SQLite, mas não seria o meu caso. Tentei com o código abaixo, mas quando executo, ele mostra que o app parou de funcionar:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tela_login);

        editEmail = (EditText)findViewById(R.id.editEmail);
        editSenha = (EditText)findViewById(R.id.editSenha);
        btnAcessar = (Button)findViewById(R.id.btnAcessar);
        txtLembrarSenha = (TextView)findViewById(R.id.txtLembrarSenha);

       btnAcessar.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               ConnectivityManager connectivityManager =
                       (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
               NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

               if(networkInfo != null && networkInfo.isConnected()){

                   String email = editEmail.getText().toString();
                   String senha = editSenha.getText().toString();

                   if(email.isEmpty() || senha.isEmpty()){
                       Toast.makeText(getApplicationContext(),"Favor preencher corretamente os campos",Toast.LENGTH_LONG).show();
                   }else{
                       url = "http://192.168.0.13/projeto/conexao-mobile/logar.php";
                       parametros = "email=" + email + "&senha=" + senha;
                       new SolicitaDados().execute(url);
                   }

               }else {
                   Toast.makeText(getApplicationContext(), "Nenhuma conexão ativa", Toast.LENGTH_LONG).show();
               }
           }
       });
    }

    private class SolicitaDados extends AsyncTask<String, Void, String> {

       @Override
       protected String doInBackground(String... urls){

            return Conexao.postDados(urls[0], parametros);

       }

        @Override
        protected void onPostExecute(String resultado){
           // textView.setText(result);
            txtErro.setText(resultado);

        }
    }

O erro que aparece é:
01-21 17:20:21.947 16889-16889/br.com.projeto.acessosistema E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.projeto.acessosistema, PID: 16889
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at br.com.projeto.acessosistema.TelaLogin$SolicitaDados.onPostExecute(TelaLogin.java:78)
at br.com.projeto.acessosistema.TelaLogin$SolicitaDados.onPostExecute(TelaLogin.java:66)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

A Conexão estou usando de forma básica:
<?php
$email = $_POST["Login"];
$senha = $_POST["Senha"];

$conexao = mysqli_connect('192.168.0.13','root','','projeto');

$sql = mysqli_query($conexao,"SELECT * FROM pe_acessos Email = '".$email."' AND SenhaAcessos = '".$senha."'");

if(mysqli_num_rows($sql) == 0){
   echo "Login ou senha inválidos";
}else{
 echo "Vamos conectar";
}
?>

O banco de dados, assim como as tabelas existem.


text:
Q: Excluding top level directory from WordPress htaccess rewrite rules We recently changed over our website to WordPress, with the WordPress files in directory /wp/
I still want to serve other pages from other root level directories i.e., a link such as
http://www.2minuteexplainer.com/clients/xxx/some_subdir/
But any attempt to reach this directory returns a Wordpress 404 error. If I comment out the
WordPress stuff in htaccess, the link above works as expected, but, of course, the rest of the old website shows up too.
I can't seem to find the right combination of rewrite rules.
Here is the htaccess file.
Header add Access-Control-Allow-Origin "*"
Options +FollowSymLinks

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?2minuteexplainer.com$

# RewriteRule ^clients/.*$ /clients$ - [PT]
# one of a number of workarounds I've tried in order to use this directory

# canonical WordPress stuff follows:

RewriteRule ^(/)?$ wp [L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wp/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wp/index.php [L]
</IfModule>

# END WordPress

Seems like I must be making a simple mistake. But what is it??
Thx.

A: The solution is to move the mod_rewrite stuff ( starting with #BEGIN WordPress) into the .htaccess file that controls the WordPress install. It's /wp/ in my case.  Simple, once you know how :-)


text:
Q: Reveal JS - Controls only on speaker view Is it possible to have Reveal JS only display the control arrows on the speaker view?
Setting controls: false disables the arrows on both the main display, and the speaker display. My presentation is in front of a live audience, so they don't need to see the controls, but it'd be handy for me to be able to see them, so I know when I've got slides "below" the current one, as well as "to the right" of it.

A: Assuming that your presentation is loaded as the main page (not in an iframe) adding the following to your presentation should work.
<style>
  .reveal .controls {
    visibility: hidden;
  }
  .notes .reveal .controls {
    visibility: visible;
  }
</style>

<script>
  if (window.self !== window.top) {
    document.body.className += " notes";
  }
</script>

This adds a notes class to the body when the presentation is loaded within an iframe (as is done with the notes plugin). The styling then hides the controls unless it's on the speaker notes page.
If you add it before the call to Reveal.initialize() you shouldn't see the controls at all. Adding it after may result in the controls briefly appearing before being hidden.


text:
Q: There is a fork of my organisation's repo on my Github account and I don't know how that happened? I just started developing for an organisation and cloned their Github repo to my own computer using HTTPS. It's been a few days and I have only been studying the code. Today I noticed that on my own Github account there is a forked version of the organisation's repo. I don't remember forking the project and don't know when or how it happened. It is not impossible that I pressed the fork button on the Github repo page, but I don't think I did. Is there any other way for a repo to get forked to your own account?
When I first cloned the organisation's repo I only had read access to it. I tried to push a new branch to the repo and got an error message (don't remember what it said) and realised that I didn't have write access. Could this have caused the fork to be created?

A: If you didn't use the fork button, it's possible you just edited a file from a repository where you don't have write access, in that case it will automatically fork the repo :


text:
Q: Stay logged in with Selenium using Chrome default profile I want to use selenium with my Google profile, I created this code:
options = webdriver.ChromeOptions()

options.add_argument(r"user-data-dir=C:\Users\myprofile\AppData\Local\Google\Chrome\User Data") #Path to my chrome profile

driver = webdriver.Chrome(executable_path=r"C:\chromedriver.exe", options=options)

driver.get(url)

I got this error:
InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir

I also tried another profile, but return the same error:
options = webdriver.ChromeOptions()

options.add_argument('--user-data-dir=C:/Users/mxs/AppData/Local/Google/Chrome/User Data')
options.add_argument('--profile-directory=Profile 2')

driver = webdriver.Chrome(executable_path=r"C:\chromedriver.exe", options=options)

driver.get(url)

also, I tried codes in both Jupyter Notebook and VSCode

A: Suggestion 1
If you are okay with only one selenium process running at a time, you can use queue to achieve it. As long as you use only one process to access user-dir, it'll not cause any error.
Suggestion 2
If you are trying to stay logged in for some website, you can reuse cookies. In this case you don't need to use user-data-dir thing. Selenium will automatically create temporary user-data-dir on every run.
Suggestion 3
If you still want to use the same profile for every session, here is the hack to do it. You keep original --user-data-dir unused, instead you copy all the content of your original profile directory to some temporary directory and use it with --user-data-dir every time you initiate chrome selenium.

A: Suggestion
When you are trying to run your python script close all the chrome windows. I got the error
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir

when I had one of the chrome windows open. So it is better to close all the chrome windows and try again.


text:
Q: Converting a vector to factor in R and keeping undeclared levels I want to convert a character vector in R to a factor (let's take the example from the DataCamp Introduction to R course) and would like to label a few of the factor levels. How do I avoid, that any unmentioned/undeclared levels are automatically put to NA?
speed_vector <- c("fast", "slow", "slow", "fast", "insane")

factor_speed_vector <- factor(speed_vector, ordered = TRUE, levels = c("slow", "insane"), labels = c("Speed < 30 mph", "Speed > 100 mph"))

results in
> summary(factor_speed_vector)
 Speed < 30 mph Speed > 100 mph            NA's
              2               1               2
> factor_speed_vector
[1] <NA>            Speed < 30 mph  Speed < 30 mph  <NA>            Speed > 100 mph
Levels: Speed < 30 mph < Speed > 100 mph

How can I make sure that any undefined factor level (like "fast" in this example) gets carried over with the original value instead of being set to NA?
Edit:
My previous comment here, was due to a confusion of the level and labels option in the factor function. Anybody, also not knowing the difference can read up here: Confusion between factor levels and factor labels

A: The forcats package has some nice helper functions to deal with factors. The fct_recode() function lets you change factor levels by hand. You can specify a sequence of named character vectors where the name gives the new level, and the value gives the old level. Levels not otherwise mentioned will be left as is.  (from ?fct_recode, emphasis mine).
speed_vector <- c("fast", "slow", "slow", "fast", "insane")
speed_vector

[1] "fast"   "slow"   "slow"   "fast"   "insane"

forcats::fct_recode(speed_vector, "Speed < 30 mph" = "slow", "Speed > 100 mph" = "insane")

[1] fast            Speed < 30 mph  Speed < 30 mph  fast            Speed > 100 mph
Levels: fast Speed > 100 mph Speed < 30 mph

A: Would this suit you ?
speed_vector <- c("fast", "slow", "slow", "fast", "insane")
factor_speed_vector <- factor(speed_vector)
levels(factor_speed_vector)[factor_speed_vector == "slow"]   <- "Speed < 30 mph"
levels(factor_speed_vector)[factor_speed_vector == "insane"] <-  "Speed > 100 mph"
factor_speed_vector
# [1] fast            Speed < 30 mph  Speed < 30 mph  fast            Speed > 100 mph
# Levels: fast Speed > 100 mph Speed < 30 mph

A: Using levels and match, you can do the following.
Start with a factor variable:
factor_speed_vector <- factor(c("fast", "slow", "slow", "fast", "insane"), ordered = TRUE)

Then, change the levels of the variable pulling the proper indices with match
levels(factor_speed_vector)[match(c("slow", "insane"), levels(factor_speed_vector))] <-
c("Speed < 30 mph", "Speed > 100 mph")

Here, match(c("slow", "insane"), levels(factor_speed_vector)) finds the indices for the factor levels matching "slow" and "insane". These indices are used to subset the levels and then the new labels are fed in.

A: factor_speed_vector = as.factor(speed_vector)

# > levels(factor_speed_vector)
# [1] "fast"   "insane" "slow"

levels(factor_speed_vector)[3:2] = c("Speed < 30 mph", "Speed > 100 mph")

# > factor_speed_vector
# [1] fast            Speed < 30 mph  Speed < 30 mph  fast            Speed > 100 mph
# Levels: fast Speed > 100 mph Speed < 30 mph


text:
Q: using onscroll on an element that doesnt scroll So I have an element that I want to be able to zoom in and out of using the scroll wheel on my mouse. I thought a good way to go about this would be something like this:
JavaScript:
var container = document.getElementById("container"),
    zoom = document.getElementById("zoom");
var x = 0, lastScrollTop = 0;
const zoomWidth = zoom.getBoundingClientRect().width;
// I want the container to be the one that is targeted because
// sometimes the zoom element will be offset horizontally by too much
container.onscroll = function(e){
    e.preventDefault();
    var scrollTop = this.scrollTop;
    x += (scrollTop < lastScrollTop ? 0.1 : -0.1);

    zoom.style.width = (zoomWidth * x) + "px";
    lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
}

HTML:

JsFiddle
The only problem with this is that you can't detect whether or not the user is scrolling up or down (or detect if the scroll wheel is being used at all for that matter), when the element itself doesn't scroll.
So how do I go about zooming using the scroll wheel, on an element that doesn't actually scroll? Cheers.

A: There is an event called wheel
you can attached a wheel event listener on the element
el.addEventListener('wheel', function(event){
  //do your job here
});

available properties in wheel event
    {
    altKey: false
    bubbles: true
    button: 0
    buttons: 0
    cancelBubble: false
    cancelable: true
    clientX: 345
    clientY: 154
    composed: true
    ctrlKey: false
    currentTarget: div
    defaultPrevented: false
    deltaMode: 0
    deltaX: -0
    deltaY: -125
    deltaZ: 0
    detail: 0
    eventPhase: 2
    fromElement: null
    isTrusted: true
    layerX: 89
    layerY: 61
    metaKey: false
    movementX: 0
    movementY: 0
    offsetX: 90
    offsetY: 62
    pageX: 345
    pageY: 154
    path: (5)[div, body, html, document, Window]
    relatedTarget: null
    returnValue: true
    screenX: 822
    screenY: 491
    shiftKey: false
    sourceCapabilities: null
    srcElement: div
    target: div
    timeStamp: 171662.21500000005
    toElement: div
    type: "wheel"
    wheelDelta: 150
    wheelDeltaX: 0
    wheelDeltaY: 150
    which: 0
    x: 345
    y: 154
}

property    deltaX , deltaY are sufficient for calculating
There is a nice example in mdn check here


text:
Q: Move values duplicated between columns
*

*This is my Excel sheet. Columns G and Column J have the same values but in different order.

*The code runs and moves the values from Column J to Column H, beside the same value of column G.

*The problem with this is that when there are two values the same it moves it to the first value it finds in Column H. The value 747.00 in J:2 must move to H:2 while the value 747.00 in J:5 must move to H:6 not to H:2.

This is the code:
Dim cel As Range, cel2 As Range
Dim lastRow As Long
lastRow = Cells(Rows.Count, 10).End(xlUp).Row
For Each cel In Range(Cells(1, 7), Cells(lastRow, 7))
    For Each cel2 In Range(Cells(1, 10), Cells(lastRow, 10))
        If cel2.Value = cel.Value Then
            cel.Offset(0, 1).Value = cel2.Value
            cel2.Value = ""
        End If
    Next cel2
Next cel

A: It sounds like you are cycling through column J and looking for a match in column G. I've reversed that by cycling through column G and looking for a match in column J. Once one match has been found it is moved over to column H thereby removing it from column J.
Sub match_em_up()
    Dim rwg As Long, rwj As Long

    With Worksheets("Sheet1")
        For rwg = 2 To .Cells(Rows.Count, "G").End(xlUp).Row
            If CBool(Application.CountIf(.Columns("J"), .Cells(rwg, "G").Value2)) Then
                rwj = Application.Match(.Cells(rwg, "G").Value2, .Columns("J"), 0)
                .Cells(rwg, "H") = .Cells(rwj, "J").Value2
                .Cells(rwj, "J").ClearContents
            End If
        Next rwg
    End With
End Sub

Before:

After:


text:
Q: How to format an object of objects I have this object
myObject = {
  id: "44",
  name: "name",
  firstName: "fn",
  lastName: "tt",
  cars: [],
  houses: [],
  family: {}
}

I want to format this object to
myObject = {
  person: {
    id: "44",
    name: "name",
    firstName: "fn",
    lastName: "tt"
  },
  cars: [],
  houses: [],
  family: {}
}

Is there anyway i can do this without using delete?

A: You can use destructuring:

const myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}

const { houses, cars, family, ...rest } = myObject

const myNewObject = {
  person: rest,
  houses,
  cars,
  family
}
console.log(myNewObject)

A: You can use destructuring assignments to decompose your object into variables and restructure them in a simple function.

const format = (obj) => {
    const {id, name, firstName, lastName, ...props} = obj;
    return {person: {id, name, firstName, lastName}, ...props}
}

const formatted = format(myObject);

console.log (formatted)
<script>
var myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
</script>

A: You could create a new object and assign the properties to it:

let obj = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}

//I want to format this object to
//myObject = { person: {id:"44", name:"name", firstName:"fn", lastName:"tt"}, cars: [], houses:[], family:{}}

let res =  {}

res.person = {id: obj.id, name: obj.name, firstName: obj.firstName, lastName: obj.lastName}
res.cars = obj.cars
res.houses = obj.houses
res.family = obj.family

console.log(res)

A: You can destructure what you need, put the rest into a variable rest, and then re-assign myObject:

let myObject = {
  id: "44",
  name: "name",
  firstName: "fn",
  lastName: "tt",
  cars: [],
  houses: [],
  family: {}
}

const {id, name, firstName, lastName, ...rest } = myObject;

myObject = {
  person: { id, name, firstName, lastName },
  ...rest
}

console.log(myObject);


text:
Q: Do we say someone has wrinkles "on" or "in" their forehead? I asked some native speakers, and they all say that "she has wrinkles on her forehead".
However, the dictionary says "He had deep wrinkles in his forehead." and "I tried to iron out the wrinkles in my shirt.".
Another dictionary says "They were always paired with some sign of effort — eyes narrowing, drawing a wrinkle on his forehead."
I wonder why the first dictionary says "wrinkles in his forehead."?

A:
He has wrinkles on his forehead

The native speakers are referring to the surface of his skin. This is the common way of talking about wrinkles because the wrinkles are visible.

He had deep wrinkles in his forehead.

As evident from the word "deep", the wrinkles are situated below the skin surface and may or may not be visible to the human eye.

A: Perhaps the English dictionary you consulted was old, and hasn't been updated in a long time. For me, I would always use 'on' in the above examples.


text:
Q: Android dataBinding - How to get resource id of a View in xml In Android Studio my data binding itself works and is set up fine. I have a boolean defined like this:
<resources>
    <bool name="showAds">false</bool>
</resources>

and in a layout.xml file i would like to referenced this boolean (which works fine) but i want to assign a id based on this boolean. Let me show you what i am trying to accomplish:
I have a button that is in a relativeLayout tag and depending on this boolean i would like to reposition the button. So I have this:
<Button
   android:id="@+id/startButton"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="64dip"
   ****************
   android:layout_below="@{@bool/showAds ? @+id/adone : @+id/title_main}"
   ****************
   android:layout_centerHorizontal="true"
   android:textColor="#0080FF"
   android:text="@string/start_btn_title" />

See what i want to to do? I want to layout the button below a layout called adone if the showAds boolean is true, otherwise place it below a layout called title_main.  Whats the syntax for this as what I have here is not compiling. I get a compile error:

expression expected after the second @ sign

A: The above is the same problem as in How to get dimensions from dimens.xml
None of the LayoutParams attributes have built-in support. As answered in the linked article, data binding of LayoutParams was thought to be too easy to abuse so it was left out of the built-in BindingAdapters. You are not abusing it, so you should add your own.
@BindingAdapter("android:layout_below")
public static void setLayoutBelow(View view, int oldTargetId, int newTargetId) {
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
        view.getLayoutParams();
    if (oldTargetId != 0) {
        // remove the previous rule
        layoutParams.removeRule(RelativeLayout.BELOW);
    }
    if (newTargetId != 0) {
        // add new rule
        layoutParams.addRule(RelativeLayout.BELOW, newTargetId);
    }
    view.setLayoutParams(layoutParams);
}

As an aside, the @+id/adone in the binding syntax will not create the id. You should create the id in the View you're binding to.


text:
Q: How do I display a latex string as latex output in sympy (jupyter notebook)? My preamble in Jupyter is:
%reset
import numpy as np
from sympy import *
from sympy.physics.quantum import Commutator, Dagger, Operator
from sympy.vector import CoordSys3D
import matplotlib.pyplot as plt
from sympy.interactive import printing
printing.init_printing(use_latex = True)

How do I print the following string in latex form? I crucially do not want the order of the terms within the string to change.
'\\mathbf{R}_B \\cdot j'

A: So an answer is:
from IPython.display import Math
display(Math('\\mathbf{R}_B \\cdot j'))

Which preserves the order of the symbols. However, 'Math' has no attribute 'subs' and has trouble sympifying, so it seems doing sympy operations on this output isn't possible.

A: Following this solution
from IPython.display import display, Math
display(Math('\\mathbf{R}_B \\cdot j'))

Output


text:
Q: Выбор чисел Фибоначчи Задача не практическая. Хочется оценить, какими подходами ее можно решить на SQL'ях разных диалектов (PostgreSQL, SQLite3, MySQL). И как сложно это решаемо.
Задача
Есть таблица с положительными числами [0..N]. Нужно вывести в порядке возрастания все числа из указанной таблицы, которые входят в последовательность Фибоначчи.

A: Генератор без использования таблиц для SQLite, postgresql:
WITH Recursive Q(Num,Prev) as(
   select 1,1
  union all
   select Q.Num+Q.Prev,Q.Num
     from Q
    where Q.Num<10000
)
select Num from Q

Если надо выбрать из них только те числа, что есть в некой таблице - то в итоговый select добавить join с этой таблицей для проверки наличия числа в ней.
Для MS SQL и Oracle - убрать из запроса выше фразу Recursive. Для Oracle дополнительно добавить from DUAL после select 1,1.
Для MySQL требуется опорная таблица с нужным количеством записей, содержимое этих записей значения не имеет:
select @tmp:=@Prev+@Num as Num, @Prev:=@Num, @Num:=@tmp
  from seqnum, (select @Prev:=1, @Num:=1) A
 order by Num

Это опять же генератор. Для проверки наличия в некой таблице - заключить в подзапрос и сделать join.

A: Отвечаю сам себе :) пока для PostgreSQL:
Решается в несколько этапов:
1) Поиск максимального значения в таблице
2) CROSS JOIN всей таблицы с результатом выборки от хранимой процедуры по соответствию
CREATE OR REPLACE FUNCTION fib(f INTEGER)
RETURNS SETOF INTEGER
LANGUAGE SQL
AS $$
WITH RECURSIVE t(a,b) AS (
        VALUES(0,1)
    UNION ALL
        SELECT greatest(a,b), a + b AS a FROM t
        WHERE b < $1
   )
SELECT a FROM t;
$$;

где аргументом будет максимальное значение из таблицы
Для SQLite3 и MySQL ждем-c ... ) Хотя, чего греха таить, возможно и для PostgreSQL без хранимой процедуры.


text:
Q: How to Download file on frontend in KeystoneJS I have used a local file field and full file URL not store in a database.
Would you please let me know a possible way to solve this problem.
Thanks

A: There is a couple of ways to do this.

*

*Save your file in your assets folder, from where you serve your CSS and JS files and fetch it from there.
OR

*Create an API/Route on the server which will send this file to the browser. <Check This>


text:
Q: LCI data format in BW2 So I want to import my own LCI database to Brightway2, and my process has 3 valuable products.
I found this example with co-products: https://github.com/massimopizzol/B4B/blob/main/02.2_Simple_LCA_co_products.py
The example shows more or less how it works, but I would like to use allocation for my process and not substitution. Should I just change the type to "allocation" instead of putting there "substitution", or is bw2 not supporting allocation? Also, if we have 3 valuable products, the first one is part of the main activity as type="production", and 2 others have 'type="substitution"? And for the other 2, we create 2 separate activities and they are just kinda one exchange activity, in which their type is production, like the example?
Besides just to make sure, if one of the inputs has the type="technosphere", we need to create another activity where we show the process behind it. When it comes to raw products, they have the type="biosphere", and their amounts are negative, in comparison to emissions.
I set other valuable products type as "substitution" and for each of them I created a new activity, where their type was equal to "production". Overall it worked, but the obtained LCA score wasn't correct, so I don't know if it wasn't conceptual mistake.
Thank you in advance for all your help and time!

A: Changing "substitution" by "allocation" will not work. If you want to use allocation / partition, I would create the activities with the exchanges already allocated.
The meaning of the "substitution" exchange as well as the sign conventions for biosphere flows is explained in the documentation here.

A: So, Brightway currently does not have a model where you can enter a multifunctional process and get the software to do allocation for you. You will need to do the allocation yourself :) Here is a notebook I wrote up that shows a simple allocation procedure.
P.S. In the future please only post to one of the beginners mailing list or SO, otherwise everyone doesn't get notified twice.


text:
Q: Python os.access() reads file no matter what I have a script that checks a file for vulnerabilities. If the file path exists, the script then checks to see if the file can be read. However, when I set the file's permissions,  os.access() is able to read the file no matter what. In windows I have denied all permissions and in Linux, I have tried chmod 000 on the file and got the same output on both machines.Here is the code:
import sys
import os

if len(sys.argv) == 2:
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '[-] ' + filename + ' does not exist.'
        exit(0)
    if not os.access(filename, os.R_OK):
        print '[-] ' + filename + ': access denied.'
        exit(0)

    print '[+] Reading Vulnerabilities From: ' + filename

Whenever I pass an incorrect file name or path, os.path.isFile() works fine, however os.access() doesn't. I'm fairly new to python as well, all help will be appreciated
UPDATED:
When I run the script I use the command:
python scriptName.py vuln_banners.txt

after I have already ran
chmod 000 vuln_banners.txt

The only output I get is:
'[+] Reading Vulnerabilities From: vuln_banners.txt

I ran
ls -la vuln_banners.txt

and got the output:
---------- 1 root root 397 Dec 31 22:32 vuln_banners.txt

A: It seems from your last comment that you are running the script as root which is a no no in Linux unless you REALLY know what you're doing.
os.access() will return True if you're running in root as you will have access to read the file even if its permissions are 000.
I was able to reproduce your issue when I tried running your script under root privileges. Try running it under a normal user and it should behave as expected then.
Also, if the script fails, you don't want it to return a 0, you want to return another value. The value 0 represents exiting with no error. Your script should look something similar to this where the return value of the exit is meaningful to you.
import sys
import os

if len(sys.argv) == 2:
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '[-] ' + filename + ' does not exist.'
        rvalue = 1
    elif not os.access(filename, os.R_OK):
        print '[-] ' + filename + ': access denied.'
        rvalue = 2
    else:
        print '[+] Reading Vulnerabilities From: ' + filenam
        rvalue = 0

exit(rvalue)


text:
Q: Save image and retrieve it to velocity template I'm using spring 2.5 + velocity for my application. I have requirement to upload an image and retrieve it.
I need to just save the url in the DB ,but not the actual image.
how to achieve this requirement, so that it will work in production environment as well.
I did in the following way, but i'm unable to retrieve the image.
I uploaded the image and save it to a local folder in local disk.(D:/..)
in velocity template i ponited the img src to the picture location(i.e: D:/..)
And, i'm able to see the picture using firebug, but picture is not displayed the browser.
Please help me in finding the efficient way to implement this functionality.
Thanks

A: Assuming all your pictures are located in the same folder which is web accessible (you can access it via http://, like http://example.com/images/), you should only save image filename into the database, like image.jpg.
After that you can build image url for display by appending image folder url (usually stored in config file) and filename from db.
So at the end it would be something like:
<img src="${imgRootUrl}${filename}">


text:
Q: Graph of Extracted Links Can anyone tell me if it is possible to get some analytics on the links extracted by a crawler? I know there is the analytics API but I can't quite figure out how to use it and the docs are pretty scant.
I'm trying to troubleshoot why my crawler is extracting some links but not others. For example, I start my crawl on a home page in which there are links to URLs containing the word business but the following rule will not return any items.
rules = (
        Rule(LinkExtractor(allow=('business', )), callback='parse_item', follow=True),
    )

It would be great if there is a way to log some sort of graph of extracted links but I cannot find a way to implement this.

A: You are misunderstanding scrapy LinkExtractor's parameters:

allow (a regular expression (or list of)) – a single regular expression (or list of regular expressions) that the (absolute) urls must match in order to be extracted. If not given (or empty), it will match all links.

You can test your linkextractors in python shell:
>: from scrapy.linkextractors import LinkExtractor
>: from scrapy.http import HtmlResponse
>: body = "business"
>: resp = HtmlResponse('http://example.com', 200, body=body, encoding='utf8')
>: LinkExtractor().extract_links(resp)
<: [Link(url='http://example.com/somewhere.html', text='business', fragment='', nofollow=False)]
>: LinkExtractor(allow='business').extract_links(resp)
<: []

To match text you can use restrict_xpath parameter:
>: LinkExtractor(restrict_xpaths='//*[contains(text(),"business")]').extract_links(re
   sp)
<: [Link(url='http://example.com/somewhere.html', text='business', fragment='', nofollow=False)]

Check out official docs for LinkExtractor

A: I think that the easier way to test your rule is to test your LinkExtractor obj using scrapy shell and assuming you're talking about the CrawlSpider I think there's no built-in way of doing that. Nonetheless, if you want to generate some sort of directed graph you could subclass the LinkeExtractor and overwrite the extract_links method to print the "graph edges" like:
logger = logging.getLogger('VerboseLinkExtractor')
class VerboseLinkExtractor(LinkExtractor):
    def extract_links(self, response):
        links = super(Graph, self).extract_links(response)
        for link in links:
            logger.debug("{} ==> {}".format(response.url, link.url)) # or a simple print
        return links


text:
Q: How to create animation when select IconButton in flutter I have just created a simple selectable 2 IconButton as the below code:
class _RadioBtnSimState extends State<RadioBtnSim> {
  bool _isSelectedLeftButton = true;
  bool _isSelectedRightButton = false;

  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Column(
            children: [
              Ink(
                height: _isSelectedLeftButton ? 80.0 : 60.0,
                width: _isSelectedLeftButton ? 80.0 : 60.0,
                decoration: ShapeDecoration(
                  color: _isSelectedLeftButton
                      ? Colors.green.withOpacity(0.50)
                      : Colors.grey.withOpacity(0.50),
                  shape: CircleBorder(),
                ),
                child: IconButton(
                  icon: Icon(Icons.sim_card),
                  color: Colors.white,
                  iconSize: _isSelectedLeftButton ? 40.0 : 30.0,
                  onPressed: () {
                    setState(() {
                      _isSelectedLeftButton = true;
                      _isSelectedRightButton = false;
                    });
                  },
                ),
              ),
              Text(
                'Sim 1',
                style: _isSelectedLeftButton
                    ? TextStyle(color: Colors.green)
                    : TextStyle(color: Colors.grey),
              ),
            ],
          ),
          SizedBox(
            width: 20.0,
          ),
          Column(
            children: [
              Ink(
                height: _isSelectedRightButton ? 80.0 : 60.0,
                width: _isSelectedRightButton ? 80.0 : 60.0,
                decoration: ShapeDecoration(
                  color: _isSelectedRightButton
                      ? Colors.green.withOpacity(0.50)
                      : Colors.grey.withOpacity(0.50),
                  shape: CircleBorder(),
                ),
                child: IconButton(
                  icon: Icon(Icons.sim_card),
                  color: Colors.white,
                  iconSize: _isSelectedRightButton ? 40.0 : 30.0,
                  onPressed: () {
                    setState(() {
                      _isSelectedLeftButton = false;
                      _isSelectedRightButton = true;
                    });
                  },
                ),
              ),
              Text(
                'Sim 2',
                style: _isSelectedRightButton
                    ? TextStyle(color: Colors.green)
                    : TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

now all I need, I want to create a simple animation when select the IconButton...
Is there's simple and easy way to do this?

A: You can wrap it in a AnimatedContainer with a box decoration. The color will animate automatically when changed.
Something like this:
var buttonColor = Colors.blue;

AnimatedContainer(
width: 100,
height: 100,
decoration: BoxDecoration(color: buttonColor,)
child: yourWidget
)

And then to change it:
SetState((){
buttonColor = Colors.red // or any other color
})

EDIT
In your case it would be something like this
class _RadioBtnSimState extends State<RadioBtnSim> {
  bool _isSelectedLeftButton = true;
  bool _isSelectedRightButton = false;

  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Column(
            children: [
              AnimatedContainer(
                height: _isSelectedLeftButton ? 80.0 : 60.0,
                width: _isSelectedLeftButton ? 80.0 : 60.0,
                decoration: BoxDecoration(
                  color: _isSelectedLeftButton
                      ? Colors.green.withOpacity(0.50)
                      : Colors.grey.withOpacity(0.50),
                  shape: RoundedRectangleBorder(borderRadius: 20.0),
                ),
                child: IconButton(
                  icon: Icon(Icons.sim_card),
                  color: Colors.white,
                  iconSize: _isSelectedLeftButton ? 40.0 : 30.0,
                  onPressed: () {
                    setState(() {
                      _isSelectedLeftButton = true;
                      _isSelectedRightButton = false;
                    });
                  },
                ),
              ),
              Text(
                'Sim 1',
                style: _isSelectedLeftButton
                    ? TextStyle(color: Colors.green)
                    : TextStyle(color: Colors.grey),
              ),
            ],
          ),
          SizedBox(
            width: 20.0,
          ),
          Column(
            children: [
              Ink(
                height: _isSelectedRightButton ? 80.0 : 60.0,
                width: _isSelectedRightButton ? 80.0 : 60.0,
                decoration: ShapeDecoration(
                  color: _isSelectedRightButton
                      ? Colors.green.withOpacity(0.50)
                      : Colors.grey.withOpacity(0.50),
                  shape: CircleBorder(),
                ),
                child: IconButton(
                  icon: Icon(Icons.sim_card),
                  color: Colors.white,
                  iconSize: _isSelectedRightButton ? 40.0 : 30.0,
                  onPressed: () {
                    setState(() {
                      _isSelectedLeftButton = false;
                      _isSelectedRightButton = true;
                    });
                  },
                ),
              ),
              Text(
                'Sim 2',
                style: _isSelectedRightButton
                    ? TextStyle(color: Colors.green)
                    : TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

A: for easy resizing and so many other animations you can use animatedContainer but if you want to use complex animations you have to use animationController and animatedWidget.

A: Just Replace both the Ink widgets with AnimatedContainer and give it a duration to it..
this way -
AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  height: _isSelectedLeftButton ? 80.0 : 60.0,
                  width: _isSelectedLeftButton ? 80.0 : 60.0,
                  decoration: ShapeDecoration(
                    color: _isSelectedLeftButton
                        ? Colors.green.withOpacity(0.50)
                        : Colors.grey.withOpacity(0.50),
                    shape: CircleBorder(),
                  ),
                  child: IconButton(
                    icon: Icon(Icons.sim_card),
                    color: Colors.white,
                    iconSize: _isSelectedLeftButton ? 40.0 : 30.0,
                    onPressed: () {
                      setState(() {
                        _isSelectedLeftButton = true;
                        _isSelectedRightButton = false;
                      });
                    },
                  ),
                ),


text:
Q: Jhipster Swagger configuration How to override Jhipster swagger configuration in a microservice project to change the /api path in the backend and update gateway Swagger UI accordingly ?

A: Have you tried setting default-include-pattern in swagger section of your config file (probably application.yml)?
Default setting is /api/.*. For my project I changed it to /(api|io)/.* (its a regex) to include api and io paths.

A: As of JHipster 7.0, the following changes were made to the backend:

*

*swagger maven profile becomes api-docs

*jhipster.swagger property becomes jhipster.api-docs
In order to enable swagger api and to change the default uri pattern I had to:
1 - Enable the maven api-docs profile
2 - Add the following property under to application.yml (replace with your api path):
jhipster:

  api-docs:
    default-include-pattern: /api-new-path/.*


text:
Q: How to reconstruct with Agda the proof of a theorem produced by one ATP I am trying to prove a theorem of differential geometry:  the Cartan structural equation.
I am using the following code
 cnf(axio1,axiom,
   (w(h(X))= zero)).

cnf(axio2,axiom,
   (w(v(X))= v(X))).
cnf(axio2A,axiom,
   (X= sum(h(X),v(X))  )).

cnf(axio3A,axiom,
   (dw(sum(X,Y),Z)= sum(dw(X,Z),dw(Y,Z))  )).
cnf(axio3,axiom,
   (dw(X,sum(Y,Z))= sum(dw(X,Y),dw(X,Z))  )).

cnf(axio4,axiom,
   (w(sum(X,Y))= sum(w(X),w(Y))  )).

cnf(axio5,axiom,
   (sum(zero,X)= X  )).

cnf(axio5A,axiom,
   (sum(X,sum(Y,Z))= sum(sum(X,Y),Z)  )).

cnf(axio6,axiom,
   (dw(X,Y)= divi(subst(subst(act(X,w(Y)),act(Y,w(X))),w(commu(X,Y))),two)  )).

cnf(axio6A,axiom,
   (subst(zero,zero) = zero      )).

cnf(axio6B,axiom,
   (subst(zero,X) = minus(X)      )).

cnf(axio7,axiom,
   (act(X,w(v(Y)))=zero                )).

cnf(axio7A,axiom,
   (act(X,zero)=zero                )).

cnf(axio8,axiom,
   (commu(h(X),v(Y))=h(z)                    )).

cnf(axio9,axiom,
    (minus(zero)=zero)).

cnf(axio10,axiom,
    (divi(zero,two) = zero      )).

cnf(axio11,axiom,
    (commu(X,Y)=minus(commu(Y,X))      )).

cnf(axio12,axiom,
    (w(minus(X))=minus(w(X))  )).

cnf(axio13,axiom,
   (sum(zero,X) = X        )).

cnf(axio14,axiom,
   (divi(minus(X),two) =minus(divi(X,two))  )).

cnf(axio14A,axiom,
   (sum(minus(X),X) = zero       )).

cnf(axio15,axiom,
    (w(commu(v(X),v(Y))) = commu(v(X),v(Y))      )).

cnf(axio15A,axiom,
   ( omega(X,Y)=dw(h(X),h(Y))              )).

cnf(goal,negated_conjecture,
   (sum(dw(X,Y),divi(commu(w(X),w(Y)),two))!=
omega(X,Y)   )).

The following ATPs were able to produce the proof: Bliksem, CiME, CVC4, E, EQP, Fiesta, Geo, Isabelle, Isabelle-HOT, LEO-II, Matita, Metis, Otter, Prover9, SNARK, SPASS, Vampire, Vampire-SAT.
My question is: how to reconstruct with Agda the proof generated by the mentioned ATPs?


text:
Q: L(a/ua)TeX kernel/package solution incorporating the globally optimised float placement/pagination It was interesting to read Frank Mittelbach's articles on globally optimized pagination and  float placement.
https://www.latex-project.org/publications/
But, there is no mention of these proposed improvements being incorporated into the kernel or as a package.
I wonder if the mischief has actually been managed, i.e. are the improvements ready for rest of the world?
PS: I was long hoping that the standard greedy algorithm for float placement would get superseded by something fancier, and the articles seem to promise just that.

A: Unfortunately there is a huge difference between a proof of concept prototype that shows the feasibility of an approach and a fully working version that could be released to the world.
The problem that I tackled in these research papers is after all a very old problem. It has been raised in the early '80s in the PhD thesis of Michael Plass and since then there hasn't been much in terms of theoretical further results, let alone practical solutions to it.
What I have been able to show in the recent work, is that the problem is solvable in practice (in a flexible/customizable way that makes it suitable for real life situations) and if doing so with a time penalty that is acceptable.
However, to turn that into a LaTeX package or kernel code (or even its own eco system) that can actually deal with all kind of real life issues one finds in normal TeX documents is something totally different.
E.g., it is a big difference to prove that something like footnotes are a minor nuisance that do not change the overall complexity of the algorithm and its time bounds to actually implementing footnotes into such an algorithm so that they work in practice, etc. for all the niggling issues that one encounters in real documents.
So bottom line is, I would expect several 1000 (yes 3 zeros multiplied with a factor strictly greater than 1) hours of work to make that happen and I simply don't have the time for that on an unpaid basis right now, because in some way I need to make a living (and that is not easier after I left HP). I was wondering at some point, if it would be a sensible project for crowd funding and perhaps I give it a try and see what happens.
Otherwise it will take a looong time simply because it is a huge problem (there is a reason that there are only a handful research papers between Michel's and my work).
Remark on @Marijn's comment above
I fear you are mistaken. Yes the actual problem as stated is due to the placement questions that are raised from physical restrictions of the medium (like book type pages). However, there is no way to "lift" them. You only replace them with other mediums to present your data. That medium might be more flexible and not have pagebreaks as problems, but then new questions arrise that are of a similar kind (and possibly more difficult to solve in fact). After all if your search space is too big optimization can be a challenge too.  Take the simple problem of todays ebook novels (no math, nothing complicated, ...). They can do all kind of reflows but often end up with something that is really horrible quality-wise and better algorithms that do some level of optimization given current reflow text size etc would be a very hard problem.
Or take math: your medium whatever that is will have some sort of boundary (if only by what you can grasp with your eyes, even if the placement option to the left or right would be wider ... what does that mean to math formulas? Proofs written in a single 20 foot line just because you can? No, whatever the medium is and its possibilities you will end up with conventions that are needed to convey information successfully and these conventions are then posing restrictions (with or without flexibility) that you need to optimize against, either manually or through algorithms. But don't believe those algorithms being a single iota simpler.
In other words, if not you are distracted by the layout issues (whatever they are with your medium) your consumers will be, as it will hinder them.
cheers - frank


text:
Q: distinct values xslt using overriding param or Array My xml looks like this:
<topics>
   <topic name="topic1" />
 <topic name="topic2" />
 <topic name="topic3" />
 <topic name="topic4" />
 <topic name="topic5" />
 <topic name="topic6" />
<topic name="topic7" />
</topics>
<supertopics>
  <supertopic title="supertopic1" name="1;topic1;#2;#topic2;3;#topic3" />
  <supertopic title="supertopic2" name="4;#topic4;#7;#topic7" />
    <supertopic title="supertopic3" name="2;#topic2;#3;#topic3" />
  <supertopic title="supertopic4" name="5;#topic5;#7;#topic7" />
  <supertopic title="supertopic5" name="3;#topic3;#7;#topic7" />
  <supertopic title="supertopic6" name="4;#topic4;#7;#topic7" />
  <supertopic title="supertopic7" name="5;#topic5;#7;#topic7" />
  <supertopic title="supertopic8" name="2;#topic2;#6;#topic6" />
  <supertopic title="supertopic9" name="5;#topic6;#7;#topic7" />
  <supertopic title="supertopic10" name="3;#topic3;#4;#topic4" />
</supertopics>

I basically want 1 supertopic per topic.So that means I have 7 topics and I want 7 most recent supertopics associated with it. I have date also with it through I m doing sorting but main thing is I want these 7 supertopics to be unique as there are multiple supertopics per topic.
So I want my output to be like this:
supertopic1 (topic1 is associated to supertopic1)
supertopic3 (topic2 is associated to supertopic1 but as its already there i want it to look for next supertopic its associated to)
supertopic5 (topic3)
supertopic2 (topic4)
supertopic4 (topic5)
supertopic8 (topic6)
supertopic6 (topic7)

I am using xsl 1.0
and I was trying to achieve it using  but i couldn't find any way to do this:
<xsl:param name="FilteredAssets1">
 <stopic></stopic>
  <ttopic></ttopic>
</xsl:param>
    <xsl:for-each select="topics/topic/@name">
            <xsl:variable name="topicname">
                <xsl:value-of select="."></xsl:value-of>
            </xsl:variable>
   <xsl:for-each select="/supertopics/supertopic[contains(@name,$topicname)]">
             <xsl:if test="not(contains(msxsl:node-set($FilteredAssets1)/stopic,@title)) and not(contains(msxsl:node-set($FilteredAssets1)/ttopic,$programname))">
        <stopic><xsl:value-of select="@title"></xsl:value-of></stopic>
        <ttopic><xsl:value-of select="$programname"></xsl:value-of></ttopic>

            </xsl:if>
            </xsl:for-each>
         </xsl:for-each>

A: This transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vSupers"
      select="/*/supertopics/supertopic"/>

 <xsl:template match="/*">
  <xsl:apply-templates select="topics/topic[1]"/>
 </xsl:template>

 <xsl:template match="topic">
   <xsl:param name="pUsedSupers" select="/.."/>

   <xsl:variable name="vNewSuper" select=
   "$vSupers
       [not(@title = $pUsedSupers/@title)
      and
        contains(concat(@name, ';'),
                 concat('#', current()/@name, ';')
                )
       ]
        [1]
   "/>

   <xsl:value-of select="concat('
', $vNewSuper/@title)"/>

   <xsl:apply-templates select="following-sibling::topic[1]">
    <xsl:with-param name="pUsedSupers"
     select="$pUsedSupers | $vNewSuper"/>
   </xsl:apply-templates>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML text (wrapped in with a single top element to be made a well-formed XML document and also with acorrection to what I think is a typo for supertopic1):
<t>
    <topics>
        <topic name="topic1" />
        <topic name="topic2" />
        <topic name="topic3" />
        <topic name="topic4" />
        <topic name="topic5" />
        <topic name="topic6" />
        <topic name="topic7" />
    </topics>
    <supertopics>
        <supertopic title="supertopic1" name="1;#topic1;#2;#topic2;3;#topic3" />
        <supertopic title="supertopic2" name="4;#topic4;#7;#topic7" />
        <supertopic title="supertopic3" name="2;#topic2;#3;#topic3" />
        <supertopic title="supertopic4" name="5;#topic5;#7;#topic7" />
        <supertopic title="supertopic5" name="3;#topic3;#7;#topic7" />
        <supertopic title="supertopic6" name="4;#topic4;#7;#topic7" />
        <supertopic title="supertopic7" name="5;#topic5;#7;#topic7" />
        <supertopic title="supertopic8" name="2;#topic2;#6;#topic6" />
        <supertopic title="supertopic9" name="5;#topic6;#7;#topic7" />
        <supertopic title="supertopic10" name="3;#topic3;#4;#topic4" />
    </supertopics>
</t>

produces the wanted, correct result:
supertopic1
supertopic3
supertopic5
supertopic2
supertopic4
supertopic8
supertopic6


text:
Q: Lua flavored Nginx rewrite or internal redirection cycle I'm new both to nginx and lua. I'm trying to follow this tutorial http://leafo.net/posts/creating_an_image_server.html#installation_requirements but for the life of me I can't get the nginx.conf right.
I've checked other questions similar to this where the problem is location, but I can't see what wrong with my code.
Here is the nginx.conf:
error_log stderr notice;
daemon off;

events { }

http {
  include /usr/local/openresty/nginx/conf/mime.types;

  server {
    listen 6789;
    lua_code_cache on;

    location @image_server {
      content_by_lua_file "serve_image.lua";
    }

    location ~ ^/images/(?<size>[^/]+)/(?<path>.*\.(?<ext>[a-z_]*))$ {
      root cache;
      try_files /$path @image_server;
    }

  }
}

And this is the serve_image.lua code
local sig, size, path, ext =

ngx.var.sig, ngx.var.size, ngx.var.path, ngx.var.ext
    local images_dir = "images/" -- where images come from
    local cache_dir = "cache/" -- where images are cached
local function return_not_found(msg)
  ngx.status = ngx.HTTP_NOT_FOUND
  ngx.header["Content-type"] = "text/html"
  ngx.say(msg or "not found")
  ngx.exit(0)
end

local source_fname = images_dir .. path
ngx.log(ngx.STDERR, "->>>>  " .. source_fname)

-- make sure the file exists
local file = io.open(source_fname)

if not file then
  ngx.log(ngx.STDERR, "Couldn't find the input file" .. source_fname)
  return_not_found()
end

file:close()

local dest_fname = cache_dir .. "/" .. size .. "/" .. path

-- resize the image
local magick = require("magick")
magick.thumb(source_fname, size, dest_fname)

ngx.exec(ngx.var.request_uri)

When I run the server I get a code 500.
This is the error in the terminal
rewrite or internal redirection cycle while redirect to named location "@image_server", client: 127.0.0.1, server: , request: "GET /images/80x80/wow.png HTTP/1.1", host: "localhost:6789"
I'm hoping a more experienced and fresh pair of eyes can point out what I'm doing wrong. Thanks.


text:
Q: Android Spinner Custom? I am trying to create a spinner that looks exactly like the one in this android example, but not sure how or if it has to be custom?  I cant imaging it would have to be a custom layout since it is shown this way in their example...
http://developer.android.com/guide/topics/ui/controls/spinner.html#Populate

I am not concerned with how the list looks, but just the way the spinner looks with the lower corner arrow.  that is what I want.

A: This project is an attempt to backport the holo theme by building it into and Android Library project. You can link that library with your project in order to gain access to the holo theme widgets.
I have never used it but I would think that it contains the spinner widget that you are looking for.


text:
Q: How does Highchart's performanace depends on the axis and legend for same numer of points? I am plotting a highchart based chart. I have 3 attributes: salary, person phone number  (cardinality 1000) and person's state (cardinality 10).
Y Axis: Salary,
Every Legend: Different Color
So here is the problem:
When I have phone number as X axis and state as legend, the charts renders almost immediately. But when I have state as x-axis and phone number as legend (all with unique color), the chart takes around 10 sec and entire browser freezes till then (Chrome).
I was wondering what's the reason for this? Is this expected behavior? If yes, what's the reason? If not, what can I do in Javascript/otherwise to address this issue?
EDIT:
I also tried disabling animation as per Highcharts recommendations. This did not have any effect.