text:
Q: Where are the trace templates saved to? I recently created a profiler template, and I was wondering where it is saved to? The reason that I'm asking is because sometimes when I log to another instance of SQL Server my template is not there for use. I know this could be because of the SQL server version, but I was wondering if the template is saved on the server where the SQL instance is located or is it on my local computer?

A: SQL Profiler Trace Templates are specific to the SQL Server version... templates for 2008 will not work for 20012 and vice-versa.
The way you need to deal with this is to either manually create one for each server version, or export/import the trace templates.
To move a template from one instance to another, just export the source, and then import it into the destination.  This works more reliably than trying to find the template files on disk and then copying them around.
Just open SQL Profiler, and go to File->Templates, and use the Export and Import functions there.
As for where the files are stored, they're tucked away in your hidden AppData folder at this approximate location (varies depending on version, and you'll need to enable the display of hidden folders before you'll see it):
C:\Users\UserName\AppData\Roaming\Microsoft\SQL Profiler\10.0\Templates\Microsoft SQL Server

The "UserName" will vary with your logged in user, and the "10.0" will vary with your version of SQL Server.  But this really shouldn't be how you manipulate the trace templates... you should use the Export/Import facility to move templates around.

A: The accepted answer - using the "File" > "Templates" > "Export/import template" menu items - is the first step to make this work.
The second step is to copy the files inside the aforementioned folder to match your new version. I was exporting from SQL 2017 and into SQL 2019. Export and import succeeded, but the templates were not listed in the dropdown. The solution is open this folder:
%appdata%\Microsoft\SQL Profiler\15.0\Templates\Microsoft SQL Server\

Then open each folder other than 150 (which is the 2019 version), such as 130 and 140, and copy files inside those folders to the 150 folder, like so: (in command line, if the above folder is current working folder)
copy 130\*.* 150\
copy 140\*.* 150\


text:
Q: Do Federation prisons still use bars on the cells? Watching DS9, S2E21, The Maquis, Pt II.  Sisko is trying to talk Cal out of further activities with the Maquis. He tells Cal that the Federation won't stop until Cal was "behind bars".
Since we know that on star ships and space stations at least, prison cells all use force fields to prevent escape from the cells, does that mean that bars are no longer used? Or do full scale, planet-side prisons still use bars on their cells?

A:
In the 2266, we see a couple of bars in a brig on the Enterprise — of course, these particular ones wouldn't do a very good job of keeping the prisoner inside without the force field that is also in place.
After an extensive search, I cannot find an example of a brig or cell on a Federation starship or installation from the 23rd Century or later that does not involve a force field in some crucial way.  Any bars that are present are merely part of the electrostatic force field generator and are not positioned in a way that would confine the prisoner when the field is inactive (as in the "Charlie X" example above).
If Cal were sent to a prison, it would likely be the Federation Penal Colony in New Zealand where Tom Paris and other Maquis collaborators were sent:

Apart from the unstylish grey jumpsuits, this seems to be a fairly comfortable open-air prison.  No bars in sight.
In short, it seems that force-field-based brigs and open-plan penal colonies are standard in the Federation of the 23rd and 24th centuries.  This seems to be consistent with the general ethos of the Federation.
By then, "behind bars" is probably just a figure of speech, like "hang up the phone" or "dial the number" or "make sure you get that on tape".

A: Old expressions are widely used today even if they are practically obsolete and unfit for current times. Like the old 'lets go for a ride'.
Phone "lines". In this cellphone world there are no "lines", everything is wireless. Term is still used. Some mobile phones even have the option to switch between lines.
"The tube" – a popular synonym for a television. Once upon a time there were tubes in a TV set. No longer. Now it's used to sometimes refer to youtube.
"Sampling" used to mean trying a variety of selections. Today in the music world it means stealing someone else's work and justifying it as an homage.
"Kodak Moments" are also used even if you use DSLRs.
"Records" is also a currently use term, even if now they don't exist anymore.

A: Idioms last forever.Terms like "Behind Bars" or "Stone walls" or in the clink (the sound made when a door shuts).  WHY use forcefields at all, they require constant energy, they fail in case of incident or power failure. Brigs using conventional doors are safer. In the voyager episode "Repentance" a ship attacks Voyager carrying a group of prisoners, the force fields fail permitting the prisoners to escape, while the cells are made of "Tritanium" bulk heads, strong stuff. But use forcefield doors.
The Federation utilizes penal colonies (Voyager ep: Caretaker) which were often much different than prisons, in a sense the inmates cannot leave the perimeter but other than that are roving and allowed prisoners freedom to move about the compound.
In the Abramverse; the Enterprise Brig uses transparent solid walls.

redpajama_set_name: RedPajamaStackExchange


text:
Q: add video and image with package imagepicker from one button flutter with the package ImagePicker I can easily pick an image or video, but from the perspective of user experience, is it possible to pick an image and video from one button, I mean while taking picture, the camera can change the mode from image to video by the user, but from code side, we have to use two methods:
final XFile? video = await _picker.pickVideo(source: ImageSource.camera);
final XFile? photo = await _picker.pickImage(source: ImageSource.camera);

So please tell me how to let flutter or package automatically detect which mode(picture/video) current camera is, thanks a lot!


text:
Q: CMD FINDSTR execution issue I am currently trying to execute a search (specific string in specific files) in a server by using CMD and command FINDSTR as follows (calling this .bat file from CMD):
@echo off

>C:\Users\myuser\test1.txt (
     pushd \\Targeted_Server\DATA\
     FINDSTR /S "XXX=XXXXXX" *."sas"
     popd
if not errorlevel 0 goto ERR
)

Problem: the script does not end (keeping a blank space in CMD) and the results file is kept empty (tried 2ish hours and still no results). Do you guys know any chance of getting it done quicker or most important: how to get the results file written as results are being found by the script (real time)?
Thanks in advance


text:
Q: Wordpress include php file I am trying to create a php website on WordPress for the first time.
When I create a page, it creates a permalink which is of the form http://localhost/?p=123. I don't know if there is a corresponding file.

I've installed insert-php plugin to read php code. It works fine on a static page. But how do I include another php file? I want to include my_utilities which contains all the back-end functions, in login. It has a permalink 'http://localhost/?page_id=45'.
What to do?
include 'http://localhost/?page_id=45' doesn't work.

A: Pages you define in WordPress's backend are pages mostly setup for your users to view / read. They, by default, have this URL structure of http://localhost/?p=123 (though this can be changed, but that's a whole different lesson).
To include a script file, upload the file to your folder structure where you have your website then refer to it in your include statement as follows:
include('path/to/folder/my_script.php');

EDIT: You may also want to have a look into WordPress Page Templates:

Pages are one of WordPress's built-in Post Types. You'll probably want most of your website Pages to look about the same. Sometimes, though, you may need a specific Page, or a group of Pages, to display or behave differently. This is easily accomplished with Page Templates.

A: For exapmle your wordpress file is at
/var/www/html/wp-content/myphpfiles/test.php
To include the test.php file in your wordpress page you have to following.
[insert_php] include('wp-content/myphpfiles/test.php'); [/insert_php]

Thats it.


text:
Q: how to retreive from memory an object associated to a destroyed object My application has a Micropost model and a Comment model.
I introduced in the Micropost partial links for showing/hiding and refreshing comments:
<li id="micropost-<%= micropost.id %>">
  <%= link_to micropost.user.name, micropost.user %>

    <%= micropost.content %>
    <%= image_tag micropost.picture.url if micropost.picture? %>

  <% if micropost.comments.any? %>
    ~ <%= link_to "Show/hide comments", "#", class: "comments-link", remote: true %>
    ~ <%= link_to "Refresh comments", fetch_comments_path(micropost), remote: true %>
  <% end %>
  <% if logged_in? && (current_user == micropost.user || current_user.friend?(micropost.user)) %>

        <%= form_for(current_user.comments.build, remote: true) do |f| %>
            ...
        <% end %>

  <% end %>

    <% if micropost.comments.any? %>
        <ol id="comments_micropost-<%= micropost.id %>">
            <% micropost.comments.each do |comment| %>
                <%= render comment %>
            <% end %>

    <% end %>

This links are added to the page after creating the first comment and are loaded if the micropost has comments.
However, in case there is just one comment and it is deleted, they are useless so I would like to remove them with Ajax via the destroy action of the comments controller.
I am having my troubles to realize this.
The main problem is that I cannot refer to the micropost using the to-be-destroyed comment.
Once the comment is destroyed any @micropost = @comment.micropost association would return a nil object:
def destroy
  @comment = current_user.comments.find_by(id: params[:id])
  @micropost = @comment.micropost
  @comment.destroy
  respond_to do |format|
    format.html do
      flash[:success] = "Comment deleted"
      redirect_to request.referrer || root_url
    end
    format.js
  end
end

Thus, inside create.js.erb I cannot use a if @micropost.comments.nil? remove links conditional
Moving @comment.destroy after the respond_to block would not work for format.html, without refreshing the page.
If it worked, I could use a if @micropost.comments.count == 1 remove links conditional in create.js.erb
I cannot move @comment.destroy inside the format.html block, because it would not be used by format.js.
What solution can I use?
The delete link in the comment partial is:
<%= link_to "delete", comment, method: :delete, remote: true %>

Is it possible to pass in link_to a params value equal to micropost.id, such as:
<%= link_to "delete", comment, method: :delete, micropost_id: micropost.id, remote: true %>

so that I can write in the destroy action:
@micropost = Micropost.find(params[:micropost_id]) ?

A: When you destroy your object it is destroyed form database and all reference keys are destroyed immediately. So you can first grab post Id and the remove comment.
def destroy
 @micropost_id = @comment.micropost.id
 @comment.destroy
end

Now you can use @micropost_id to take another action or to redirect to the parent post like this:
redirect_to '/microposts/'+ @micropost_id

Or
redirect_to MicroPost.find(micropost_id)


text: Q: iPhone stocks app bubble I am trying to draw a bubble similar to the one used in the Stocks app. However, I cannot seem to replicate the graphics. I have jagged lines although I use anti aliasing and the colors are blurred. Am I not using Quartz at its real power or I simply need to change my approach? Is there any alternative to Quartz that can deliver sharper graphics?


