text:
Q: NEOS CMS Installation crashed (with empty package creation) I can't install Neos CMS especially when I try to init it with new empty package.
What I did:
This is manual method:
composer create-project neos/neos-base-distribution neos-example

./flow setup:database

./flow doctrine:migrate

./flow setup:imagehandler

./flow user:create --roles Administrator username password firstname lastname

./flow kickstart:site Vendor.Site

And at this point I get this error:
Script Neos\Flow\Composer\InstallerScripts::postUpdateAndInstall handling the post-update-cmd event terminated with an exception

In PackageManager.php line 589:

  The package with the name "neos/kickstarter" was found more than once, please make sure it exists only once. Paths "Framework/Neos.Kickstarter/" and "Libraries/neos/kickstarter/".

require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--no-audit] [--audit-format AUDIT-FORMAT] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] [<packages>...]

The installation was not successful.
Composer returned the error code: 1493030262

  Type: Neos\Flow\Package\Exception
  Code: 1572187932
  File: Packages/Framework/Neos.Flow/Classes/Package/PackageManager.php
  Line: 385

Open Data/Logs/Exceptions/20221120073428fa79d0.txt for a full stack trace.

Log content:
Exception #1572187932 in line 67 of /var/www/neos.test/Data/Temporary/Development/Cache/Code/Flow_Object_Classes/Neos_SiteKickstarter_Generator_AfxTemplateGenerator.php:
The installation was not successful. Composer returned the error code: 1493030262

12 Neos\Flow\Package\PackageManager::createPackage()
11 Neos\SiteKickstarter\Generator\AfxTemplateGenerator_Original::generateSitePackage()
10 Neos\SiteKickstarter\Command\KickstartCommandController_Original::siteCommand()
9 Neos\Flow\Cli\CommandController_Original::callCommandMethod()
8 Neos\Flow\Cli\CommandController_Original::processRequest()
7 Neos\Flow\Cli\Dispatcher_Original::dispatch()
6 Neos\Flow\Cli\CommandRequestHandler::Neos\Flow\Cli\{closure}()
5 Closure::__invoke()
4 Neos\Flow\Security\Context_Original::withoutAuthorizationChecks()
3 Neos\Flow\Cli\CommandRequestHandler::handleRequest()
2 Neos\Flow\Core\Bootstrap::run()
1 require("/var/www/neos.test/Packages/Framework/Neos.Flow/Scripts/flow.php")

And here is installation method with browser '/setup':
All is going well until step 4 "Create new site"
I fill the fields like on screenshot and then get error:
The installation was not successful. Composer returned the error code: 1

Error log:
Exception #1572187932 in line 67 of /var/www/neos.test/Data/Temporary/Development/Cache/Code/Flow_Object_Classes/Neos_SiteKickstarter_Generator_AfxTemplateGenerator.php:
 The installation was not successful. Composer returned the error code: 1

50 Neos\Flow\Package\PackageManager::createPackage()
49 Neos\SiteKickstarter\Generator\AfxTemplateGenerator_Original::generateSitePackage()
48 Neos\Neos\Setup\Step\SiteImportStep_Original::importSite()
47 Neos\Neos\Setup\Step\SiteImportStep_Original::Neos\Neos\Setup\Step\{closure}()
46 Neos\Form\Finishers\ClosureFinisher_Original::executeInternal()
45 Neos\Form\Core\Model\AbstractFinisher::execute()
44 Neos\Form\Core\Runtime\FormRuntime_Original::invokeFinishers()
43 Neos\Form\Core\Runtime\FormRuntime_Original::render()
42 Neos\Setup\Controller\SetupController_Original::indexAction()
41 Neos\Setup\Controller\SetupController::indexAction()
40 Neos\Setup\Controller\SetupController::Flow_Aop_Proxy_invokeJoinPoint()
39 Neos\Flow\Aop\Advice\AdviceChain::proceed()
38 Neos\Flow\Security\Aspect\PolicyEnforcementAspect_Original::enforcePolicy()
37 Neos\Flow\Aop\Advice\AroundAdvice::invoke()
36 Neos\Flow\Aop\Advice\AdviceChain::proceed()
35 Neos\Setup\Controller\SetupController::indexAction()
34 Neos\Flow\Mvc\Controller\ActionController_Original::callActionMethod()
33 Neos\Flow\Mvc\Controller\ActionController_Original::processRequest()
32 Neos\Flow\Mvc\Dispatcher_Original::initiateDispatchLoop()
31 Neos\Flow\Mvc\Dispatcher_Original::dispatch()
30 Neos\Flow\Mvc\DispatchMiddleware_Original::process()
29 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
28 Neos\Flow\Http\Middleware\SecurityEntryPointMiddleware_Original::process()
27 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
26 Neos\Flow\Http\Middleware\RequestBodyParsingMiddleware_Original::process()
25 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
24 Neos\Flow\Mvc\FlashMessage\FlashMessageMiddleware_Original::process()
23 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
22 Neos\Flow\Http\Middleware\PoweredByMiddleware_Original::process()
21 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
20 Neos\RedirectHandler\RedirectMiddleware_Original::process()
19 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
18 Neos\Flow\Mvc\Routing\RoutingMiddleware_Original::process()
17 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
16 Neos\Setup\Core\ConfigureRoutingMiddleware_Original::process()
15 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
14 Neos\Neos\Routing\RequestUriHostMiddleware_Original::process()
13 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
12 Neos\FluidAdaptor\Core\Widget\AjaxWidgetMiddleware_Original::process()
11 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
10 Neos\Flow\Http\Middleware\SessionMiddleware_Original::process()
9 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
8 Neos\Flow\Http\Middleware\MethodOverrideMiddleware_Original::process()
7 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
6 Neos\Flow\Http\Middleware\TrustedProxiesMiddleware_Original::process()
5 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
4 Neos\Flow\Http\Middleware\StandardsComplianceMiddleware_Original::process()
3 Neos\Flow\Http\Middleware\MiddlewaresChain_Original::handle()
2 Neos\Setup\Core\RequestHandler::handleRequest()
1 Neos\Flow\Core\Bootstrap::run()

HTTP REQUEST:
target: /setup/index?step=3
Host: neos.test
Connection: keep-alive
Content-Length: 1211
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
Origin: http://neos.test
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarydhLD8IdBGG1o29ES
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://neos.test/setup/index?step=3
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,de;q=0.8
Cookie: Neos_Session=6He2koxfjwXOIQZmsnx01j4ShyohGGmv

PHP PROCESS:
Inode: 20074432
PID: 8315
UID: 1000
GID: 1000
User: noname

If I leave 'package name' and 'site name' fields empty then it works.
My environment:

*

*Ubuntu 20.04.4 LTS

*apache2

*5.7.37 - MySQL Community Server (GPL)

*apache-php 8.1 and php-cli 8.1

*composer 2.4.4


text:
Q: dotnet run --ulrs on a systemctl service I need to run dotnet run --urls https://0.0.0.0:443 to run a dotnet core API, but I want to turn that into a service, right now I have this:
sudo nano /etc/systemd/system/mdvAPI.service

[Unit]
Description=Dotnet API MDV

[Service]
WorkingDirectory=/home/g67Admin/projeto_integrador_grupo67/mdv/
ExecStart=dotnet run --urls https://0.0.0.0:443

[Install]
WantedBy=multi-user.target

and when I try to start it I get this:
sudo systemctl start mdvAPI.service

Failed to start mdvAPI.service: Unit mdvAPI.service is not loaded properly: Exec format error.
See system logs and 'systemctl status mdvAPI.service' for details.

What am I doing wrong here?

A: I developed the following system service script:
[Unit]
Description=Whatever you want

[Service]
WorkingDirectory=/path/to/my/project
ExecStart=/usr/bin/dotnet run --urls https://0.0.0.0:443
User=root
Group=root

[Install]
WantedBy=multi-user.target

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable require my password under CMD in unity? We want to make a image with no entering passward when awaking from suspend in ubuntu unity. How can I do it? Thanks in advance.

A: If the following is what you want
gsettings set org.gnome.desktop.screensaver ubuntu-lock-on-suspend 'false'

Then simply follow the guide about changing gconf values in custom live iso:
https://help.ubuntu.com/community/LiveCDCustomization#Change_gconf_values_.28fonts.2C_panels_etc..29
Once chrooted, run this
gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults --type string --set yourkey "yourvalue"


text:
Q: Transforming XML into JSON loadable structure for BigQuery I'm learning python on the job and need help improving my solution.
I need to load XML data into BigQuery.
I have it working but not sure if I have done it in a sensible way.
I call an API that returns an XML structure.
I use ElementTree to parse the XML and use tree.iter() to return the tags and text from the XML.
Printing my tags and text with:
for node in tree.iter():
    print(f'{node.tag}, {node.text}')

Returns:
Tag              Text
Responses        None
Response         None
ResponseId       393
ResponseText     Please respond "Has this loaded"
ResponseType     single
ResponseStatus   0

The Responses tag appears only once per API call but Response through to ResponseStatus are   repeating groups, ResponseId is the key for each group. Each call would return less than a 100 repeating groups.
There is a key returned in the header, Response_key, that is the parent of all ResponseIds.
My aim is to take this data, convert to JSON and stream to BigQuery.
The table structure I need is:
ResponseKey, ResponseID, Response, ResponseText, ResponseType , ResponseStatus
The  approach  I use is

*

*Use tree.iter()  to loop and create a list
node_list = []
for node in tree.iter():
node_list.append(node.tag)
node_list.append(node.text)

*Use itertools to group the list (this I found a difficult step)

r = 'Response '
response _split = [list(y) for x, y in itertools.groupby(node_list, lambda z:
    z == r) if not x]

