text:
Q: Popup is not appearing when used page_action I am new to Google Chrome extension development. I am having the two following queries

*

*Popup is not appearing when I use page_action in manifest.json but appearing when I used browser_action. I would like to know why? Or am I doing wrong

*Also the icon is showing inactive state. Where as when I use browser_action, the icon is showing in active state (means I could see the color if active, or I could see as black and white icon, when inactive)
Manifest.json
{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "page_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title":"getStarted Extension"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

UPDATE:
Thanks to Teepemm . Followed his explanation and added the answer with code

A: You need to use a background page (or better, event page) to call chrome.pageAction.show.
You've chosen an unfortunate time to develop a chrome page action.  Google recently changed how page actions work, and the documentation hasn't really caught up.  Previously, page actions appeared in the address bar, and only appeared on tabs where you had called show.  Now, page actions appear to the right of the address bar (unless you move them into the chrome menu), are always present, but are only active when you call show.  So the functions are still called show and hide, even though their effect is more akin to enable and disable.

A: Thanks to Teepemm for guiding me with proper explanation, so in order to make the icon active and inactive, you have to use chrome.pageAction.show(tabId) (to activate the icon) and chrome.pageAction.hide(tabId) (to deactivate the icon) => https://developer.chrome.com/extensions/pageAction#method-show
You need to call this method from background.js by invoking it from client.js
//background.js
chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
    if (request.message === "activate_icon") {
        chrome.pageAction.show(sender.tab.id);
    }
});

//content-script.js
chrome.runtime.sendMessage({"message": "activate_icon"});

So once your extension icon is active, on click of the icon, popup will appear. So the popup will appear only when icon is active.
Hope this helps


text:
Q: How to return to app after openURL in my app I need to open a url by using
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"urlstring"]];

after a certain process in the page how can i return to the app.(like facebook doing for safari authentication)

A: You can't unless you also build the website part, then you can open your own app by calling the App custom URL scheme, wich you will have to add your self to info.plist.

A: What the Facebook app does is it registers fb:// URLs to redirect to it. Then it sends you to a special link at facebook.com that redirects to an fb:// link while passing some information along (a token or whatever). If you open Safari and type "fb://" into the URL bar you'll get sent to the Facebook app. rckoenes' answer shows how to register URLs to do that, but the part about returning to your app is up to your website (you have to write that redirect page).