text:
Q: Value not getting passed to controller after post request I'm trying to do a simple post call using ajax, the form contains a language identifier, an i18n key, and a string translation value.
I have my route set up as follows:
post '/translate/' => 'pages#translate'

For test purposes, in PagesController::translate I am simply calling:
render json: params

In my coffee script I am using the following code:
console.log $form.serialize()
$.post $form.attr('action'), $form.serialize(),
    (json) ->
        console.log json
        return
, 'json'

And I'm using the following HAML to output the form:
%div#translation-control
    = form_tag '/translate/', :method => "post" do
        = hidden_field_tag :translationlang, I18n.locale
        = select_tag :translationkey, options_for_select(get_all_translations().invert())
        = text_area_tag(:translationvalue, '', :rows => '1')
        = button_tag "Add"

In my log I see:
translationlang=en&translationkey=home.welcome&translationvalue=Welcome+to+this+site
Object {
    action: "translate"
    controller: "pages"
    translationlang: "en"
}

I have tried several different methods of setting up my route, including:
post '/translate/:translationlang/:translationkey/:translationvalue' => 'pages#translate'

match '/translate/:translationlang/:translationkey/:translationvalue' => 'pages#translate',
:constraints => { :translationkey => /[\w\_\-\.]+/, :translationvalue => /.*/ },
via: [:post]

But nothing seems to work. Why are translationkey and translationvalue not getting passed to the controller?

A: Was going to write a comment, but this will be clearer:

.to_json
Have you tried .to_json?
This answer seems to be very receptive of the idea:
render json: params.to_json

Failing that, have you considered just testing static text:
render "hello".to_json ?

Controller
Are you sure you're getting the right data / params sent to your controller? Some good feedback would be your log of the requests


text:
Q: Как вычислить размер ячейки CollectionView? У меня есть CollectionView. В одной из ячеек этого CollectionView(1) содержится другой CollectionView(2). Возникла проблема, если во втором CollectionView(2) много элементов, то происходит скроллинг не основного CollectionView(1), а того, который содержится в ячейке.
На сколько я понял, необходимо вычислить размер всех ячеек CollectionView(2) и задать высоту ячейки CollectionView(1) равную этому размеру(чтобы CollectionView(2) растянулся и не скролился, т.к. он имеет достаточную высоту).
Правильно ли я додумался? Существуют ли готовые решения моей проблемы?


text:
Q: how to install php_mysqli for php 7.3 with yum I am setting up my server which is an EC2 (fedora) instance.
I have php version 7.3.30.
When I run my web I get the error:
Fatal error: Uncaught Error: Call to undefined function mysqli_connect()
It looks like I don't have php_mysql installed.
With the yum install php-mysqli command I see that the following will be installed:

===============================================================================================================================================================================================================
 Package                                           Arch                                       Version                                                   Repository                                        Size
===============================================================================================================================================================================================================
Installing:
 php56-mysqlnd                                     x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     398 k
Installing for dependencies:
 php56-cli                                         x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     4.2 M
 php56-common                                      x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     1.4 M
 php56-jsonc                                       x86_64                                     1.3.10-1.20.amzn1                                         amzn-main                                         82 k
 php56-pdo                                         x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     199 k
 php56-process                                     x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     100 k
 php56-xml                                         x86_64                                     5.6.40-1.143.amzn1                                        amzn-updates                                     345 k

Transaction Summary
===============================================================================================================================================================================================================
Install  1 Package (+6 Dependent packages)

However, my php has version 7.3.
Is there a way to install php-mysqli for version 7.3?


text:
Q: Why directing output of command to a variable doesnt work in batch file I am trying to assign the output of the command python --version to a variable in batch script but it does not work.
Here is the sample code I am using
FOR /F "tokens=* USEBACKQ" %%F IN (`python --version`) DO (
SET message=%%F
)
ECHO %message%

Although it prints the version for python, it does not assign to the variable var.
If I use another command instead of python --version then the output is correctly assigned. e.g. using dir works.
What could be wrong?
NOTE -
@echo off
set message=Hello

FOR /F "tokens=* USEBACKQ" %%F IN (`python --version`) DO (
SET message=%%F
)
ECHO %message%
PAUSE

OUTPUT -
C:\Users\nik>extra.bat
Python 2.7.9
Hello
Press any key to continue . . .

A: The installed version of Python outputs obviously the version information to handle STDERR (standard error) instead of handle STDOUT (standard output). For that reason it is necessary to redirect the standard error stream with the version information to standard output stream using 2>&1 as described by Microsoft in the documentation about Using command redirection operators.
The command line to use is:
for /F "delims=" %%I in ('python.exe --version 2^>^&1') do set "message=%%I"

The redirection operators > and & must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR.
FOR respectively cmd.exe processing the batch file with this command line starts in background one more command process with %ComSpec% /c and the command line specified within ' appended as additional arguments. Therefore is executed with Windows installed into C:\Windows in the background:
C:\Windows\System32\cmd.exe /c python.exe --version 2>&1

The command process in background searches now for an executable python.exe as described at What is the reason for "X is not recognized as an internal or external command, operable program or batch file"? When the file python.exe could be found by cmd.exe running in background without a visible console window, it executes it and Python outputs the version information to standard error stream which is redirected to standard output stream of the background command process.
The started cmd.exe closes itself after python.exe terminated itself after printing the version information.
The cmd.exe instance processing the batch file captures everything written to handle STDOUT of started background command process and FOR processes the captured lines after started cmd.exe closed itself.
There is split up by default a non-empty captured line into substrings using normal space and horizontal tab as string delimiters. If the first substring after removal of 0 or more leading spaces/tabs starts with a semicolon, the captured line is ignored, otherwise the first substring is assigned to the specified loop variable I.
The default line handling behavior is not wanted here. For that reason the for /F option delims= defines an empty list of string delimiters to disable the line splitting behavior to get the entire captured line assigned to the specified loop variable I. The implicit default eol=; (semicolon is end of line) can be kept in this case as the version information output by Python starts never with a semicolon.


text:
Q: FirebaseError: Missing or insufficient permissions. for update or create Here is my security rule in my Firebase db:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /links/{linkId} {
      allow update, create: if request.auth.uid;
    }
  }
}

Here is my JS using version 9 of Firebase:
const db = getFirestore()
await addDoc(collection(db, "links"), {
    title: 'my link title'
})

I'm 100% certain that I am currently signed in. Just before my addDoc code, this is correctly logging the current user's uid:
const { getAuth } = await import('firebase/auth');
console.log(getAuth().currentUser.uid)

A: Change your security rule to:
allow update, create: if request.auth.uid != null;


text:
Q: Is there any way to access the second element of every tuple in a list of tuples? I have a list of tuples with two elements in each tuple, like so:
[('cat', 'meow'), ('dog', 'bark'), ('wolf', 'bark'), ('cow', 'moo')]

I am searching for tuples with bark that have bark or meow in previous tuple, and print animal names:
cat, dog
dog, wolf

I know this can be done using the previous and next pointers in a C linked list, but is there any in-built method to do the same in Python?

A: I do not think that you need an in-built method to do that, neither is it available. You can simply scan each element of the list and get your result. Have a look at this:
L = [("cat", "meow"), ("dog", "bark"), ("wolf", "bark"), ("cow", "moo")]
for idx in range(1,len(L)):
    if L[idx][1] == "bark":
        if L[idx-1][1] in ["bark", "meow"]:
            print L[idx-1][0]+", "+L[idx][0]

Hope it helps.

A: list = [('cat', 'meow'), ('dog', 'bark'), ('wolf', 'bark'), ('cow', 'moo')]
filter1st = ["bark","meow"]
filter2nd = ["bark"]

for i in range(1,len(list)):
  (name1,sound1)=list[i-1]
  (name2,sound2)=list[i]
  if sound1 in filter1st and sound2 in filter2nd:
    print name1 + ", " + name2

A: A more functional approach might be
inp = [('cat', 'meow'), ('dog', 'bark'), ('wolf', 'bark'), ('cow', 'moo')]

for (an1, snd1), (an2, snd2) in zip(inp, inp[1:]):
    if snd2 == 'bark' and snd1 in ('bark, meow'):
        print('%s, %s' % (an1, an2))

You can use zip on the list and a slice of the list, to iterate over it 2 elements at a time. Thats probably about as close to built in you'll get.

A: You can use a simple list comprehension for that (you need to scan the elements anyway):
v = [("cat", "meow"), ("dog", "bark"), ("wolf", "bark"), ("cow", "moo")]

print [ itm[0] for itm in v if itm[1] in ["bark", "meow"] ]


text:
Q: Eclipse cannot find module even the module path is explicitly provided I have created a module com.company.ep that is located in the source folder com.company.ep. (Yes, I have removed src from the build path and deleted it!) Inside the source folder, I have a couple of packages as the following:
com.company.ep    <--- root source folder
    com.company.ep.main    <--- package 1
    com.company.ep.model   <--- package 2
    com.company.ep.view    <--- package 3
    // ... more packages
    module-info.java

The main class is located in the package com.company.ep.main.Main. In my module-info.java, I have configured the dependencies:
module com.company.ep {
    exports com.company.ep.main;
    exports com.company.ep.model;
    exports com.company.ep.view;
    // ... more exports
    requires javafx.controls;
    requires javafx.graphics;
}

When I tried to launch my program, eclipse told me that:
Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.controls not found, required by com.company.ep

So, I tried to run it on the command prompt:
java -p d:\Applications\openjfx-sdk-11\lib;bin -m com.company.ep/com.company.ep.main.Main
bin is the output folder of eclipse, and it worked.
So, I went to Properties → Run/Debug Settings → Main → Show Command Line, it showed:
D:\Applications\openjdk-11.0.1\bin\javaw.exe -Dfile.encoding=UTF-8 -p "D:\Development\Eclipse-Workspace\MyProject\bin" -classpath "D:\Applications\openjfx-sdk-11\lib\javafx.base.jar;D:\Applications\openjfx-sdk-11\lib\javafx.controls.jar;D:\Applications\openjfx-sdk-11\lib\javafx.fxml.jar;D:\Applications\openjfx-sdk-11\lib\javafx.graphics.jar;D:\Applications\openjfx-sdk-11\lib\javafx.media.jar;D:\Applications\openjfx-sdk-11\lib\javafx.swing.jar;D:\Applications\openjfx-sdk-11\lib\javafx.web.jar;D:\Applications\openjfx-sdk-11\lib\javafx-swt.jar" -m com.company.ep/com.company.ep.main.Main
I have created a user library with all JARs added, and the library is added to the project's Modulepath.
Then I have tried to set the module path explicitly in VM arguments in Run/Debug Settings: -p D:\Applications\openjfx-sdk-11\lib, I'd still no luck.
My questions are:

*

*Why javaw.exe?

*Why classpath? As my library is added as a module-path entry.

*How to configure the module dependencies in eclipse.

I am not sure if I have configured eclipse correctly, or whether it is probably a problem of OpenJDK as it worked when I worked on another computer with Oracle Java SE installed.
Thank you!

A: The explanation of why Eclipse fails on running your modular project can be found in the OpenJFX docs for Eclipse (modular from IDE section).
As it was already mentioned:

Being a modular project, and since we already added the JavaFX SDK library to the module-path, there is no need to add any VM arguments.

But if you run on Eclipse you will get the mentioned error:

Error occurred during initialization of boot layer
  java.lang.module.FindException: Module javafx.graphics not found, required by hellofx

So why is it failing??
As explained in the docs:

This exception happens because the Eclipse ant task overrides the module-path

How does this happen??
Checking the command line applied (Show Command Line from Run Configurations...), you can find out why:
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p bin/hellofx \
    -classpath $PATH_TO_FX \
    -m hellofx/org.openjfx.MainApp

If you copy it and paste it and run it in a terminal, it will fail of course with the same message. The reason is that Eclipse doesn't add the JavaFX library to the module path.
If the task generates the wrong arguments, let's try to fix it by adding our own VM arguments by editing Run configurations... and adding -p $PATH_TO_FX:bin/hellofx.
But if you run it, it will fail again.
Let's check why, with Show Command Line from Run Configurations...
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p $PATH_TO_FX:bin/hellofx \
    -p bin/hellofx \
    -classpath $PATH_TO_FX \
    -m hellofx/org.openjfx.MainApp