which returns:
[['Responses', 'None'], ['None', 'ResponseId', '393', 'ResponseText', Please respond "Has this loaded"
"', 'ResponseType', 'single', 'ResponseStatus', '0'], ['None', 'ResponseId', '394', 'ResponseText', Please confirm "Connection made" "', 'ResponseType', 'single', 'ResponseStatus', '0']]

*Load into a Pandas data frame, remove any double quotes in case that causes BigQuery any issues.

*Add ResponseKey as a column to the dataframe.

*Convert data frame to JSON and pass to load_table_from_json.

It works but not sure if it is sensible.
Any suggested improvements would be appreciated.
Here is a sample of the XML:
{"GetResponses":"<Responses><Response><ResponseId>393938<\/ResponseId><ResponseText>Please respond to the following statement:\"The assigned task was easy to complete\"<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393939<\/ResponseId><ResponseText>Did you save your  datafor later? Why\/why not?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>1<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393940<\/ResponseId><ResponseText>Did you notice how much it cost to find the item? How much was it?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393941<\/ResponseId><ResponseText>Did you select 'signature on form'? Why\/why not?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>1<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393942<\/ResponseId><ResponseText>Was it easy to find thethe new page? Why\/why not?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>1<\/ResponseStatus><ExtendedType>4<\/ExtendedType><\/Response><Response><ResponseId>393943<\/ResponseId><ResponseText>Please enter your email. So that we can track your responses, we need you to provide this for each task.<\/ResponseText><ResponseShortCode>email<\/ResponseShortCode><ResponseType>text<\/ResponseType><ResponseStatus>1<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393944<\/ResponseId><ResponseText>Why didn't you save your  datafor later?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393945<\/ResponseId><ResponseText>Why did you save your  datafor later?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>4<\/ExtendedType><\/Response><Response><ResponseId>393946<\/ResponseId><ResponseText>Did you save your  datafor later?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393947<\/ResponseId><ResponseText>Why didn't you select 'signature on form'?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393948<\/ResponseId><ResponseText>Why did you select 'signature on form'?<\/ResponseText><ResponseType>text<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>4444449<\/ResponseId><ResponseText>Did you select 'signature on form'?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393950<\/ResponseId><ResponseText>Why wasn't it easy to find thethe new page?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>4<\/ExtendedType><\/Response><Response><ResponseId>393951<\/ResponseId><ResponseText>Was it easy to find thethe new page?<\/ResponseText><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>0<\/ExtendedType><\/Response><Response><ResponseId>393952<\/ResponseId><ResponseText>Please enter your email addressSo that we can track your responses, we need you to provide this for each task<\/ResponseText><ResponseShortCode>email<\/ResponseShortCode><ResponseType>single<\/ResponseType><ResponseStatus>0<\/ResponseStatus><ExtendedType>4<\/ExtendedType><\/Response><\/Responses>"}

A sample JSON without all the processing steps:
node_list = []
for node in tree.iter():
    node_list.append(node.tag)
    node_list.append(node.text)

json_format = json.dumps(node_list )
print(json_format)

["Responses", null, "Response", null, "ResponseId", "393938", "ResponseText", Please respond to the following statement:\"The assigned task was easy to complete"", "ResponseType", "single", "ResponseStatus", "0", "ExtendedType", "0"]

A: I'm not sure what is the required outpot,
this is one way of doing it
import xml.etree.ElementTree as ET
import json

p = r"d:\tmp.xml"
tree = ET.parse(p)

root = tree.getroot()

json_dict = {}

json_dict[root.tag] = root.text

json_dict['response_list'] = []

for node in root:
    tmp_dict = {}
    for response_info in node:
        tmp_dict[response_info.tag] = response_info.text
    json_dict['response_list'].append(tmp_dict)

with open(r'd:\out.json', 'w') as of:
    json.dump(json_dict, of)


text:
Q: Starting Tomcat6 - "/usr/share/tomcat6/bin/startup.sh" **OR** "/etc/init.d/tomcat6 start"? What is the difference between starting TOMCAT6 on an Ubuntu system using the following methods:

/usr/share/tomcat6/bin/startup.sh

sudo /etc/init.d/tomcat6 start

A: The init.d script is the startup script for the system service, that internally should call to /usr/share/tomcat6/bin/startup.sh, that should be the tomcat start script.
If you want to start tomcat when the machine is booted, you should use the update-rc.d command to add it to the list of services that will be started at boot time.

A: You can use either one.  I use startup.sh when I need to manage tomcat myself.  I  use the /etc/init.d script when I want to run tomcat as a daemon/service.


text:
Q: How to display a message to the user about maintenance and nightly jobs in PHP + MS SQL application we have nightly jobs updating the database(SQL server) and tables.And we have a PHP application which displays the data(And does CRUD). These jobs take few hours to run, When these jobs are running, We would like to inform user that "Job/data update is in progress, Please come back later".
  Also we do have a table which has start time of the first job and end time of the last job.
Question
What(and how) is the best way to check the table for the job start and then display the "Maintenance" message?

A: *

*Add a table to your database, Add a row in that table in the start of the each job (probably the very first step in the job to insert this row).

*At the end of the job delete that row for that job (the very last step in the job to delete that row).

*In application code check for any rows in that table, if the row exists show your message ("Come back later bla bla")

*If there is no row in that table application works as usual.
Table schema should be something like:
CREATE TABLE ProcessMonitor
(
  JobName NVARCHAR(1000)
, StatusID  INT
)
GO

Note
You can add additional steps in the job to change the statusID of the job, and only block users when they absolutely need to be, else allow them in with few warnings etc.

A: Additionally, to check which jobs are currently running in the server..
SELECT
    ja.job_id,
    j.name AS job_name,
    ja.start_execution_date,
    ISNULL(last_executed_step_id,0)+1 AS current_executed_step_id,
    Js.step_name
FROM msdb.dbo.sysjobactivity ja
LEFT JOIN msdb.dbo.sysjobhistory jh
    ON ja.job_history_id = jh.instance_id
JOIN msdb.dbo.sysjobs j
ON ja.job_id = j.job_id
JOIN msdb.dbo.sysjobsteps js
    ON ja.job_id = js.job_id
    AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id
WHERE ja.session_id = (SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC)
AND start_execution_date is not null
AND stop_execution_date is null;

Courtesy: https://dba.stackexchange.com/questions/58859/script-to-see-running-jobs-in-sql-server-with-job-start-time


text:
Q: SPM_select command results in indices not compatible on the left and right sides for SPM batch script no matter what I do I am trying to load in .nii files for some smoothed/preprocessed fMRI images to run first level analyses using a batch script in SPM. But when I use spm_select to do so the stats.scans() line sends me an error. This is despite the fact that the structure of the cell array from my spm_select code I wrote is identical to the structure that results when I run the import code from the batch script I exported from the SPM GUI (which ran just fine). Both are 218x1 cell arrays where each cell is a string with the exact same number of characters.
Error code
This is the spm_select code I wrote:
run1{1,1}=spm_select('ExtFPList', 'D:\Smooth\', ['swr',subject,'_ses-7_task-Gram_acq_run-01_bold.nii.*'], 1);

for q=2:218

    run1{q,1} = spm_select('ExtFPList', 'D:\Smooth\',['swr',subject,'_ses-7_task-Gram_acq_run-01_bold.nii.*'], q);

end

matlabbatch{1}.spm.stats.fmri_spec.sess(1).scans(1) = run1;

When I replace the final line with "=cellstr(run1)" I get the same error message...I'm at a loss- any help is appreciated!


text:
Q: Roots of circulant binary equation Let $N\geq3$. Let $w_{N k} = \exp (i 2 \pi k/N)$, $k = 0 \cdots N-1$, be the powers of the N-th root of 1, i.e. the solutions of $w_{N k}^N = 1$. Consider an array of coefficients $(a_j)$,  $j = 0 \cdots N-1$, where the values are $a_j = \pm 1$, i.e. there is only a binary choice.
Define the function
$$f((a_j),w_{N k}) =  \sum_{j=0}^{N-1} a_j \;w_{N k}^j
$$
For which choices of $(a_j)$ and for which $k$ exists a solution $f((a_j),w_{N k}) = 0$ ?
Note, for the motivation of this question: The function $f$ computes the eigenvalues of a circulant matrix with row vector $(a_j)$ from its associated polynomial. If there are $N_k$ zeroes of $f$ with different $k$, then the rank of the circulant matrix is $N - N_k$. In other words, if you have another method which directly gives the rank of a circulant matrix with binary ($\pm1$) row vector $(a_j)$, I'm happy as well.
I can see two obvious symmetries:
a) sign inversion: if there exists a solution for some $(a_j)$ and some $k$ then there is also a solution for $(-a_j)$ and $k$.
b) cyclic shift: if there exists a solution for some $(a_j)$ and some $k$ then, by multiplying with $w_{N k}^q$,  there is also a solution for that $k$ and for $(a_{((j+q)\mod N)})$  with $q=1\cdots N-1$, i.e. for all cyclic shifts of $(a_j)$.
Also, clearly $k=0$ will appear only if $N$ is even.
I performed computer simulations which suggest:
a) If $N$ is prime, then the only solution to $f((a_j),w_{N k}) = 0$ is to set all $a_j=1$. This holds for $k = 1\cdots N-1$, and also, by the first symmetry above,   setting all $a_j=-1$ holds.
Can one prove  that this is the only solution for $N$ prime?
b) If $N$ is not prime, things get considerably more involved.  Let us index the array $(a_j)$ by a unique decimal number $A = \sum_{j=0}^{N-1} 2^{j-1} (1+a_j)$. So the array with all $a_j=-1$ has $A=0$, and the array with all $a_j=1$ has $A=2^N -1$.   If the $a_j$ were $(0,1)$, then $(a_j)$ were the binary representation of $A$. Switching all signs of the $a_j$ results in $B = \sum_{j=0}^{N-1} 2^{j-1} (1-a_j) = - \sum_{j=0}^{N-1} 2^{j-1} (-2 + 1+a_j) = 2^N - 1- A$, so by the first symmetry above, only $A = 0 \cdots 2^{N-1}$ needs to be considered. Further, cyclic shifts in $(a_j)$ - the second symmetry above - produce, from $A$, further solutions with the same $k$s for $(2^q A \mod (2^N-1))$.
Can you give a general result which $A$ and $k$ lead to a solution  of $f(A,w_{N k}) = 0$?
Here are some results where solutions occur:
$N=4$ (contains $k=0$):
A=0 at k = 1 2 3
A=3 at k = 0 2 3
A=5 at k = 0 1 3
A=6 at k = 0 2 3
and, for completeness,
A=9 at k = 0 2 3
A=10 at k = 0 1 3
A=12 at k = 0 2 3
A=15 at k = 1 2 3
$N=9$ (does not contain $k=0$):
A=0 at k = 1 2 3 4 5 6 7 8
A=7 at k = 3 6
A=14 at k = 3 6
A=21 at k = 3 6
A=28 at k = 3 6
A=35 at k = 3 6
A=42 at k = 3 6
A=49 at k = 3 6
A=56 at k = 3 6
A=63 at k = 3 6
A=70 at k = 3 6
A=73 at k = 1 2 4 5 7 8
A=84 at k = 3 6
A=98 at k = 3 6
A=112 at k = 3 6
A=119 at k = 3 6
A=126 at k = 3 6
A=133 at k = 3 6
A=140 at k = 3 6
A=146 at k = 1 2 4 5 7 8
A=161 at k = 3 6
A=168 at k = 3 6
A=175 at k = 3 6
A=189 at k = 3 6
A=196 at k = 3 6
A=219 at k = 1 2 4 5 7 8
A=224 at k = 3 6
A=231 at k = 3 6
A=238 at k = 3 6
A=245 at k = 3 6
A=252 at k = 3 6
and symmetric continuation until A=511.


text:
Q: dialog-box not loading a view in server after publishing the project Here i am trying to load a partial view inside a dialog-box using jquery. This is my code:
 $('#newdialog').dialog({
            autoOpen: false,
            width: 900,
            top: 76,
            resizable: false,
            title: 'Modify Add image',
            modal: true,
            open: function (event, ui) {
                //Load the CreateAlbumPartial action which will return
                // the partial view _CreateAlbumPartial
                // alert(idimg);
                $(this).load("@Url.Action("GridView1","LandingSetting")");
            },
            buttons: false,
            //            {
            //                "Close": function () {
            //                    $(this).dialog("close");
            //                }
            //            },
            position: {
                my: 'top',
                at: 'top',
                of: $('.maindiv')
            }

        });

My View Code:
@{
    ViewBag.Title = "GridView";
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Home</title>

                    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "adform" }))
                    {
                        if (Model.Count == 0)
                        {

                            Sorry No Ads Found! Please Add some ads.

                        }

                        else
                        {

                                @{
                            int crow = 1;
                            foreach (var item in Model)
                            {

                                                <input id="@item.banner" type="radio" name="one" value="@item.banner" />

                                if (crow % 2 == 0)
                                {

                                }
                                crow++;

                            }

                                }

                        <input id="Submit1" type="submit" value="submit" />
                        }
                    }