A: This might work?
UIWebView webView = [[UIWebView alloc] init];
NSURL *url = [NSURL URLWithString:@"urlstring"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is efficient way to align 32 bit data using c I'm looking for best methods to handle the alignment boundaries while that will helpful to work with systems for 8/16/32 bit target systems.

A: Use CHAR_BIT. For example: if you define mask, you can always use it as mask*CHAR_BIT. check limits.h for more information


text:
Q: Get the directory path of a running process ID How can I get a full path to the directory of a running process (I know the process ID & name).
I was using ls -l /proc/PID/cwd earlier in Debian, but it doesn't work in FreeBSD.
Any ideas will be appreciated.

A: Nvm, found the answer: procinfo -b PIDID.


text:
Q: How to configure sonarqube msbuild scanner I am checking the documentation for sonarqube msbuild scanner. But I can't find the SonarQube.Scanner.MSBuild.exe in the distribution given. So when I point the bin directory and run sonar command given in that page
SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end

I got an error saying
'SonarQube.Scanner.MSBuild.exe' is not recognized as an internal or external command,

Since this exe file is not in the distribution and it runs using sonar-scanner bat file what is the correct command to run the project?
When I using sonar-scanner instead of SonarQube.Scanner.MSBuild.exe, it complains about /k option.

A: You need to download the latest version of SonarScanner for MsBuild. The zip file contains all needed executables.
You should not use sonar-scanner for analyzing .NET projects.


text:
Q: LaTeX Syntax Highlighting in Google Drive I like the LaTeX syntax highlighting in emacs through AUCTeX, but for various reasons like to write my LaTeX documents in Google Drive. I wanted to write a Google Script to do LaTeX syntax highlighting directly in my Google Drive LaTeX documents.
I've looked around online to see if people have attempted this. I've seen the source code for latex-lab, which is a standalone online editor, that reads from Google Drive. I would prefer writing directly in Google Drive itself. The code uses codemirror, and has a latexparser JavaScript that seems like it shouldn't be too painful to port to Google Script.
My main question is: does this sound feasible? I don't want to dedicate the time if it's just going to turn out too slow, or if someone has already written such a script.


text:
Q: Babel not running on imports from `node_modules` via Webpack loader I'm having trouble getting Webpack to run babel on a file in node_modules.  In particular, I'm trying to transform a .svg file (from FontAwesome or other .svg sources) with a custom webpack loader, then pass that to Babel for a transform to JSX.
Across the many different configurations I've tried, the problem typically exhibits as either:
1. Unexpected token

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
<svg ...></svg>

Which indicates that neither the custom loader nor babel is being applied i.e. the file is simply being passed through without any loader.
2. Syntax Error

SyntaxError: /Users/bmh/Repos/bug-reports/node_modules/icon/ad.svg:
  Unexpected token (2:20)
1 |
2 |     const element =
hey
;

Which indicates that the custom loader is working (since for the purpose of the test it's hard-coded to a
hey
), but that the subsequent babel-loader isn't being called.
The issue does not occur when the .svg is not in node_modules, meaning that both the custom loader and the babel-loader are working as expected.  Either webpack or babel is deciding to not apply babel transforms to files in node_modules, and it's not clear how to workaround this problem.
The one suggestion I found that seemed to have weight was to provide include and exclude arguments to the webpack module.rules, but the various permutations I tried didn't seem to work.
Reproduce
Repository: https://github.com/brianmhunt/bug-reports/tree/jsx-svg-import
$ git clone git@github.com:brianmhunt/bug-reports.git`
$ git checkout jsx-svg-import
$ make

A: As detailed in bug #736 of babel-loader:

... convert .babelrc to babel.config.js with same configuration, babel-loader [works] as expected.

The explanation was:

... because .babelrc doesn't "leak" across different packages (delimited by package.json)


text:
Q: Similarity between unitary operators and ladder operators I observed a similarity. Is this a co-incidence?:
$$(I+\epsilon P)|x\rangle =|x+\epsilon\rangle$$
And,
$$(X+iP)|n\rangle=A_n|n+1\rangle$$
Here, $|x\rangle$ is an eigenfunction of position. $|n\rangle$ is an eigenfunction of the Hamiltonian $X^2+P^2$
The similarity that I observe is that $(I+\epsilon P)$ works as an "infinitesmial ladder operator" for $|x\rangle$
Is the motivation for ladder operators rooted in this similarity? If so, how? Can ladder operators be systematically derived by exploiting this similarity? I've only seen ladder operators introduced abruptly as a "mathematical trick".
EDIT There's one more clue. The first equation works only because of the value of the commutator $[X,P]$. The second equation also works because of the commutator $[a,H]$
Given all these clues, can we systematically motivate ladder operators?

A: The defining equation for a ladder (or lowering) operator $\hat{L}$ with respect to some observable $\hat{X}$ is* $$[\hat{X},\hat{L}] = -\Delta \hat{L},$$ where $\Delta$ is some difference in eigenvalues of $\hat{X}$. It follows that if $|\xi\rangle$ is some eigenvector of $\hat{X}$ with eigenvalue $\xi$, then $\hat{L}|\xi\rangle$ is another eigenvector with eigenvalue $\xi-\Delta$, since
$$ \hat{X}\hat{L}|\xi\rangle = [\hat{X},\hat{L}]|\xi\rangle +\hat{L}\hat{X}|\xi\rangle = -\Delta \hat{L}|\xi\rangle +  \hat{L}\xi |\xi\rangle = (\xi-\Delta)\hat{L} |\xi\rangle.$$
So far this is completely general, but there are numerous famous and familiar examples in quantum physics. For the simple harmonic oscillator, the relevant ladder operator is $\hat{L} = \hat{a} = \hat{x}+{\rm i}\hat{p}$ (in appropriate adimensional units), the observable is the Hamiltonian $\hat{X} = \hat{H} = \omega\hat{a}^\dagger\hat{a},$ and we have $[\hat{H},\hat{a}] = -\omega\hat{a}$ (taking $\hbar=1$). The OP raises another example: the unitary translation operator $\hat{T}(y) = {\rm e}^{{\rm i}y \hat{p}}$, whose action is usually written as
$$\hat{T}^\dagger(y) \hat{x}\hat{T}(y) = \hat{x}+y,$$ but this is equivalent to a commutation relation
$$ [\hat{x},\hat{T}(y)] = y \hat{T}(y),$$
which defines $\hat{T}(y)$ as a "ladder operator" that "lowers" the observable $\hat{x}$ by an amount $\Delta = -y$. (The OP describes the example of an infinitesimal transformation $\hat{T}(\varepsilon)$ up to order $O(\varepsilon)$ but the relation actually holds in general).
It should be obvious from the above argument that any other continuous unitary symmetry operator is also a ladder/lowering operator with respect to the transformed observable, which accords intuitively with our notion of translations, rotations etc. as a shift of spatial, angular coordinate etc.

*It is not always so easy to gain physical intuition from commutator relations but you can check out this nice question for some insights. Mathematically, the defining commutation relation of a ladder operator encapsulates the fact that $\hat{L}$ changes the (eigen)value of $\hat{X}$.


text:
Q: What is difference between Hydra and Torque and what is better: MPICH2 or OpenMPI I have two questions:

*

*What is difference between Hydra and Torque, or to ask in other way: what more Hydra have to offer in compare to Torque? Do I need Hydra at all if I choose to use Torque (+ MAUI)?

*Also, what is an advantage of MPICH2 in advance of OpenMPI, since OpenMPI is supporting IB and also have continuously supporting Windows platform? For me it looks like swiss knife. Am I wrong?

A: Torque and Hydra are two completely separate things. Torque is a distributed resource manager that allows execution in batch mode of tasks (jobs) on a network of compute systems. Hydra is part of MPICH and is responsible for launching and controlling processes that are part of the MPI job. The way Torque and Hydra work together is that one submits a job to Torque, which reserves cluster resources and at some point start the job. The mpiexec command in turn uses Hydra to start and control the processes that make the MPI job on the compute nodes provided by Torque.
MPICH2 and Open MPI are both quite mature MPI implementations. While Open MPI supports more connection protocols, there is an InfiniBand-enabled version of MPICH called MVAPICH. MPICH is also basis of several commercial MPI implementations including Intel MPI and Microsoft MPI. While Open MPI has supported Windows for a long time, their Windows maintainer left some time ago and it is unclear if they will continue to support that OS.


text:
Q: Calculating percentile of moving matrix I am dealing with financial ratios and I would like to construct a data frame consisting of the percentual order of an observation relative to a moving matrix.
Suppose that I have the following data frame
AAPL <- c(5,7,15,6,9,15,12,10,5,8)
MSFT <- c(20,14,12,15,10,15,18,22,17,20)
df <- data.frame (AAPL, MSFT)

What I would like to do is to create a new data frame consisting of the percentual order of a given observation based on the last 4 observations and the observation itself.
For this simplified exercise, I have run it in Excel and the new data frame would be:
AAPL.new <- c(NA,NA,NA,NA,0.75,0.75,0.5,0.5,0,0.25)
MSFT.new <- c(NA,NA,NA,NA,0,0.75,1,1,0.5,0.75)
df.new <- c(AAPL.new, MSFT.new)

I am a begginer, trying to move from working with small samples in Excel to larger samples in R. In Excel the function for this exercise would be percentrank.
What is the equivalent function in R? I have tried quantile() but I don't know how to make it give me a percentual order of a moving matrix.
Thank you in advance for your help

A: We can write a helper function prank for this job:
prank <- function(x, n){
    sapply(seq_along(x), function(i){
        if(i > n) sum(x[i] > x[(i-n):(i-1)]) / n
        else NA
    })
}

df.new <- as.data.frame(lapply(df, prank, n = 4))
# > df.new
#    AAPL MSFT
# 1    NA   NA
# 2    NA   NA
# 3    NA   NA
# 4    NA   NA
# 5  0.75 0.00
# 6  0.75 0.75
# 7  0.50 1.00
# 8  0.50 1.00
# 9  0.00 0.50
# 10 0.25 0.75


text:
Q: Backup huge .tar with low free disk space guys! I have a problem: i need to backup a big folder - 35GB, but i have just a 5 GB free disk space. I think i have in my head right algorithm, but I have little knowledge in bash scripting:

*

*Packing with tar

*Splitting it

*Get the current splitted filename and upload it via WebDAV

*Delete it

*Then split more -> upload an so on

So i think i have to do it with piping |, but i don't know how. Please help me, if you know.
Maybe you know another method.

A: Sorry, I am unfamiliar with WebDAV.  I can provide an answer for remote storage of the archive over ssh.  Maybe you can apply this for WebDAV.
To store an archive remotely over ssh, use
tar cvf dirToArchive | gzip -c | ssh user@remoteHost 'cat > ~/archive.tgz'


text:
Q: "shaky" vs "shaking" in the use with "old age"
Her hands were shaky because of her old age.
Her hands were shaking because of her old age.

Are there any differences between "shaky" and "shaking"?

A: There certainly is a difference:
"Her hands were shaky because of her old age." In this example, the word is used as an adjective, so her hands were prone to shake, but there is no indication that they were shaking at the time.
"Her hands were shaking because of her old age." Here, the word is used as a verb, so her hands were actually shaking at the time in question.


text:
Q: How to style a part of the Text in Flutter? I have a Text widget and I want to make a part of it bold. How can I do that?
Example: Text("Required interests: Music, Guitar")
I want "Required interests:" to be bold and rest to be normal.

A: You can use the Text.rich() to achieve this.
Text.rich(
  TextSpan(
    text: 'Required interests: ',
    style: TextStyle(fontWeight: FontWeight.bold),
    children: <TextSpan>[
      TextSpan(text: 'Music, Guitar',
        style: TextStyle(fontWeight: FontWeight.normal),
      )
    ]
  ),
);

Note if you do not specify any style in any of the children's TextSpan it will use the parent's style.


text:
Q: Code produces unexpected output when extra output statement added So I'm testing out certain arguments for an assignment, which is basically encrypt a text file using a provided cipher. Here's the code, which is not working as I expect:
int main()
{
fstream file("text.txt",ios::out, ios::trunc);
ifstream key("key.txt");
char box[16][2];
string input;
getline(cin, input);
file << input;

for (int row = 0; row < 16; row++)
{
    for (int col = 0; col < 2; col++)
    {
        key >> box[row][col];

    }
}

for (int i = 0; i < input.length(); i++)
{
    for (int row = 0; row < 16; row++)
    {
        if (input.at(i) != box[row][0])
        {
            cout << input.at(i);
        }
        else if (input.at(i) == box[row][0])
        {
            input.at(i) = box[row][1];
            cout << input.at(i);
        }
    }
}

file.close();
key.close();

system("pause");
}

But if I replace the i loop by:
for (int i = 0; i < input.length(); i++)
{
    for (int row = 0; row < 16; row++)
    {
        if (input.at(i) == box[row][0])
        {
            input.at(i) = box[row][1];
            cout << input.at(i);
        }
    }
}

It works just fine with the exception that it doesn't read anything that isn't in the cipher file. This includes whitespaces and everything. So I thought, alright let's just add some code that does something when my previous conditions are not met. Well... that produces unexpected output.. Just for reference, here is the output of the original code  with the same word used.

A: With the revised logic, you are printing each character 16 times. If the cypher for it can be found, you are still printing it 15 more times.


text:
Q: UIView: how to set property before initWithFrame is called? I have some MyView as a subclass of UIView with following methods:
@interface MyView : UIView

@property (nonatomic, strong) UIImage *image;

@end

@implementation

- (id)initWithImage:(UIImage *)image {
    self = [self init];
    self.image = image;

    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //here I want to access my image property
    }
}

@end

Out of this class I initialize object like that:
[[MyView alloc] initWithImage: someimage];

initWithFrame: is required, initWithImage: is optional

A: If you init your "MyView" with initWithImage, I doubt it shall call initWithFrame. What I recomend you is to use
   - (id)initWithFrame:(CGRect)frame :(UIImage *)image

or better
   - (id)initWithFrame:(CGRect)frame image:(UIImage *)image.

So you can pass image in the same method call.  Make sure you add
   - (id)initWithFrame:(CGRect)frame image:(UIImage *)image;

also in your .h file.

A: You can't set a property on the object before you call the initialiser because until that has been called the object does not exist. If the initialiser needs access to a property, you will need to supply it as a parameter (since it is a requirement for successful creation of your object).
- (id)initWithFrame:(CGRect)frame

takes a CGRect parameter because the purpose of this method is to create an instance with a predefined frame; it adds functionality to the default NSObject's - (instancetype) init, so is supplied with the frame parameter to work with.
A UIView needs a frame so it can be layed out on screen and rendered (amongst other things). At some point in the implementation it will perform a call to the default [super init] method and then access self to work with the frame it has been handed. It builds on an existing class.
You are building on the UIView class in that you want to to be able to initialise it with a UIImage.  You can either opt to provide a default frame for your subclass:
- (instancetype)initWithImage:(UIImage *)image {

    if (self = [super initWithFrame:CGRectMake(0,0,0,0)]) {
        self.image = image;
    }
}

Or provide a more 'useful' default value (Like UIImageView would do) and take the image dimensions as the default frame:

Initializing a UIImageView Object
- (instancetype)initWithImage:(UIImage *)image
Discussion
This method adjusts the frame of the receiver to match the size of the specified image. It also disables user interactions for the image view by default.

With an initialiser like:
- (instancetype)initWithImage:(UIImage *)image {

    if (self = [super initWithFrame:CGRectMake(0,0,image.size.width,image.size.height)]) {
        self.image = image;
    }
}


text:
Q: convolutional autoencoder on an odd size image I am trying to apply convolutional autoencdeor on a odd size image.
Below is the code:
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
# from keras import backend as K

input_img = Input(shape=(91, 91, 1))  # adapt this if using `channels_first` image data format

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.summary()

which gives the following:
Layer (type)                 Output Shape              Param #
=================================================================
input_22 (InputLayer)        (None, 91, 91, 1)         0
_________________________________________________________________
conv2d_145 (Conv2D)          (None, 91, 91, 16)        160
_________________________________________________________________
max_pooling2d_64 (MaxPooling (None, 46, 46, 16)        0
_________________________________________________________________
conv2d_146 (Conv2D)          (None, 46, 46, 8)         1160
_________________________________________________________________
max_pooling2d_65 (MaxPooling (None, 23, 23, 8)         0
_________________________________________________________________
conv2d_147 (Conv2D)          (None, 23, 23, 8)         584
_________________________________________________________________
max_pooling2d_66 (MaxPooling (None, 12, 12, 8)         0
_________________________________________________________________
conv2d_148 (Conv2D)          (None, 12, 12, 8)         584
_________________________________________________________________
up_sampling2d_64 (UpSampling (None, 24, 24, 8)         0
_________________________________________________________________
conv2d_149 (Conv2D)          (None, 24, 24, 8)         584
_________________________________________________________________
up_sampling2d_65 (UpSampling (None, 48, 48, 8)         0
_________________________________________________________________
conv2d_150 (Conv2D)          (None, 46, 46, 16)        1168
_________________________________________________________________
up_sampling2d_66 (UpSampling (None, 92, 92, 16)        0
_________________________________________________________________
conv2d_151 (Conv2D)          (None, 92, 92, 1)         145
=================================================================
Total params: 4,385
Trainable params: 4,385
Non-trainable params: 0

We can see that the input and output are not of the same size. So when i do the autoencoder.fit, it throws the error that ValueError: Error when checking target: expected conv2d_7 to have shape (92, 92, 1) but got array with shape (91, 91, 1). What to do to rectify this?

A: I got the solution by adding a cropping layer in the end. The full code is as below:
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
# from keras import backend as K

input_img = Input(shape=(91, 91, 1))  # adapt this if using `channels_first` image data format

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
decoded = Cropping2D(cropping=((1, 0), (1, 0)), data_format=None)(x) # this is the added step

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

A: You can add ZeroPadding to the input layer so that the expected input dimension is even. Or you have to add padding layers in between so that you do not need to do divisions on odd numbers (which will get rounded off).
Maybe this will help you to manually pre-calculate the effective spatial dimensions of your feature maps using the following formulae:
out_width = (W - F_w + 2P)/S_w + 1
out_height = (H - F_h + 2P)/S_h + 1

where (W, H) = spatial dimensions of the input
(F_w, F_h) = spatial dimensions of filters
P = the amount of zero padding added to the border of the image
S_w, S_h are horizontal and vertical stride of the convolution, respectively


text:
Q: Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [customer_number] in table [customers] I'm working on Spring Boot (V2.2.2.RELEASE) and Spring Data JPA Integration example. In this example, I am validating the schema using spring.jpa.hibernate.ddl-auto=validate, using same schema mentioned here: http://www.mysqltutorial.org/mysql-sample-database.aspx.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [customer_number] in table [customers]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    at com.example.SpringBootJpaMysqlComplexApplication.main(SpringBootJpaMysqlComplexApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [customer_number] in table [customers]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [customer_number] in table [customers]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:136) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:89) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:192) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:320) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    ... 20 common frames omitted

application.properties
# MYSQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/classicmodels
spring.datasource.username=root
spring.datasource.password=root

# JPA
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.format_sql=true

#spring.datasource.initialization-mode=always
spring.datasource.continueOnError=true

logging.level.org.springframework.web=DEBUG

Customer Table
CREATE TABLE `customers` (
  `customerNumber` int(11) NOT NULL,
  `customerName` varchar(50) NOT NULL,
  `contactLastName` varchar(50) NOT NULL,
  `contactFirstName` varchar(50) NOT NULL,
  `phone` varchar(50) NOT NULL,
  `addressLine1` varchar(50) NOT NULL,
  `addressLine2` varchar(50) DEFAULT NULL,
  `city` varchar(50) NOT NULL,
  `state` varchar(50) DEFAULT NULL,
  `postalCode` varchar(15) DEFAULT NULL,
  `country` varchar(50) NOT NULL,
  `salesRepEmployeeNumber` int(11) DEFAULT NULL,
  `creditLimit` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`customerNumber`),
  KEY `salesRepEmployeeNumber` (`salesRepEmployeeNumber`),
  CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`salesRepEmployeeNumber`) REFERENCES `employees` (`employeeNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Customer Entity
@Entity
@Table(name="customers")
@NamedQuery(name="Customer.findAll", query="SELECT c FROM Customer c")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int customerNumber;

    private String addressLine1;

    private String addressLine2;

    private String city;

    private String contactFirstName;

    private String contactLastName;

    private String country;

    private BigDecimal creditLimit;

    private String customerName;

    private String phone;

    private String postalCode;

    private String state;

    //bi-directional many-to-one association to Employee
    @ManyToOne
    @JoinColumn(name="salesRepEmployeeNumber")
    private Employee employee;

    //bi-directional many-to-one association to Order
    @OneToMany(mappedBy="customer")
    private List<Order> orders;

    //bi-directional many-to-one association to Payment
    @OneToMany(mappedBy="customer")
    private List<Payment> payments;

    public Customer() {
    }

    public int getCustomerNumber() {
        return this.customerNumber;
    }

    public void setCustomerNumber(int customerNumber) {
        this.customerNumber = customerNumber;
    }

    public String getAddressLine1() {
        return this.addressLine1;
    }

    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }

    public String getAddressLine2() {
        return this.addressLine2;
    }

    public void setAddressLine2(String addressLine2) {
        this.addressLine2 = addressLine2;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getContactFirstName() {
        return this.contactFirstName;
    }

    public void setContactFirstName(String contactFirstName) {
        this.contactFirstName = contactFirstName;
    }

    public String getContactLastName() {
        return this.contactLastName;
    }

    public void setContactLastName(String contactLastName) {
        this.contactLastName = contactLastName;
    }

    public String getCountry() {
        return this.country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public BigDecimal getCreditLimit() {
        return this.creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }

    public String getCustomerName() {
        return this.customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getPhone() {
        return this.phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPostalCode() {
        return this.postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Employee getEmployee() {
        return this.employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public List<Order> getOrders() {
        return this.orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

    public Order addOrder(Order order) {
        getOrders().add(order);
        order.setCustomer(this);

        return order;
    }

    public Order removeOrder(Order order) {
        getOrders().remove(order);
        order.setCustomer(null);

        return order;
    }

    public List<Payment> getPayments() {
        return this.payments;
    }

    public void setPayments(List<Payment> payments) {
        this.payments = payments;
    }

    public Payment addPayment(Payment payment) {
        getPayments().add(payment);
        payment.setCustomer(this);

        return payment;
    }

    public Payment removePayment(Payment payment) {
        getPayments().remove(payment);
        payment.setCustomer(null);

        return payment;
    }
}

A: I was able to solve the issue by adding -
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl


text:
Q: On Win 10, I've installed emacs (with AucTeX) and Miktex. How do I get emacs to invoke MikTex? I've installed emacs and installed the AucTeX package using emacs (which seems to be the consensus advice). I've installed MikTeX. How do I get C-c C-c latex to invoke MikTex and let me view the compiled file?
Thanks!

A: Problem solved. I installed emacs and then MikTeX. After installing MikTeX, I needed to reboot so that emacs recognized the command pdflatex.


text:
Q: Dynamic horizontal aggregate (AVG) I have a table which contains 3 float(nullable) columns:
Value1  ||  Value2  ||  Value3
NULL        NULL        100.00
10.00       20.00       NULL
10.00       10.00       100.00

I need to get the average from these field (value1+value2+value3 / 3), but the divider is actually how many of these field that has value. So the expected result would be :
Value1  ||  Value2  ||  Value3 || AVG
NULL        NULL        100.00    100.00 (from 100/1)
10.00       20.00       NULL      15.00  (from 30/2)
10.00       10.00       100.00    40.00  (from 120/3)

Anyone can help?
I've tried a solution according to this thread :
Average of multiple columns
But didn't seem to work.
I've also tried to handle this in C#, in which i use for loop and a counter to determine the divider, and then divide them. It actually works, but i prefer to handle this via query, because it took too much time when the records went over 3000 row(s).
My current query:
SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(Value1),
                      (Value2),
                      (Value3)) T (c)) AS [Average]
FROM   tbl_trans_score

Thanks in advance.

A: You can try this below script-
SELECT
CASE
    WHEN (COALESCE(Value1,0)+COALESCE(Value2,0)+COALESCE(Value3,0)) = 0 THEN 0
    ELSE
    (
        COALESCE(Value1,0)+
        COALESCE(Value2,0)+
        COALESCE(Value3,0)
    )/
    (
        CASE WHEN Value1 IS NULL THEN 0 ELSE 1 END+
        CASE WHEN Value2 IS NULL THEN 0 ELSE 1 END+
        CASE WHEN Value3 IS NULL THEN 0 ELSE 1 END
    )
END
FROM your_table

A: One method using a sub query and the VALUES operator to normalise the data:
SELECT V.Value1,
       V.Value2,
       V.Value3,
       A.Average
FROM (VALUES(NULL ,NULL ,100.00),
            (10.00,20.00,NULL),
            (10.00,10.00,100.00))V(Value1,Value2,Value3)
     CROSS APPLY (SELECT AVG(L.[Value]) AS Average
                  FROM (VALUES(V.Value1),
                              (V.Value2),
                              (V.Value3)) L([Value])) A;

A: There is 2 way to solved your problem...
First Way:
SELECT AVG (Vals) AVG_COL
FROM
(
SELECT Row_Num = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)
) ,
Value1,Value2,Value3
FROM tblFloat ) UNPIVOT_SOURCE
UNPIVOT
(
Vals FOR Cols IN ( Value1,Value2,Value3 )
) UNPIVOT_HANDLER
GROUP BY
Row_Num

Second Way:
SELECT
    ISNULL(
        CONVERT(
            DECIMAL(10, 2),
            1.0 *
            (
                ISNULL(Value1, 0 ) + ISNULL( Value2, 0 ) + ISNULL( Value3, 0 )
            )
            /
            NULLIF(
                ISNULL(SIGN(ABS(Value1)),0) + ISNULL(SIGN(ABS(Value2)),0) + ISNULL(SIGN(ABS(Value3)),0)
            ,0 )
        ) ,
        COALESCE(Value1,Value2,Value3)
    )
FROM tblFloat


text:
Q: Microsoft TPL Dataflow Library | MaxDegreeOfParallelism and IO-bound work My use case is this: send 100,000+ web requests to our application server and wait the results. Here, most of the delay is IO-bound, not CPU-bound, so I understand the Dataflow libraries may not be the best tool for this. I've managed to use it will a lot of success and have set the MaxDegreeOfParallelism to the number of requests that I trust the server to be able to handle, however, since this is the maximum number of tasks, it's no guarantee that this will actually be the number of tasks running at any time.
The only bit of information I could find in the documentation is this:

Because the MaxDegreeOfParallelism property represents the maximum degree of parallelism, the dataflow block might execute with a lesser degree of parallelism than you specify. The dataflow block can use a lesser degree of parallelism to meet its functional requirements or to account for a lack of available system resources. A dataflow block never chooses a greater degree of parallelism than you specify.

This explanation is quite vague on how it actually determines when to spin up a new task. My hope was that it will recognize that the task is blocked due to IO, not any system resources, and it will basically stay at the maximum degrees of parallelism for the entire duration of the operation.
However, after monitoring a network capture, it seems to be MUCH quicker in the beginning and slower near the end. I can see from the capture, that at the beginning it does reach the maximum as specified. The TPL library doesn't have any built-in way to monitor the current number of active threads, so I'm not really sure of the best way to investigate further on that end.
My implementation:
   internal static ExecutionDataflowBlockOptions GetDefaultBlockOptions(int maxDegreeOfParallelism,
        CancellationToken token) => new()
        {
            MaxDegreeOfParallelism = maxDegreeOfParallelism,
            CancellationToken = token,
            SingleProducerConstrained = true,
            EnsureOrdered = false
        };

    private static async ValueTask<T?> ReceiveAsync<T>(this ISourceBlock<T?> block, bool configureAwait, CancellationToken token)
    {
        try
        {
            return await block.ReceiveAsync(token).ConfigureAwait(configureAwait);
        } catch (InvalidOperationException)
        {
            return default;
        }
    }

    internal static async IAsyncEnumerable<T> YieldResults<T>(this ISourceBlock<T?> block, bool configureAwait,
        [EnumeratorCancellation]CancellationToken token)
    {
        while (await block.OutputAvailableAsync(token).ConfigureAwait(configureAwait))
            if (await block.ReceiveAsync(configureAwait, token).ConfigureAwait(configureAwait) is T result)
                yield return result;

        // by the time OutputAvailableAsync returns false, the block is gauranteed to be complete. However,
        // we want to await it anyway, since this will propogate any exception thrown to the consumer.
        // we don't simply await the completed task, because that wouldn't return all aggregate exceptions,
        // just the last to occur
        if (block.Completion.Exception != null)
            throw block.Completion.Exception;
    }

    public static IAsyncEnumerable<TResult> ParallelSelectAsync<T, TResult>(this IEnumerable<T> source, Func<T, Task<TResult?>> body,
        int maxDegreeOfParallelism = DataflowBlockOptions.Unbounded, TaskScheduler? scheduler = null, CancellationToken token = default)
    {
        var options = GetDefaultBlockOptions(maxDegreeOfParallelism, token);

        if (scheduler != null)
            options.TaskScheduler = scheduler;

        var block = new TransformBlock<T, TResult?>(body, options);

        foreach (var item in source)
            block.Post(item);

        block.Complete();

        return block.YieldResults(scheduler != null && scheduler != TaskScheduler.Default, token);
    }

So, basically, my question is this: when an IO-bound action is executed in a TPL Dataflow block, how can I ensure the block stays at the MaxDegreeOfParallelism that is set?

A: On the contrary, Dataflow is great at IO work and perfect for this scenario. DataFlow architectures work by creating pipelines similar to Bash or PowerShell pipelines. Each block acting as a separate command, reading messages from its input queue and passing them to the next block through its output queue. That's why the default DOP is 1 - parallelism and concurrency come from using multiple commands/blocks, not a fat block with a high DOP
This is a simplified example of what I use at work request daily sales reports from about a hundred airlines (BSPs for those that know about air tickets), parse the reports and then download individual ticket records, before importing everything into the database.
In this case the head block downloads content with a DOP=10, then the parser block parses the responses one at a time. The downloader is IO-bound so it can make a lot more requests than there are cores, as many as the services allow, or the application wants to handle.
The parser on the other hand is CPU bound. A high DOP would lock a lot of core which would harm not just the application, but other processes as well.
// Create the blocks
var dlOptions = new ExecutionDataflowBlockOptions {
    MaxDegreeOfParallelism=10
};
var downloader=new TransformBlock<string,string>(
                     url => _client.GetStringAsync(url,cancellationToken),
                     dlOptions);
var parser=new TransformBlock<string,Something>(ParseIntoSomething);
var importer=new ActionBlock<Something>(ImportInDb);

// Link the blocks
var linkOptions = new DataflowLinkOptions {PropagateCompletion = true};
downloader.LinkTo(parser,linkOptions);
parser.LinkTo(importer,linkOptions);

After building this 3 step pipeline I post URLs at the front and expect the tail block to complete
foreach(var url in urls)
{
    downloader.Post(url);
}

downloader.Complete();
await importer.Completion;

There are a lot of improvements to this. Right now, if the downloader is faster than the parser,  all the content will be buffered in memory. In a long running pipeline this can easily take up all available memory.
A simple way to avoid this is add BoundedCapacity=N to the parser block options. If the parser input buffer is full, upstream blocks, in this case the downloader, will pause and wait until a slot becomes available :
var parserOptions = new ExecutionDataflowBlockOptions {
    BoundedCapacity=2,
    MaxDegreeOfParallelism=2,
};
var parser=new TransformBlock<string,Something>(ParseIntoSomething, parserOptions);


text:
Q: How to keep redis server running I am using redis for session support in nodejs app. I have installed redis server and it works when I run redis-server, but when I close terminal redis stops and does not work. How do I keep redis server running after closing the terminal?

A: The easiest way to launch Redis as a daemon is to edit the configuration file and change the following line:
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes

Be sure to provide the configuration file on the redis-server command line when you launch it.
An example of configuration file is provided in the Redis distribution.

A: The accepted answer is mostly outdated.
While the question is old, Google still ranks this highly, so allow me to correct this.
The OP did not provide any detail about his setup, but you can assume it is a linux, and he doesn't mention containers, so you can also assume he is running redis without them.
There is three detail that make the accepted answer a thing to forget

*

*Most (popular) distros come with systemd by default

*Most (popular) distros have redis in their official repos

*that official redis package installs systemd service for redis

So

*

*It will have supervised systemd in its default config

*To start: the redis daemon with sudo systemctl start redis@instanceName where you substitue "instanceName". Also sudo systemctl enable redis@instanceName for auto-starting on boot. (BTW, forget about service start, and init scripts already! These are less portable nowdays than calling directly systemctl).

*do NOT set to daemonize: yes, that will interfere with the systemd supervisioning redis!

Systemd will supervise, restart your redis, and you can set service depenedencies and service preconditions to/for it, even for a custom executable it is not that hard, search for systemd unit files (you'll need a ~10 lines config file). Chances are, you'd want it.
If the three detail (making systemd the correct answer) are not met/relevant, you are most likely running redis containerized. For docker/podman/etc., it is another question altogether... (no systemd in the inner linux, but you'd have to (or already do) supervise(d) the container-daemon itself)

A: As mentioned by @DidierSpezia in his answer,
Set daemonize yes in Redis conf file.
Set daemonize yes in Redis conf file at /path/to/redis.conf Generally
it should be there at /etc/.
And :
Then trigger redis-server with the conf file as an argument:
./redis-server /etc/redis.conf

UPDATE
You may directly run the redis with demonize flag as well
redis-server --daemonize yes

A: And, if you'd like a quick option, run: redis-server --daemonize yes.


text:
Q: Name for the future time period with the creation/surpassing of artifical intelligence? I need to know the term or time period to come that means the creation or surpassing of Artificial Intelligence. I know that there are different time periods humanity has gone through like the stone age, the bronze age but I need the term for a future term. I know it is out there because I watched a scishow video (youtube channel) and saw the time periods and there was a time period that is to come. It means the surpassing of artificial intelligence. I just forgot the word/term but I know what it means. I need this for a project, thank you!

A: I think you're referring to the Technological Singularity. This is a common sci-fi or speculative-science term to the time when AI will exist and can improve itself.


text:
Q: What should I do if I am on fire? I noticed that in Defiance you can roll your character (default Alt).
If I am on fire, will rolling make it stop?  Do any other nano effects stop after rolling?

A: Yes, "stop, drop and roll" still works after the Arkfall. And it does work on other Nano Effects.
You can find this information in game in Intel -> Help -> Combat -> Dive Roll.
I find Alt awkward to press rapidly with the normal WASD combination, and I tend to hit the Windows key instead, and have remapped it to an extra button on my mouse.


text:
Q: Image blurring using gaussian low pass filter I'm trying to blur a grayscale image using Gaussian low pass filter( 5*5 kernal).I tried the following code.
I = imread('Lena.png');
G = fspecial('gaussian',[5 5],2);
Ig = imfilter(I,G,'same');
imshow(Ig);

But I'm getting an error in file 'meshgrid.m' as follows.
Error: File: meshgrid.m Line: 1 Column: 5
The input character is not valid in MATLAB statements or expressions.
Error in fspecial (line 145)
[x,y] = meshgrid(-siz(2):siz(2),-siz(1):siz(1));
Error in Untitled2 (line 2)
G = fspecial('gaussian',[5 5],2);

I'm not understanding what the error is.Can anyone help me please.The input image that I used is uploaded below('Lena.png').Thanks in advance


text:
Q: How to get the proper PID of a newly created Firefox window in Powershell? Here is a very simple example of the problem I am experiencing:
$process = Start-Process 'C:\Program Files\Mozilla Firefox\firefox.exe' -argumentlist "-new-window https://google.com -foreground" -PassThru

Write-Host $process.Id

The firefox window will start and work as expected, it will return a process id, but when I actually check the running processes, I see no results for that PID.
I tried adding this just to see,
while (-not $process.HasExited){
    Write-Host "..."
}

Write-Host $process.HasExited

And it looks like the process does run for maybe a couple milliseconds before it exits.
I'm thinking this may have something to do with how Firefox handles it's own processes. Because I tested a similar setup with some other random apps and they all worked as expected.
Any ideas on how to work around this when it comes to Firefox?

A: There are several challenges to overcome:

*

*The firefox process that ends up presenting the actual browser window is different from the one that is initially launched. That is, as you've observed, the launched process spawns other processes and itself exits quickly.

*As Olaf points out, modern browsers typically launch multiple non-transient processes, so the challenge is how to identify the one that represent the browser window.

*Browsers may reuse existing processes, so a single process can present multiple windows / tabs, and closing one of them won't terminate the process as a whole.

*

*If you need to ensure that a dedicated, new process is used, you have two options:

*

*(a) Make sure that no preexisting Firefox instance is running, either by erroring out, or - if acceptable for your use case - by forcefully terminating all existing instances first (Stop-Process -Name firefox).

*(b) With significantly more effort, create a dedicated, temporary Firefox profile that you can launch with the -new-instance option, which allows multiple independent Firefox instances to run concurrently and whose lifetime can be tracked separately.

The following - cumbersome - solution implements option (b):

*

*If no firefox process is found, there is no concern about creating independent instances, and Firefox can be launched normally.

*Otherwise, a temporary profile is created, and launched via the -new-instance and -profile options to ensure that a new process will be used to present the new browser window.

*After launching the initial process, loop until a firefox process appears that was launched later and has a nonempty window title, which is then presumed to be the real process of interest.

*You can then wait for the termination of this process to know when the dedicated browser window has been closed. If a temporary profile had to be created, it is cleaned up afterwards.
# Comment this statement out to silence the verbose messages below.
$VerbosePreference = 'Continue'

$now = Get-Date
$url = 'https://example.org'  # URL to open.

# Launch a (new) Firefox instance.
if ($alreadyRunning = [bool] (Get-Process -ErrorAction Ignore firefox)) {
  # Determine the path for a temporary profile with a unique name.
  $tempProfilePath = Join-Path ([IO.Path]::GetTempPath()) ([datetime]::utcnow.tostring('o') -replace '\D')
  Write-Verbose  "Firefox is already running. Creating temp. profile $tempProfilePath..."
  # Note: Creating an empty directory for the profile is seemingly enough.
  $null = New-Item -Type Directory $tempProfilePath
  Write-Verbose "and starting a new instance with it..."
  Start-Process firefox "-new-instance -profile $tempProfilePath $url"
} else {
  Write-Verbose 'Firefox isn''t running. Starting normally...'
  Start-Process firefox $url
}

# Find the newly launched process that is the actual browser window.
Write-Verbose 'Waiting for a recently launched Firefox process with a nonempty window title to appear...'
while (-not (
  $ps = Get-Process firefox |
    Where-Object StartTime -gt $now |
      Where-Object MainWindowTitle
)) {
  Write-Host -NoNewLine .
  Start-Sleep -MilliSeconds 500
}
Write-Host

Write-Verbose "Found. Waiting for process to exit..."
$ps.WaitForExit()

Write-Verbose 'Process has exited.'

if ($alreadyRunning) {
  Write-Verbose "Cleaning up temporary profile $tempProfilePath..."
  do {
    # The profile dir. is typically held on to for a little while longer by associated processes that may not have terminated yet.
    Start-Sleep -MilliSeconds 200
    Remove-Item -ErrorAction Ignore -Literalpath $tempProfilePath -Recurse -Force
  }
  while (Test-Path -LiteralPath $tempProfilePath)
}

A: Thanks to @mklement0 work, in your case you can use the parent Process ID.
I use WMI to get the parent process, but it works for the very first launch.
$parentProcess = Start-Process 'C:\Program Files\Mozilla Firefox\firefox.exe' -argumentlist "-new-window https://google.com -foreground" -PassThru
$childProcess = get-process -id $(Get-CimInstance -Class Win32_Process -Filter "Name = 'firefox.exe'"  | where {$_.ParentProcessId -eq $parentProcess.id}).ProcessId
# effectively stop the child
$childProcess | Stop-Process


text:
Q: Why does Bitbake build get stucked during parsing of receipts when running in gitlab-ci? I am running a bitbake (version 1.44) build inside a docker container inside gitlab-ci. But the build get stucket at the beginning of parsing recipes.... Even after several hours of waiting I see no process.
Nevertheless the build runs inside the container on my local machine pretty fine.
Why does Bitbake build get stucked during parsing of receipts when running in gitlab-ci?
In earlier versions pf Bitbake there was a -i option to drop interactive mode. I tried to use this option to solve the problem but it did not help.


text:
Q: Is there a shorter/faster way to show these two expressions are equal? I want to know if the two expressions are equivalent:

*

*$\frac{1}{2}(k+2)(2a+(k+1)b)$

*$\frac{1}{2}(k+1)(2a+kb)+(a+(k+1)b)$

My attempt:
First, I decided to start with 2 as 1 looks complicated to me (expanding it is time consuming).
Since 1 has $\frac{1}{2}$ as a factor, I try to express 2 in terms of $\frac{1}{2}$ to get:
$\frac{1}{2}\left[(k+1)(2a+kb)+2a+2(k+1)b \right]$
Since there is a $(k+2)$ in 1, I decided to expand everything in the square bracket and hope that $(k+2)$ is a factor of that expression:
$\frac{1}{2} \left[ k^2b+3b+2ak+4a+2b\right]$
Using polynomial long division to divide the expression in the square brackets by $(k+2)$, I get:
$\frac{1}{2} \left[(k+2) (kb+b+2a) \right]$
Which can be simplified to:
$\frac{1}{2}(k+2)(2a+b(k+1))$, as required.
Is there a more efficient method to solve this kind of question and how will you reason about it? I feel that I am missing some obvious shortcuts/properties since I had to resort to polynomial long division.

A: Try this:
$$\eqalign{\frac{1}{2}(k+2)(2a+(k+1)b)
  &=\frac{1}{2}[(k+1)+1][(2a+kb)+b]\cr
  &=\frac{1}{2}[(k+1)(2a+kb)+(k+1)b+(2a+kb)+b]\cr
  &=\frac{1}{2}[(k+1)(2a+kb)+(2a+2kb+2b)]\cr
  &=\frac{1}{2}(k+1)(2a+kb)+(a+kb+b)\cr
  &=\frac{1}{2}(k+1)(2a+kb)+(a+(k+1)b)\cr}$$

A: I would look at the coefficients of $a$ and $b$ independently, since each expression can be written as $f(k)\cdot a+g(k)\cdot b$ for some $f()$ and $g()$.  For $a$, we need to check that $\frac12(k+2)\cdot 2$ $= \frac12(k+1)\cdot2+1$, which is pretty immediate (cancel the $\frac12$ and the factor of $2$ in both expressions); for $b$, we need to check that $\frac12(k+2)(k+1)$ $=\frac12(k+1)(k)+k+1$.  Multiplying by $2$, this comes down to checking that $(k+2)(k+1) = (k+1)(k)+2(k+1)$, and a few moments' looking will show that this is true (note that you can cancel $k+1$ algebraically from both sides).

A: By inspection, the two expressions are quadratics in $k$.  Therefore, if they are equal at three different values of $k$, they are equal at all values of $k$.  The easiest values to check are $k=0$, $-1$, and $-2$.
For $k=0$ the expressions become
$${1\over2}(0+2)(2a+(0+1)b)=2a+b$$
and
$${1\over2}(0+1)(2a+0b)+(a+(0+1)b)=2a+b$$
For $k=-1$, they become
$${1\over2}(-1+2)(2a+0b)=a$$
and
$${1\over2}(0)(2a-b)+a+0b=a$$
And for $k=-2$, they become
$${1\over2}(0)(2a-b)=0$$
and
$${1\over2}(-1)(2a-2b)+(a-b)=0$$


text:
Q: How to run calculations on sum of two columns? In the Invoice class of my Rails application I need to find all invoices that are overdue.
I have only two database columns, date (which is a type datetime field) and days_allowed (which is a type integer field).
This is what I've got:
class Invoice < ActiveRecord::Base

  def self.overdue
    where("date + days_allowed < ?", Date.today)
  end

end

It's neither throwing an error nor returning the relation that I need, though.
Is there a better way to sum two database columns and then do calculations on it?
Thanks for any help.

A: This depends on what type of database adapter you're using with ActiveRecord; for example, using PostgreSQL, you can add an INTERVAL to any DATETIME (aka TIMESTAMP), which uses a pretty natural syntax.
TIMESTAMP '2014-01-26' + INTERVAL '3 days' = TIMESTAMP '2014-01-29'
However, SQL itself has a DATEADD() function you could certainly use. What database are you using?
And here's a PostgreSQL wiki link for more information.

A: While there are database-specific sql hackery that could do this, and other answers have suggested, I would do this a different way...  You are interested in an attribute called "date_due", but that attribute doesn't exist.  I'd make it.

*

*Add a migration that adds an invoice_due_on field to your table

*in your model add a before_save hook, something like this:

    before_save :calculate_due_date

    def calculate_due_date
      invoice_due_on = your_other_date + days_allowed.days
    end

*

*do something to trigger all the existing invoices to get them to save, updating the new field.  for instance, from a console:

    Invoice.all.each do |i|
      i.save
    end

This answer relies on some date magic given to you in Rails by the ActiveSupport gem.  With ActiveSupport, you can do all kinds of date math, like:

    4.days.from_now
    my_birthday - 7.days

and so on.  Thats what the 'days_allowed.days' method does above.

A: Give this a shot if you're using mysql:
def self.overdue
  where("DATE_ADD(date, INTERVAL days_allowed DAY) < ?", Date.today)
end


text:
Q: Does index occupy disk memory for rows for which index expression is NULL? Let's assume that I have following pg_trgm index on mydata JSONB column:
CREATE TABLE mytable (mydata JSONB);
CREATE INDEX trgm_index_1 ON mytable
USING gin ((mydata#>>'{myfield}') gin_trgm_ops);

And let's assume that I will insert following data into mytable:
500k rows with mydata = { "myfield": "some_text" }
500k rows with mydata = { "another_field": "some_text" }

So 1M rows in total, but half of them contains value that is used in index expression (mydata#>>'{myfield}'). Does it mean that index will use ~50% less memory on disk than it would use if all of rows contained myfield json field?

A: Let's simply try it!
I've created the table from your question, then did the following:
INSERT INTO mytable
SELECT json_object(ARRAY['myfield', i::text || 'bla'])::jsonb
FROM generate_series (1, 100000) t(i);

\di+ trgm_index_1

 Schema │     Name     │ Type  │ Owner  │  Table  │ Size  │ Description
────────┼──────────────┼───────┼────────┼─────────┼───────┼─────────────
 test   │ trgm_index_1 │ index │ avaczi │ mytable │ 19 MB │

So far, we have only rows where myfield is present.  Let's now add some other rows, too:
INSERT INTO mytable
SELECT json_object(ARRAY['other_field', i::text || 'bla'])::jsonb
FROM generate_series (100001, 200000) t(i);

After this, the reported index size has changed to 22 MB, meaning that the new rows are also accounted for.  If you want to exclude them, you have to create a partial index:
CREATE INDEX trgm_index_partial ON mytable
USING gin ((mydata#>>'{myfield}') gin_trgm_ops)
WHERE mydata ? 'myfield';

The size of this one is initially the same (19 MB) as the non-partial index, but after adding the second group of rows, it does not change:
\di+ trgm_index_*

 Schema │        Name        │ Type  │ Owner  │  Table  │ Size  │ Description
────────┼────────────────────┼───────┼────────┼─────────┼───────┼─────────────
 test   │ trgm_index_1       │ index │ avaczi │ mytable │ 22 MB │
 test   │ trgm_index_partial │ index │ avaczi │ mytable │ 19 MB │


text:
Q: Microsoft Sync framework delete not working I have implemented synchronize between SQL server 2008 and SQL Compact database with two way.
It is perfectly working with insert and update data in database and synced very well.
But if I try to delete a record from one database like sql server after that i synced with sql compact it is come back again.
I want that if I delete record from one database it is necessary to delete from other database.
I don't know why it is come back again please help me.
My source code given here.
        string serverCon = "Data Source=192.168.0.2\\sqlserver2008r2;Initial Catalog=test;Integrated Security=false;UID=sa;PWD=ifour@1234;";
        const string localCon = "Data Source=|DataDirectory|\\DB\\test.sdf;Persist Security Info=False;";

        var serverConn = new SqlConnection(serverCon);
        var clientSqlConn = new SqlCeConnection(localCon);

        DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("filter");

        DbSyncTableDescription customerDescription =
           SqlSyncDescriptionBuilder.GetDescriptionForTable("Demo", serverConn);
        scopeDesc.Tables.Add(customerDescription);

        SqlSyncScopeDeprovisioning serverSqlDepro = new SqlSyncScopeDeprovisioning(serverConn);
        SqlSyncScopeProvisioning serverTemplate = new SqlSyncScopeProvisioning(serverConn, scopeDesc, SqlSyncScopeProvisioningType.Template);
        serverTemplate.ObjectSchema = "dbo";

        serverTemplate.Tables["Demo"].AddFilterColumn("bit");
        serverTemplate.Tables["Demo"].FilterClause = "[side].[bit] = @customertype";
        SqlParameter param = new SqlParameter("@customertype", SqlDbType.Bit, 1);
        serverTemplate.Tables["Demo"].FilterParameters.Add(param);

        if (serverTemplate.TemplateExists("filter"))
        {
            serverSqlDepro.DeprovisionTemplate("filter");
        }

        serverTemplate.Apply();

        SqlSyncScopeProvisioning serverProvRetail = new SqlSyncScopeProvisioning(serverConn);
        serverProvRetail.ObjectSchema = "dbo";
        serverProvRetail.PopulateFromTemplate("RetailCustomers", "filter");
        serverProvRetail.Tables["Demo"].FilterParameters["@customertype"].Value = false;

        if (serverProvRetail.ScopeExists("filter"))
        {
            serverSqlDepro.DeprovisionScope("filter");
        }
        //serverProvRetail.PopulateFromScopeDescription(scopeDesc);
        serverProvRetail.Apply();
        serverProvRetail.PopulateFromScopeDescription(scopeDesc);
        SqlCeSyncScopeDeprovisioning clientSqlCeDepro = new SqlCeSyncScopeDeprovisioning(clientSqlConn);
        var clientSqlDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope("RetailCustomers", null, "dbo", serverConn);
        var clientSqlConfig = new SqlCeSyncScopeProvisioning(clientSqlConn, clientSqlDesc);

        if (clientSqlConfig.ScopeExists("RetailCustomers"))
        {
            clientSqlCeDepro.DeprovisionScope("RetailCustomers");
        }

        clientSqlConfig.Apply();

        SampleSyncOrchestrator syncOrchestrator;
        SyncOperationStatistics syncStats;

        // Data is downloaded from the server to the SQL Server client.
        syncOrchestrator = new SampleSyncOrchestrator(
            new SqlCeSyncProvider("RetailCustomers", clientSqlConn, null),
            new SqlSyncProvider("RetailCustomers", serverConn, null, "dbo")
            );
        syncStats = syncOrchestrator.Synchronize();
    }

public class SampleSyncOrchestrator : SyncOrchestrator
{
        public  SampleSyncOrchestrator(RelationalSyncProvider localProvider, RelationalSyncProvider remoteProvider)
        {

        this.LocalProvider = localProvider;
        this.RemoteProvider = remoteProvider;
        this.Direction = SyncDirectionOrder.DownloadAndUpload;
        }
}


text:
Q: Ruby create an array or hash with id=>company_name from a find(:all) query I have a list of vendors. I need to put them in a formtastic select menu using the collection attribute. I need the values to be id's and the label to be company names.
I have this :as => :select, :collection => Vendor.find(:all, :order => "company_name", :select => "company_name").map(&:company_name) but that would give me something like
<option value="Company A">Company A</option>
<option value="Company B">Company B</option>

and I need
<option value="1">Company A</option>
<option value="2">Company B</option>

A: You can map each vendor to a mini-array that contains the id and name:
Vendor.all(:order => "company_name", :select => "vendors.id, vendors.company_name").map{|v| [v.company_name, v.id] }

In this case, the "vendors" isn't strictly necessary, but if you ever combine this with other queries (eg my_product.vendors.all(:select => ...)) it'll get confused as to which id you want if you don't specify.


text:
Q: Does the LT Spice monte carlo simulation definitely output the max and min voltage for any number of simulation runs? I have the following circuit, in which i need to calculate max and min voltages possible (considering resistor tolerance).

 Does running a monte carlo simulation consider the absolute max and min values of voltage output that can be obtained at every point in the circuit, or is it purely based on number of iterations in the step command? Basically, if I do only two rounds of simulation, I must get the absolute max and min voltages at every point in the circuit. Is this method the right one for my needs? If not, please provide a step-by-step solution for my case.

A: Let's take a simple voltage divider AND you are only interested in resistor tolerances, not supply tolerances (assume psu is ideal)

It is trivial to calculate the nominal, minimum and maximum
max: \$10\cdot \frac{10k*1.01}{(10k*1.01) + (10k*0.99)}\$ = 5.05V
nom: \$10\cdot \frac{10k}{10k + 10k}\$ = 5V
min:\$10\cdot \frac{10k*0.99}{(10k*1.01) + (10k*0.99)}\$ = 4.95V
Can a Monte-Carlo output this value? Probably, a very very VERY small probably occurrence. Why?
A Monte-Carlo simulation will generate a random value within stated bounds (normal distributed, 1%, mean value). Statistically speaking it could generate, but this is a one in a billion type occurrence. To then pick the absolute max and hte absolute minimum, in the same run?  I would rather bet on a national lottery.

The absolute max/min output "worst of the worst" is a best suited for pen & paper, excel, mathCAD, Jupyter etc ... and is extremely valuable in determining whether a design will operate over all possible tolerances (very useful for stress calculations). Real world type behaviour?  the probabilistic approach relies on these types of sweeps.
In practice both are useful as you can take credit since 6\$\sigma\$ covers 99.999997% and thus anything outside of this is 3.4 errors per million
So in short.. Will a Monte-Carlo run provide the extreme outputs? probably. If you want to know the extreme outputs then most tool can be set for extreme value calculation, but you need to guide them to determine which combination will provide the maximum/minimum

A: A brute force solution can be implemented using the following number system.
This described method will cover the minimum and maximum result.
For example, using a decimal number system, you can specify the tolerance by 10 values.
The number of digits is the number of components you want to vary.
ABCD
0000  all components have their minimum value
0001
0002
....
0009 components A,B and C have their minimum value and component D its maximum value
....
9999 all components have their maximum value

Now, using the LSpice directive .step param run 0 9999 1 you can use the run parameter to define the value of each component.
Using floor() you can select the component, e.g. component C is selected by floor(run/10)-floor(run/100)*10.
(Note that the divisors are powers of 10, because a decimal number system is used. For other number systems, corresponding divisors must be used).
In the decimal number system, we have 10 tolerance values. Spreading them evenly, the digit has to be subtracted and then divided by (10-1)/2. So, digit value "0" gives -1, digit value "9" gives +1.
With these notes, if the value for component B is e.g. 680Ω 1% the LTspice resistor value becomes R={ 680 * (1 + 0.01*( floor(run/10)- floor(run/100)*10 -4.5)/4.5 )}
Below is a comparative result. I didn't have the diode, so I left it out.
The first waveform is the total result, the second waveform zoomed in at the maximum values, the third waveform zoomed in at the minimum values, the last waveform is showing the values of the resistors.

A: The Monte Carlo analysis assumes a normal distribution of the component tolerance. The more runs you make, the more accurate your result will be.
You will not get the minimum and maximum voltage for your circuit with two runs.
The solution for your problem is well described in "LTspice: Worst-Case Circuit Analysis with Minimal Simulations Runs".
Where, the number of runs is determined by \$2^N +1 \$, where N equals the number of indexed components, to cover all the max and min combinations of the device plus the nominal.


text:
Q: How can I set up a mappings file in a Moovweb project if there are no unique URL paths? I want to set up the mappings.ts file in my Moovweb project. The answer on how to set up the mappings file was informative but focused on URL paths.
My site has lots of pages that look the same (so can probably be transformed with the same Tritium file), but there are no common elements to those URLs (e.g. they don't have a nice /product/ in the path of the product pages).
Is there any way I can map pages on my site?

A: You can import Tritium files based on page elements rather than URLs by checking for an element's existence and importing within that scope. I've seen it done in this sort of format:
$("./div[@id='product_element']") {
  $page_type = "product"
}

...

match($page_type) {
  with(/product/) {
    @import "product.ts"
  }
}

When your URL structure isn't especially consistent, this can be a good way to differentiate between types of pages.


text:
Q: how to use AVQueuePlayer in AVPlayer currently i am using following codes to play song
playerItem = [AVPlayerItem playerItemWithURL:[song valueForProperty:MPMediaItemPropertyAssetURL]];
    [_avPlayer replaceCurrentItemWithPlayerItem:playerItem];

here i am using AVPlayer for playing audio files, but my requirement is need to play group (NSArray) of song continuously(currently player stop after playing one song).I heared about AVQueuePlayer but don't know how to use is it with avplayer if anyone know this please help me

A: Look at The following Apple documentation: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVQueuePlayer_Class/Reference/Reference.html
The basics of AVQueuePlayer are not much different than AVPlayer. You can initialize your player with a list of AVPlayerItems, and the continuous playback will be handled for you.
AVPlayerItem *item1 = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://www.playeritemurl.com/item1.aac"]];
AVPlayerItem *item2 = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://www.playeritemurl.com/item2.aac"]];
AVPlayerItem *item3 = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://www.playeritemurl.com/item3.aac"]];
AVQueuePlayer *player = [[AVQueuePlayer alloc] initWithItems:@[item1, item2, item3]];

You can post a more specific question, if you have one, but the documentation should be fairly clear on how to get started.


text:
Q: Why does my text align vertically instead of horizontally?

div {
     background-color:green;
     height:500px;
     width:500px;
     margin:auto;
     border-radius:50%;
     overflow:hidden;
     padding:300px;
     border: 4px solid red;
     box-sizing:border-box;
}

This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text .

Hello, I would like to know how am I supposed to make this text go vertically and don't move out of the div? I've already tried doing vertical alignment but it didn't work for some reason.

A: You can easily achieve this by using flexbox.

div {
  background-color: green;
  height: 500px;
  width: 500px;
  margin: auto;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid red;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text . This is text .

A: Did you set CSS setting box-sizing to border-box? If so, this is the reason. Your padding is too big, so the width & height are small. You can decrease the padding, or set the CSS setting box-sizing to content-box especially for this element.


text:
Q: BIC and AIC(c) and group data I would like to compare two models using the BIC and AICc. Doing so seems fairly straightforward if both models are fit to only one dataset. However, I have data from 10 participants, and there is no reason to assume that they are all well-described by the same set of parameters.
Is it appropriate to sum the log-likelihoods of a model across all participants and multiply the number of parameters by the number of participants to obtain a "group BIC/AICc" for that model, or is there another way of obtaining the BIC/AICc in such a situation?

A: I did not see the rationale of using your "group BIC/AIC". Your proposed group BIC/AIC is comparing a different pair of models. Let $f(\mathbf{x}_i \mid \alpha)$ and $g(\mathbf{y}_i \mid \beta)$ be two competing models. For simplicity, suppose we have two groups, ande denote $D_i$ the group dummy variable. $D_i=1$ indicates that $i$ belongs to group $1$, and $D_i=0$ refers to the case that $i$ belongs to group $2$. Correspondingly, let $\alpha_1$ and $\alpha_2$ be the two sets of parameters specifying the distribution of group $1$ and $2$, respectively. $\beta_1$ and $\beta_2$ are defined similarly. Define two new densities/models:
$$\tilde{f}(\mathbf{x}_i, D_i \mid \alpha_1, \alpha_2)=f(\mathbf{x}_i\mid \alpha_1)^{D_i}f(\mathbf{x}_i\mid \alpha_2)^{1-D_i},$$
$$\tilde{g}(\mathbf{y}_i, D_i \mid \beta_1, \beta_2)=g(\mathbf{y}_i\mid \beta_1)^{D_i}g(\mathbf{y}_i\mid \beta_2)^{1-D_i}.$$
Note that
$$\log\tilde{f}(\mathbf{x}_i, D_i \mid \alpha_1, \alpha_2)=D_i \log f(\mathbf{x}_i\mid \alpha_1)+(1-D_i)\log f(\mathbf{x}_i\mid \alpha_2),$$
$$\log\tilde{g}(\mathbf{y}_i, D_i \mid \beta_1, \beta_2)=D_i \log g(\mathbf{y}_i\mid \beta_1)+(1-D_i)\log g(\mathbf{y}_i\mid \beta_2).$$
If you fit the above two models to the two groups of data, the ordinary AIC/BIC would be your AIC/BIC. I am not sure if this connection might help you.


text:
Q: How can i change the default Auth Password field name i want to change the default password field name of Laravel Auth, this because im using ORACLE, How can i change ? i tried this but i cant login
User.php
protected $table = 'SEG_USUARIOS1';

public function getAuthPassword()
{
    return $this->contrasenha;
}

RegisterController.php
protected function validator(array $data)
{
    return Validator::make($data, [

        'email' => 'required|string|email|max:255|unique:SEG_USUARIOS1',
        'contrasenha' => 'required|string|min:6|confirmed',
    ]);
}

protected function create(array $data)
{

    $user =  User::create([
        'nombre' => $data['name'],
        'email' => $data['email'],
        'contrasenha' => bcrypt($data['password']),
        'verifytoken' => Str::random(40),
    ]);

    $thisUser = User::findOrFail($user->usuario_id);
    $this->sendEmail($thisUser);
    return $user;
}

Im Using laravel 5.4

A: My code was ok, the only problem was that I'am using another primary key,
so you have to use it in User.php
protected $primaryKey = 'your_id';


text:
Q: Calculate average value from netcdf I have precipitation data from NOAA in a NetCDF format. I imported that into ArcGIS as a raster layer. Now I see that I can only get the precipitation value for one year at a time.
I need to calculate the annual average precipitation for the decade (1980-1990).
Is there any way to do this?
I am very new to GIS and don't know how to use Python. I have dabbled with the ModelBuilder a bit.

A: Assuming that you can get each year as a separate raster, do so.  Then use ArcToolbox > Spatial Analyst > Local > Cell Statistics to compute a new raster whose cell values are the mean of the precipitation values at corresponding locations in all the other one-year rasters.

A: There are several ways of doing this, and probably by now you have already solved it. In case you haven't, I would make use of GDAL.
GDAL
Just open a terminal on a machine that has gdal installed, and type in:
gdal_calc.py -A yourNOAAfile.nc --A_band=1 -B C:/yourNOAAfile.nc --B_band=2 -C yourNOAAfile.nc --C_band=3 --outfile=Avergage.nc --calc="((A+B+C)/3)"
ArcMap
In case you are not familiar with commandline tools and prefer a more ArcGIS solution, have a look here. Basically you either make use of the raster calculator or the cell statistics function.
QGIS
And the QGIS alternative with a very sweet tutorial by Gregory Giuliani.

A: In QGIS, you can use Mesh Calculator (main menu > Mesh > Mesh calculator). The expression you need is average (aggr).
You can filter Start and End time (temporal filter) or using Mask Layer or an extent to limit the calculation to a certain geographic area:

A: I think you solved it by now, but to benefit other users. I faced the same problem but solved it following this approach:
First go to multidimension tools > make NetCDF raster layer, in the interface (see pic) select the suitable inputs but pay attention that you need to put 'time' in the 'band dimension' not band values. You will get one raster layer that might not show your data and might not look right, but that's okay proceed to step two

Second, go to SDM toolbox (if you don't have it you can download it freely just google it) > Basic tools> Raster tools > multiband netcdf to separate rasters and you should get all your separate rasters. The tool might exist in other toolboxes that you might have so check.

Note that you can't put the NetCDF immediately in the second tool as you must first convert your NetCDF file to an ArcGIS friendly format using the first tool.


text:
Q: How do GPU handle indirect branches My understanding of GPUs is that they handle branches by executing all path while suspending instances that are not supposed to execute the path. This works well for if/then/else kind of construct and loops (instance that terminated the loop can be suspended until all instance are suspended).
This flat out does not work if the branch is indirect. But modern GPUs (Fermi and beyond for nVidia, not sure when it appear for AMD, R600 ?) claim to support indirect branches (function pointers, virtual dispatch, ...).
Question is, what kind of magic is going on in the chip to make this happen ?

A: Accordingly to the Cuda programming guide there is some strong restrictions on virtual functions and dynamic dispatching.
See http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#functions for more information. Another interesting article about how code is mapped to the GPU hardware is http://yosefk.com/blog/simd-simt-smt-parallelism-in-nvidia-gpus.html .

A: GPUs are like CPUs in regards to indirect branches. They both have an IP (instruction pointer) that points to physical memory.  This IP is incremented for each hardware instruction that gets executed. An indirect branch just sets the IP to the new location.  How this is done is a little bit more complicated. I will use PTX for Nvidia and GCN Assembly for AMD.
An AMD GCN GPU can have its IP simply set from any register. Example: "s_branch S8" The IP can be set with any value. In fact, on an AMD GPU, its possible to write to the program memory in a kernel and then set the IP to execute it (self modifying code).
On NVidia's PTX there is no indirect jump. I have been waiting for real hardware indirect branch support since 2009. The most current version of the PTX ISA 4.3 still does not have indirect branching.  In the current PTX ISA manual, http://docs.nvidia.com/cuda/parallel-thread-execution, it still reads that "Indirect branch is currently unimplemented".
However, "indirect calls" are supported via jump tables. These are slightly different then indirect branches but do the same thing. I did some testing with jump tables in the past and the performance was not great. I believe the way this works is that the kernel is lunched with a table of already known call locations. Then when it runs across a "call %r10(params)" (something like that) it saves the current IP and then references the jump table by an index and then sets the IP to that address. I'm not 100% sure but its something like that.
Like you said, besides branching both AMD and NVidia GPUS also allow instructions to be executed but ignored. It executes them but does not write the output. This is another way of handing an if/then/else as some cores are ignored while others run. This does not really have much to do with branching. This is a trick to just avoid a time consuming branches. Some CPUs like the Intel Itanium also do this.
You can also try searching under these other names also: Indirect Calls, Indirect Branches, Dynamic branching, virtual functions, function pointers or jump tables
Hope this helps. Sorry I went so long.


text:
Q: Android Animation Choppy on Drawables I've had some difficulty with animating simple ImageViews in an app. I noticed that when using the hdpi images that I had and placed in the drawable-hdpi folder, animations came out as choppy and lagged, but when they were placed in the xhdpi and xxhdpi folder, the images were scaled but came out smooth. I assume its an issue with the way I am displaying my images.
Currently there are four ImageViews in my layout that are around a similar size as the image I am animating which is 1460 x 1080 pixels. I am testing on a tablet 1920 x 1200. When three of the four images are on the screen, the animation is significantly smoother as I want it to be, but when all images are displayed, the animation is choppy and slow.
I also noticed that when testing on an emulator, the animation seemed smooth unlike when tested on a tablet (1920 x 1200).
Here is the simple animation code.
 TranslateAnimation anim = new TranslateAnimation(0f, -1200f, 0f, 0f);
     anim.setInterpolator(new  LinearInterpolator());
     anim.setRepeatCount(Animation.INFINITE);
     anim.setRepeatMode(TranslateAnimation.REVERSE);
     anim.setDuration(2300);
     left.setAnimation(anim);

Here is the xml for my layout.
<ImageView
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:scaleType="fitXY"

    />

Thanks a lot

A: The probable reason why animation is smoother if you put your images in the xhdpi/xxhdpi folder on your hdpi device is, that it will get downscaled by at least 50%, so you might consider downscaling your original and using the correct drawable selector.
Second: activate hardware acceleration in your manifest, this fixes animation in most cases.
<application android:hardwareAccelerated="true" ...>

But mind the few differences when harware acceleration is on (see link)
EDIT: Please dont mind the hardware acceleration hint: it should be on by default (this changed in recent years)


text:
Q: Can't get audio to play using jQuery.each() I'm trying to get audio files associated with specific words to play successively with the individual words  being hilited while the audio is playing and with brief delays between the events. I want this process to be repeated for each word in the page. This is part of  the html:

/templates/beez_20/audio/word_sets/word_set1/

1

Word Learning 1

1the คำนำหน้านามเจาะจง

2and    และ

3of       ของ

4to       ถึง

5a        หนึ่ง

etc. And here is the js:
    "use strict";
    jQuery.noConflict();
    jQuery(document).ready(function() {
    alert("1st");
      jQuery("div#word_learning").click(function (evnt) {
      alert("2nd");
        var  pathVar = document.getElementById("pathVar").innerHTML,
          setNum = document.getElementById("setNum").innerHTML,
          audioElement = document.createElement("audio"),
          audioType = Modernizr.audio.ogg? ".ogg": ".mp3";
        jQuery("p.word_learn").each(function(i)  {
          jQuery(this).css("color : red;");
          audioElement.src = pathVar+"b"+setNum+"e"+i+audioType;
          jQuery(this).delay(250);
          audioElement.load();
          audioElement.play();
          jQuery(this).delay(500);
          jQuery(this).css("color : black;");
        });
      });
    });

The first alert displays when the page is loaded, but the second does not when the initial word in the list is clicked. I would be grateful for any help. in


text:
Q: Array equal another array I have a loop that goes something like this, where arrayfunction sets all array values and compute_with_both_arrays computes a number based on both these arrays.
They way i did it below does not work for array1 = array2. Is there a way i can do this without running the arrayfuncion twice in each loop?
float sum = 0;

float array1[10];
arrayfunction(0, array1);

for(i=1; i<10; i++) {
  float array2[10]
  arrayfunction(1, array2);

  float s;
  s = compute_with_both_arrays(array1, array2);
  sum = sum + s;

  array1 = array2;
}

A: You have to manually copy the memory from one array to another using a function like memcpy.
So for instance:
memcpy(array1, array2, sizeof(array1));

Keep in mind that we can use the sizeof operator on array1 because it's an explicit array allocated on the stack.  As a commenter noted, we pass the size of the destination to avoid a buffer over-run.  Note that the same technique could be done for a statically allocated array as well, but you cannot use it on an array dynamically allocated on the heap using malloc, or with some pointer-to-an-array ... in those situations, you must explicitly pass the size of the array in bytes as the third argument.
Finally, you'll want to use memcpy over a for-loop because the function is typically optimized for copying blocks of memory using instructions at the machine-code level that will far out-strip the efficiency of a for-loop, even with compiler optimizations turned on.


text:
Q: How to modify dataframe based on some condition and selecting last 3 rows I have a dataframe that looks likes this
    a   b   c
0  222  34  23
1  333  31  11
2  444  16  21
3  555  32  22
4  666  33  27
5  777  35  11

I need to check if column C is greater than some value(mean of something else) in the last 3 rows than affect old value → new value (mean)
for example, in column "C" row 5 I will get 11 → 22
there is what I tried but it breeds an error
import pandas as pd

mean=22
# List of Tuples
matrix = [(222, 34, 23),
(333, 31, 11),
(444, 16, 21),
(555, 32, 22),
(666, 33, 27),
(777, 35, 11)
]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('abc'))
print(df)
df.iloc[-3:].loc[df["c"] < mean, "c"] = pd.Series(map(lambda x: str(x)+" → "+ str(mean), df.iloc[-3:].loc[df["c"] < mean, "c"]))

A: You can create another mask for testing last 3 index values with Index.isin, so no iloc is necessary and processing only matched rows by mask:
mean=22
mask = (df["c"] < mean) & df.index.isin(df.index[-3:])
df.loc[mask, "c"] = df.loc[mask, "c"].astype(str) +" → "+ str(mean)
print (df)

     a   b        c
0  222  34       23
1  333  31       11
2  444  16       21
3  555  32       22
4  666  33       27
5  777  35  11 → 22

To replace mean by mask, the solution is simplier:
mean=22
mask = (df["c"] < mean) & df.index.isin(df.index[-3:])
df.loc[mask, "c"] = mean

A: You could take a copy of the last 3 lines, process that copy and then report the new value into the initial dataframe:
df1 = df.iloc[-3:].copy()            # use copy to be allowed to modify the values
df1.loc[df1.c < mean, 'c'] = mean    # process the copy
df.loc[df1.index, 'c'] = df1['c']    # copy back into the original dataframe

which gives:
     a   b   c
0  222  34  23
1  333  31  11
2  444  16  21
3  555  32  22
4  666  33  27
5  777  35  22

A: I did not try to mimic the exact example but you are able to replace any value in the dataframe based on iloc and loc which people use to overlook when start using pandas.
import pandas as pd
import io

# intialise data of lists.
txt_data = '''a,b,c
222,34,23
333,31,11
444,16,21
555,32,22
666,33,27
777,35,11'''

df = pd.read_csv(io.StringIO(txt_data))
# pick the value we want to replace
any_value = 21
# pick the mean value
mean_value = 12
# -3 means last 3 rows based on row index, 2 means last column based on column index
# apply a lambda function to change the value
df.iloc[-3:, 2] = df.iloc[-3:, 2].apply(lambda x: any_value if x > mean_value else x)