As you can see, the user's VM arguments are added before the default ant task arguments, so there are two -p (--module-path) options, and the first one (the user's one with the JavaFX jars) is overridden by the second one (only the project's module), so, again, the JavaFX jars are not added to the module path, and hence you get the error.
So how can we fix it??
As mentioned in the linked documentation, the possible fix is:

To prevent this issue click on Run -> Run Configurations... -> Java Application -> Dependencies, select Override Dependencies... and add -p /path-to/javafx-sdk-11/lib:bin/hellofx, and press Override.

With this solution, you can see it works, and you can check the command line:
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p $PATH_TO_FX:bin/hellofx \
    -p bin/hellofx \
    -classpath $PATH_TO_FX \
    -p /path-to/javafx-sdk-11/lib:bin/hellofx \
    -m hellofx/org.openjfx.MainApp

Basically we are adding again the "right" module path option, after all the failed ones.
While now the project runs, the solution is obviously not nice.
Here you can find a sample referred from the OpenJFX documentation.
EDIT
Based on @kleopatra comments, another workaround to make it work is the following:
For some reason, the library JavaFX11 (that contains modular jars) is not scanned and Eclipse doesn't include those jars into its -p option, but into the classpath:
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p bin/hellofx \
    -classpath $PATH_TO_FX \
    ...

But, if you add those jars directly to the module path, it will do add them, and this will run fine:
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p bin/hellofx:$PATH_TO_FX/javafx.base.jar:...:$PATH_TO_FX/javafx.controls \
    ...

Then with this there is no more need to override the dependencies.
EDIT 2
As @mipa points out in a comment, there was a bug filed on this issue, and it has already been solved. I've tested it with Eclipse 2018-12 M2  (4.10.0M2) Build id: 20181108-1653, and it works with the JavaFX11 library only (as it should):
$JAVA_HOME/bin/java -Dfile.encoding=UTF-8 \
    -p bin/hellofx:$PATH_TO_FX/javafx.base.jar:... \
    -m hellofx/org.openjfx.MainApp


text:
Q: Color not rendering properly This stems from a problem that many people get from following vanZeben's game engine tutorial you can find here. The problem is a the rendering function vanZeben uses. It is very awkward and limiting. I need to remove it and replace it with code that renders the color that is on the sprite sheet.
Edit: Here is a link to the entire project's source.
The closest I've come is removing color >> from the int col initialization. It still removes all color, except for a tile that I added after I finished the tutorial.
//I know the problem comes from this section of code.

int col = (color >> (sheet.pixels[xSheet + ySheet * sheet.width + tileOffset] * 8) & 255);

            if (col < 255)
            {
                for(int yScale = 0; yScale < scale; yScale++)
                {
                    if (yPixel + yScale < 0 || yPixel + yScale >= height) continue;

                    for(int xScale = 0; xScale < scale; xScale++)
                    {
                        if (xPixel + xScale < 0 || xPixel + xScale >= width) continue;
                        pixels[(xPixel + xScale) + (yPixel + yScale) * width] = col;
                    }
                }
            }

I just need col to equal the color of the pixel on the sprite sheet.


text:
Q: When I try to run this VB Script it says "object required" and I cannot find an error Dim objMessage
Set objMessage = CreateObject("CDO.Message")

objMessage.Subject = "ALARMNO SPOROĆILO Z NADZORNEGA SISTEMA"
objMessage.From = "someemail@hotmail.com"
objMessage.To = "toemail@hotmail.com"
objMessage.HTMLBody = "Zdravo"

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someemail@gmail"

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "00000000000000"

objMessage.Configuration.Fields.Update

REM Now send the message

On error Resume Next
Obj.Message.Send

IF err.Number <> 0 Then

MsgBox Err.Description,16,"Error sending Mail "
Else
MsgBox " Message sent "
END IF

I wrote this code in Notepad++ and saved it as a .vbs file and try to run it, but I get "object required" error. I cannot find the problem.

A:
'Create the objects require for sending email using CDO
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields

'Set various parameters and properties of CDO object
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
'your smtp server domain or IP address goes here such as smtp.yourdomain.com
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
'uncomment next three lines if you need to use SMTP Authorization
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "email@gmail.com"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
objFlds.Update
objMail.Configuration = objConf
objMail.From = "email@gmail.com"
objMail.To = "email@hotmail.com"
objMail.Subject = "Put your email's subject line here"
objMail.TextBody = "Your email body content goes here"
objMail.Send

'Set all objects to nothing after sending the email
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing

With little more search i found this on the internet...and it works so if anybody else needs a solution here it is ...also if there is somebody who could explain me where i went wrong in my own script...i would be grateful.

A: I suspect your original script failed because you had
Obj.Message.Send

... instead of
objMessage.Send


text:
Q: Find the distribution of $Y=X'\Sigma^{-1}X$ using mgf
Let $\bf{X}\sim N_p(\bf{0},\bf{\Sigma})$, find the distribution of
  $\bf{Y=X'\Sigma^{-1}X}$ using the moment generating function.

I know that
$$M_X(t)=E[\exp(t'X]=\exp(\frac{1}{2}t'\Sigma t)$$
then
$$M_Y(t)=E[\exp(t'Y)]=E[\exp(t'X'\Sigma^{-1}X)]$$
Here I think about use the fact that $\Sigma=LL'$ where $L$ is a lower triangular matrix, then
$$M_Y(t)=E[\exp(t'X'(LL')^{-1}X)]=E[\exp(t'X'(L')^{-1}L^{-1}X]=E[\exp(t'X'(L^{-1})'L^{-1}X]$$
$$=E[\exp(t'(L^{-1}X)'(L^{-1}X))]$$
but now I don't know what to do. Any hint?

A: First, note that $X'\Sigma^{-1}X$ is a number, not a vector, so you don't really need that prime on the $t$ of your mgf for Y.
I suppose we're assuming $\Sigma$ is invertible based on the premise of he question, so we can take the expectation $E(\exp(t(X'\Sigma^{-1}X)))$ using the density for $N(0,\Sigma)$ $$ f(x) = \frac{1}{\sqrt{\det(2\pi\Sigma)}} \exp(-\frac{1}{2}x'\Sigma^{-1}x).$$ So we have $$ E(\exp(t(X'\Sigma^{-1}X))) = \frac{1}{\sqrt{\det(2\pi\Sigma)}}  \int \exp(tx'\Sigma^{-1}x)\exp\left(-\frac{1}{2}x'\Sigma^{-1}x\right)\,d^p x\\= \frac{1}{\sqrt{\det(2\pi\Sigma)}}  \int \exp\left(-\frac{1}{2}(1-2t)x'\Sigma^{-1}x\right)\,d^p x \\= \frac{\sqrt{\det\left(\frac{2\pi}{1-2t}\Sigma\right)}}{\sqrt{\det(2\pi\Sigma)}} \\= \frac{1}{(1-2t)^{p/2}}.$$


text:
Q: Does there exist some relations between Cryptography and Algebraic Topology? We  know that there are many application of Cryptography in our real life.
 Are there any relation between Cryptography and Algebraic Topology?
If yes, please suggest me some link or books.
Thanks in advance.

A: Braid-based cryptography uses braid groups to produce cryptographic schemes starting with the Anshel–Anshel–Goldfeld key exchange at around year 2000. Braid groups arise as the fundamental groups of topological spaces called the configuration spaces, and they also arise as the mapping class groups of punctured disks. However, braid-based cryptographic schemes are now thought to be insecure even though they originally looked very promising.
See Patrick Dehornoy's survey paper or David Garber's survey paper for more information on Braids based cryptography.


text:
Q: Stop receiving push notification after user logout I have created an application with firestore database. When user logged in or registered in application, firebase device token will be add as a field in database. At the time of logout i have put the code of delete instanceid and token too. Still i am receiving notification of previous user after logout. Here is my code.
On Registration Page:
private fun addNewUser(uid: String, socialUser: FirebaseUser? = null) {
  FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(activity, OnSuccessListener<InstanceIdResult> { instanceIdResult ->
        val mToken = instanceIdResult.token
        userModel.deviceToken = mToken
    })
  val mapData = userModel.getMap()
   database.collection(UserModel.COLLECTION_APP_USERS).document(uid).set(mapData, SetOptions.merge())
            .addOnSuccessListener { _: Void? ->
                UserTokenManager(activity).setUserMe(userModel)
                isSignInSuccessful.value = ApiResponse(true)
            }
            .addOnFailureListener { exception: Exception ->
                isSignInSuccessful.value = ApiResponse(exception)
            }

}

So here i am adding token id in firestore database.
Now following code on logout.
fun endSession() {
    try {
        val sharedPreferenceHelper = SharedPreferenceHelper(context)
        FirebaseAuth.getInstance().signOut()
        FirebaseInstanceId.getInstance().deleteInstanceId()
        FirebaseInstanceId.getInstance().deleteToken("7398260350" , "FCM")
        SharedPreferenceHelper(context).clearAll()
        val intent = Intent(this, SignInActivity::class.java)
        startActivity(intent)
        finish()
       } catch (e: Exception) {
        Log.e("exception", "==->${e.message}")
   }
}

Still i am receiving notifications after logout.


text:
Q: Godot 3.0 Change Animation of KinimaticBody 2D following a path I'm trying to get a kinematic body to change its animation to the appropriate isometric one as it follows a path. The code I'm using is below and it is attached to A KinematicBody2D. Any idea would be helpful even changes to structure etc.
Game
--TileMap
----Pathe2D
------PatheFollow2D
--------KinematicBody2D
--------CollisionShape2D
--------AnimationSprite

The Code Currently
extends KinematicBody2D

var direction = Vector2()
var currentdirection = Vector2(0,0)

# Called when the node enters the scene tree for the first time.
func _ready():
    set_physics_process(true)

func _physics_process(delta):
    var dir = position
    var direction = dir.normalized()
    print(position)

    ghost_anim(dir)
    # Moves Ghost
    get_parent().set_offset(get_parent().get_offset() + 250 * delta)

func ghost_anim(direction):
    var spritedir
    if currentdirection != direction:
        if currentdirection == Vector2(-1,-1):
            spritedir = "Back_Left"
        elif currentdirection == Vector2(1,-1):
            spritedir = "Back_Right"
        elif direction == Vector2(-1,1):
            spritedir = "Front_Left"
        elif direction == Vector2(1,1):
            spritedir = "Front_Right"
        else:
            pass
    else:
        spritedir = "Front_Left"

    get_node("Ghost").set_animation(spritedir)

    currentdirection = direction
    return currentdirection


text:
Q: Принадлежность точки прямой в трехмерном пространстве Есть структура описывающая прямую
typedef struct line
{
    coord m;//координаты первой точки прямой
    coord n;//координаты второй точки прямой
    coord v;//координаты направляющего вектора

} Line;

Я написал проверку на принадлежность, но при определенных тестовых данных она не работает(если ввести одну и туже точку), т.к возникает деление на 0. Я просматривал вопросы на сайте для двумерного пространства, но их решение не подходит.
int isBelong(Line l, coord p)
{
    coord t;
    t.x = (l.v.x / (p.x - l.m.x));
    t.y = (l.v.y / (p.y - l.m.y));
    t.z = (l.v.z / (p.z - l.m.z));
    return (t.x == t.y) && (t.y == t.z) ? 1 : 0;
}

Как можно модифицировать функции, чтобы она работа для всех данных?

A: Как идея - если есть две точки A и B, определяющие прямую, и точка C, то эта точка лежит на прямой AB, если |AC| + |BC| == |AB| или |AC| + |AB| == |BC| или |AB| + |BC| == |AC| (в зависимости от взаимного расположения точек).
Ну, а расстояние типа |AC| по теореме Пифагора находится без всякого деления...
Или посчитать |AC|, |BC| и |AB| и найти площадь треугольника (а лучше ее квадрат - легче) по формуле Герона. Если нуль - значит, все три точки на одной прямой.
Впрочем, это одно и то же :) - ведь первые три равенства проверить можно легко как  равно ли нулю выражение (|AC| + |BC| - |AB|)*(|AC| + |AB| - |BC|)*(|AB| + |BC| - |AC|) (что эквивалентно проверке, равна ли нулю площадь по формуле Герона).

A: Избавиться от деления можно, перегруппировав выражения так:
  l.v.x * (p.y - l.m.y) - (p.x - l.m.x) * l.v.y == 0  &&
  l.v.y * (p.z - l.m.z) - (p.y - l.m.y) * l.v.z == 0  &&
  l.v.z * (p.x - l.m.x) - (p.z - l.m.z) * l.v.x == 0;

По сути это означает:  каждый компонент векторного произведения равен нулю.
Для вещественных координат можно также проверять, что сумма абсолютных  значений этих компонентов не превышает некой погрешности.

Общий случай с учётом погрешностей вещественной арифметики:
В двумерном случае наиболее выгодный вариант - использование векторного произведения. В трёхмерном случае векторное произведение требует заметно больше операций, и лучше использовать подход на основе скалярного произведения.
Имеются векторы v - направляющий вектор прямой и w = p - m-  вектор из базовой точки прямой на точку.

Вектор из m до проекции точки p на прямую
pl = v * Dot(w, v) / Dot(v, v)

Вектор проекции
 pr = p - pl
 len =  |pr|

его длина len для точки на прямой нулевая, в реальных вычислениях с плавающей точкой нужно учитывать небольшой допуск. Лучше использовать квадрат расстояния
 Dot(pr, pr) < eps^2

чтобы корень не извлекать


text:
Q: Mssql queue implementation I have table QUEUE (job_id) on MS SQL which holds stored jobs to be done on Node.JS/Express.js (separate application, separate session)
When a row to queue is inserted (from second table trigger), I need to trigger a job in Node.js (by job id)

*

*I found some solutions using Service Broker, but there are limitations because of Express version of MS SQL

*A working but dirty solution is something like this (written on Node.js)
while (1=1) {

  read queue

  if (queue not empty) {
      do job
      clear queue
  }
  wait few seconds
}

Is there another option? To eliminate waiting a few seconds? Is it possible to stop select (for example by application lock) until queue is filled?


text:
Q: Python website scraping for all of a tag using 'soup.findall' I'm just beginning to dabble with Python, and as many have done I am starting with a web-scraping example to try the language.
What I am attempting is to gather everything of a certain tag type and return as a list.
For this I am using BeautifulSoup and requests.
The site being used for this test is the blog for a small game called 'Staxel'
I can get my code to output the first occurrence of the tag using [soup.find] and [print], but when I change the code to the below I get warnings about printing a list as a fixed variable.
Can someone please indicate what I should be using for this?
# import libraries
import requests
import ssl
from bs4 import BeautifulSoup

# set the URL string
quote_page = 'https://blog.playstaxel.com'

# query the website and return the html to give us a 'page' variable
page = requests.get(quote_page)

# parse the html using beautiful soup and store in a variable ... 'soup'
soup = BeautifulSoup(page.content, 'lxml')

# Remove the 'div' of name and get it's value
name_box = soup.find_all('h1',attrs={'class':'entry-title'})
name = name_box.text.strip() #strip() is used to remove the starting and trailing
print ("Title {}".format(name))

A: By using .find_all(), you're creating a list of all occurences of h1. You simply need to wrap your print statement in a for loop. Your code with that structure looks like:
# import libraries
import requests
import ssl
from bs4 import BeautifulSoup

# set the URL string
quote_page = 'https://blog.playstaxel.com'

# query the website and return the html to give us a 'page' variable
page = requests.get(quote_page)

# parse the html using beautiful soup and store in a variable ... 'soup'
soup = BeautifulSoup(page.content, 'lxml')

# Remove the 'div' of name and get it's value
name_box = soup.find_all('h1',attrs={'class':'entry-title'})
for name in name_box:
    print ("Title {}".format(name.text.strip()))

Output:
Title Magic update – feature preview
Title New Years
Title Staxel Changelog for 1.3.52
Title Staxel Changelog for 1.3.49
Title Staxel Changelog for 1.3.48
Title Halloween Update & GOG
Title Staxel Changelog for 1.3.44
Title Staxel Changelog for 1.3.42
Title Staxel Changelog for 1.3.40
Title Staxel Changelog for 1.3.34 to 1.3.39

A: That's because soup.find_all returns a list not a string like soup.find
The snippets below should avoid the error and print any titles found in python 2.7 and 3.*:
Python 3.*:
name_box = soup.find_all('h1',attrs={'class':'entry-title'})
titles = [name.text.strip() for name in name_box]  # loop over results and strip extract space
for title in titles:  # loop over titles and print
    print ("Title {}".format(title))

Python 2.7:
   name_box = soup.find_all('h1',attrs={'class':'entry-title'})
    titles = [name.text.strip() for name in name_box]  # loop over results and strip extract space
    for title in titles:  # loop over titles and print
        print ("Title {}".format(title.encode('utf-8')))

As mentioned in the comments by @Vantagilt the output for him was adding a 'b' before the string. This is to due to differences in the way strings are interpreted between python 2.7 and python 3. Here's a good blog on the subject.
The main point is by default strings are unicode in python 3 therefore the encode part can be dropped. In python 2.7 strings are stored as bytes and need to encoded explicitly or else we will see errors like:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 13: ordinal not in range(128)

A: Instead of using attrs, you can use the class.
As find_all will return the list, you have to loop over and format each value.
Python 2.7
name_box = soup.find_all('h1', class_='entry-title')
# name_box is a list, which contain all the value of `h1` tag of given class value

for name in name_box:
  title = name.text.strip()
  print ("Title {}".format(title.encode('utf-8')))

Python 3.*
name_box = soup.find_all('h1', class_='entry-title')
# name_box is a list, which contain all the value of `h1` tag of given class value

for name in name_box:
  title = name.text.strip()
  print ("Title {}".format(title))


text:
Q: What chart type can display 8 scores together with averages per subsets of scores? I'm looking for a chart that can display the following data:
Nanoentities    LoC   Dependencies  SCC   Entities  Responsibilities    Relations   Semantic
2.9             0.0   10.0          10.0  3.0       2.9                 6.7         7.6

Until now a simple column chart would do! Yet, I still need to show the average per attribute (which can be grouped as follows):
Granularity=AVG(Nanoentities,LoC)
Coupling=AVG(Dependencies,SCC)
Cohesion=AVG(Entities,Responsibilities,Relations,Semantic)

in the same chart.
What type of chart would better represent this kind of data?

A: You are searching for another possibilty to display your chart rather than in bar plots.
You can use the plotly or ggplot function to do so.
Like on this site you can display your numbers by setting different factors. If you just want to display one variable against another a scatterplot can be used like this:
#install.packages("ggplot2")
library(ggplot2)
plot(x=iris$Sepal.Length, y=iris$Sepal.Width, xlab="Sepal Length", ylab="Sepal Width", main="Sepal Length-Width")
You just have to exchange the x and y values for your parts of data,xlab and ylab describe the axes and main is for the chart title.
For more charts just search for them (see the link above for their names and how they look) and see example codes for them in the individual package.

A: A multicategory bar/line combo should do the trick.


text:
Q: C++ convert Int value to 4 bytes how to convert in c++ int value to 4 byte representation.
I tried in that way:
int digit = 2;
unsigned char a[4];
a[3] = (digit>>24) & 0xFF;
a[2] = (digit>>16) & 0xFF;
a[1] = (digit>>8) & 0xFF;
a[0] = digit & 0xFF;

cout << a[0] << a[1] << a[2] << a[3] << endl;

but cout don't display anything.


text:
Q: Specify parameter that contains a dot in its name using rpy2 With Python, how can I implement the following R statement using rpy2?
library(climatol)
homogen('Vel',2011,2012,tinc='6 hour',expl=TRUE,dz.max=10)

The following code in Python has worked for all parameters except dz.max.
from rpy2.robjects import r
from rpy2.robjects.packages import importr
importr('climatol')

r['homogen']('Vel',2011,2012,tinc='6 hour',expl=r['as.logical']('T'))

I see that I can call R functions using r[<function_name>] regardless of whether they have a dot in their name, for example as.logical, which I used to invoke the boolean value True. Now how can I specify parameters whose name contains dots, as in the case of dz.max?
Thanks for the help.

A: from rpy2.robjects import r
from rpy2.robjects.packages import importr
climatol = importr('climatol')
climatol.homogen('Vel', 2011, 2012, tinc='6 hour', expl=True, dz_max=10)

Consider checking the documentation, for example the introduction:
https://rpy2.github.io/doc/v3.3.x/html/introduction.html


text:
Q: price range problem I am developing an application which deals with commission based on price range
I have 2 text-boxes (input type="text"), one for lower-limit, and another for upper-limit
Everytime someone adds new price range, I need to validate that it is available before hand or not, and whether it will fall in any of the previous price range
Example for Valid Ranges:
1-10
11-20
21-30
31-40
what should not be allowed are:
(considering following range is available with us
1-10
11-20
21-30
31-40
)
following should not be allowed
0-5
2-8
0-15
5-12

Help appriciated.

A: If the available ranges are predefined and known, why not simply replace the two text boxes with a single select box with an <option> for each range?

A: Use the following php code on your page
$ranges = array('1-10','11-20','21-30','31-40');

echo "<script type='text/javascript'> var ranges = [". "'" .implode("','",$ranges) . "'" . "];</script>";

Assuming your textboxes have ids lowerlimit and upperlimit you can simply check before submit
function check(){
  var lowerlimit = document.getElementById('lowerlimit').value;
  var upperlimit = document.getElementById('upperlimit ').value;
  for (var i=0; i<ranges.length; i++) {
    if(ranges[i] == lowerlimit+'-'+uperlimit){
       return true;
    }
  }
  return false;
}

if (!check()){
   alert('Please enter valid range!')
}


text:
Q: When or who does pass resolve and reject functions to JS promises? I have begun learning javascript promises. But I just can't understand the concept of promises.
The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?
See this example of Promise:
function getImage(url){
    return new Promise(function(resolve, reject){
        var img = new Image()
        img.onload = function(){
            resolve(url)
        }
        img.onerror = function(){
            reject(url)
        }
        img.src = url
    })
}

Now who does pass resolve and reject methods, as my understanding of javascript says to me that this script will throw unknown variable errors as resolve and rejects are not defined?
getImage('doggy.jpg').then(function(successurl){
    document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
    console.log('Error loading ' + errorurl)
})

Now you see a method like the above, the only way these methods(resolve and reject) are passed are via then and catch as used in above method call to getImage.

A:
The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

Nobody.
The functions are passed by the promise constructor.
They are passed to the function which you pass as the first argument to the promise constructor.

A: The Promise constructor is initialized with a callback, and the constructor passes reject and resolve as parameters when the callback is called.
Here is a simple demo:

class PromiseDemo {
  constructor(cb) {
    cb(this.resolve.bind(this), this.reject.bind(this));
  }

  resolve(d) {
    console.log('resolve', d);
  }

  reject(d) {
    console.log('reject', d);
  }
}

new PromiseDemo((resolve, reject) => {
  Math.random() > 0.5 ? resolve('1') : reject('1');
});

A: I had the same problem in understanding Promises.You need to look at the process of promise creation carefully.
when you write
var promise= new Promise(function(resolve,reject){...})
you are actually invoking constructor of Promise class or creating an object of Promise class. Now Promise constructor requires a function callback.
Now resolve and reject are just function arguments and not any other values.
You can write anything in place of resolve or reject like resolveHandler or rejectHandler.
These resolve or reject are nothing but the function callback that Promise calls when Promise is executed.
Now resolve is called when Promise is executed successfully and reject is called when promise is executed with some error or unsuccessfully .
The argument with which resolve is called can be accessed inside then like this
getImage().then(function(valueSentInResolve){ console.log('')})

The argument with which reject is called can be accessed inside catch like this
getImage().then(function(valueSentInResolve)
  {//..do something}
).catch(function(errorSentInReject){
  console.log('error',errorSentInReject )
})

I hope that helps.Let me know if I said anything wrong.

A: I have been studying Promises all day, and had the same question. I finally figured it out.
When you make a Promise object, you give the Promise Constructor an executor, which can be any function, as long as it has this signature.
anyFunction(resolutionFunction, rejectionFunction){
    // typically, some asynchronous operation.
}

So any function with 2 functions as the arguments can be used. The first function is what you call when it works, the second is what you call when it breaks. You can name those functions whatever you want as well.
The Promise Constructor takes the function you pass in and does a few things with it.

*

*It takes those 2 function arguments and generates a corresponding pair of functions that are "connected" to the Promise object.

*It runs the executor

*It ignores any return value from your executor

Now in your executor function when the promise resolves you call the positionally first function and pass it one value. It will look something like:
resolutionFunction(value)

You may be wondering, where is resolutionFunction defined? Remember the Promise Constructor defined that function for us. So we can call resolutionFunction without having to define it ourselves. Behind the scenes, when we call that resolutionFunction generated by the Promise Constructor, it sets the state of the promise to fulfilled, calls the function inside the promiseObject.then function, and passes the value into the .then function so you can use it.
You would call the 2nd positional function if the promise failed and the same things would happen and you could deal with the failure.
This Mozilla Doc on the Promise Constructor was very helpful.
Here is a short examples that shows what I explained above.
function anyFunction(callThisFunctionWhenItWorks, callThisFunctionWhenItBreaks) {
  let importantNumber = 10; //change to 11 if you want the promise to reject
  if (importantNumber == 10) {
    callThisFunctionWhenItWorks('Hooray, success, so we call resolved for the promise.');
  } else {
    callThisFunctionWhenItBreaks('Boo, rejected because important number is not equal to 10');
  }
}

//make a new promise
const examplePromise = new Promise(anyFunction);

//use the promise
examplePromise.then(function(result) {
  console.log(result);
}).catch(function (error) {
  console.log(error);
})

A: The promise library creates and passes those functions, along with all the other metadata needed to track the promise and record completion, store state and progress, cancel it, etc.
The folks behind Bluebird have published some info on how the library works internally, and you can see more in the Bluebird source.

A: does this make sense? This explanation could be completely incorrect!!
We provide the logic which should run asynchronously. The logic should accept 2 functions, resolve and reject. The reference of these functions is provided by Promise. These functions should be called by our logic when we have the final value or error. The Promise created initially is in Pending state. Calling resolve and reject changes the state to Fulfilled or Rejected respectively.
executeFunction(res,rej) = {
 do some op, say DB query.
 if (success) res(value) //executeFunction uses the resolving functions to change state of the Promise. Calling res fulfills the promise with value
 if (fail) rej(reason)//executeFunction uses the resolving functions to change state of the Promise. Calling rej rejects the promise with reason
}

Rather than calling executeFunction directly (which would make the call synchronous), we create a Promise will will run the executeFunction code in a separate thread (asynchronously) let p = Promise(executeFunction(res,rej));. We get back a reference of the Promise.
My guess is that internally in the Promise, the following happens
Promise(e(res,rej)) = {

// the Promise's constructor creates a new promise, initially in the pending state. It calls `e` (the executeFunction function) and provides references to the resolving functions to it that can be used to change its state.
  state = pending;
  e(_res,_rej); //starts my op. asynchronously (a new thread). Reference to resolving functions, _res, _rej is provided. _res and _rej are Promise's internal functions (see below)
  //constructor doesn't return till the async thread finishes
}

_res (value){ //Promise's internal method
 //probably sets the state of promise to Fulfilled and store the result of the Promise
 state = fulfilled
 resolvedValue = value;
}

_rej {//Promise's internal method
 probably sets the state of promise to Rejected and store the result of the Promise
 state = rejected
 resolvedValue = error;
}

Creating the Promise starts the execution of the code asynchronously. Now we are interested in knowing what is the result of executeFunction (we don't care when executeFunction finishes). To do this, we call then of the Promise p. then takes two optional arguments and registers them as callbacks. I am not sure when and who calls these callbacks. I know that then returns another Promise but I am not able to understand how that works
   then(executeFnIfPromiseResolved, executeFnIfPromiseRejected):Promise {
      register executeFnIfPromiseResolved as callback
      register executeFnIfPromiseRejected as callback
      //NOT SURE WHO AND WHEN THE CALLBACKS ARE CALLED
      //then needs to return Promise. What would be the executor function of that Promise?
}


text:
Q: Getting wrong answer on project euler # 8 This might be repeated but trust me I dint find satisfactory answer.
Can someone please tell me why am I getting wrong answer to this problem : https://projecteuler.net/problem=8. I used brute-forcing. My code gives correct answer for small numbers. However for 13- digit it is giving a wrong answer. Code:
#include <iostream>
#include<string>
#include<cmath>
using namespace std;

int main()
{
     string str = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
    int len = str.size();
    double maxi = 0, product = 1;
    for(int i = 0; i < len - 13; i ++){
        product = (str[i] - '0') * (str[i+1] - '0') * (str[i+2] - '0') * (str[i+3] - '0') * (str[i+4] - '0') * (str[i+5] - '0')* (str[i+6] - '0') * (str[i+7] - '0') * (str[i+8] - '0') * (str[i+9] - '0') * (str[i+10] - '0') * (str[i+11] - '0') * (str[i+12] - '0');
        if(maxi < product){
            maxi = product;
        }
    }
    cout << maxi;
    cin.get();
    return 0;
}

For the example they have given. That is product of 4-consecutive digits, I get correct answer 5832. Code for the same:
#include <iostream>
#include<string>
#include<cmath>
using namespace std;

int main()
{
     string str = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
    int len = str.size();
    double maxi = 0, product = 1;
    for(int i = 0; i < len - 13; i ++){
        product = (str[i] - '0') * (str[i+1] - '0') * (str[i+2] - '0') * (str[i+3] - '0'); //* (str[i+4] - '0') * (str[i+5] - '0')* (str[i+6] - '0') * (str[i+7] - '0') * (str[i+8] - '0') * (str[i+9] - '0') * (str[i+10] - '0') * (str[i+11] - '0') * (str[i+12] - '0');
        if(maxi < product){
            maxi = product;
        }
    }
    cout << maxi;
    cin.get();
    return 0;
}

A: The most likely reason is that there is an integer overflow happening.
The maximum value of the product of 13 digits is 9^13, and a double can't support that accurately.
So, the solution is to use long long instead of double.

A: Every time you encounter a problem like this, where you get the correct results for an example but a wrong one for the large dataset you should think about overflows. Your product and maxi are of type double. I changed them to long long and got the correct result. I also cleaned up your code a little bit. Here it goes
#include <iostream>
#include<string>
#include<cmath>
using namespace std;

int main()
{
    string str = "73167176531330624919225119674426574742355349194934" \
                 "96983520312774506326239578318016984801869478851843" \
                 "85861560789112949495459501737958331952853208805511" \
                 "12540698747158523863050715693290963295227443043557" \
                 "66896648950445244523161731856403098711121722383113" \
                 "62229893423380308135336276614282806444486645238749" \
                 "30358907296290491560440772390713810515859307960866" \
                 "70172427121883998797908792274921901699720888093776" \
                 "65727333001053367881220235421809751254540594752243" \
                 "52584907711670556013604839586446706324415722155397" \
                 "53697817977846174064955149290862569321978468622482" \
                 "83972241375657056057490261407972968652414535100474" \
                 "82166370484403199890008895243450658541227588666881" \
                 "16427171479924442928230863465674813919123162824586" \
                 "17866458359124566529476545682848912883142607690042" \
                 "24219022671055626321111109370544217506941658960408" \
                 "07198403850962455444362981230987879927244284909188" \
                 "84580156166097919133875499200524063689912560717606" \
                 "05886116467109405077541002256983155200055935729725" \
                 "71636269561882670428252483600823257530420752963450";

    const size_t adjacent = 13;
    size_t len = str.size();

    long long max = 0, product = 1;
    for(size_t i = 0; i+adjacent < len; ++i) {
        product = 1;
        for (size_t j = 0; j < adjacent; ++j)
            product *= str[i+j] - '0';
        if (max < product)
            max = product;
    }
    cout << max << endl;
    return 0;
}

Demo


text:
Q: Como insertar una gráfica en un jPanel con JFreeChart en Java? Tengo el gráfico generado pero no consigo que aparezca en el panel que quiero, cabe recalcar que es un panel dentro de otro panel, pero de ninguna forma consigo mostrarlo, siempre se queda en blanco
JSONObject json = readJsonFromUrl("http://ddragon.leagueoflegends.com/cdn/12.10.1/data/es_ES/champion/"+Nombrepj+".json");
JSONObject jsondata = json.getJSONObject("data");
JSONObject jspj = jsondata.getJSONObject(Nombrepj);
JSONObject jsppass = jspj.getJSONObject("info");

Datos.addValue(jsppass.getInt("attack"), "Ataque", "Atq");
Datos.addValue(jsppass.getInt("defense"), "Defensa", "Def");
Datos.addValue(jsppass.getInt("magic"), "Mágia", "Mg");

Estadisticas = ChartFactory.createBarChart("Estadísticas Básicas","Estadísticas", "Número", Datos,PlotOrientation.VERTICAL, true, true, false);

jPanel_EstBasicas.add(Estadisticas);


text:
Q: Display value in a modal i have a table that i want the user to be able to edit, when the edit button is clicked i want the value of the field shown in the modal. i managed to do that however all values are being displayed i only want the values of the field related to the edit button clicked.
this is my code

        {%for element in data%}
            <form method="post">

Edit User

                    <input name="_id" value="_id" id="the.id" hidden></input>

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

                        First Name
                        <input type="text" name="UPusername"  value="{{ element['username'] }}" class="form-control" >

                        Last Name
                        <input type="text" name="UPlast_name"  value="{{ element['last_name']}}" class="form-control" >

                        Email
                        <input type="email" name="UPemail"  value="{{ element['email'] }}" class="form-control" >

                        Registration number
                        <input type="text" name="UPrej_num"  value="{{ element['rej_num'] }}" class="form-control" >

                        Position
                                <select class=" position-form" id="exampleFormControlSelect1" name="UPposition">
                                  <option value="">Choose Option...</option>
                                  <option value="President">President</option>
                                  <option value="Manager">Manager </option>
                                  <option value="Managing Director">Managing Director</option>
                                  <option value="R department">HR department </option>
                                  <option value="Accountant">Accountant</option>
                                  <option value="Project Manager">Project Manager</option>
                                  <option value="Other">Other</option>
                                </select>

                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                    <input type="submit" class="btn btn-info" value="Save">

            </form>
            {%endfor%}

And this is how it's currently shown:


text:
Q: Google Sheets API reading an empty string from a column I'm having a strange occurrence with google sheets.  When we read column D from a spreadsheet, we only get values in the headers and first two rows.  Subsequent rows are returning empty strings for column D.
Here's the main src/index.js code

    const response = await reader.readRange('Special Use Cases Detailed Country ROW Matrix!A:I');
    const spreadsheetData = response.data.values;

Here's my spreadhseet reader class:

module.exports = class SpreadsheetReader {

    constructor(inSpreadsheetId, inAuthClient, inClient) {
        this.spreadsheetId = inSpreadsheetId;
        this.authClient = inAuthClient;
        this.client = inClient;
    }

    // returns a promise that resolves to spreadsheet data
    async readRange(range, valueRenderOption = 'UNFORMATTED_VALUE') {
        return this.client.spreadsheets.values.get({
            auth: this.authClient,
            range: range,
            valueRenderOption: valueRenderOption,
            spreadsheetId: this.spreadsheetId
        });
    }
};

I've checked the spreadsheet and it's all straightforward string data. There doesn't appear to be any formulas or special symbols.  Rows 1 and 2 only differ by a couple characters, nothing substantial it seems.  Any ideas?


text:
Q: закругленные края для держателя фрагментов имеется main_activity (слева), не могу понять как реализовать закругление содержимого как справа в material3
как это можно реализовать?

увидел что данную идею уже реализовывали


text:
Q: Unable to connect to hbase from java I have set up local hbase and everything is working fine on hbase shell. On running the status command i can see the following output.
1 active master, 0 backup masters, 1 servers, 0 dead, 3.0000 average load

However when i try to run the following lines in java -
Configuration hBaseConfiguration = HBaseConfiguration.create();
hBaseConfiguration.set("hbase.zookeeper.quorum", "localhost");
hBaseConfiguration.set("hbase.zookeeper.property.clientPort", "2181");
hBaseConfiguration.set("zookeeper.znode.parent", "/hbase");
HBaseAdmin.available(hBaseConfiguration);

It gives me the exception
Caused by: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/hbaseid
at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient$ZKTask$1.exec(ReadOnlyZKClient.java:189)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient.run(ReadOnlyZKClient.java:323)
at java.lang.Thread.run(Thread.java:748)

Can you give me any help regarding this?


text:
Q: How does Selenium click on elements that are 50% on screen and 50% not on screen? There is a div-Element. 50% of its size are on the screen. The other 50% go over the screen height and are not visible.
There is no scrolling possible.
I tried to automate a test with Selenium and click on that div-element, but sometimes it works and sometimes it does not.
Why does Selenium not just click on the "on-screen-area" of that div?
And how is this functionality implemented? When I tell Selenium to click on a huge div-element, does it click on a random position on that div?

A: element's in-view center point
As per the WebDriver W3C Specification an element's in-view center point is the origin position of the rectangle that is the intersection between the element's first DOM client rectangle and the initial viewport.
Given an element that is known to be in view, it can be calculated this way:

*

*Let rectangle be the first element of the DOMRect sequence returned by calling getClientRects on element.

*Let left be max(0, min(x coordinate, x coordinate + width dimension)).

*Let right be min(innerWidth, max(x coordinate, x coordinate + width dimension)).

*Let top be max(0, min(y coordinate, y coordinate + height dimension)).

*Let bottom be min(innerHeight, max(y coordinate, y coordinate + height dimension)).

*Let x be floor((left + right) ÷ 2.0).

*Let y be floor((top + bottom) ÷ 2.0).

*Return the pair of (x, y).

An element is in view if it is a member of its own pointer-interactable paint tree, given the pretense that its pointer events are not disabled.

Element Click

As per the documentation the Element Click command scrolls into view the element if it is not already pointer-interactable, and clicks its in-view center point.
Note: If the element's center point is obscured by another element, an element click intercepted error is returned. If the element is outside the viewport, an element not interactable error is returned.

Solution
In such cases there are two possible solutionas follows:

*

*You can induce WebDriverWait setting the expected_conditions as element_to_be_clickable(). So effectively your line of code will be:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".reply-button"))).click()

*You can use move_to_element(to_element) and click(on_element=None) method respectively. So effectively your line of code will be:
ActionChains(driver).move_to_element(element).click(element).perform()

Reference
You can find a relevant discussion in selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python

A: If you are clicking based on the locators like xpath,id and others, yes it clicks on random position. But it does not matter as long as it the element is being clicked, and resulting action of that click is executed.
About Sometimes it works or not, if have you checked for button to be enabled or clicked, it will work always.


text:
Q: point color in ggbetweenstats Is there a way to change the point color in ggbetweenstats?
I have checked the document and didn't see a parameter that can simpliy change the point color.
I try the ggplot2::scale_fill_manual(values = c(purple,darkred,blue)) but nothing happened.
There three colors has been identified and the detailed code is as following:
ggbetweenstats(
  data = box.dat,
  x = Class,
  y = Pre_NeoAts,
  notch = T,
  outlier.tagging = F,
  messages = FALSE,
  mean.color = "black",
  mean.size = 3
)   +   ggplot2::scale_fill_manual(values = c(purple,darkred,blue))

Could anyone give me a hint?
Many thanks advanced!

A: Here is how you can change the point colors.
(This is with ggstatsplot 0.0.6, which is currently on CRAN)
ggstatsplot::ggbetweenstats(
  data = iris,
  x = Species,
  y = Sepal.Length,
  messages = FALSE,
  mean.color = 'black'
) +
  ggplot2::scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))