This code works fine in the localhost.But when I publish my project and run it on a server, the dialog box opens but the parial view is not loading in it.What am i doing wrong? can anyone help.Thanks
Edit: The jquery code is on my main view which has a layout page reference as well as the required jquery reference. In that page if i click a button, the dialog box should open and the above mentioned view should load in it.

A: I have a feeling this is caused by Cross Domain Request. If your action url leads to a different host (possibly even a subdomain) you will have an error in your console stating you cannot make such requests. Anyway if your console does output something let us know.
Otherwise try removing the doctype, html, head, body etc. tags from the partial view, you already have those on your page no need to create a bad nesting situation.


text:
Q: Draw vertical line inside Angular2 component using ng2-charts? I am using latest ng2-charts version 1.4.1 and chart.js 2.4.0. Can someone tell how can I make a single vertical line using ng2-charts or chart.js
Click http://jsfiddle.net/dbyze2ga/14/
I want to draw line using ng2-charts. How can I access chart.js inside Angular2 component.ts file?


text:
Q: HashSet.contains(object) returns false for instance modified after insertion According to the JavaDoc of java.util.HashSet.contains() the method does following

Returns true if this set contains the specified element. More
  formally, returns true if and only if this set contains an element e
  such that (o==null ? e==null : o.equals(e)).

However this does not seem to work for following code:
public static void main(String[] args) {
    HashSet<DemoClass> set = new HashSet<DemoClass>();
    DemoClass toInsert = new DemoClass();
    toInsert.v1 = "test1";
    toInsert.v2 = "test2";
    set.add(toInsert);
    toInsert.v1 = null;

    DemoClass toCheck = new DemoClass();
    toCheck.v1 = null;
    toCheck.v2 = "test2";

    System.out.println(set.contains(toCheck));
    System.out.println(toCheck.equals(toInsert));
}

private static class DemoClass {
    String v1;
    String v2;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((v1 == null) ? 0 : v1.hashCode());
        result = prime * result + ((v2 == null) ? 0 : v2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DemoClass other = (DemoClass) obj;
        if (v1 == null) {
            if (other.v1 != null)
                return false;
        } else if (!v1.equals(other.v1))
            return false;
        if (v2 == null) {
            if (other.v2 != null)
                return false;
        } else if (!v2.equals(other.v2))
            return false;
        return true;
    }

}

prints out:

false
true

So although the equals method returns true, HashSet.contains() returns false.
I guess this is because I modified the toInsert instance AFTER it was added to the collection.
However this is in no way documented (or at least I wasn't able to find such). Also the documentation referenced above the equals method should be used but it does not seem so.

A: When an object is stored in a HashSet its put in a data structure that's easily (read: efficiently) searchable by the object's hashCode(). Modifying an object may change its hashCode() (depending on how you implemented it), but does not update its location in the HashSet, as the object has no way of knowing its contained in one.
There are a couple of things you can do here:

*

*Modify the implementation of hashCode() so it isn't affected by the field you're changing. Assuming this field is important to the object's state, and participates in the equals(Object) method, this is somewhat of a code smell, and should probably be avoided.

*Before modifying the object, remove it from the set, and then re-add it once you're done modifying it:

Set<DemoClass> mySet = ...;
DemoClass demo = ...;
boolean wasInSet = mySet.remove(demo);
demo.setV1("new v1");
demo.setV2("new v2");
if (wasInSet) {
    set.add(demo);
}

A: HashSet and HashMap use both hashCode and equals methods to locate an object in their inner structure. hashCode is used to find a correct bucket and then equals is consulted to distinguish between different objects with the same hashCode, as the latter is not guaranteed to be unique. In almost any cases this is an extremely bad idea to modify object which serves as a key in a HashMap or is put into a HashSet. If those modifications change either hashCode or semantics of equals method, your object will not be found.

A: This is by-design behavior.
HashSet uses hashes to identify objects it holds.
So, if you change an object after it was placed into collection, it may be unable to find it.
You should either hold immutable objects only, or make mutable only that part of an object, which is not affect the hash.
I think better is to use HashMap, which clearly separates mutable and immutable parts.

A: It is quite clear, you are changing toInsert.v1 after adding to the set, and due to DemoClass obtain hashCode from v1 and v2 attributes, it won't find changed hashCode for elementes.


text:
Q: A nice function to escape $_POST // what do you think about it I'm using $_POST and aware about mysql exploit, I decided to use this function on the top of my page, therefore all POST will be safe:
Can you tell me if I miss something and this function will really do the job as I think it will?
function clean_post(){
    if ( $_POST){
            foreach ($_POST as $k => $v) {
            $_POST[$k]=stripslashes($v);
            $_POST[$k]=mysql_real_escape_string($v);
            $_POST[$k]=preg_replace('/<.*>/', "", "$v");
        }
  }

  if ( $_COOKIE){
            foreach ($_COOKIE as $k => $v) {
            $_COOKIE[$k]=stripslashes($v);
            $_COOKIE[$k]=mysql_real_escape_string($v);
            $_COOKIE[$k]=preg_replace('/<.*>/', "", "$v");
        }
  }
}

It will also remove all html tag, a safest option to output the result might be to use:
<pre>
  $foo
</pre>

Cheers!
Cheers!

A: There are some problems with it.
First you apply functions on types that doesn't need them, your integers for example needs only a (int) cast to be secure.
Second you do not secure lenght, when you're requesting a '12 chars string' it would be a good idea to ensure you've got only 12 chars, and not 2048. Limiting size is really something your attackers will not like.
Third in your foreach loop you have a $v variable, you assign 3 times a function on $v to $_POST[$k]. So the 1st two assignements are lost when the 3rd occurs...
Then all the things previous people said are right :-)
The rule is apply the filter at the right moment for the right output. HTML output need an html filter (htmlspecialchars), but the database doesn't need it, it need a database escaping. Let's say you want to extract data from your database to build a CSV or a PDF, HTML escaping will make you life harder. You'll need CSV escaping at this time, or PDF escaping.
Finally it is effectively hard to remember if you are manipulating a data which is already well escaped for your output. And I recommend you an excellent read on Joel on Software about Apps Hungarian. The text is quite long, but very good, and the web escaping sequence is used as an example on why Apps Hungarian is good (even if System Hungarain is bad).

A: I think it's a bad idea to do this. It will corrupt the data your users enter even before it hits the database. This approach will also encourage you to use lazy coding where you consistently don't escape data because you believe that all your data is already "clean". This will come back to bite you one day when you do need to output some unsafe characters and you either forget to escape them or you aren't really sure which function you need to call so you just try something and hope that it works.
To do it properly you should ensure that magic quotes is disabled and only escape data when necessary, using precisely the correct escaping method - no more, no less.

A: Hi this is my first answer for any question asked on web so please review it.
Put this code in top of your script and no need to assign these posted values to any variables for doing the same job of making the input data safe for database. Just use $_POST values as it is in your query statements.
foreach ($_POST as $k => $v) {
      if(!is_array($_POST[$k]) ) {       //checks for a checkbox array & so if present do not escape it to protect data from being corrupted.
          if (ini_get('magic_quotes_gpc')) {
                $v = stripslashes($v);
            }

            $v = preg_replace('/<.*>/', "", "$v");           //replaces html chars
            $_POST[$k]= mysql_real_escape_string(trim($v));

        }
 }

A: When working with stripslashes I'd use get_magic_quotes_gpc():
if (get_magic_quotes_gpc()) {
    $_POST[$k]=stripslashes($v);
}

Otherwise you'll over-strip.

A: Don't forget $_GET[]
if ($_POST OR $_GET)