Moreover, you can also specify palette from your package of choosing to change colors instead of specifying them manually:
ggstatsplot::ggbetweenstats(
  data = iris,
  x = Species,
  y = Sepal.Length,
  messages = FALSE,
  palette = "Royal1",
  package = "wesanderson"
)

Created on 2018-10-10 by the reprex package (v0.2.1)

A: Are you talking about the color point of the mean?
You can change it with the argument mean.color in ggstatsplot::ggbetweenstats().
However you can only assign a single color here.
In addition, each group is already assigned a color as shown in the example below:
library(gapminder)

ggstatsplot::ggbetweenstats(
    data = dplyr::filter(.data = gapminder, year == 2007),
    x = continent,
    y = lifeExp,
    messages = FALSE
)

Thus, there is already a scale_color_discrete() defined in this plot. So if you add a scale_color_*() function it will replace this scale. It does not seem possible to get different colors.


text:
Q: How is the Affine connection related to the Affine group? I'm simultaneously learning some group theory and differential geometry in different contexts and I find myself wondering....
We utilize an affine connection in general relativity (specifically a torsionless levi-cevita type usually), but can imagine using a general affine connection as well. No group theory is ever mentioned.
On the other side of the coin, I'm learning that the double cover of the Poincare group is the special affine group, which has innumerable physical applications. What's the deal, the two are clearly related in some way, but neither class mentions anything suggesting the link.


text:
Q: кастомный инспектор unity попытался сделать кастомный инспектор для некоторых компонентов, и столкнулся с проблемой.
[CanEditMultipleObjects]
public class transform : Editor
{
    public override void OnInspectorGUI()
    {
        Transform unit = target as Transform;

        Undo.RecordObject(target, "позиция");
        unit.localPosition = EditorGUILayout.Vector2Field("позиция", unit.localPosition);

        Undo.RecordObject(target, "размер");
        unit.localScale = EditorGUILayout.Vector2Field("размер", unit.localScale);

        Undo.RecordObject(target, "поаорот");
        float rotation = EditorGUILayout.FloatField("поаорот", unit.localEulerAngles.y);
}

как сделать вот такой параметр поворота вместо Vector2Field,
чтобы можно было изменить только вращение по оси Y?

A: все решил.
    public override void OnInspectorGUI()
    {
        Transform unit = target as Transform;

        Undo.RecordObject(target, "позиция");
        unit.localPosition = EditorGUILayout.Vector2Field("позиция", unit.localPosition);

        Undo.RecordObject(target, "размер");
        unit.localScale = EditorGUILayout.Vector2Field("размер", unit.localScale);

        Undo.RecordObject(target, "паворот");
        float rotationZ = EditorGUILayout.FloatField("поаорот", unit.localEulerAngles.z);
        unit.localEulerAngles = new Vector3(unit.localEulerAngles.x, unit.localEulerAngles.y, rotationZ);
    }


text:
Q: Why doesn't Xcode complain about undeclared methods when using @selector? Why are warnings generated when calling methods undeclared in a class interface using conventional means, but not when calling methods using @selector?  Is it because selectors can be executed by a different caller than self?
For example:
-(void) doStuff
{
    [self doNow]; // Warning: instance method not found
    SEL sel = @selector(doNow); // no warnings
}

-(void) doNow {} // this method is not declared in the interface

A: A similar question was asked on SO a few weeks ago.
This is basically because selectors are late-bound. They're not looked up until runtime. There are options for forcing verification during compilation. The question I linked to has some more information on how you can do that.

A: The way @selector works by default is you are telling the compiler; trust me I have this method somewhere in my class. Its the same concept if you do @class yourclassname instead of importing the .h file which contains the class.

A: This is because the compiler needs to know the signature of the method in order to call it (i.e. [self doNow];), because such a call translates to either a call to objc_msgSend or objc_msgSend_stret depending on whether the method signature has a return type of a struct or not. (Remember the difference between the selector (simply the name with the colons in it, but with no types) and the signature (the types) of a method.) So it needs to warn because it could be calling the wrong function if it doesn't know.
However, just getting a selector (@selector(...)), it doesn't need to know the types. The selector is simply a name, and you've provided the name. It's all about what you use the selector for. If you use it in performSelector:, it also doesn't need to know the types, because that method only works for methods with argument and return types of objects, so there is no ambiguity. Hence there is no need for a warning.

A: The "Undeclared Selector" warning is turned off by default. I don't know why. You can turn it back on in the Build Settings.
The documentation for this settings reads:

Warn if a "@selector(...)" expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the "@selector(...)" expression, either explicitly in an @interface or @protocol declaration, or implicitly in an @implementation section. This option always performs its checks as soon as a "@selector(...)" expression is found, while -Wselector only performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. [GCC_WARN_UNDECLARED_SELECTOR, -Wundeclared-selector]


text:
Q: Moonwalker visits an old church made of moon rock I'm looking for a short story featuring a moonwalker (I think James Irwin) who is on a speaking tour. One of the stops is near a church which according to legend is made from moon rocks.
The legend is about someone flying to the Moon in a chariot pulled by geese and returning with the rock.
The closing line has the moonwalker chiselling a small sample of rock off the church. When exposed to the air, the rock gives off the same smell he remembers from returning to the lander with moon dust on his spacesuit.

A: I suspect this is "Moon-calf", a short story by Stephen Baxter published in 1998. The main character in the story is Colonel James ("Jays") Holland (rather than Jim Irwin), a retired Apollo astronaut who indeed had been to the Moon. While visiting Godwin chapel in Hereford, he notices basalt in the wall of the building:

I know basalts. All the damn Moon rocks we picked up were basalts.
It's just unusual for such an old building to feature such displaced
materials. They didn't have the haulage capability we have now …'

and as the OP remembers, notes its characteristic tang is similar to that of moon-rocks:

pungent smell, the odour of wood-smoke, or maybe of gunpowder: it is
the smell of Moondust, slow-burning in oxygen from Earth …

The Godwin chapel is named after Francis Godwin, bishop of Hereford, who wrote one of the first science fiction stories "The man in the moone":

The story is about how a man called Gonsales trains swans to carry him
through the air. Twenty-five of them, each attached to a pulley, save
him from a shipwreck. But the swans hibernate on the Moon, and carry
Gonsales there …

In "The man in the moone", the protagonist is actually propelled by geese rather than swans, so this seems to be a slip by Baxter. In any case,
the implication is that Gonsales really did travel to the Moon back in the fifteenth/sixteenth century, although probably not by flying geese or swans.


text:
Q: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in /app/node_modules/@babel/helper-compilation-targets/package.json I'm having trouble building my nuxt images in a travis CI pipeline. My local environment is ubuntu 18.04 - docker version 19.03.11 docker-compose version 1.24.1 I'm able to build and run my images locally but on the travis CI I get the following error
Step 5/7 : RUN npm run build
 ---> Running in d3e9433b79f0
> nuxt_app@1.0.0 build /app
> nuxt build
ℹ Production build
✔ Builder initialized
✔ Nuxt files generated
ℹ Compiling Client
ℹ Starting type checking service...
ℹ Using 1 worker with 2048MB memory limit
✔ Client: Compiled with some errors in 1.62s
Hash: 1b9cf81215d31b9f0ed3
Version: webpack 4.43.0
Time: 1624ms
Built at: 06/07/2020 2:20:27 PM
                  Asset      Size  Chunks               Chunk Names
4bff68cc9fb4c003b7f2.js  1.49 KiB       1  [immutable]  runtime
b4f22db01be076446c20.js   1.4 KiB       0  [immutable]  app
Entrypoint app = 4bff68cc9fb4c003b7f2.js b4f22db01be076446c20.js
ERROR in ./.nuxt/client.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in /app/node_modules/@babel/helper-compilation-targets/package.json
    at applyExports (internal/modules/cjs/loader.js:491:9)
    at resolveExports (internal/modules/cjs/loader.js:507:23)
    at Function.Module._findPath (internal/modules/cjs/loader.js:635:31)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:953:27)
    at Function.Module._load (internal/modules/cjs/loader.js:842:27)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/app/node_modules/@babel/preset-env/lib/debug.js:8:33)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/app/node_modules/@babel/preset-env/lib/index.js:11:14)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
 @ multi ./.nuxt/client.js app[0]
 FATAL  Nuxt build error
  at WebpackBundler.webpackCompile (node_modules/@nuxt/webpack/dist/webpack.js:5326:21)
  at processTicksAndRejections (internal/process/task_queues.js:97:5)
  at async WebpackBundler.build (node_modules/@nuxt/webpack/dist/webpack.js:5275:5)
  at async Builder.build (node_modules/@nuxt/builder/dist/builder.js:5598:5)
  at async Object.run (node_modules/@nuxt/cli/dist/cli-build.js:100:7)
  at async NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-command.js:2575:7)