Also you can add strip_tags()

A: I don't know whether your function is correct or not, but the principle is certainly incorrect.  You want to escape only where you need to, i.e. just before you pass things into MySQL (in fact you don't even want to do that, ideally; use bound parameters).
There are plenty of situations where you might want the raw data as passed in over the HTTP request.  With your approach, there's no ability to do so.

A: In general, I don't think it's that good of an idea.

*

*Not all post data necessarily goes into MySQL, so there is no need to escape it if it doesn't. That said, using something like PDO and prepared statements is a better way, mysql_* functions are deprecated.

*The regular expression could destroy a lot of potentially valid text. You should worry about things like HTML when outputting, not inputting. Furthermore, use a function like strip_tags or htmlspecilchars to handle this.

*stripslashes is only necessary if magic quotes are enabled (which they shouldn't be, but always is possible)


text:
Q: Why do I still have "No Debuggable Application" in my Android Studio project? I put android:debuggable="true" in the AndroidManifest.xml:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:debuggable="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I also put debuggable true in the build.gradle script:
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug{
        debuggable true;
    }
}


text:
Q: Terminating WebSocket connections on AWS EBS behind ALB Does anyone have an approach to gracefully terminate WebSocket connections to Elastic Beanstalk behind an Application Load Balancer?
During scaling in, EC2 instances are terminated and immediately drop their connections. I'm wondering if there's a good way to handle the termination, or if I can only terminate an instance that no longer has any active connections.
Each WebSocket client is stateful, through the magic of sticky sessions/cookies. Reconnecting a client to a different issue is fine, but I want to avoid doing this when possible.

A:
EC2 instances are terminated and immediately drop their connections.
  I'm wondering if there's a good way to handle the termination,

You can make the experience more graceful for your users:
Simple Approach:
There is a feature called 'Connection Draining', when an instance needs to shut down due to a scale-in event, it will wait for the predefined time for existing coonections to complete, it will not send new requests to that instance and after the specified duration it will forcefully terminate the remaining connections if any. So the time can be set longer than the Sticky session cookie time duration you specified, and also the longer than the TTL for WebSocket you have setup from your application and ensure that app retries to connect after this duration.
As you are using Elastic Beanstalk. The feature is under ELB -> Application -> Environment -> Configuration -> LoadBalancers

It should satisfy your current need.
More Dynamic (Complex) approach:

"graceful way to terminate those open connections."

"graceful" termination can happen when both the client and server are notified of the impending termination of the connection due to scale-in event so that they can then perform house-cleaning tasks before the connection is terminated ie instance being shut down.
It depends on your use-case if you want to venture into that route. But, if you need that, you could do the following

*

*When the WebSocket connection is established. The client application is provided with the underlying EC2 instance id. (the counterpart of the websocket connection)

*Create a cloud watch alarm for the cloud Watch event "Pending:Wait", the event details are here

*Create an SNS topic for the cloud watch alarm notifications. The notification should have the ec2 instance id.

*Both the client application and server applications subscribe to this topic. And when a notification arrives, they can check the ec2 instance id to verify if it is the host of the WebSocket connection. If yes, they prepare for the connection to be terminated on scale-in event.
As you can see, there are more moving part. But, if it improves the user experience and use case justifies it. Then it would be a solution.


text:
Q: for-loop calling strings to turn into booleans This is prob a really dumb question but I'm stuck on this one...
So I have a bunch of booleans called monster1, monster2, ...
And I want to use a for-loop to toggle the respective booleans for the col.name s . The col.name returns monster1, monster2, ... and I don't know how to turn those strings into booleans
private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        if (col.name == "monster" + i)
        {
            "monster" + i = false;
        }
    }
}

A: Why not use an array of booleans?
private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        if (col.name == "monster" + i)
        {
            monster[i] = false;
        }
    }
}

A: In case you need to refer to the monster by its ID, a simple Dictionary is recommended.
Also, remember that dictionaries may have worse performance than arrays. Unless you are dealing with >10.000 monsters, this should not be an issue.
Dictionary<string, bool> Monsters = new Dictionary<string, bool>();

private void OnTriggerExit2D(Collider2D col)
{
    for (var i = 0; i < 9; i++)
    {
        string monsterID = "monster" + i;
        Monsters[monsterID] = col.name != monsterID;
    }
}

Then you may later use it like this:
if(Monsters["monster3"])
    // Do something...


text:
Q: How to characterize the level sets of an homogeneous function? Let us consider a $C^1$ function $f : \mathbb R_+^* \times \mathbb R_+^* \to \mathbb R_+^*$.
If $f$ is homogeneous of degree $d$, then $\forall (x,y) \in \mathbb R_+^* \times \mathbb R_+^*, \frac{\partial_x f(\lambda x, \lambda y)}{\partial_y f(\lambda x, \lambda y)}$ is independent of $\lambda \in \mathbb R_+^*$.
In other words, any half-line starting at the origin with positive slope crosses the level sets at points where the level sets have the same slope
If I assume that level sets are convex and decrease from $(0,+\infty)$ to $(+\infty, 0)$, is the reciprocal true? i.e. do the level sets correspond to those of an homogeneous $f$?
Remark: of course, replacing $f$ by $\log(f)$ keeps the same level sets and one of the two is not homogeneous, but I am interested in the existence of an homogeneous function with such level sets.


text:
Q: Were there any verbal spells in Transfiguration? If yes, were there only few? I have never heard of any verbal spells during Transfiguration (in the book), this class was the least mentioned ever. So were there any verbal spells in Transfiguration? If there were, were there only few of them? Because the only difference will be changing living and non-living things separately. Only complicated wand movements (and thoughts) would have changed the way an object would convert. Am I correct?

A: Transfiguration spells can be both verbal and non-verbal.
An example of a verbal spell is Evanesco, studied by 5th-year Hogwarts students in Transfiguration class (source: HP and the Order of the Phoenix, chapters 13 and 15). From the HP Lexicon:

The basic form of Vanishing is the Vanishing Spell. Taught in fifth year Transfiguration (OP13), this spell is usually cast using the incantation Evanesco which is Latin for "vanish." McGonagall starts students out with Vanishing invertebrates -- snails --and then works them up to mice because they're more difficult (OP15). The Evanesco spell apparently doesn't need an object word (you don't have to say "Evaesco Potion," for example). The intent of the caster provides the needed focus on a particular object.

The last two sentences make the Evanesco spell perhaps partially non-verbal: some of the magic comes from the wizard's intent rather than from the words spoken. However, the necessity of saying "Evanesco" does make it technically a verbal spell.
Another example, depending on your definition of 'spell', might be the gargoyle outside the Headmaster's office. It transforms from stone to life when a password is spoken verbally - however, since the password can hardly be considered a spell (Lemon Sherbet, anyone?), this probably doesn't count and the real magic was done previously and possibly non-verbally.
Examples of non-verbal spells appear to be more widespread. One good example is the magic used by Animagi to transform never seems to be accompanied by any incantation. Again from HP Lexicon:

The Animagus Transfiguration can be performed wandlessly, since Sirius was able to accomplish it in Azkaban when his own wand was long gone (PA19). It is possible for another witch or wizard who is sufficiently knowledgeable to force an Animagus to Transfigure from animal shape back into human shape; the incantation (if any) for the spell is not currently known, but it is accompanied by a flash of light around the target Animagus. If used on a true animal, the "resume natural shape" spell would have no effect (PA19).

And when we've seen McGonagall, Sirius, etc. transform, they used no verbal spells.
There's also the spell Dumbledore uses to transform Slughorn from an armchair in HP and the Half-Blood Prince, and the spell 'Moody' uses to transform Malfoy into a ferret in HP and the Goblet of Fire. In both cases, no verbal spell was cast.
Fuller lists of spells used in Transfiguration, both verbal and non-verbal, can be found here (HP Lexicon) and here (HP Wikia).


text:
Q: How does Google Desktop Search manage to stay light and fast? I always wondered what different methods Google Desktop Search is using so that it uses least CPU and memory while indexing a computer containing more 100,000 files on an average.
In just few hours it has indexed the whole system and I did not see it eating up my CPU, memory etc.
If any of you have done some research, please do share.

A: The trick is simple: It starts to work then very soon stops and just sits there in in memory, doing nothing. Of course it's then totally useless but at least, it keeps light and fast. Sorry, couldn't resist :-) I Switched to Windows Search 4.0 and I'm much happier about it.

A: It doesn't...
I installed it on one computer, and quickly removed it because it was intrusive (although this can be probably configured) and hungry (particularly on a low end PC).
It is installed on a laptop near me right now, and if I compare it to a couple of small utilities I run permanently (SlickRun, CLCL, my AutoHotkey script...) it uses more than 10 times their CPU and 5 to 20 times their memory. Times two, since, for some reason, I have one instance running another, plus the ToolbarNotifier (less hungry).
Even Trend Micro anti-virus uses less memory and CPU.
Perhaps I will try it again when I will get a more modern PC with lot of memory, but right now I am happy enough with some grep utilities, even if they are slower.

A: Take a look at disk usage.  If you build many keys/indexes you will use lots of disk space and the searches will be fast.
For example;
30 gig drive 75% used. 3.6 gig used for 2 instances of Google Desktop.  (roaming profiles suck)

A: Once it has done the initial index, and written it to disc, it doesn't need to anything.
Searching using the index will require very little resources, the only thing that will is indexing new or modified files..


text:
Q: Woocommerce Custom Order Action and Order Update WebHook problem i'm trying to solve this issue for weeks, have tried everything.
I have a Custom Order Action in my order admin panel like this:
function manage_actions( $actions ) {
   $actions['wc_my_custom_action'] = 'My Custom Action';
   return $actions;
}
add_action( 'woocommerce_order_actions', 'manage_actions');

function custom_action_function( $order ) {
    update_post_meta( $order->id, 'Custom_Meta', 'Value' );
}
add_action( 'woocommerce_order_action_my_custom_action', 'custom_action_function' );

This works fine, if i open an order and then click on the 'My Custom Action' in the actions menu the 'Custom_Meta' key value pair is added to the order.
Now i have an Order Update WebHook (using API v3) set up and unfortunately it triggers before the 'custom_action_function' function runs so i always get the payload of the order without the new meta tag. I have tried everything i can to add the meta data prior to the webhook being fired, does anyone have an idea on how to accomplish this? Thanks


text:
Q: Wi-Fi USB stick on custom linux system appears to be working, but the outside world cannot see it OK, I have a problem to which I cannot find a solution, or even understand what is going on.
I am working on a custom Linux system, built using yocto Linux, and I have installed a driver in our kernel for the RTL8192cu chipset. The install worked, and using iwconfig I have started the driver etc. The chipset is from an ASUS USB-N10 Nano USB stick. From the embedded system, it appears that the card/stick/chipset is functioning, the blue light blinks etc, but when I scan the area using my smartphone as a scanner (using both ScanFi  and Wifi analyzer) I don't see any trace of the Wi-Fi stick, nothing at all.
Here is the output from  iwconfig:
wlan1     unassociated  Nickname:"<WIFI@REALTEK>"
          Mode:Managed  Frequency=2.412 GHz  Access Point: Not-Associated
          Sensitivity:0/0
          Retry:off   RTS thr:off   Fragment thr:off
          Encryption key:off
          Power Management:off
          Link Quality=0/100  Signal level=0 dBm  Noise level=0 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

I cannot use iwconfig to set any of the signal values etc, I always get the result operation not permitted.
This is what I get back when I use ifconfig:
Link encap:Ethernet  HWaddr 18:31:BF:56:DD:7E
          inet addr:192.168.1.99  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:87 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

When I use iwlist txpower i get the following:
wlan1     unknown transmit-power information.

I am not an expert on this system by any means, nor with yocto Linux etc. It's possible that I'm missing a key program somewhere, but it does appear to me that I have brought up the card correctly, why else would it show using the above commands and why would the LED be blinking.


text:
Q: InvalidStateError when drawing SVG to canvas in Firefox (works in Chrome) My code works perfectly in Chrome, but throws errors in Firefox. The console says:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

This is my code:
glitchElement('http://naratif.jvitasek.cz/images/past-no-b.svg', 'canvas1');
glitchElement('http://naratif.jvitasek.cz/images/medialni-no-b.svg', 'canvas2');
glitchElement('http://naratif.jvitasek.cz/images/subverz-no-b.svg', 'canvas3');
function glitchElement(sourceImg, idCanvas) {
    var canvas = document.getElementById(idCanvas),
        context = canvas.getContext('2d'),
        img = new Image(),
        w,
        h,
        offset,
        glitchInterval;

    img.src = sourceImg;
    img.onload = function() {
        init();
        window.onresize = init;
        redraw();
    };

    var init = function() {
        clearInterval(glitchInterval);
        canvas.width = w = window.innerWidth;
        offset = w * 0.1;
        canvas.height = h = ~~(230 * ((w - (offset * 2)) / img.width));
        glitchInterval = setInterval(function() {
            clear();
            console.log(offset);
            console.log(w - (offset*2));
            console.log(h);
            context.drawImage(img, 0, 0, img.width, 230, offset, 0, w - (offset * 2), h);
            glitchImg();
            setTimeout(function() {
                clear();
                redraw();
            }, randInt(100,130)); // doba, po kterou je obrazek glitchnut
        }, randInt(3000,7000)); // interval mezi kazdym glitchem
    };

    var clear = function() {
        context.rect(0, 0, w, h);
        context.fillStyle = "white";
        context.fill();
    };

    var glitchImg = function() {
        for (var i = 0; i < randInt(1, 7); i++) {
            var x = Math.random() * w;
            var y = Math.random() * h;
            var spliceWidth = w - x;
            var spliceHeight = randInt(5, h / 3);
            context.drawImage(canvas, 0, y, spliceWidth, spliceHeight, x, y, spliceWidth, spliceHeight);
            context.drawImage(canvas, spliceWidth, y, x, spliceHeight, 0, y, x, spliceHeight);
        }
    };

    var randInt = function(a, b) {
        return ~~(Math.random() * (b - a) + a);
    };

    function redraw() {
        context.drawImage(img, 0, 0, img.width, 230, offset, 0, w - (offset * 2), h);
    }
}

I read this might be a bug in Firefox, but I tried some methods to fix this (like adding width/height, canvg, ...) and nothing seems to work for me. Could anyone please hint me how to solve this so the code runs in Firefox as well?

A: In order for drawImage to work with an SVG image in Firefox the SVG image file must have a root <svg> element that has both width and height attributes, neither of which can be percentages.


text:
Q: How to return only one result when making a double await Node.js Hi I can´t find a solution to my problem of functions in cascade,
Service A
print(await serviceB.methodA(myParameter));

Service B
async methodA(MyParameter){

            return await methodB(MyParamter).then((value) =>{
                serviceA.methodC(value);
               }

         );
    }

So the output is
undefined
result

How I can wait to the second result of the then?? Because when getting undefined is broking my service A

A: Using your code structure, you need to return the inner promise.
Change this:
async methodA(MyParameter){
    return await methodB(MyParamter).then((value) =>{
        serviceA.methodC(value);
    });
}

to this:
async methodA(MyParameter){
    return methodB(MyParamter).then((value) =>{
        return serviceA.methodC(value);
    });
}

The result of the .then() becomes the resolved value of the promise chain.  Since you weren't returning anything from the .then() handler, that resolved value became undefined.

But, since you're using async/await, it is generally better to not also mix .then() in the same code so I'd recommend changing to this:
async methodA(MyParameter){
    let value = await methodB(MyParamter);
    return serviceA.methodC(value);
}


text:
Q: Upload doesn't work using Carrierwave in Rails 5 So I was working on my app and trying to put on an uploader feature.
First I generated a course uploader and allowed jpeg, jpg, png and gif.
Next I've added the ff code mount on my course model:
  mount_uploader :thumb_image, CoursesUploader
  mount_uploader :main_image, CoursesUploader

Next, I place the file upload form code on my new.html.erb file:

    <%= f.file_field :main_image %>

  <%= f.file_field :thumb_image %>

And when I tried to submit my form with my images uploaded it did not even show the index page instead I refresh the page and then see if it got uploaded and the form was submitted successfully but it did not.
I also look at the strong params on my controller and these two items are there:
  # Never trust parameters from the scary internet, only allow the white list through.
    def course_params
      params.require(:course).permit(:title, :price, :body, :main_image, :thumb_image)
    end

Any idea what am I missing here?
Here's something I got from my terminal after submission:
Started POST "/courses" for 127.0.0.1 at 2019-01-16 20:52:20 +0800
Processing by CoursesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wlKpv8czsuC6AZjCctxYk203wry4cb0dnOYI9IoAkzRZNV2vB4/vREU5L5u4G7vh5ZhCbHZlJ6nHPN95qO+cbA==", "course"=>{"title"=>"Goody", "price"=>"33", "main_image"=>#<ActionDispatch::Http::UploadedFile:0x007f81e52eed48 @tempfile=#<Tempfile:/var/folders/3_/8bmsd3j13bxfdl1jp7gzvvsm0000gn/T/RackMultipart20190116-2359-17w6pb.jpg>, @original_filename="61230.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"course[main_image]\"; filename=\"61230.jpg\"\r\nContent-Type: image/jpeg\r\n">, "thumb_image"=>#<ActionDispatch::Http::UploadedFile:0x007f81e52eecd0 @tempfile=#<Tempfile:/var/folders/3_/8bmsd3j13bxfdl1jp7gzvvsm0000gn/T/RackMultipart20190116-2359-2mcy4i.jpg>, @original_filename="61230.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"course[thumb_image]\"; filename=\"61230.jpg\"\r\nContent-Type: image/jpeg\r\n">, "body"=>""}, "commit"=>"Create Course"}
   (0.5ms)  BEGIN
  ↳ app/controllers/courses_controller.rb:27
  Course Exists (1.5ms)  SELECT  1 AS one FROM "courses" WHERE "courses"."id" IS NOT NULL AND "courses"."slug" = $1 LIMIT $2  [["slug", "goody"], ["LIMIT", 1]]
  ↳ app/controllers/courses_controller.rb:27
   (0.6ms)  ROLLBACK
  ↳ app/controllers/courses_controller.rb:27
  Rendering courses/new.html.erb within layouts/application
  Rendered courses/new.html.erb within layouts/application (12.6ms)
  Rendered shared/_application_nav.html.erb (6.2ms)
  Rendered shared/_application_footer.html.erb (1.3ms)
Completed 200 OK in 394ms (Views: 356.6ms | ActiveRecord: 2.6ms)

UPDATE: FULL MODEL CONTENT
class Course < ApplicationRecord
  include DefaultsConcern

  enum status: { draft: 0, published: 1 }
  validates_presence_of :title, :price, :body, :main_image, :thumb_image

  mount_uploader :thumb_image, CoursesUploader
  mount_uploader :main_image, CoursesUploader

  extend FriendlyId
  friendly_id :title, use: :slugged

end

FULL FORM CONTENT:

New Form

<%= form_for(@course) do |f| %>

    <%= f.label :title %>
    <%= f.text_field :title %>

    <%= f.label :price %>
    <%= f.number_field :price %>

    <%= f.file_field :main_image %>

  <%= f.file_field :thumb_image %>

    <%= f.label :body %>
    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

A: Validation failed as params[:course][:body] is nil due to which creating course rolled back
validates_presence_of :title, :price, :body, :main_image, :thumb_image

=> So just fillup body field in form or remove validates_presence_of :body

A: I can see the Image is ActionDispatch already but are you sure you created your table column like this -Regardless of creating table or adding_column-
I'm focusing on
:string, array: true, default: []

Migration should look like:
add_column :courses, :main_image, :string, array: true, default: []

As creating the column as String won't let carrierwave add it's object as an array inside it, so it should be an array
Also you can set thumb and main images in one uploader if you are going to change the size only, otherwise you're fine to use :thumb_image and :main_image but make sure the migration is correct
If you can't change it, just drop and re-create it