My travis CI
sudo: required

dist: trusty

services:
    - docker

# language: node_js
# node_js: 12

before_install:
    - sudo rm /usr/local/bin/docker-compose
    - sudo curl -L "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    - sudo chmod +x /usr/local/bin/docker-compose
    - sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
    - sudo chmod 400 -R .ops/ssh/*

# before_script:
#     - my_script

script:
    - .ops/build.sh
    - .ops/push.sh

my docker-compose file
    web:
        build:
            context: ${GITROOT:-.}
            dockerfile: Dockerfile.web
        image: moovinit_web
        container_name: moovinit_web
        command: npm start
        environment:
            WEB_PORT: ${WEB_PORT:-3200}
            API_URL: ${API_URL:-http://api:3201}
            <<: *node-common

Why does it build on my laptop but not on travis?

A: Using npm update fixed the same error for me.

A: fixed by npm update && npm audit fix --force

A: I had the similar problem. npm install @babel/helper-compilation-targets --save-dev
 solved this situation

A: UUID npm module was causing this error,
// const uuidv4 = require('uuid/v4'); // OLD
const { v4: uuidv4 } = require('uuid'); // NEW

removing node_modules, package-lock.josn didn't help

A: Quick Fix:
For yarn
yarn upgrade

For npm
npm update

A: I was experiencing this issue and I resolved it by removing the lock file and then reinstall everything again.
This is probably not a good solution for everyone but it works for me.
Here's exactly what I have done.

*

*Removing the lock file. In this case I'm using yarn so I need to delete the yarn.lock file. If you're using npm the lock file is package-lock.json.

# for yarn user
rm yarn.lock

# for npm user
rm package-lock.json

*And then I reinstall all the dependencies.

# for yarn user
yarn install

# for npm user
npm install

A: The solution that worked for me was simply to update node.
For, example, using node 12.22.0 worked, as well as 14.17.4. Note that node version of 13.x will not work at all.
I was also having this issue and found out that this error seems to be specific to some node js versions.

*

*node 13.14.0, node 12.18.4, 12.19.0, 12.19.1 show the error : ERR_PACKAGE_PATH_NOT_EXPORTED

*With node 12.20.0, node 14.17.4, the error is not thrown.

The issue is that a new system for exports has been created, as defined here :
https://github.com/nodejs/modules/issues/535
This feature allows to define the allowed requires that are possible in a package using globs, like this :
  "exports": {
    ".": {
      "import": "./dist/pako.esm.mjs",
      "require": "./index.js"
    },
    "./package.json": "./package.json",
    "./dist/*": "./dist/*",
    "./lib/*": "./lib/*",
    "./lib/zlib/*": "./lib/zlib/*",
    "./lib/utils/*": "./lib/utils/*"
  },

The pull request for this feature can be found here : https://github.com/nodejs/modules/issues/535
Now if you include a package that uses this new "glob" feature in the exports file, it can fail if you require that specific file.

A: Fixed for me executing the following commands:
Upgrade Node.js:
nvm install 16
nvm use 16
node -v

Install yarn:
curl -o- -L https://yarnpkg.com/install.sh | bash
yarn -v

For yarn users:
rm yarn.lock
yarn install

A: I was facing a very similar issue:
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /home/dima/Projects/project/node_modules/@babel/helper-compilation-targets/package.json.
I was trying to launch an older project and installed the last version of node 12 (which was used for the project initially): v12.22.12. I was hesitant to do major node version upgrade of the project for a small fix. But with this version, I was facing this error. After reading answer of edi9999, I tried to downgrade node to the precise node version used at that project during main development time: v12.13.0. And with this version everything worked well.
Seems like some babel package used internal node API, which was removed in the newer node 12 and therefore it became broken. So if you have a similar case, try to use precise node version of an old project.


text:
Q: How to make matplotlib handle custom class "units" I am trying to make my class compatible with matplotlib's units and facing an unexpected behaviour.
Here is a simplified version of my custom class, that is not a subclass of numpy's ndarray :
import numpy as np
import matplotlib
import matplotlib.units as units

class Toto:
    def __init__(self, value_like, unit_like):
        self.value_like = value_like # typically a scalar or array
        self.unit_like = unit_like # a string describing the unit

    def __array__(self, *args, **kwargs):
        return np.array(self.value_like, *args, **kwargs)

# To test if plot as expected, without units handling
arr_x = Toto(np.arange(5), "meter")
arr_y = Toto(np.arange(5), "second")
plt.plot(arr_x, arr_y)

Notice I added a __array__ method in order to make it "plottable" with matplotlib (if not, I get a TypeError: float() argument must be a string or a number, not 'Toto' exception, when numpy tries to cast Toto with array(toto_instance, float)). I suspect my problem actually come from this method but I can't figure out why/how. Anyway, moving on the actual problem :
Now I followed the example in the doc to make a conversion-interface for my Toto class:
class TotoConverter(units.ConversionInterface):

    @staticmethod
    def convert(value, unit, axis):
        'Convert a toto object value to a scalar or array'
        old_toto_unit = axis.get_unit()
        # stupid computation to determine new_unit (simpler for a MWE)
        new_unit = old_toto_unit
        new_toto = Toto(value, new_unit)
        return new_toto.value_like

    @staticmethod
    def axisinfo(unit, axis):
        return units.AxisInfo(label=str(unit))

    @staticmethod
    def default_units(x, axis):
        'Return the default unit for x or None'
        return getattr(x, 'unit_like', None)

In the end, I add the conversion interface of my class to matplotlib's registry of conversion interfaces:
units.registry[Toto] = TotoConverter()

Then the problem :
At this point, I should get the unit on the label when plotting Toto instances, but I get the same result as before defining and registering my unit conversion-interface. Why is that ?
I suspect the conversion object is never called since my Toto instances are converted into ndarray but I'm not sure
Cheers

A: I suspect you mean something like this, where you have a list/array of Totos, and not a Toto of values.
import matplotlib.pyplot as plt
import matplotlib.units as units

class Toto:
    def __init__(self, value_like, unit_like):
        self.value_like = value_like # typically a scalar or array
        self.unit_like = unit_like # a string describing the unit

class TotoConverter(units.ConversionInterface):

    @staticmethod
    def convert(value, unit, axis):
        if isinstance(value, Toto):
            return value.value_like
        else:
            return [toto.value_like for toto in value]

    @staticmethod
    def axisinfo(unit, axis):
        return units.AxisInfo(label=str(unit))

    @staticmethod
    def default_units(x, axis):
        'Return the default unit for x or None'
        if isinstance(x, Toto):
            return getattr(x, 'unit_like', None)
        else:
            return getattr(x[0], 'unit_like', None)

Then register and use it,
units.registry[Toto] = TotoConverter()

arr_x = [Toto(i, "meter") for i in range(5)]
arr_y = [Toto(i, "second") for i in range(5)]

plt.plot(arr_x, arr_y)            #use lists of Totos
plt.axhline(Toto(2, "second"))    # use Toto scalars
plt.xlim(Toto(-1, "meter"), None) # use Toto scalars

plt.show()


text:
Q: How to determine if object is in array? I have a javascript array that looks like this:
myFields = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-location","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
]

I'm able to loop through the array and deal with specific bits like this:
len = fields.length;

//first check to make sure required fields are filled in
for(i=0; i<len; i++) {
     a = fields[i];
     if(a[0] != "fb-method") {
        // do stuff
    }
}

I need to be able to (outside the loop) do something if a specific element isn't part of the array, specifically one that looks like this:
["fb-location","drop",false,""]

I've tried using jQuery's .inArray function, but it returns true even when it should return false. See fiddle here.
What's the best way to go about this? jQuery or standard js is fine.

A: $.inArray does not return a bool, it returns the index (if no match exists, it returns -1).  You would want this statement (based on your jsfiddle):
if(jQuery.inArray("fb-location", tmp) > -1) {
    alert("it exists");
}
else {
    alert("it doesn't exist");
}

DEMO:
http://jsfiddle.net/azWLC/2/
UPDATE:
As mentioned in the comments, this is only a half solution since the array is multidimensional.  I recommend first using $.map():
var tmp = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
];
var values = $.map(tmp, function(n, i){
    return n[0];
});

if(jQuery.inArray("fb-location", values) > -1) {
    alert("it exists");
}
else {
    alert("it doesn't exist");
}

DEMO:
http://jsfiddle.net/azWLC/4/

A: jquery.inArray returns the index of the element. If it is not found it returns -1.. And any number except 0 is true and hence it says 'it exists'

A: Besides $.inArray you could use Array.filter on tmp this way:
if(  tmp.filter(function(a) {return -~a.indexOf('fb-location');}).length ) {
  // exists
}

JsFiddle
See also: Array.filter, Array.indexOf
Using JQuery, you'd use the JQuery grep method
if(  $.grep(tmp,function(a) {return -~a.indexOf('fb-location');}).length ) {
  // exists
}


text:
Q: How to cache or memoize data in actix-web route? I have an API I'm implementing where I have an expensive function that needs to be called. I'd like to either memoize this function or use a key value cache to look up previous results. I'd also consider a Mutex or similar structure, but I would like to avoid something external like Redis or Memcached. From what I've read, a Mutex has bad performance for caching though. How can I use a key value store like a HashMap or memoize a function inside an actix_web async route? Right now, I am trying a simple HashMap but I get this error: can't borrow data in an Arc as mutable.
async fn index(
    kv: web::Data<HashMap<&str, i64>>,
) -> Result<HttpResponse> {
    dbg!(kv);
    kv.insert("four", 4);
    Ok(HttpResponse::Ok().json(kv)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let tuples: Vec<(&str, i64)> = vec![("one", 1), ("two", 2), ("three", 3)];
    let mut m = tuples.into_iter().collect::<HashMap<&str, i64>>();
    let mut kv = web::Data::new(m);
    // move is necessary to give closure below ownership of counter1
    HttpServer::new(move || {
            App::new()
                .app_data(kv.clone())
                .route("/", web::get().to(index))
        })
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

A: Seems like you can use the cached crate.
Move the logic to another function. Something like the following code works:
use actix_web::{web, App, HttpServer, HttpResponse};
use cached::proc_macro::cached;

async fn index() -> HttpResponse {
    dbg!("in index");
    let number = get_number(2);
    HttpResponse::Ok().body(number.to_string())
}

#[cached]
fn get_number(n: i32) -> i32 {
    dbg!("in get_number");
    n * 2
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(move || {
            App::new()
                .route("/", web::get().to(index))
        })
        .bind("127.0.0.1:8080")?
        .run()
        .await
}