text:
Q: Change Location of zcompdump Files Is it possible to change the location of .zcompdump and .zhistory files generated by ZSH?
They are polluting my Home Directory.
One possible solution I found was changing the value of $ZDOTDIR to $HOME/.config/zsh. I did the following, but it does not seem to work (temp files are still created in the home directory).
$ cat ~/.zshenv
ZDOTDIR=$HOME/.zsh
. $ZDOTDIR/.zshenv

A: .zcompdump files are produced to speed up the running of compinit, Which initializes the shell completion in zsh. You could specify an explicit dump file by compinit -d <dumpfile> in your .zshrc to change the location where compdump are stored.
Change the value for HISTFILE to set different location to store you zsh command history.

A: $ man zshall
/Use of compinit

 To speed up the running of compinit, it can be made to produce a dumped
configuration that will be read in on future invocations; this is the
default, but can be turned off by calling compinit with the option -D.  The
dumped file is .zcompdump in the same directory as the startup files (i.e.
$ZDOTDIR or $HOME); alternatively, an explicit file name can be given by
`compinit -d dumpfile'.  The next invocation of compinit will read the
dumped file instead of performing a full initialization.


text:
Q: How did they get rid of the "j" in this equation of a low pass filter? I'm trying to learn how to do equations of filters for synthesizer design. I am stuck on this:
https://s15.postimg.cc/eiuti9fbv/image.png
How did they get from the equation with the jw to the one without the j in it?
ie. How did they get rid of the "j"?
I need to be able to do this for other equations. I don't even know what the "j" is though I do understand the rest. If I can understand this I should be able to make gain equations for all the filter types I need.
Thanks.
That equation comes from:
http://www.kves.uniza.sk/kvesnew/dokumenty/DREP/Filters/SecondOrderFilters.pdf
Edit: Solved. Thanks guys.

A: Since my comment apparently answered the question, I'll post it as an answer so the question can be closed:
What is often denoted by $j$ in electrical engineering and control system contexts is usually denoted by $\mathrm i$ in mathematics; see imaginary unit at Wikipedia.


text:
Q: How to access a text service from an Applescript? If an application exposes a Text Service (for example, one that would normally paste the time of day inside the text field of an application such as TextEdit), how to programmatically access this service from an Applescript and capture this text in a variable ?

A: Normally, there would have to be an entry in the Dictionary to give access to any function. If there is a function that isn't made available then there is GUI scripting, scripting the actual mouse and keyboard clicks to get to something in the menu system, but that there are many new issues that will have to be worked around. There is an excellent starter tutorial here: http://www.macosxautomation.com/applescript/uiscripting/index.html


text:
Q: U-SQL code behind breakpoints not hit I am just learning Azure data lake analytics and U-SQL. I have a simple script that runs and produces the expected output. However when I set a breakpoint in the code behind helper method it is never hit because no symbols have been loaded. I have looked at all the available Microsoft tutorials and none suggest that I must do anything to enable debugging, it should just work when I run.

*

*I am running on Local.

*I am using F5 to run in debug mode.

*Script completes successfully.

*Output confirms that helper method is executed

U-SQL
@searchlog =
EXTRACT UserId          int,
        Start           DateTime,
        Region          string,
        Query           string,
        Duration        int,
        Urls            string,
        ClickedUrls     string
FROM "/SearchLog.tsv"
USING Extractors.Tsv();

@searchlog = SELECT
            UserId,
            DataLake.Helper.Test() AS Test,
            Start,
            Region,
            Query,
            Duration,
            Urls,
            ClickedUrls
    FROM @searchlog;

OUTPUT @searchlog
TO "/SearchLog_output.tsv"
USING Outputters.Tsv();

Code Behind
namespace DataLake
{
public class Helper
{
    public static string Test()
    {
        Console.WriteLine("Stop");
        return "Test";
    }
}
}

Output Window
'DebugHost.exe' (CLR v4.0.30319: DefaultDomain): Loaded.
'C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561
934e089\mscorlib.dll'. Symbols loaded.
'DebugHost.exe' (CLR v4.0.30319: DefaultDomain): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\DebugHost.exe'.
Symbols loaded.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\Microsoft.Cosmos
.ScopeStudio.BusinessObjects.Debugger.dll'. Cannot find or open the PDB
file.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\Microsoft.Cosmos
.ScopeStudio.BusinessObjects.Common.dll'. Cannot find or open the PDB file.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\Microsoft.Analytics
.LocalRun.dll'. Cannot find or open the PDB file.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c56
1934e089\System.dll'. Symbols loaded.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\Microsoft.Cosmos.
ClientTools.Shared.dll'. Cannot find or open the PDB file.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__
b77a5c561934e089\System.Core.dll'. Symbols loaded.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b
77a5c561934e089\System.Xml.dll'. Symbols loaded.
'DebugHost.exe' (CLR v4.0.30319: DebugHost.exe): Loaded
'C:\Users\ksmith\Documents\Visual Studio
2017\Projects\USQLApplication1\DataLake\bin\LocalDebug\ScopeRuntime.exe'.
Cannot find or open the PDB file.
The program '[28036] DebugHost.exe' has exited with code 0 (0x0).

Can anyone shed some light on why the breakpoints are not hit?
Adding Debugger.Launch(); caused the Choose Just-In-Time Debugger window to appear. If I select one of the options I then get an instance of visual studio were the code behind break points are hit. The VS instance is called LocalVertexHost
JIT Debugger
Thanks

A: It is some issue that the extension of DataLake Analytics has for visual studio. I have had, and still having, this issue. Follow these steps and it can be ok for some runs, then repeat it again:

*

*Clean all the projects you have: ADLA and ADLA Class library;

*Make sure that the debug folders are empty on both projects;

*Rebuild and Register to your local ADLA the Class Library with the code behind;

*Rebuild the script you are trying to debug;

*Make the ADLA project your startup project;

*Submit the script to your local ADLA (makes sure that you have all the needed files in debug and that the script is assigned as the startup script);

*After the submit is successful, put the brak point into the code behind;

*Start debugging;

If the breakpoint is not hit yet, then try to delete everything from the local U-SQL temporary folder and repeat again all the steps.

A: This happenes in my environment me when I click the Submit button in Visual Studio instead of hitting F5 or clicking on start (with debugging). Thought I should share even though you mention already running with f5 because this was the only mention of this issue I could find. Maybe this will be helpful to others.
I think clicking submit runs the usql script in a separate process without the debugger attached.

A: Go to the Debug options in Visual Studio and ensure the following:

*

*Uncheck "Enable Just My Code"

*Check "Suppress JIT optimization on module load"


text:
Q: Wordpress Reader error - An RSS or Atom feed could not be found for that blog Well, I found this stackoverflow question Wordpress feed - (A feed could not be found at)
Since there are no accepted answers there and I don't have the reputation to add comments to that question, I am adding this question.
Some of the feeds with which I faced issues when adding to Wordpress reader are the following:
http://msopentech.com/feed/
http://www.dwheeler.com/blog/index.rss

A: the first feed, msopentech.com/feed/, is pretty slow (takes > 10s to load, Wordpress.com stops trying after 3s currently), which is triggering the error.
The second is broken because it's using a mimetype of text/plain instead of application/rss+xml.


text:
Q: Name/number column name with a loop or similar I want to add new columns to a existing data frame and I would like to increase the number/name of these columns.
E.g from
Apples Raspberries Bananas

I want to go to
Apples Raspberries Bananas Beta_0 Beta_1 Beta_2 Beta_3 Beta_..

Up to now I just have
for(i in 0:3){
  data.frame[ , "Beta_[(%d<- %d i)"] <- "NA"
}

I guess it must work somehow but cannot figure out how, so I tried something different:
colnames(data.frame)<- paste("Beta", 0:3, sep="")

which worked in such a way that the first four column names were changed. But I need additional columns and the appropriate names.

A: Here's an example using the built-in dataset mtcars:
mtcars[paste("Beta", 0:2, sep = "_")] <- NA

The column names in the resulting data.frame are:
names(mtcars)
# [1] "mpg"    "cyl"    "disp"   "hp"     "drat"   "wt"     "qsec"   "vs"     "am"
#[10] "gear"   "carb"   "Beta_0" "Beta_1" "Beta_2"

All new columns have only NA-values.


text:
Q: Black bar between keyboard and textField I ran into a little problem. I am taking a course on iOS development, and I ran into a problem. I'm a perfectionist, and I want to bring applications to perfection, but I can't figure out which way to dig. There is a small black line between the keyboard and the textField that clearly draws attention to itself.

How to be? What to do to remove it? Which way should I drip? Maybe this is a problem in Xcode 12.3? Could this be because IQKeyboardManagerSwift is conflicting with the current version of Xcode? The video I watched didn't have this problem.
AppDelegate.swift (Here I call up the keyboard):
import UIKit
import Firebase
import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        let db = Firestore.firestore()
        print(db)

        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true

        return true
    }

    // MARK: UISceneSession Lifecycle
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

}

ChatViewController.swift (In this view the keyboard pops up. Here I added a clear button for the textField):
import UIKit
import Firebase

class ChatViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var messageTextfield: UITextField!

    let db = Firestore.firestore()

    var messages: [Message] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        title = K.appName
        navigationItem.hidesBackButton = true

        tableView.register(UINib(nibName: K.cellNibName, bundle: nil), forCellReuseIdentifier: K.cellIdentifier)

        loadMessages()

        // add clear button in text field
        messageTextfield.clearButtonMode = .always
        messageTextfield.clearButtonMode = .whileEditing

        // попробовать сделать так, чтобы при нажатии на кнопку переходило на новый абзац в Textfield
    }

    func loadMessages() {
        db.collection(K.FStore.collectionName).order(by: K.FStore.dateField).addSnapshotListener { (querySnapshot, error) in
            self.messages = []
            if let e = error {
                print("There was an issue retrieving data from firestore, \(e)")
            } else {
                if let snapshotDocuments = querySnapshot?.documents {
                    for doc in snapshotDocuments {
                        let data = doc.data()
                        if let messageSender = data[K.FStore.senderField] as? String, let messageBody = data[K.FStore.bodyField] as? String {
                            let newMessage = Message(sender: messageSender, body: messageBody)
                            self.messages.append(newMessage)
                            DispatchQueue.main.async {
                                self.tableView.reloadData()
                                let indexPath = IndexPath(row: self.messages.count - 1, section: 0)
                                self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                            }
                        }
                    }
                }
            }
        }
    }

    @IBAction func sendPressed(_ sender: UIButton) {
        if let messageBody = messageTextfield.text, let messageSender = Auth.auth().currentUser?.email {
            db.collection(K.FStore.collectionName).addDocument(data: [
                K.FStore.senderField: messageSender,
                K.FStore.bodyField: messageBody,
                K.FStore.dateField: Date().timeIntervalSince1970
            ]) { (error) in
                if let e = error {
                    print("There was an issue saving data to firestore, \(e)")
                } else {
                    print("Successfully saved data")
                    DispatchQueue.main.async {
                        self.messageTextfield.text = ""
                    }
                }
            }
        }
    }

    @IBAction func logOutPressed(_ sender: UIBarButtonItem) {
        do {
            try Auth.auth().signOut()
            navigationController?.popToRootViewController(animated: true)
        } catch let signOutError as NSError {
            print ("Error signing out: %@", signOutError)
        }
    }
}

extension ChatViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let message = messages[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! MessageCell
        cell.label.text = message.body

        if message.sender == Auth.auth().currentUser?.email {
            cell.leftImageView.isHidden = true
            cell.rightImageView.isHidden = false
            cell.messageBubble.backgroundColor = UIColor(named: K.BrandColors.lightPurple)
            cell.label.textColor = UIColor(named: K.BrandColors.purple)
        } else {
            cell.leftImageView.isHidden = false
            cell.rightImageView.isHidden = true
            cell.messageBubble.backgroundColor = UIColor(named: K.BrandColors.purple)
            cell.label.textColor = UIColor(named: K.BrandColors.lightPurple)
        }
        return cell
    }
}

A: The solution to this problem is to add this line of code:
IQKeyboardManager.shared.keyboardDistanceFromTextField = 0


text:
Q: json.net performance over a 77kb json string I am profiling my ASP.NET MVC app and when I hit my local version on IIS and I have noticed that deserializing an object of about 77kb takes around 100ms, is this expected?
Also the CPU seems to max out while im profiling, is the task of deserializing very intense, or should I be looking elsewhere?
Thanks for any help you can give.

A: The complexity of the object usually plays a major role with regards to deserializing. Objects that contain child objects in a recursive pattern will eat CPU and memory to parse correctly.
A simple Name:Value map can become much more complex if the Value is another map (object) of Name:Value. If this type of recursion is going on you may want to try denormalizing (making a Name:[primitive]Value) your JSON so it's easier for the system to parse.
Denormalizing with respect to MVC (rdbms data) may be a bit difficult. Flattening many-to-many relationships isn't feasible in many cases.
You could try comparing JSON.net to the built-in JavaScriptSerializer and see if you can get an improvement.

A: At a certain point, objects become cumbersome to deserialise, given that several serialisation frameworks, inclusing JSON.NET, leverage Reflection. Also, when an object reaches 85KB in size, it is immediately pushed to the Large Object Heap by the Garbage Collector, which will have a performance impact.
I suggest using JSON# - a performance sctentric .NET JSON parser to improve performance, and avoid memory bottlenecks.


text:
Q: Flutter tabs not properly underlined I have the following tabs:
class _HomeState extends State<Home> {

  int _currentIndex = 0;

  final List<Widget> _children = [
    DefaultTabController(
        length: 3,
        child: Scaffold(
            appBar: AppBar(
              flexibleSpace: SafeArea(
                child: TabBar(
                  tabs: [
                    Tab(icon: Icon(FontAwesomeIcons.listAlt)),
                    Tab(icon: Icon(FontAwesomeIcons.map)),
                    Tab(icon: Icon(FontAwesomeIcons.cog))
                  ],
                )
              )
            ),
            body: TabBarView(
              children: [
                TrendingList(),
                TrendingMap(),
                TrendingConfiguration()
              ],
            )
        )
    ),
    PlaceholderWidget(Colors.white),
    PlaceholderWidget(Colors.deepOrange),
    PlaceholderWidget(Colors.green)
  ];

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
            icon: new Icon(FontAwesomeIcons.chartLine),
            title: new Text('Trending'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(FontAwesomeIcons.glasses),
            title: new Text('Watchlist'),
          ),
          BottomNavigationBarItem(
              icon: Icon(FontAwesomeIcons.user),
              title: Text('Me'),
          ),
          BottomNavigationBarItem(
            icon: Icon(FontAwesomeIcons.bell),
            title: Text('Notifications'),
          )
        ],
      ),
    );
  }
}

This results in the following:

Why are my tabs not properly underlined and how do I fix it?
I don't want a title.

A: The Right place to use TabBar is bottom of AppBar.
As mentioned in Docs - https://api.flutter.dev/flutter/material/AppBar-class.html

The bottom is usually used for a TabBar.

Code:
child: Scaffold(
            appBar: AppBar(
              title: Text('Dummy'),
              bottom: TabBar(
                tabs: [
                  Tab(icon: Icon(FontAwesomeIcons.listAlt)),
                  Tab(icon: Icon(FontAwesomeIcons.map)),
                  Tab(icon: Icon(FontAwesomeIcons.cog))
                ],
              ),
            ),

UPDATE:
Code: With no title.
appBar: AppBar(
              flexibleSpace: SafeArea(
                child: SizedBox(
                  height: kToolbarHeight,
                  child: TabBar(
                    tabs: [
                      Tab(icon: Icon(FontAwesomeIcons.listAlt)),
                      Tab(icon: Icon(FontAwesomeIcons.map)),
                      Tab(icon: Icon(FontAwesomeIcons.cog))
                    ],
                  ),
                ),
              ),
              bottom: PreferredSize(child: SizedBox(), preferredSize: Size.zero),
            ),


text:
Q: Retrieve a number from a table by EF Entity Frame 5.0 question.
I am new to Entity Frame, basically I have a table "MyPIN".
[Table("MyPIN")]
public class BatchPINDetail
{
    public BatchPINDetail();
    public int Number { get; set; }

I want to run a query
int x = the biggest Number FROM MyPIN

The correspond codes are:
public class InContext : DbContext
{
    public InContext();
    public InContext(string connectionString);

    public DbSet<BatchDetail> BatchDetailsRecords { get; set; }

}

Question 1: I am not sure how to retrieve it.
Question 2: After I get the value, I want to reassign the value, say Number += 1; I need to write it to DB.
Thanks for help.

A: InContext inContext = new InContext(cnStr);
// get first biggest item
BatchPINDetail entity = inContext.BatchDetailsRecords
                                 .OrderByDescending(x => x.Number)
                                 .First();
// get all biggest items
BatchPINDetail entities = inContext.BatchDetailsRecords
                                 .Where(x => x.Number == x.Max(x => x.Number))
                                 .ToArray();

// and if you just want to get biggest number.
// but note that if you just change `num` nothing will happen.
int num = inContext.BatchDetailsRecords.Max(x => x.Number);

entity.Number += 1;
inContext.SaveChanges();

A: You can use direct approach like the following code and avoid forth and back call to the database.
    InContext inContext = new InContext(cnStr);
    string Sql="SELECT *  FROM MyPIN where Number in (Select MAX(Number) from MyPIN)";
    BatchPINDetail[] entities = inContext.BatchDetailsRecords.SqlQuery(Sql).ToArray();

Now you can do your changes and call SaveChanges() after that.


text:
Q: Proving that function is constant So I have $f$ - $\mathbb{C}$-differentiable complex function in some domain $D$ and $F$-differentiable real-valued function on $\mathbb{R}$ if $Re f(z)=F(Im f(z))$ in $D$ then  $f$ is constant
I don't know how to attempt this problem. I tried to use Cauchy-Riemann conditions but I didn't get needed result

A: If $f$ is a non-constant holomorphic function then $f(D)$ is an open set, according to the Open mapping theorem.
Now choose an arbitrary  $z_0 \in D$. Then  $u_0 + i v_0 = f(z_0)$ is an interior point of $f(D)$. In particular, there is an $\epsilon > 0$ such that
$$
 \{ (u_0 + t) + i v_0| -\epsilon <  t < \epsilon \} \subset f(D) \, .
$$
It follows that
$$
 u_0 + t = F(v_0) \quad \text{for all $t \in (-\epsilon , \epsilon)$}
$$
which is not possible. Therefore $f$ is necessarily constant.

A: Assume $a:=f'(z_0)\ne 0$ for some $z_0\in D$.
Then $f(z)-f(z_0)-a\cdot (z-z_0)+o(|z-z_0|)$.
In particular, letting $z=z_0+it\overline a$ with $t\in(-\epsilon,\epsilon)$, we find that
$\Im f(z)>\Im f(z_0)$ for small positive $t$ (say, for $t=\frac1n$ with $n\gg 0$) and $\Im f(z)<\Im f(z_0)$ for absolutely small negative $t$ (say, for $t=-\frac1n$ with $n\gg0$). Hence on any path within $D$ leading from $z_0-\frac1n i\overline a$ to  $z_0+\frac1n i\overline a$, there is a point $z_n$ with $\Im f(z_n)=\Im f(z_0)$.
By choosing a nice path, we can easily ensure that $0<|z_n-z_0|<\frac1n|a|$.
By the given condition, also $\Re f(z_n)=\Re f(z_0)$, i.e., $f(z_n)=f(z_0)$ for all $n\gg 0$. As $z_n\to z_0$, we find that $0\ne a=\lim_{n\to\infty}\frac{f(_n)-f(z_0)}{z_n-z_0}=0$, contradiction.
Note that we did not even use the smoothness of $F$. :)


text:
Q: Divide and conquer JAVA vector This is my code:
   import java.io.IOException;
    import java.util.Scanner;
public class Main {
    static int operaciones;
    public static int GetFrequency(int A[],int valor, int izq, int der){
        int cont = 0;
        for(int i=izq; i<= der; i++){
            if(A[i] == valor){
                cont++;
            }
            operaciones++;
        }
        return cont;
    }
    public static void print(int A[]){
        System.out.println("El vector Ingresado Fue: ");
        System.out.println("--------------------------");
        for(int i=1; i<A.length;i++){
            System.out.print(A[i] + "\n");
        }
    }
    public static void ingresar(int A[], int elementos, Scanner sc){
        System.out.println("Ingrese los elementos");
        for(int i=1; i<A.length;i++){
            elementos = sc.nextInt();
            A[i]=elementos;
        }
    }
    public static boolean mayoritario(int A[],int i, int j){
        if(i<=j){
            int valor = 0;
            for(int x = i; i <j; x++){
            valor = GetFrequency(A, A[x], i, j);
            operaciones++;
            }
            if(((A.length-1)%2) == 0){
                if(valor > (A.length-1)/2){
                    return true;
                }
            }else{
                if(valor >= (A.length/2)){
                    return true;
                }
            }
            return false;
        }
        if(mayoritario(A,i,j/2)){
            return true;
        }if(mayoritario(A,((i+(j/2))),j)){

            return true;
        }
        return false;

    }
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("Ingrese cantidad de elementos");
        int n = sc.nextInt();
        int A [] = new int [n+1];
        int elementos = 0;
        int maximo = n;
        int minimo = 1;
        ingresar(A,elementos,sc);
        print(A);
        System.out.println("-------------------------");
        if(mayoritario(A,minimo,maximo)){
            System.out.println("Existe un mayoritario");
        }else{
            System.out.println("No existe un mayoritario");
        }
        System.out.println("Operaciones = "+operaciones);

    }

}

I need to find the most repeated num with getfrequency and divide and conquer, but I have a T(n) = n^2, and this supposed to be T(n) = nlog(n).
I think I need to merge my solutions but I dont know how to do this. any suggestion ?

A: Instead of running GetFrequency at every iteration, break your problem into two steps.  In step 1, tabulate your frequencies into a Map.  You should be able to do this in O(n).  In step 2, iterate through the Map and find the key associated with the largest value.


text:
Q: How to load data checked on JsTree i wonder, how to load a new data on JsTree, i have to load data on click like this:
 function showTree(group_id){
        $("#jstree").jstree({
            "core": {
                "themes": {
                    'name': 'proton',
                    'responsive': true
                },
                "data": {
                   type: "POST",
                   url: "/menu/tree",
                   dataType: "json",
                   data: {
                         group_id: group_id
                   },
                   success: function (data) {
                      data.d;
                      console.log(data);
                      $(data).each(function () {
                         return { "id": this.id };
                      });
                   }
                },
             },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "checkbox" , "types", "json_data"]
        });
}

When i call function on the first time its' working but the second time with different data the data doesn't change.
Note : the different data is from checked value
data example :
new:
   {
      id          : "1"
      text        : "Test 1"
      state       : {
        selected  : true
      },
    }
    {
      id          : "2"
      text        : "Test 2"
      state       : {
        selected  : false
      },
    }

i change to :

{
  id          : "1"
  text        : "Test 1"
  state       : {
    selected  : false
  },
}
{
  id          : "2"
  text        : "Test 2"
  state       : {
    selected  : false
  },
}

can i change only data selected from JsTree?

A: The jsTree initialization with $("#jstree").jstree() is a one time thing and is not meant to be re-used. Calling the jstree function on the element again might not re-create the tree. If you're using ajax sourced data you can use jsTree's functions to re-draw with new data.
The refresh function can load new data from the ajax url.
function updateTree(group_id){
    $("#jstree").jstree(true).settings.core.data = {
        type: "POST",
        url: "/menu/tree",
        dataType: "json",
        data: {
             group_id: group_id
        },
        success: function (data) {
          data.d;
          console.log(data);
          $(data).each(function () {
             return { "id": this.id };
          });
        }
    };

    $("#jstree").jstree(true).refresh();
}


text:
Q: On which platforms does integer divide by zero trigger a floating point exception? In another question, someone was wondering why they were getting a "floating point error" when in fact they had an integer divide-by-zero in their C++ program. A discussion arose around this, with some asserting that floating point exceptions are in fact never raised for float divide by zero, but only arise on integer divide by zero.
This sounds strange to me, because I know that:

*

*MSVC-compiled code on x86 and x64 on all Windows platforms reports an int divide by zero as "0xc0000094: Integer division by zero", and float divide by zero as 0xC000008E "Floating-point division by zero" (when enabled)

*IA-32 and AMD64 ISAs specify #DE (integer divide exception) as interrupt 0.  Floating-point exceptions trigger interrupt 16 (x87 floating-point) or interrupt 19 (SIMD floating-point).

*Other hardware have similarly different interrupts (eg PPC raises 0x7000 on float-div-by-zero and doesn't trap for int/0 at all).

*Our application unmasks floating-point exceptions for divide-by-zero with the _controlfp_s intrinsic (ultimately stmxcsr op) and then catches them for debugging purposes. So I have definitely seen IEEE754 divide-by-zero exceptions in practice.
So I conclude that there are some platforms that report int exceptions as floating point exceptions, such as x64 Linux (raising SIGFPE for all arithmetic errors regardless of ALU pipe).
What other operating systems (or C/C++ runtimes if you are the operating system) report integer div-by-zero as a floating point exception?

A:
What other operating systems (or C/C++ runtimes if you are the operating system) report integer div-by-zero as a floating point exception?

The answer depends on whether you are in kernel space or user space. If you are in kernel space, you can put "i / 0" in kernel_main(), have your interrupt handler call an exception handler and halt your kernel. If you're in user space, the answer depends on your operating system and compiler settings.

AMD64 hardware specifies integer divide by zero as interrupt 0, different from interrupt 16 (x87 floating-point exception) and interrupt 19 (SIMD floating-point exception).

The "Divide-by-zero" exception is for dividing by zero with the div instruction. Discussing the x87 FPU is outside the scope of this question.

Other hardware have similarly different interrupts (eg PPC raises 0x7000 on float-div-by-zero and doesn't trap for int/0 at all).

More specifically, 00700 is mapped to exception type "Program", which includes a floating-point enabled exception. Such an exception is raised if trying to divide-by-zero using a floating point instruction.
On the other hand, integer division is undefined behavior per the PPC PEM:

8-53 divw
If an attempt is made to perform either of the divisions—0x8000_0000 ÷
  –1 or  ÷ 0, then the contents of rD are undefined, as are
  the contents of the LT, GT, and EQ bits of the CR0 field (if Rc = 1).
  In this case, if OE = 1 then OV is set.

Our application unmasks floating-point exceptions for divide-by-zero with the _controlfp_s intrinsic (ultimately stmxcsr op) and then catches them for debugging purposes. So I have definitely seen IEEE754 divide-by-zero exceptions in practice.

I think your time is better spent catching divide by zero at compile-time rather than at run-time.

A: I'm not sure how the current situation came to be, but it's currently the case that FP exception detection support is very different from integer.  It's common for integer division to trap.  POSIX requires it to raise SIGFPE if it raises an exception at all.
However, you can sort out what kind of SIGFPE it was, to see that it was actually a division exception.  (Not necessarily divide-by-zero, though: 2's complement INT_MIN / -1 division traps, and x86's div and idiv also trap when the quotient of 64b/32b division doesn't fit in the 32b output register.  But that's not the case on AArch64 using sdiv.)
The glibc manual explains that BSD and GNU systems deliver an extra arg to the signal handler for SIGFPE, which will be FPE_INTDIV_TRAP for divide by zero.  POSIX documents FPE_INTDIV_TRAP as a possible value for siginfo_t's int si_code field, on systems where siginfo_t includes that member.
IDK if Windows delivers a different exception in the first place, or if it bundles things into different flavours of the same arithmetic exception like Unix does.  If so, the default handler decodes the extra info to tell you what kind of exception it was.
POSIX and Windows both use the phrase "division by zero" to cover all integer division exceptions, so apparently this is common shorthand.  For people that do know about about INT_MIN / -1 (with 2's complement) being a problem, the phrase "division by zero" can be taken as synonymous with a divide exception.  The phrase immediately points out the common case for people that don't know why integer division might be a problem.

FP exceptions semantics
FP exceptions are masked by default for user-space processes in most operating systems / C ABIs.
This makes sense, because IEEE floating point can represent infinities, and has NaN to propagate the error to all future calculations using the value.

*

*0.0/0.0 => NaN

*If x is finite:  x/0.0 => +/-Inf with the sign of x

This even allows things like this to produce a sensible result when exceptions are masked:
double x = 0.0;
double y = 1.0/x;   // y = +Inf
double z = 1.0/y;   // z = 1/Inf = 0.0, no FP exception

FP vs. integer error detection
The FP way of detecting errors is pretty good:  when exceptions are masked, they set a flag in the FP status register instead of trapping.  (e.g. x86's MXCSR for SSE instructions).  The flag stays set until manually cleared, so you can check once (after a loop for example) to see which exceptions happened, but not where they happened.
There have been proposals for having similar "sticky" integer-overflow flags to record if overflow happened at any point during a sequence of computations.  Allowing integer division exceptions to be masked would be nice in some cases, but dangerous in other cases (e.g. in an address calculation, you should trap instead of potentially storing to a bogus location).
On x86, though, detecting if integer overflow happened during a sequence of calculations requires putting a conditional branch after every one of them, because flags are just overwritten.  MIPS has an add instruction that will trap on signed overflow, and an unsigned instruction that never traps.  So integer exception detection and handling is a lot less standardized.

Integer division doesn't have the option of producing NaN or Inf results, so it makes sense for it to work this way.
Any integer bit pattern produced by integer division will be wrong, because it will represent a specific finite value.
However, on x86, converting an out-of-range floating point value to integer with cvtsd2si or any similar conversion instruction produces the "integer indefinite" value if the "floating-point invalid" exception is masked.  The value is all-zero except the sign bit.  i.e. INT_MIN.
(See the Intel manuals, links in the x86 tag wiki.

A: For userspace, this happens on AIX running on POWER, HP-UX running on PA-RISC, Linux running on x86-64, macOS running on x86-64, Tru64 running on Alpha and Solaris running on SPARC.
Avoiding divides-by-zero at compile time is much better.