text:
Q: How can I disable browser go to previous page when making HTML form.submit()? Please see this minimum example
When using location.href to navigate to a new page, I can easily go to previous thanks to the browser.
<button>Can Go To Previous Page</button>

<script>
  document.querySelector("button").addEventListener("click", () => {
    window.location.href = "https://google.com";
  });
</script>

And I can easily disable the behavior simply using location.replace
<button>Can Not Go Back Anymore!</button>

<script>
  document.querySelector("button").addEventListener("click", () => {
    window.location.replace("https://google.com");
  });
</script>

Now, how can I make form.submit() acts like location.replace?
Because you can still go back to the previous page when you submitting a form.
Is it possible to do this?
<form action="/action_page.php">
  <label>
    First name:
    <input type="text" id="firstname" name="firstname" />
  </label>
  <button>Submit, Can still go back here</button>
</form>

<script>
  document.querySelector("button").addEventListener("click", () => {
    const form = document.querySelector("form");

    form.submit();
  });
</script>

A: Forms have a default behavior which causes them to submit the values of the form to the endpoint of the action attribute, or reload the form on the same page. The former action causes a redirect from the backend and therefor you've navigated forwards and can now go back.
You can use AJAX to manually submit the form with JavaScript and disable the default behavior. First, listen for the submit event on the form itself, not the button. A button without a specified type attribute will automatically be a submit button if it is inside a form.
Then immediately call Event.preventDefault() to stop the form from submitting. Now you can create your own submitting behavior.
Extract the values from the form with a FormData constructor. This will return you an iterable object in which all input fields are stored in pairs of name and value.
Now use the Fetch API to send the FormData object to your endpoint, which you've specified in your action attribute, and send it with a POST method. Make sure that your backend also expects this method.
Then after the request has finished use location.replace() to change the URL to your liking.
The example below contains all that I've described here above. Check it out and please let me know if you have any questions.
const form = document.querySelector("form");
form.addEventListener("submit", async event => {
  event.preventDefault();
  const formData = new FormData(form)
  const response = await fetch(form.action, {
    method: 'POST',
    body: formData
  }
  if (response.ok) {
    location.replace('yourredirecturl')
  }
});

A: You could do a simple workaround that looks like this:
<form onsubmit="event.preventDefault(); validateMyForm();">

Then you'd need to write the validateMyForm function to handle the form and redirect the user.

A: For this scenario you can simple delete browser history on action_page.php while loading
browser.history.deleteAll();
FYI :- https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/deleteAll


text:
Q: Is It Possible to Restore Accidentally Deleted Widgets? I accidentally deleted the widgets without dragging it to the inactive widgets section.
I have a backup of all the files and the database but i have changed many things on the site other than the widgets.
Can I only restore the widgets?

A: You have to search the wp_options database table for option_name's that contains widget.

That search results in:

Using the values of your backups, you'll then proceed to restore the option_value of the missing widgets. And also the value of the option of sidebars_widgets.
Goes without saying that backing up before doing this modifications is essential.

A: Due to my impatience and lack of confidence in Hostgator's willingness to assist me with this issue, I have found a possible solution if you are comfortable looking at source code. I recommend looking up the site you wish to recover the widgets from The WayBackMachine.

A: Accidently deleted very essential widgets (wifi and battery)
so created a new user and then copied its configuration to the older one,
and IT WORKED!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access my entire browsing history via Javascript If i click on the history tab on my browser I can reach a folder with all of the links ive visited organized by date.
How can I access this programmatically with Javascript? I'm still new to Javascript but I want something like:
var aListOfDateLinkPairs = window.history.some_get_list_function;

I'm sure this is a big privacy issue for some arbitrary entity but what If I want to implement this (programmatically) for myself in my own browser?
Thanks!

A: Short Answer no, you cannot access the history of your browser via common Javascript.
You could create an extension that would be cross browser with something like: http://crossrider.com/
The Docs for accessing the Places storage, which enables you to access the history of the browser is here for firefox: https://developer.mozilla.org/en-US/docs/Using_the_Places_history_service
And for chrome it is here: http://developer.chrome.com/extensions/history.html
There is a file for Places called Places.sqlite is an sqlite database, if you would build a local application that reads from that file, instead of accessing it from your browser, that would be simpler in my opinion.
You could also use the https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/ sqlite manager and order the history according to dates directly from the database. Here's an ERD for that http://people.mozilla.org/~dietrich/places-erd.png

A: The URI place: schema provides a modicum of potential for the javascript "only" (mousing around required) solution given below.
First note the distinction between session history, which can be accessed via History and window.history, and the overall browser history (in FF this is known as part of the library and another library part being bookmarks) which has no direct javascript access interfacing.
ref:

*

*Places query URIs | MDN

*History - Web API Interfaces | MDN

*Window.history - Web API Interfaces | MDN
  on the web: developer.mozilla.org/en-US/docs/Web/API/Window.history
tested with:

window.navigator.userAgent=
      Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
                                                                                (Splashtop-v1.2.17.0)

(The intimate familiarity with this subject is unfortunately due to the severely crippled FF released as QuickWeb by Device VM in the Splashtop system.)
Here is what can be done:
Note:

*

*the FF test environment identified above - some of the "conventions"
used maybe exclusive and not universally available in other browsers
or FF versions

*at the expense of a little more manually labour intensive intervention than
  1 a simple activation click ...
  the solution suggested here also requires
  2 a bookmark link click
  3 save it click
  4 ~ 6 bookmark open and select sequence
  7 results drag & drop
  8 ~ 10 cleanup and delete results from bookmarks
  (is not this anathema to the whole precept of the Order of Automata aka computer automation?
  js js is js - Just Saying JavaScript is Just [too] "Simple")
Using javascript construct a place: scheme URI with the appropriate .some_get_list_function and bookmark it.
extract history

Clicking the link fails but right click bookmarking it and then clicking the bookmark "succeeds". Ergo, might as well resolve left click to redirect immediately to bookmark.
extract history

Drag and drop the now bookmarked place: URI "hystryx" into a target <form><textarea> . Note a significant limitation is that this process retrieves ONLY the history's URI's and none of the history chronology, titles, etc. It is possible to recover some of this information (such as titles by opening each URI to extract them, doing so of course changes the URI "most recent access date" in the history) to render the URI as "nice" links.
Putting it all together:
data:text/html;charset=utf-8,
<title >Heuristic History Hysterics scURIple</title>

A: In general history is protected by the browser against javascript accessing it except through back and forward functionality.  There are some hacks that can view some amount of history, but they are just that--hacks.
If you want to view/modify history programatically, you could do so via browser plugins.  For example, Chrome plugins can use this API
EDIT
Mozilla also has some info about history modification available to Javascript here.
It also looks like this question talks about some of the same things you need.

A: Javascript only offers basic calls once your page takes control of the browser like:
history.length
window.history.back()
history.forward()
window.history.go(-3)

But if you were to write your own browser then you'd be using a 3GL in which case you'd be in total control of what the user has typed in the search or address fields you provided so you shouldn't have any problems there keeping a record of what the user did if you know what you're doing.


text:
Q: How to import from Qt:: namespase (Qt5, Python3.x)? For my application, I need to set some widget parameters like alignment (Qt::AlignBottom) and others. But I can't import them (other PyQt5 stuff imports without any issues).
Using this code
from PyQt5 import Qt

progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBottom)

I got the following error:
Traceback (most recent call last):
  File "run_app.py", line 50, in <module>
    runSemApp(sys.argv)
  File "run_app.py", line 32, in runSemApp
    progressBar.setAlignment(Qt.AlignBottom)
AttributeError: 'module' object has no attribute 'AlignBottom'

And using this one works:
from PyQt5.Qt import *

progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBottom)

Though I have a working solution, I would like to import only Qt.AlignBottom and not *. Also, why doesn't Qt.AlignBottom work with from PyQt5 import Qt?

A: You can do this
>>> from PyQt5.QtCore import Qt
>>> Qt.AlignBottom
64
>>>

You can't import AlignBottom only because QtCore is not a package itself, it's just a module on it's own (a single file). it's important to know that all packages are modules, but not all modules are packages
so this won't work
import PyQt5.QtCore.Qt

ImportError: No module named 'PyQt5.QtCore.Qt'; 'PyQt5.QtCore' is not a package
>>> import PyQt5.QtCore
>>> QtCore
<module 'PyQt5.QtCore' from '/usr/lib/python3.5/site-packages/PyQt5/QtCore.so'>
>>> import PyQt5
>>> PyQt5
<module 'PyQt5' from '/usr/lib/python3.5/site-packages/PyQt5/__init__.py'>
>>>

Looking at the output you can see that QtCore is a single file which contains a class Qt that contains other classes and methods on which AlignBottom is part of, you can see that with.
>>> from PyQt5.QtCore import Qt
>>> help(Qt)

On the otherhand PyQt5 is a package (folder containing other modules) points to it's __init__.py
i'll suggest you read the docs on Modules and this SO question

A: I think the confusion here is that PyQt has a special virtual module called Qt, which imports everything into a single namespace. This is a quite useful feature, but it's a real shame that the name clash with QtCore.Qt wasn't avoided.
In the first example, the error can be "fixed" by using the somewhat weird-looking Qt.Qt.AlignBottom. But obviously, explicitly importing from QtCore is a much better solution. It's also worth noting that the PyQt5 package is a lazy loader, so import PyQt5 will just import an empty namespace with no access to the other modules.

A: If you''re using PySide - as of Pyside6, the QtCore has been refactored. The alignment flags are in the AlignmentFlag module. The following works for me (Python 3.10, Pyside 6, Ubuntu 22.04).
import Pyside6.QtCore as qtc

my_align = qtc.Qt.AlignmentFlag.AlignCenter | qtc.Qt.AlignmentFlag.AlignVCenter

title_label.setAlignment(my_align)


text:
Q: Glide showing ImageView background in between loading images I've got a simple use case. I have a local image uri (content://path) that I load into an ImageView - that's step 1. After a button is pressed, the image is replaced with an image from our server - that's step 2.
My code is quite simple - or at least, I can reproduce the issue even after I simplified the code to the following:
Glide.with(imageHolder.getContext()).load(url).into(imageHolder);

The first time, this is called with a local uri (content://path), followed by a remote url (http://path.com).
Loading the local uri works just fine. The problem is that, once I initiate the load from the server (which might take a second), Glide rolls back to the ImageView's background image colour. So visually I get old image -> background colour -> new image, which is quite annoying.
Is there some sort of a hidden way in Glide to work around this?

A: this is because while the server image is being loaded there is a gap between removing local image and showing the new one and that gap is your problem.
one of the workarounds to this issue is to give Glide a placeholder (set your local image as the placeholder) so while Glide is loading image from server it still shows the local image and once the server image is loaded the local one goes away.
Glide.with(imageHolder.getContext())
    .placeholder(YOUR_LOCAL_IMAGE_HERE)
    .load(url)
    .into(imageHolder);


text:
Q: Linux: Hostname to Spring Cloud Web Application not recognized I have a development environment in windows where I can access the spring build in both IP Address and Hostname(PC-Name) for my Eureka Config Server / Client. When I move it to the RedHat environment it does not recognize the URL if it is a hostname.
My main goal is to change the eureka client status page to point to the hysterix monitor for the eureka client's hysterix stream. The value of ${spring.cloud.client.hostname} resolves to the hostname. I was wondering what is the way to make it the current IP of the eureka client?
To be exact here is an example of what I want am trying to do.
eureka:
 instance:
  preferIPAddress: true
  statusPageUrlPath: http://${spring.cloud.client.hostname}:${eureka.cloud.config.port}/hystrix/monitor?stream=http%3A%2F%2F${spring.cloud.client.hostname}%3A${server.port}%2Factuator%2Fhystrix.stream

It just so happen that the client and the server are both in the same machine so I am contented in using the client hostname for both the Eureka Config Server path and the Eureka Client hystrix stream.
Note that I already set the preferIPAddress to true but the generated hostname is still the value of "/etc/hostname". I saw some solution that explicitly specifies the IP Address in the Eureka Client Instance. But I prefer to make it dynamic so that the same code can run smoothly on either Development and Deploy environment.
What can I do so that the hostname can also be recognized the same as the ip address?

A: The answer has dawn upon me just now. I just changed the following to this.

${spring.cloud.client.hostname}

    ↓↓↓↓↓↓↓↓↓↓↓↓

${spring.cloud.client.ip-address}

I was thrown to a wrong conclusion because other sites would tell me to use this configuration ${spring.cloud.client.ipAddress} which does not work.
Probably there was a change in Finchley / Spring boot 2.0 version. If anyone can give me a link to a documentation or discussion describing the configuration change, it would be helpful.


text:
Q: Simple oscillator design not working when implemented I thought this would be a quick build, but maybe there is something wrong with the design. Even though no waveform occurs, the MOSFET gets very hot.

f = 1/(2π√[C(L1+L2)])
An n-channel 2N7000 MOSFET was chosen with the Hartly configuration to make a 160 kHz oscillator with an output power greater than 16 dBm (or 0.0398 W).
The tank circuit has L1 = L2 = 50 nH and C = 10uF.
Find choke:
\$A_V = g_mR_D\$
\$A_V = (2\sqrt{K_nI_d})(L_D2\pi*f)\$
\$10 = (2\sqrt{4*0.002})(56*10^{-6}2\pi*160000)\$
\$L_D = 56uH = L_3\$
Find Cc:
\$160k = 1/(2\pi*L_{3}C_{c})\$
\$C_{c} = 18uF\$
Find R1:
\$Let: V_{GS} = 2\$
\$10=RI_D + V_{GS}\$
R = 4kΩ
Should I redesign something? Should I add a buffer stage of some sort?
Should I just start the implementation from scratch again? Should I give up on trying to use a FET for this application? Why?

I also swapped it out the Hartley tank with Colpitts, but the signal rapidly attenuated within seconds. If I said that correctly:

I also looked at the others, but they all use BJTs. I really wanted to use a MOSFET to be unique.

*

*This one isn't really about my situation: AC analysis of a oscillator

*My choke is bigger, but their's is for higher frequency: Colpitts not oscillating as expected


text:
Q: What is the DataView class in ASP.NET? Can anyone tell me the what DataView class is in ASP.NET? I don't know where or how to use it.
I know about all the objects: Dataset ,DataProvider, Connection, Command, etc., but I don't know anything about the DataView class.


text:
Q: Laravel Eloquent nested query I was working with Laravel and got stuck in a situation. I have following models:

*

*Category

*Product

*CategoryProduct

CategoryProduct holds the information about which product belongs to which category (a product may belong to multiple categories).
Now, when I want to load all products belonging to a particular category, I need to run query on Product and CategoryProduct  which is where I'm stuck.
I gave it the following try but was unsuccessful:
$products = Product::where('status', '=', 'active')
->where('category_id', '=', $category_id)
->take($count)
->skip($skip)
->get();

Obviously, it will say that category_id is not a column.
Here is my DB & Model structure:
categories table
id,
name,
etc.
products table
id,
name,
sku,
etc.
category_products table
id,
product_id,       ( Foreign key to Product.id )
category_id,      ( Foreign key to Category.id )
etc.
Product model

class Product extends Eloquent {

protected $table = 'products';

protected $hidden = array();

    public static $rules = array('name' => 'required|min:3');

}

Category model
class Category extends Eloquent {

protected $table = 'categories';

public static $rules = array('name' => 'required|min:3');

}

CategoryProduct model
<?php

class CategoryProduct extends Eloquent {

protected $table = 'category_products';

public function product()
{
    return $this->belongsTo('Product');
}

public function category()
{
    return $this->belongsTo('Category');
}
}

Update
A new question on this
I'm trying to display products. If category is not passed (value is -1), then I will show all products, otherwise I will show products from the passed category.
Now, when I show all products, those products may already exist in a category. I want to display ticked checkbox for products that are already in a category. I'm doing something like this:
if($category_id==-1)
        $products = Product::where('status', '=', 'active')->take($count)->skip($skip)->get();
    else{
        $products = Product::whereHas('categories', function($q) use ($category_id)
        {
            $q->where('category_id', $category_id);
        })->where('status', 'active')
            ->take($count)
            ->skip($skip)
            ->get();
    }

The table category_products have product_id, category_id as columns.
Now, the query:
$products = Product::where('status', '=', 'active')->take($count)->skip($skip)->get();
will pick products only from products table. If I check each product for its existence in category_products, then there will be too many database queries for large number of products.
Any idea, how to achieve this. I hope I was able to clear my situation. Thanks

A: The CategoryProduct model should not be necessary unless you have additional fields besides product_id and category_id which point to other relationships.
What is necessary are the methods for setting up the relationship on the Category and Product models.
In Category, add the relationship function...
public function products()
{
    return $this->belongsToMany('Product', 'category_products');
}

In your Product model, do the same for categories.
public function categories()
{
    return $this->belongsToMany('Category', 'category_products');
}

Then you can query for your active products that belong to that category using your relationship method and whereHas()
$products = Product::whereHas('categories', function($q) use ($category_id)
{
    $q->where('id', $category_id);
})->where('status', 'active')
->take($count)
->skip($skip)
->get();

A: You don't need a model for a pivot table in Many-to-Many relationships. Look at this section of the Eloquent documentation for further explanation.
You still need to create a migration to set up the pivot table (or do it manually if you don't use migrations), but not a model. Instead, create a function for Category to designate the relationship:
public function products()
{
    return $this->belongsToMany('App\Product', 'category_products');
    // - You might need to adjust the namespace of App\Product
    // - category_products refers to the pivot table name
}

Likewise, Product needs a similar public function.
Then you're able to do it the other way around, by finding the category and then listing all its related products:
$products = Category::find($category_id)
   ->products()
   ->where('status', 'active')
   ->take($count)
   ->skip($skip)
   ->get();

This question could also be relevant to yours.


text:
Q: Modify the core/paragraph block I'm trying to extend the core/paragraph block to add additional settings to the Gutenberg Inspector(?) (the right side panel settings) but I'm running into issues with it not yet being registered. I'm trying to start out simple just to wrap my head around what's going on and simply change the title of the block for now.
I've seen many of articles/readme's/discussions on how to achieve this:
 - https://riad.blog/2017/10/16/one-thousand-and-one-way-to-extend-gutenberg-today/
 - https://github.com/WordPress/gutenberg/tree/master/packages/hooks
 - https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/
The closest I have come is that first article where you unregister, make your changes, then re-register the block. The only problem is, when I attempt to unregister the block, it says that Block "core/paragraph" is not registered. :(.
Here is the section in my functions.php where I enqueue the block editor assets:
class StarterSite extends Site {
    /** @var string App Version */
    const VERSION = '0.0.1';

    public function __construct() {
        parent::__construct();
        $this->register_autoload();
        $this->register_timber();
    }

    ...

    public function backend() {
        add_action('init', [$this, 'register_menus']);
        add_action('after_setup_theme', [$this, 'theme_supports']);
        add_theme_support('editor-styles');
        add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts']);
        add_action('enqueue_block_assets', [$this, 'enqueue_block_editor_assets']);
    }

    ...

    public function enqueue_block_editor_assets() {
        wp_register_script('block-js', get_stylesheet_directory_uri() . '/dist/js/blocks.js', ['wp-blocks'], self::VERSION, true);
        wp_enqueue_script('block-js');
        wp_enqueue_style('site-gutenberg-css', get_stylesheet_directory_uri() . '/dist/css/gutenberg.css', ['wp-edit-blocks'], '1.0.0', 'all');
    }
}

$site = new StarterSite();

if (!is_admin() || wp_doing_ajax()) {
    $site->frontend();
}
else {
    $site->backend();
}

Here is my JS that gets compiled into the dist/js/blocks.js files:
console.log(wp.blocks.getBlockTypes());

let paragraphBlock = wp.blocks.unregisterBlockType('core/paragraph');
paragraphBlock.title = 'Text';
wp.blocks.registerBlockType('core/paragraph', paragraphBlock);

The console.log(wp.blocks.getBlockTypes()); shows this in the browser console:

So at this point the issue is definitely because the core blocks have not yet been registered, but how do I wait for those blocks to be registered? How can I wait for a specific block to be registered to know that I can modify that block?
UPDATE
I have found this documentation
So I have added this little code snippet:
wp.blocks.registerBlockStyle( 'core/paragraph', {
    name: 'container',
    label: 'Fixed Container'
} );
wp.blocks.registerBlockStyle( 'core/paragraph', {
    name: 'container-fluid',
    label: 'Fluid Container'
} );

This adds the "Style" section in the block:

Is this the recommended solution?
If yes, how do I apply this to ALL blocks programmatically? I still run into the loading issue where not all blocks are available to my script. For example, when I loop through the available blocks at the time of my script's execution:
wp.blocks.getBlockTypes().forEach(function (e) {
    console.log(e);
});

I get the following:

A: Very similar to your goal, I recently wanted to add a block-style to all existing blocks. I found that upon loading an editor page, I must wait for the WP editor JS data to populate before adding my styles, and AFAIK, there's no callback hook for this. So I chose to add a not-so-elegant delay loop.
My solution works but it's not yet robust (e.g., delay loop should exit after a while, should fail gracefully if future WP updates alter the "block types" structure, etc.), but it may get you moving in a workable direction.
Use the WordPress Block Filters tutorial to get your designated JavaScript file loaded for admin/editor pages. Here's the essential snippet from my code that does this:
"use strict";
wp.domReady(function () {

    function addFullWidthStylesToAll(block_types) {
        for (let block_type of block_types) {
            wp.blocks.registerBlockStyle(block_type.name, {
                name: 'full-page-width',
                label: 'Full Page Width',
            });
        }

    }

    (function waitForBlocksDataToFill() {
        let block_types = wp.data.select('core/blocks').getBlockTypes();
        if (0 === block_types.length) {
            setTimeout(waitForBlocksDataToFill, 100);

        } else {
            addFullWidthStylesToAll(block_types)

        }
    })();

});


text:
Q: nginx configuring subdomains on https I have a VPS Ghost installation, which runs on nginx. I have created an SSL certificate for it and everything works well, apart from the fact that all http://subdomain.example.com always redirect back to my main https://example.com when using HTTP.
However, if I visit https://subdomain.example.com, it doesn't redirect back to example.com. I want to make sure that when my users visit *.example.com, they don't redirect back to the main domain, regardless of whether they are using HTTP/S.
The reason behind this is because I'm trying to set up ownCloud on a subdomain of its own and can only access it currently by example.com/cloud.
I've spent many hours configuring the conf files on nginx, please help!
Here are my two nginx config files -
For the main domain:
server {
    listen               80;
    server_name          notepad.li;
    ssl_certificate /etc/letsencrypt/live/notepad.li/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/notepad.li/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    return         301 https://$server_name$request_uri;
}

server {
    listen               443 ssl;
    server_name          notepad.li;

    root /var/www/ghost/;
    ssl_certificate /etc/letsencrypt/live/notepad.li/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/notepad.li/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;
    client_max_body_size 200M;

    location ~ /.well-known {
                allow all;
        }

    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_pass         http://127.0.0.1:2368;
    }

    location /robots.txt {
        alias /var/www/notepad/robots.txt;
    }
    rewrite ^/cloud$ /cloud/ redirect;
    rewrite ^/cloud/$ /cloud/index.php;
    rewrite ^/cloud/(contacts|calendar|files)$ /cloud/index.php/apps/$1/ redirect;
  rewrite ^(/cloud/core/doc/[^\/]+/)$ $1/index.html;
    location /cloud/ {
    alias /var/www/owncloud/;
    location ~ ^/cloud/(build|tests|config|lib|3rdparty|templates|data|README)/ {
      deny all;
    }

    location ~ ^/cloud/(?:\.|autotest|occ|issue|indie|db_|console) {
      deny all;
    }
  }

  location ~ ^(/cloud)((?:/ocs)?/[^/]+\.php)(/.*)?$ {
    # note: ~ has precendence over a regular location block
    # Accept URLs like:
    # /cloud/index.php/apps/files/
    # /cloud/index.php/apps/files/ajax/scan.php (it's really index.php; see 6fdef379adfdeac86cc2220209bdf4eb9562268d)
    # /cloud/ocs/v1.php/apps/files_sharing/api/v1 (see #240)
    # /cloud/remote.php/webdav/yourfilehere...
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /var/www/owncloud/$2;
    fastcgi_param SCRIPT_NAME $1$2;
    fastcgi_param PATH_INFO $3;
    fastcgi_param MOD_X_ACCEL_REDIRECT_ENABLED on;
    fastcgi_param MOD_X_ACCEL_REDIRECT_PREFIX /owncloud-xaccel;
    fastcgi_read_timeout 630;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    client_max_body_size 1G;
    fastcgi_buffers 64 4K;
  }
  location ^~ /owncloud-xaccel/ {
    # This directory is for MOD_X_ACCEL_REDIRECT_ENABLED. ownCloud sends the full file
    # path on disk as a subdirectory under this virtual path.
    # We must only allow 'internal' redirects within nginx so that the filesystem
    # is not exposed to the world.
    internal;
    alias /;
  }
  location ~ ^/((caldav|carddav|webdav).*)$ {
    # Z-Push doesn't like getting a redirect, and a plain rewrite didn't work either.
    # Properly proxying like this seems to work fine.
    proxy_pass https://127.0.0.1/cloud/remote.php/$1;
  }
  rewrite ^/.well-known/host-meta /cloud/public.php?service=host-meta last;
  rewrite ^/.well-known/host-meta.json /cloud/public.php?service=host-meta-json last;
  rewrite ^/.well-known/carddav /cloud/remote.php/carddav/ redirect;
  rewrite ^/.well-known/caldav /cloud/remote.php/caldav/ redirect;

}

For the subdomain:
upstream php-handler {
  server unix:/run/php/php7.0-fpm.sock;
}

server {
  listen 80;
  server_name box.notepad.li;
  # enforce https
  return 301 https://$server_name$request_uri;
}

server {
  listen 443 ssl;
  server_name box.notepad.li;

  ssl_certificate /etc/letsencrypt/live/box.notepad.li/fullchain.crt;
  ssl_certificate_key /etc/letsencrypt/live/box.notepad.li/privkey.key;

  # Add headers to serve security related headers
  add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
  add_header X-Content-Type-Options nosniff;
  add_header X-Frame-Options "SAMEORIGIN";
  add_header X-XSS-Protection "1; mode=block";
  add_header X-Robots-Tag none;
  add_header X-Download-Options noopen;
  add_header X-Permitted-Cross-Domain-Policies none;

  # Path to the root of your installation
  root /var/www/owncloud/;
  # set max upload size
  client_max_body_size 10G;
  fastcgi_buffers 64 4K;

  # Disable gzip to avoid the removal of the ETag header
  gzip off;

  # Uncomment if your server is build with the ngx_pagespeed module
  # This module is currently not supported.
  #pagespeed off;

  index index.php;
  error_page 403 /core/templates/403.php;
  error_page 404 /core/templates/404.php;

  rewrite ^/.well-known/carddav /remote.php/dav/ permanent;
  rewrite ^/.well-known/caldav /remote.php/dav/ permanent;

  # The following 2 rules are only needed for the user_webfinger app.
  # Uncomment it if you're planning to use this app.
  #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
  #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  location ~ ^/(build|tests|config|lib|3rdparty|templates|data)/ {
    deny all;
  }

  location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
    deny all;
  }

  location / {

    rewrite ^/remote/(.*) /remote.php last;

    rewrite ^(/core/doc/[^\/]+/)$ $1/index.html;

    try_files $uri $uri/ =404;
  }

  location ~ \.php(?:$|/) {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param HTTPS on;
    fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
    fastcgi_pass php-handler;
    fastcgi_intercept_errors on;
  }

  # Adding the cache control header for js and css files
  # Make sure it is BELOW the location ~ \.php(?:$|/) { block
  location ~* \.(?:css|js)$ {
    add_header Cache-Control "public, max-age=7200";
    # Add headers to serve security related headers
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    # Optional: Don't log access to assets
    access_log off;
  }

  # Optional: Don't log access to other assets
  location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|swf)$ {
    access_log off;
  }
}

I have copied/pasted + modified nginx configuration code, regarding ownCloud. I checked everything and it seems fine. What am I doing wrong? Why can I not access http://subdomain.example.com without it being redirected to https://example.com?

A: As always, I forgot to triple-check my nginx core files. As pointed out in the comments, I forgot to include the include sites-enabled; in nginx.conf and then create a symlink for my new subdomain config in that folder.
Thanks again!


text:
Q: Showing without calculating the integral that: $\pi/2 \leq \int_{0}^{\pi} \frac{x\sin(x)}{1+\cos(x)^2} \leq \pi$ I want to prove without calculating the integral that:
$\pi/2 \leq \int_{0}^{\pi} \frac{x\sin(x)}{1+\cos(x)^2} \leq \pi$.
I have some problem, since if my function is:
$f:[0,\pi]\to R$ defined by
$f(x)=\frac{x\sin(x)}{1+\cos(x)^2}$ then $f(0)=f(\pi)=0$ and since f is non-negative in this intervel then the given integral is $\geq 0$ so is it legal to use the integral monotone theorem?
I mean can i say that for every $x\in [0,\pi]$, $\frac{x\sin(x)}{1+\cos(x)^2} \leq x\sin(x)$ and $\frac{x\sin(x)}{1+\cos(x)^2}\geq x\sin(x)/2$ ?

A: For  $x\in [0,\pi]$, $\frac{x\sin(x)}{1+\cos(x)^2} \leq x\sin(x)$ and $\frac{x\sin(x)}{1+\cos(x)^2}\geq x\sin(x)/2$  , this is true because ,the first inequality is true because the denominator is $>1$ for all $x$ in the domain and the numerator is positive and the second because the denominator is always less than equal to $2$ for all $x$ in the domain and the numerator is always positive  .
Since $f(x)>0$ you can conclude that the inequality also holds true for their integrals from $0$ to $\pi$
And since the integral of $x\sin(x)$ from $0$ to $\pi$ is $\pi$ the first inequality in the question is true .

A: You have some excellent answers about proving your inequality now. However, some seem to think that we cannot evaluate this integral directly. I will show that in fact this integral can be evaluated directly.

Firstly, we need to know the following very useful result, which can be seen by making the substitution $u=a+b-x$:
$$\int_a^bf(x)~dx=\int_a^bf(a+b-x)~dx$$
In our case, if $I$ is our integral, then
$$\begin{align}I&=\int_{0}^{\pi} \frac{x\sin(x)}{1+\cos^2(x)}dx=\int_0^{\pi}\frac{(\pi-x)\sin(\pi-x)}{1+\cos^2(\pi-x)}dx\\
&=\int_0^{\pi}\frac{(\pi-x)\sin(x)}{1+\cos^2(x)}dx=\pi\int_0^{\pi}\frac{\sin(x)}{1+\cos^2(x)}-\int_0^{\pi}\frac{x\sin(x)}{1+\cos^2(x)}dx\\
&=\pi\int_0^{\pi}\frac{\sin(x)}{1+\cos^2(x)}dx-I\\
\implies 2I&=\pi\int_0^{\pi}\frac{\sin(x)}{1+\cos^2(x)}dx\\
\implies I&=\frac{\pi}{2}\int_0^{\pi}\frac{\sin(x)}{1+\cos^2(x)}dx
\end{align}$$
Now make the substitution $y=\cos x$, so that $\sin x~dx=-dy$. Dealing with the bounds now: when $x=\pi$, $y=-1$ and when $x=0$, $y=1$. Hence,
$$\begin{align}I&=\frac{\pi}{2}\int_0^{\pi}\frac{1}{1+\cos^2(x)}\sin x~dx\\
&=\frac{\pi}{2}\int_1^{-1}\frac{-1}{1+y^2}dy=\frac{\pi}{2}\int_{-1}^1\frac{1}{1+y^2}dy\\
&=\frac{\pi}{2}\left[\arctan y\right]_{-1}^1=\frac{\pi}{2}(\arctan 1-\arctan(-1))\\
&=\frac{\pi}{2}(2\arctan 1)=\pi\arctan 1\\
&=\frac{\pi^2}{4}
\end{align}$$

A: Those inequalities in your last sentence are both obviously true when $x=0$.
And if $0 < x \le \pi/2$ then all factors occurring in those inequalities are positive (the factor $x$, the factor $\sin(x)$, and the factor $1 + \cos(x)^2$), and so after some rearrangement those inequalities are equivalent to $1 + \cos(x)^2 \ge 1$ and $1 + \cos(x)^2 \le 2$ which together are equivalent to $0 \le \cos(x)^2 \le 1$ which is true.

A: COMMENT.-This integral is not elementary so it is not question of direct calculation. However we have
$$\int_{0}^{\pi} \frac{x\sin(x)}{1+\cos(x)^2}\gt \int_{0}^{\pi} \frac{\sin(x)}{1+\cos(x)^2}=\frac{\pi}{2} $$ and something similar coul be apply maybe to the majorant $\pi$. This is just a comment.


text:
Q: Identifying if a user is in the local administrators group My Problem
I'm using PInvoked Windows API functions to verify if a user is part of the local administrators group. I'm utilizing GetCurrentProcess, OpenProcessToken, GetTokenInformationand LookupAccountSid to verify if the user is a local admin.
GetTokenInformation returns a TOKEN_GROUPS struct with an array of SID_AND_ATTRIBUTES structs. I iterate over the collection and compare the user names returned by LookupAccountSid.
My problem is that, locally (or more generally on our in-house domain), this works as expected. The builtin\Administrators is located within the group membership of the current process token and my method returns true. On another domain of another developer the function returns false.
The LookupAccountSid functions properly for the first 2 iterations of the TOKEN_GROUPS struct, returning None and Everyone, and then craps out complaining that "A Parameter is incorrect."
What would cause only two groups to work correctly?
The TOKEN_GROUPS struct indicates that there are 14 groups. I'm assuming it's the SID that is invalid.
Everything that I have PInvoked I have taken from an example on the PInvoke website. The only difference is that with the LookupAccountSid I have changed the Sid parameter from a byte[] to a IntPtr because SID_AND_ATTRIBUTESis also defined with an IntPtr. Is this ok since LookupAccountSid is defined with a PSID?
LookupAccountSid PInvoke
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool LookupAccountSid(
        string lpSystemName,
        IntPtr Sid,
        StringBuilder lpName,
        ref uint cchName,
        StringBuilder ReferencedDomainName,
        ref uint cchReferencedDomainName,
        out SID_NAME_USE peUse);

Where the code falls over
                for (int i = 0; i < usize; i++)
                {
                    accountCount = 0;
                    domainCount = 0;
                    //Get Sizes
                    LookupAccountSid(null, tokenGroups.Groups[i].SID, null, ref accountCount, null,
                                     ref domainCount, out snu);

                    accountName2.EnsureCapacity((int) accountCount);
                    domainName.EnsureCapacity((int) domainCount);

                    if (!LookupAccountSid(null, tokenGroups.Groups[i].SID, accountName2, ref accountCount, domainName,
                                     ref domainCount, out snu))
                    {
                        //Finds its way here after 2 iterations
                        //But only in a different developers domain
                        var error = Marshal.GetLastWin32Error();

                        _log.InfoFormat("Failed to look up SID's account name. {0}", new Win32Exception(error).Message);
                        continue;
                    }

If more code is needed let me know. Any help would be greatly appreciated.

A: It sounds like you're trying to duplicate the functionality of NetUserGetLocalGroups. You can also use NetUserGetInfo with an information level of 1, and check the value of usri1_priv in the USER_INFO_1 for USER_PRIV_ADMIN.

A: I'm not sure if NetUserGetLocalGroups knows about deny SIDs (If you need to verify if the current process (not the user account!) is in the admin group, you have to handle deny SIDs)
If you only need to support 2000 and later, PInvoke CheckTokenMembership (That MSDN page has a IsUserAdmin example function)
On NT4 you need to get a TokenGroups array from GetTokenInformation, but you don't call LookupAccountSid, you just call EqualSid on every item and compare it to a admin group SID you create with AllocateAndInitializeSid(...,SECURITY_BUILTIN_DOMAIN_RID,...)


text:
Q: Kubuntu Root Password I've been running Kubuntu for about a month now, still learning.  All of a sudden as of about two days ago, if I try to install or update software using Muon, it asks for the root password.  I'm assuming this is my administrative password, but that password won't work.  I know I'm typing it in correctly (case sensitive) and I haven't forgotten my admin password because I can log in to my laptop when I first turn it on using the same password.
If the administrative password is not the root password, then what is the root password?  I followed some directions online regarding booting in safe mode, but i can't get the passwd command to work.  I tried that twice and I keep getting an error message telling the password was not changed.  Then I don't know how to exit out of safe mode.  I kept hitting the escape key and that didn't work.  I ended up just powering off my laptop to get out of safe mode.

A: To manually set a password for the root user, type in the following in the Terminal:
sudo passwd

After that you are asked to type in the new root password twice.


text:
Q: Log into JavaScript login form requests I am trying to log into this website that uses a JS based form. Is this even possible with the Python requests library?
payload = {
    '_username': 'xxx@xxx.com',
    '_password': 'xxx',
    '_remember_me': 'false'
}

with requests.Session() as s:
    p = s.post('https://www.lovoo.com/login_check', data=payload)
    r = s.get('https://www.lovoo.com/list/visits')
    print(r.text)

I search r.text afterwards with grep, but I see I am still not logged in?

A: You need to do an initial get to set some cookies and add some headers:
head = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest",

}
with requests.Session() as s:
    s.get("https://www.lovoo.com")
    p = s.post('https://www.lovoo.com/login_check', data=payload, headers=head)
    r = s.get('https://www.lovoo.com/list/visits')

If you print p.json() you will see a response like {"referer":"https:\/\/www.lovoo.com\/welcome\/login","success":true,"user":{}} which means you have successfully logged in.


text:
Q: What does prevent DOMTimerCoordinator::NextID from entering a endless loop? I had a look into the Blink codebase to answer this question about the maximum possible number of timers in JavaScript.
New timers are created by DOMTimerCoordinator::InstallNewTimeout(). It calls NextID() to retrieve an available integer key. Then, it inserts the new timer and the corresponding key into timers_.
int timeout_id = NextID();
timers_.insert(timeout_id, DOMTimer::Create(context, action, timeout,
                                            single_shot, timeout_id));

NextID() gets the next id in a circular sequence from 1 to 231-1:
int DOMTimerCoordinator::NextID() {
  while (true) {
    ++circular_sequential_id_;

    if (circular_sequential_id_ <= 0)
      circular_sequential_id_ = 1;

    if (!timers_.Contains(circular_sequential_id_))
      return circular_sequential_id_;
  }
}

What happen if all the IDs are in use?
What does prevent NextID() from entering in a endless loop?
The whole process is explained with more detail in my answer to that question.

A: I needed a bit to understand this but I believe I got it.
These are the steps which turned it into sense for me.

*

*circular_sequential_id_ is used as unique identifier. It's not exposed but from the other info I suspect it's an int with 32 bit (e.g. std::int32_t).

*I suspect circular_sequential_id_ is a member variable of  class (or struct) DOMTimerCoordinator. Hence, after each call of NextID() it "remembers" the last returned value. When NextID() is entered circular_sequential_id_ is incremented first:
    ++circular_sequential_id_;

*The increment ++circular_sequential_id_; may sooner or later cause an overflow (Uuuh. If I remember right this is considered as Undefined Behavior but in real world it mostly simply wraps around.) and becomes negative. To handle this, the next line is good for:
    if (circular_sequential_id_ <= 0)
      circular_sequential_id_ = 1;

*The last statement in loop checks whether the generated ID is still in use in any timer:
    if (!timers_.Contains(circular_sequential_id_))
      return circular_sequential_id_;
If not used the ID is returned. Otherwise, "Play it again, Sam."
This brings me to the most reasonable answer:
Yes, this can become an endless loop...
...if 231 - 1 timers have been occupied and, hence, all IDs have been consumed.

*

*I assume with 231 - 1 timers you have much more essential other problems. (Alone, imaging the storage that those timers may need and the time to handle all of them...)

*Even if 231 - 1 timers are not a fatal problem, the function may cycle further until one of the timers releases it's ID and it can be occupied again. So, NextID() would be blocking if a resource (a free ID for a timer) is temporarily not available.
Thinking twice, the 2. option is rather theoretically. I cannot believe that somebody would manage limited resources this way.
I guess, this code works under assumption that there will never be 231 - 1 timers concurrently and hence it will find a free ID with a few iterations.


text:
Q: how to pass data using intent in xamarin i'm new in developing android in xamarin i just want to ask in how to pass data through other activity using intent ? This thing work (https://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/) but i want to collect first all the data in 2 activity before they show the summary in my 3rd activity.(by the way i'm creating a registration app thanks for the future answers :) )

A: *

*On the first activity you create the second activity by an intent and use the method PutExtra to pass the data you want with a relevant key name that you will need after starting the new activity to retrieve the data.
var secondActivity = new Intent (this, typeof(SecondActivity));

secondActivity.PutExtra ("Data", "Sample Data");

StartActivity(secondActivity);

*On second activity OnCreate retrieve the data using the key name it was stored with and the correct  method relevant to the data type passed. In this example as is a string by calling Intent.GetStringExtra.
string text = Intent.GetStringExtra ("Data") ?? "Data not available";

*You can repeat 1 & 2 for the summary activity.

A: you can pass whole object and desterilize that in another activity like this
//To pass:
intent.putExtra("yourKey", item);

// To retrieve object in second Activity
getIntent().getSerializableExtra("yourKey");

For only single value you can use
//Method 1
string code = Intent.GetStringExtra("id") ?? string.Empty;
string name = Intent.GetStringExtra("Name") ?? string.Empty;

//OR

//Method 2

string Id = Intent.GetStringExtra("id") ?? string.Empty;
Item item = new Item();
item = itemRepo.Find(Convert.ToInt32(id));


text:
Q: Can't Alt+Tab back to a TopMost form I have a winform tool window in C# with TopMost = true, running on XP, being shown from within an Excel add-in.  When the form is shown, I hit Alt+Tab, it brings me back to Excel.  If I hit Alt+Tab again, I would expect it to bring me back to my form, but it goes to the next window (in this case, Visual Studio).  Any subsequent Alt+Tab invocations alternate between Excel and Visual Studio.  Additionally, if I Alt+Shift+Tab, it will go back to my form (so it's still part of the order, just the order isn't what I want it to be).
If I simply set TopMost = false, everything works as expected.  I just reproduced this with a brand new empty project — literally the only thing I did was make a TopMost form.  It appears to be isolated entirely to the TopMost property.
Naturally, I'd like Alt+Tab to work the way I expect it to.
Any ideas?

A: The topmost-form of my application is included in the Alt+Tab sequence. But i found, it is not if i set the forms ShowInTaskbar-property to true. Have a look on this property.


text:
Q: Morse function on torus and real projective plane. I was considering following problem.
Let us have a torus $T^2$ and real projective plane $\mathbb{R}P^2$. Let $f: T^2 \to \mathbb{R}$ and  $g: \mathbb{R}P^2 \to \mathbb{R}$ be a Morse functions. Proof that $f$ and $g$ have at least one saddle point. Find minimal number of saddle points of $f$ and $g$.
So I know that $f$ and $g$ have at least two critical points, because torus and projective plane are compact. Moreover those points are non-degenerate. I should probably use two dimentional square model of those manifolds, but to be honest, I don't know what to do next. I would be grateful for any hints.


text:
Q: Are there any known DC super metals besides Nth? Thinking about it, we know the Marvel universe, Comic, animated, TV and movie, has a number of cool super metals...
Adamantium has heavy molecular density and bonds, but light weight, is resistant to temp extremes, corrosives and even an atomic blast...
Vibranium absorbs and redirects kinetic energyeven from most light, heat and electricity... all things but sound. And it can be charged to a capacity that it can expel this energy as a wave or beam.
Even Uru is a mystical metal possibly made from star matter yet light, durable, and almost unbreakable which can channel, redirect, absorb and amplify magic. And no known corrosives can damage it...
But all DC has is Nth metal;: an unnaturally hard yet flexible ore which can amp up or totally disrupt all energy fields, from electromagnetic to sound to radioactive to gravitational to magical. It's amazingly versatile, making for very effective weapons and armor, and even vehicles.
Does DC have any other metals which can help even the odds? Nothing that suppresses power, or is almost unbreakable, or which enhances meta-human abilities? Nothing that reflects all light and concussive forces, but is weak to solvents? Nothing that vibrates at two separate levels, pushing those who hold it into another dimension?
If you know of any, please let me know. If possible, provide a visual example or reference to each. And yes, they can be alien, but *no, K-metals don't count; they take more affect Kryptonians due to the radiation, not their physical capabilities.
What are some other possible examples?


text:
Q: Erro ao usar class para filtro por nomes de alunos Estou tentando fazer uma função para pesquisar por nome do aluno no bando de dados.
Estou tendo o seguinte erro:

Notice: Undefined index: filtro in C:\meuphp\teste\pesquisa_aluno.php on line 7

   <?php

    require 'conexao.php';
    include 'classe_aluno.php';

    $exibindo= new Aluno($mysql);
    $filtrado=$exibindo->exibirUm($_POST['filtro']);?>

A linha que mostra o erro é:
$filtrado=$exibindo->exibirUm($_POST['filtro']);?>

O segundo erro é

Fatal error: Uncaught TypeError: Argument 1 passed to Aluno::exibirUm() must be of the type string, null given, called in C:\meuphp\teste\pesquisa_aluno.php on line 7 and defined in C:\meuphp\teste\classe_aluno.php:29 Stack trace: #0 C:\meuphp\teste\pesquisa_aluno.php(7): Aluno->exibirUm(NULL) #1 {main} thrown

public function exibirUm(string $filtro){

        $exibir=$this->mysql->prepare("SELECT * FROM aluno WHERE nome LIKE  ?");
        $exibir->bind_param('s',$filtro);
        $exibir->execute();
        $filtrado=$exibir->get_result()->fetch_assoc();

        return $filtrado;
    }

A: O problema é que ao abrir a página pela primeira vez nenhum POST foi feito, portanto $_POST['filtro'] não existe. Consequentemente, o método exibirUm, que espera receber uma string, recebe NULL.
Para resolver esse problema, faça o filtro na base de dados somente quando estiver recebendo os dados do formulário. Algo como
if (isset($_POST['filtro']) === true) {
  $filtrado = $exibindo->exibirUm($_POST['filtro']);
}


text:
Q: Split Pandas DF Into Multiple Equal Parts Based On Slice I'm looking to split my starting dataframe into 3 new dataframes based on a slice of the original. I know I'm close, but cannot tell where I'm going wrong, see below. Currently, my first and last df look good, but the middle is not correct as it's extending to the very end. Appreciate any guidance, as well as if there is an overall better method.
import math
import pandas as pd

data = {'Name':['Bob','Kyle','Kevin','John','Nolan','Gary','Dylan','Brandon'],
        'attr':['abc123','1230','(ab)','asd','kgi','eiru','cmvn','mlok']}

df = pd.DataFrame(data)

one_third_count = math.ceil(len(df) / 3)
print(one_third_count)
print(one_third_count*2)

df_1 = df.iloc[:one_third_count]
display(df_1.info())

df_2 = df.iloc[one_third_count:, :one_third_count * 2]
display(df_2.info())

df_3 = df.iloc[one_third_count*2:]
display(df_3.info())

A: Your problem is this line:
df_2 = df.iloc[one_third_count:, :one_third_count * 2]

You want:
df_2 = df.iloc[one_third_count : one_third_count * 2]

The ":" notation says "Give me a slice from the left of the ':' to the right of the ':'."  If you don't include a left or right hand side then you are taken to mean "very beginning" or "very end" respectively.
Originally, with the comma, you were asking iloc for two dimensions.  The original says "Give me from one_third_count to the end" on the first dimension (rows) and then from the start to one_third_count * 2 on the second dimension (columns).  Because that's more columns than you had, this just gets everything.  That's why the original df_2 had from one_third to the end.

A: Here is a proposition with numpy.array_split and globals to create the chunks dynamically.
one_third_count = math.ceil(len(df)/3)

dfs = np.array_split(df, one_third_count)

for idx, ch in enumerate(dfs, start=1):
    globals()[f"df_{idx}"] = ch

# Output :
print(df_2)

    Name  attr
3   John   asd
4  Nolan   kgi
5   Gary  eiru


text: Q: How to dynamically change the colour of text depending on its content I have a random letter generator that puts the output onto a website. I use EJS to render this data onto the website within a  tag. Is there a way to colour specific parts of this text from the server side?


text:
Q: Printing into a pop-up, instead on main window I have this function which shows all my articles titles from 'Articles' database.
function show()
{
    database();

    $sql = "SELECT title FROM `Articles`";

    $titleSql = mysql_query( $sql ) or die("Could not select articles:");

    $html = '

Basic List Group

';

    while ($title = mysql_fetch_array($titleSql)) {
        $html .= '
'.$title["title"].'
';
    }

    $html .= '

';

    echo $html;
//  die("Functie terminata cu succes! :)");
 //   die(json_encode(array("mesaj" => "Entered data successfully ")));

}

This is the function in javascript.
function show()
    {
        var n = $('#show').val()
        $.post("functions.php", {show:n}).done(function(mesaj){
            alert(mesaj);
        });
    }

PROBLEM: because of the alert(mesaj), it shows the string $html into a pop-up, not on my main window, as I wish!
HOW can I modify my functions so the articles list will show on m window?

A: you have to give a container id to which it will set the data. Bellow i put it in document.
function show()
    {
        var n = $('#show').val()
        $.post("functions.php", {show:n}).done(function(mesaj){
            $(document).html(mesaj);
        });
    }


text:
Q: Subtracting Integer from Date returning previous date than expected date We are trying to calculate "Date A" by subtracting 5 days from "Date B".
For e.g
Date myDate = Date.newInstance(2021, 06, 26);
Date newDate = mydate.addDays(-5);
System.debug('output::'+newDate);
Output is 2021-06-20 00:00:00 expected output should be 2021-06-21 00:00:00
It might be because offset is added as 00:00:00. Any leads on how to proceed in order to work it for any user or profile correctly irrespective of timezone.

A: System.debug outputs times in GMT by default, but Date.newInstance and DateTime.newInstance are affected by the user's time zone setting. Use the GMT versions instead, or use the appropriate format methods to get the value back out in the user's local time zone, despending on what you're doing exactly.
Date myDate = Date.newInstance(2021, 06, 26);
Date newDate = mydate.addDays(-5);
System.debug('output::'+newDate.format());

Or:
Date myDate = DateTime.newInstanceGMT(2021, 06, 26).date();
Date newDate = mydate.addDays(-5);
System.debug('output::'+newDate);


text:
Q: How to delete folder or file in WordPress plugin I am developing a wordpress plugin which require user to remove (or delete) a directory or file.
After initiating the WP_Filesystem like this
function filesystem_init($form_url, $method, $context, $fields = null) {
global $wp_filesystem;
/* get credentials */
if (false === ($creds = request_filesystem_credentials($form_url, $method, false, $context, $fields))) {
return false;
}

if (!WP_Filesystem($creds)) {
/* incorrect connection data - ask for credentials again, now with error message */
request_filesystem_credentials($form_url, $method, true, $context);
return false;
}
return true; //successfully initiated
}

When the form is posted I have done this to remove a directory with one single file
WP_PLUGIN_DIR.'/myp/mfold/selectedfolder/index.php';
function RemoveData($form_url){
global $wp_filesystem;
check_admin_referer('ToRemoveData');
$ToRemove = $_POST['dirToGo'];
$form_fields = array('dirToGo');
$method = '';
$targetFolder= WP_PLUGIN_DIR . '/myp/mfold/'.$ToRemove; //target folder
$form_url = wp_nonce_url($form_url, 'ToRemoveData'); //page field with nonce value
if(!filesystem_init($form_url, $method, $targetFolder, $form_fields))
return false;
if($wp_filesystem->is_dir($targetFolder))
{
$wp_filesystem->rmdir($targetFolder);
//WP_Filesystem_Base::delete($targetFolder);
return " Successful !";
}
else
{
return new WP_Error('writing_error', 'Cannot Remove');
}//return error object
}//close function

This function return Success but the folder or the directory is not deleting.
Any idea anyone Thanks

A: $wp_filesystem->delete($target_folder, true);

Use this code to remove directory.


text:
Q: Updating element's innerText with input value on 'keyup' I am practicing JS on this challenge from FrontEndMentor.io and just need assistance in figuring out how to get desired results.
My goal is to get the '0000 0000 0000 0000' on the class demo-numbers to update individually as the value is being typed. Example, you type '234' and it updates the card number to '2340 0000 0000 0000'... so on and so forth up to 16 digits.
[CodePen - Interactive Card Details]
https://codepen.io/jdubtheegreat/pen/JjvZMBJ?editors=0010
const demoName = document.querySelector('.demo-name');
const demoNum = document.querySelector('.demo-number');
const demoExpMM = document.querySelector('.demo-exp-mm');
const demoExpYY = document.querySelector('.demo-exp-yy');
const demoCvc = document.querySelector('.demo-cvc');

const cardName = document.getElementById('cardholder');
const cardNum = document.getElementById('card-num');
const cardExpMM = document.getElementById('exp-month');
const cardExpYY = document.getElementById('exp-year');
const cardCvc = document.getElementById('cvc');

addEventListener('keyup', () => {
  if (cardNum.value) {
    let demoNumArray = Array.from(document.querySelector('.demo-number').innerText);
    demoNumArray = demoNumArray.filter(function (entry) { return entry.trim() != ''; });
    const cardNumArray = Array.from(cardNum.value);

    for (let i = 0; i < cardNumArray.length; i++) {
      if (cardNumArray[i] !== undefined) {
        demoNum.innerText = demoNumArray.splice(demoNumArray[i], 1, cardNumArray[i]);
      } else {
        demoNumArray[i] = '0';
      }
    };
  };
});

        0000 0000 0000 0000
        Jane Appleseed

        00/00

        000

          Cardholder Name
          <input type="text" id="cardholder" name="cardholder" placeholder="e.g. Jane Appleseed" required>
          Card Number
          <input type="text" id="card-num" name="card-num" placeholder="e.g. 1234 5678 9123 0000" maxlength="16" onkeyup="this.value = this.value.replace(/[^0-9]/, '')" required>
          Exp. Date (MM/YY)
          CVC

          <input type="number" id="exp-month" name="exp-month" placeholder="MM" maxlength="2" style="margin-right: 10px;" required>
          <input type="number" id="exp-year" name="exp-year" placeholder="YY" minlength="2" maxlength="2" required>
          <input type="text" id="cvc" name="cvc" placeholder="e.g. 123" maxlength="3" onkeyup="this.value = this.value.replace(/[^0-9]/, '')" required>
          <button type="submit" class="submit">Confirm</button>

The code that is commented out in the JS section on GitHub updates the card except it erases the entire string on the demo card as it's typed
TIA for any assistance provided!

A: you can use method padStart or padEnd to fill the cardNum value with 0 digit until the needed size
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

const demoNum = document.querySelector('.demo-number');
const cardNum = document.getElementById('card-num');

cardNum.addEventListener('keyup', () => {
  if (cardNum.value) {
    demoNum.innerText = cardNum.value.padEnd(16, '0').replace(/(.{4})/g, '$1 ');
  };
});
.demo-number {
  border: solid blue;
}

#card-num {
  border: solid green;
}

    0000 0000 0000 0000
    Jane Appleseed

          00/00

  000

    Cardholder Name
    <input type="text" id="cardholder" name="cardholder" placeholder="e.g. Jane Appleseed" required>
    Card Number
    <input type="text" id="card-num" name="card-num" placeholder="e.g. 1234 5678 9123 0000" maxlength="16" onkeyup="this.value = this.value.replace(/[^0-9]/, '')" required>
    Exp. Date (MM/YY)
    CVC

    <input type="number" id="exp-month" name="exp-month" placeholder="MM" maxlength="2" style="margin-right: 10px;" required>
    <input type="number" id="exp-year" name="exp-year" placeholder="YY" minlength="2" maxlength="2" required>
    <input type="text" id="cvc" name="cvc" placeholder="e.g. 123" maxlength="3" onkeyup="this.value = this.value.replace(/[^0-9]/, '')" required>
    <button type="submit" class="submit">Confirm</button>

A: My version
https://codepen.io/mplungjan/pen/bGMjqgj
const zeroes = "0000 0000 0000 0000";
cardNum.addEventListener("input", () => {
  const placeholder = [...zeroes];
  if (cardNum.value) {
    const digits = [...cardNum.value];
    let cnt = 0;
    placeholder.forEach((_, i) => {
      if (cnt>=digits.length) return;
      if (placeholder[i] !== " ") placeholder[i] = digits[cnt++];
    })
  }
  demoNum.textContent = placeholder.join("");
});


text: Q: Source code coverage indication for PHP application at specific intervals I am fuzzing a PHP web application for vulnerabilities and I want to the source code coverage over a period of time (at certain time intervals) for a certain part of the programme (specific PHP files). For example, after 10 seconds 5% of that source code is touched, after 20 seconds 6%, etc. I have looked into PHPUnit and XDEBUG. I was able to generate a report with PHPUnit, but this only gives me information about how much source code was touched at the end. Does anyone know a tool that can give me periodically information on source code coverage of a PHP application or how to use XDEBUG to extract this kind of information?


text:
Q: Помогите пожалуйста с реализацией yii2 меню widget Вот html код менюшки:

 Home

 Services

 Blog

 Gallery

 Contact Us

К сожалению не сработали все стили ссылок, а вот и сам код:
<?php

NavBar::begin([

'brandUrl' => Yii::$app->homeUrl,

    'options' => [

    'class' => ' ',
    ],
]);
echo Nav::widget([

  'options' => ['class' => 'm_nav menu__list',

  'id' => ['m_nav_list'
  ],
 'items' => [

  ['label' => 'Home', 'url' => ['/site/index'],

   'options' => ['class' => 'm_nav_item active',

   'id' => ['m_nav_item_1'],

   'template' => '{label}',
 ],
 ['label' => 'Services', 'url' => ['/site/typography'],

  'options' => ['class' => 'm_nav_item',

  'id' => ['moble_nav_item_2'],

  'template' => '{label}',
  ],

 ['label' => 'Blog', 'url' => ['/site/blog'],

  'options' => ['class' => 'm_nav_item',

  'id' => ['moble_nav_item_3'],

  'template' => '{label}',
  ],

['label' => 'Gallery', 'url' => ['/site/gallery'],

  'options' => ['class' => 'm_nav_item',

  'id' => ['moble_nav_item_5'],

  'template' => '{label}',
  ],

['label' => 'Contact Us', 'url' => ['/site/contact'],

  'options' => ['class' => 'm_nav_item',

  'id' => ['moble_nav_item_6'],

  'template' => '{label}',
  ],

NavBar::end();
?>

А точнее не сработали 'template' => ...
Что я не так прописала?

A: Доброе утро.
Вы бы внимательней документацию читали бы.
Вот Вам пример, как надо оформить пункты меню в Nav. Привожу пример только одного пункта, остальные сделайте самостоятельно, по моему примеру.
NavBar::begin([
   'brandUrl' => Yii::$app->homeUrl,
   'options' => [
       'class' => ' ',
   ],
]);
echo Nav::widget([
'id' => 'm_nav_list',
'options' => ['class' => 'm_nav menu__list'],
'encodeLabels' => false,
'items' => [

    [
        'label' => "Home",
        'url' => ['/site/index'],
        'options' => [
            'class' => 'm_nav_item active',
            'id' => 'm_nav_item_1',
        ],
        'linkOptions' => [
            'class' => 'link link--kumya',
        ]
    ]
    /* следующие пункты меню... */
  ]
])

NavBar::end();


text:
Q: UI-Router AngularJs: Prevent calling parent state controller when transitioning to child state I have multiple nested views ui-view on my page with corresponding states to set templates in those views. When I transition to a child state, controller associated to each of its parent states gets called. I want to prevent this.
For example, if I transition to state root.question.mcq.menu, the controller associated with state root.question.mcq too gets called.
How can I prevent this so that only the controller associated with root.question.mcq.menu gets called.

A: It depends where you come from. Do you come from the parent or from a sibling of the target state the parent controller should not be initialized. But if you come from any other state the parent controller will be initialized. If this behavior is wrong for you then you probably have a design issue.


text:
Q: Article and Tags relationship in ASP.NET MVC I am trying to build an Article-Tags relationship model in ASP.NET MVC. there are Articles, which can have have multiple tags (eg: funny, fools, serious etc) describing the type of the article. I am thinking of two approaches to make this relationship:
1. Making a many-to-many relationship between Article and Tags.
public class Article
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Tag> Tags { get; set; }
}

public class Tag
{
    public byte Id { get; set; }
    public string Name { get; set; }

    public IList<Article> Articles { get; set; }
}

*Making enum of all tag names and including a List of tags in Article.
public enum Tag
{
    Funny = 1,
    Fools = 2,
    Cute = 3,
    Food = 4,
}

Can anyone suggest me the best approach between two approaches? or any other approach?
thanks is advance.

A: "Best" is a little subjective, but with the many-many table design you'll find it easier to do queries.  If you use a list of tags and decide you want to find a specific type of article, you'll have to parse the tags field first.  Not impossible to do that, but definitely less convenient than having the extra table.
It's also easier to create new tags on the fly if you just have to add a record to a table rather than recompile your software.


text:
Q: Why does CoreData Debug logging not work on my Mac app? I can't get Core Data debug logging working.
I've gone into the arguments tab of my executable in Xcode and added:
-com.apple.CoreData.SQLDebug 1
as per the documentation and this question. And yes, I am on the Mac not on the iPhone.
What I've Tried

*

*Different compilers (LLVM 1.5 and GCC 4.2)

*Have all debug symbols included

*Building i386 instead of x84_64 architectures

Download
My Xcode project: http://dl.dropbox.com/u/136780/TransientDurationUpdateTest1.zip
Another project I have shows the SQL debug logs fine. What on earth am I missing here?

A: Well, it doesn't help that I set the store type to XML. What a numpty. As soon as I changed it back to SQLite all logging resumed perfectly.


text:
Q: inserting special border to tikz mindmap Hi I would like to mark certain nodes of tikz-mindmap just an example is illustrated in the figure.
Thanks in advance
The minimal working code is here

\documentclass[]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{tikzpagenodes}
\usepackage{graphicx}
\usetikzlibrary{decorations.pathmorphing}
\usetikzlibrary{decorations.text}
\tikzset{>=latex}
\usetikzlibrary{mindmap,trees,shadows}
\usetikzlibrary{decorations.text}
\usetikzlibrary{shapes.multipart}
\usepgfplotslibrary{patchplots}
\pgfplotsset{compat=1.8}
\begin{document}
\definecolor{CIR}{RGB}{255,0,35}
\definecolor{PN}{RGB}{97,189,64}
\definecolor{CFO}{RGB}{92,219,101}
\definecolor{DCO}{RGB}{255,131,211}
\definecolor{AN}{RGB}{72,163,235}
\definecolor{IQ}{RGB}{234,193,137} %253,224,158
\definecolor{IQTx}{RGB}{255,173,45} %241,88,21
\definecolor{IQRx}{RGB}{216,182,145}
\definecolor{IQFs}{RGB}{252,221,153}%206,165,75
\definecolor{IQFi}{RGB}{252,218,23}
\definecolor{baige}{RGB}{226,230,156}
\usetikzlibrary{backgrounds}
\usetikzlibrary{calc}

\begin{figure}[H]
\begin{center}
\begin{tikzpicture}[very thick, scale=0.8,
 every node/.style={scale=0.8},
 decoration={start radius=1cm, end radius=.15cm,amplitude=2mm,angle=30},
 outer sep=1pt
  ]
  \path[mindmap,concept color=red,text=white]
    node[concept] {\bf Root}
    [clockwise from=0]
    child[concept color=IQ] {
      node[concept] {\textcolor{white}{\bf A}}
      [clockwise from=120]
      child [concept color=IQTx,text=white] { node[concept] {{\bf A1}} }
      child [concept color=IQRx,text=white] { node[concept] {{\bf A2} }  }
      child [concept color=IQFs,text=white] { node[concept] {{\bf A3} }  }
      child [concept color=IQFi,text=white]{ node[concept] {\bf A4} }
      }
        child[concept color=DCO, grow=75, level distance=4.5cm,text=white ] {node[concept] {\bf B} }
child[concept color=PN, grow=150,level distance=4.5cm,text=white] { node[concept] {\bf C} }
child[concept color=CFO, grow=215, level distance=4.5cm,text=white] { node[concept] {\bf D} }
child[concept color=AN, grow=290, level distance=4.5cm,text=white] { node[concept] {\bf E} };
\end{tikzpicture}
\caption{Mindmap Problem}
\label{fig:mindmap}
\end{center}
\end{figure}
\end{document}

Any help would be much appreciated.
Muhammad Ali

A: Next code shows a possibility. It consists in drawing a bigger mindmap on background layer. In this case it has been easy because you already used every node/.style={scale=0.8}, so changing it to scale=0.85 everything grown up. Concepts with border are drawn in black (or whatever color you prefer for border) and the other ones are drawn in white (or whatever color you use for your background).
I admit it's not the best solution, but it works.
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{mindmap,backgrounds}
\begin{document}
\definecolor{PN}{RGB}{97,189,64}
\definecolor{CFO}{RGB}{92,219,101}
\definecolor{DCO}{RGB}{255,131,211}
\definecolor{AN}{RGB}{72,163,235}
\definecolor{IQ}{RGB}{234,193,137}
\definecolor{IQTx}{RGB}{255,173,45}
\definecolor{IQRx}{RGB}{216,182,145}
\definecolor{IQFs}{RGB}{252,221,153}
\definecolor{IQFi}{RGB}{252,218,23}

\begin{tikzpicture}[very thick, scale=0.8,
 every node/.style={scale=0.8},
 outer sep=1pt
  ]
  \path[mindmap,concept color=red,text=white]
    node[concept] {\bf Root}
    [clockwise from=0]
    child[concept color=IQ] {
      node[concept] {\textcolor{white}{\bf A}}
      [clockwise from=120]
      child [concept color=IQTx,text=white] {node[concept] {{\bf A1}}}
      child [concept color=IQRx,text=white] {node[concept] {{\bf A2}}}
      child [concept color=IQFs,text=white] {node[concept] {{\bf A3}}}
      child [concept color=IQFi,text=white] {node[concept] {\bf A4}}
      }
    child [concept color=DCO, grow=75, level distance=4.5cm, text=white]
          {node[concept] {\bf B}}
    child [concept color=PN, grow=150, level distance=4.5cm, text=white]
          {node[concept] {\bf C}}
    child [concept color=CFO, grow=215, level distance=4.5cm, text=white]
          {node[concept] {\bf D}}
    child [concept color=AN, grow=290, level distance=4.5cm, text=white]
          {node[concept] {\bf E}};

\begin{scope}[on background layer, every node/.style={scale=.85}]
  \path[mindmap,concept color=black,text=black]
    node[concept] {\bf Root}
    [clockwise from=0]
    child[concept color=black] {
      node[concept] {\textcolor{white}{\bf A}}
      [clockwise from=120]
      child [concept color=black,text=black] {node[concept] {{\bf A1}}}
      child [concept color=black,text=black] {node[concept] {{\bf A2}}}
      child [concept color=white,text=white] {node[concept] {{\bf A3}}}
      child [concept color=black,text=black] {node[concept] {\bf A4}}
      }
      child [concept color=white, grow=75, level distance=4.5cm, text=white]
            {node[concept] {\bf B}}
      child [concept color=white, grow=150, level distance=4.5cm, text=white]
            {node[concept] {\bf C}}
      child [concept color=black, grow=215, level distance=4.5cm, text=black]
            {node[concept] {\bf D}}
      child [concept color=white, grow=290, level distance=4.5cm, text=white]
            {node[concept] {\bf E}};
\end{scope}
\end{tikzpicture}
\end{document}

Update:
A simpler solution consists in adding a general shadow (or a preaction) to highlighted concepts. I don't know how to apply it to concepts connections.
\documentclass[tikz,border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{mindmap,shadows}
\begin{document}
\definecolor{PN}{RGB}{97,189,64}
\definecolor{CFO}{RGB}{92,219,101}
\definecolor{DCO}{RGB}{255,131,211}
\definecolor{AN}{RGB}{72,163,235}
\definecolor{IQ}{RGB}{234,193,137}
\definecolor{IQTx}{RGB}{255,173,45}
\definecolor{IQRx}{RGB}{216,182,145}
\definecolor{IQFs}{RGB}{252,221,153}
\definecolor{IQFi}{RGB}{252,218,23}

\begin{tikzpicture}[very thick, scale=0.8,
 every concept/.style={scale=.8, font=\bfseries, text=white},
 marca/.append style={general shadow={fill=black,shadow scale=1.07}},
 outer sep=1pt,
  ]
  \path[mindmap,concept color=red]
    node[concept, marca] {\bf Root}
    [clockwise from=0]
    child[concept color=IQ] {
      node[concept, marca] {\bf A}
      [clockwise from=120]
        child [concept color=IQTx] {node[concept, marca] {A1}}
        child [concept color=IQRx] {node[concept, marca] {A2}}
        child [concept color=IQFs] {node[concept] {A3}}
        child [concept color=IQFi] {node[concept, marca] {A4}}}
    child [concept color=DCO, grow=75, level distance=4.5cm] {node[concept] {B}}
    child [concept color=PN, grow=150, level distance=4.5cm] {node[concept] {C}}
    child[concept color=CFO, grow=215, level distance=4.5cm] {node[concept, marca] {D}}
    child[concept color=AN, grow=290, level distance=4.5cm] {node[concept] {E}};
\end{tikzpicture}
\end{document}


text:
Q: How to add multiple "Set-Cookie" header in servlet response? As per RFC https://www.rfc-editor.org/rfc/rfc6265#page-7 It is allowed to have two headers with same key of "Set-Cookie". The example provided in RFC is -
Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly
Set-Cookie: lang=en-US; Path=/; Domain=example.com

How do I achieve same with Jetty(or any other servlet container)? When I call  httpServletResponse.addHeader this way-
httpServletResponse.addHeader("Set-Cookie", "SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
httpServletResponse.addHeader("Set-Cookie", "lang=en-US; Path=/; Domain=example.com");

I see that the second addHeader() doesn't add a new header. According to javadoc for this method-

Adds a response header with the given name and value. This method
allows response headers to have multiple values.

So it seems that multiple values of allowed but I am not sure how to go about having multiple "Set-Cookie" in servlet response.

A: Setting Cookies directly like that is a bit awkward, considering that the Servlet API has methods specifically for working with Cookies.
Anyway, tested on Jetty 9.3.0.v20150612 and it works as expected.
Example: SetCookieTest.java
package jetty;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SetCookieTest
{
    @SuppressWarnings("serial")
    public static class SetCookieAddHeaderServlet extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("text/plain");
            resp.addHeader("Set-Cookie","SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
            resp.addHeader("Set-Cookie","lang=en-US; Path=/; Domain=example.com");
            PrintWriter out = resp.getWriter();
            out.println("Hello From: " + this.getClass().getName());
        }
    }

    @SuppressWarnings("serial")
    public static class SetCookieAddCookieServlet extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("text/plain");

            // Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly
            Cookie sidCookie = new Cookie("SID","31d4d96e407aad42");
            sidCookie.setPath("/");
            sidCookie.setSecure(true);
            sidCookie.setHttpOnly(true);
            resp.addCookie(sidCookie);

            // Set-Cookie: lang=en-US; Path=/; Domain=example.com
            Cookie langCookie = new Cookie("lang","en-US");
            langCookie.setPath("/");
            langCookie.setDomain("example.com");
            resp.addCookie(langCookie);

            PrintWriter out = resp.getWriter();
            out.println("Hello From: " + this.getClass().getName());
        }
    }

    private static Server server;

    @BeforeClass
    public static void startServer() throws Exception
    {
        server = new Server(9090);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.addServlet(SetCookieAddHeaderServlet.class,"/test-add-header");
        context.addServlet(SetCookieAddCookieServlet.class,"/test-add-cookie");
        server.setHandler(context);
        server.start();
    }

    @AfterClass
    public static void stopServer() throws Exception
    {
        server.stop();
    }

    /**
     * Issue simple GET request, returning entire response (including payload)
     *
     * @param uri
     *            the URI to request
     * @return the response
     */
    private String issueSimpleHttpGetRequest(String path) throws IOException
    {
        StringBuilder req = new StringBuilder();
        req.append("GET ").append(path).append(" HTTP/1.1\r\n");
        req.append("Host: localhost\r\n");
        req.append("Connection: close\r\n");
        req.append("\r\n");

        // Connect
        try (Socket socket = new Socket("localhost",9090))
        {
            try (OutputStream out = socket.getOutputStream())
            {

                // Issue Request
                byte rawReq[] = req.toString().getBytes(StandardCharsets.UTF_8);
                out.write(rawReq);
                out.flush();

                // Read Response
                StringBuilder resp = new StringBuilder();
                try (InputStream stream = socket.getInputStream();
                        InputStreamReader reader = new InputStreamReader(stream);
                        BufferedReader buf = new BufferedReader(reader))
                {
                    String line;
                    while ((line = buf.readLine()) != null)
                    {
                        resp.append(line).append(System.lineSeparator());
                    }
                }

                // Return Response
                return resp.toString();
            }
        }
    }

    @Test
    public void testAddHeader() throws Exception
    {
        String response = issueSimpleHttpGetRequest("/test-add-header");
        System.out.println(response);
        assertThat("response", response, containsString("Set-Cookie: SID=31d"));
        assertThat("response", response, containsString("Set-Cookie: lang=en-US"));
    }

    @Test
    public void testAddCookie() throws Exception
    {
        String response = issueSimpleHttpGetRequest("/test-add-cookie");
        System.out.println(response);
        assertThat("response", response, containsString("Set-Cookie: SID=31d"));
        assertThat("response", response, containsString("Set-Cookie: lang=en-US"));
    }
}

Console Output
2015-06-25 14:18:19.186:INFO::main: Logging initialized @167ms
2015-06-25 14:18:19.241:INFO:oejs.Server:main: jetty-9.3.0.v20150612
2015-06-25 14:18:19.276:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@56cbfb61{/,null,AVAILABLE}
2015-06-25 14:18:19.288:INFO:oejs.ServerConnector:main: Started ServerConnector@1ef05443{HTTP/1.1,[http/1.1]}{0.0.0.0:9090}
2015-06-25 14:18:19.289:INFO:oejs.Server:main: Started @270ms
HTTP/1.1 200 OK
Date: Thu, 25 Jun 2015 21:18:19 GMT
Content-Type: text/plain;charset=iso-8859-1
Set-Cookie: SID=31d4d96e407aad42;Path=/;Secure;HttpOnly
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: lang=en-US;Path=/;Domain=example.com
Connection: close
Server: Jetty(9.3.0.v20150612)

Hello From: jetty.SetCookieTest$SetCookieAddCookieServlet

HTTP/1.1 200 OK
Date: Thu, 25 Jun 2015 21:18:19 GMT
Content-Type: text/plain;charset=iso-8859-1
Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly
Set-Cookie: lang=en-US; Path=/; Domain=example.com
Connection: close
Server: Jetty(9.3.0.v20150612)

Hello From: jetty.SetCookieTest$SetCookieAddHeaderServlet

2015-06-25 14:18:19.405:INFO:oejs.ServerConnector:main: Stopped ServerConnector@1ef05443{HTTP/1.1,[http/1.1]}{0.0.0.0:9090}
2015-06-25 14:18:19.407:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler@56cbfb61{/,null,UNAVAILABLE}

A: It's probably not the answer you're looking for but I just tried this myself and it worked right away:
Set-Cookie:SID=31d4d96e407aad42; Path=/; Secure; HttpOnly
Set-Cookie:lang=en-US; Path=/; Domain=example.com
Set-Cookie:JSESSIONID=76A68D96ED044DDFF0CC266810F52DDA; Path=/; HttpOnly

That's how the response looked like. Maybe it's the problem of your particular web container, or your implementation.
Try to debug the application (using remote debugging facility) to figure out where the header gets lost.


text:
Q: How to create an image from data received from scanner I receive data (NSData) from the scanner that looks something like this when logged with NSLog:
2014-04-07 10:42:07.309 Pantelegraph[488:303] <
4c9d8f4d 9f9849a2 9a4fa79f 46a8984d a9a346aa 9f53aea0 50ad884d aa9354b4
9251b291 54b18f54 b28e47b3 9254b396 49af8d4f b3834fb1 904fb488 59b7874f
b38a4cb2 8551b186 4ab78556 b4884cb1 894eb180 59b17d4e b37b57b2 754fb386
56b98453 b38449b1 794fb37b 49ae8852 b08253ac 8652af80 58b18552 b08850b2
8856b086 51b08a51 ad9656ad 8d4fb091 50ab934c ab9753af 9a4aae9a 54af9c53
ae9c49b0 a451afa5 4faba450 aea54eae aa4db0a3 57b0a24e aea34caf a74eafa2
49b09b51 afa448ae a152b0a1 51aca147 aea44db3 9851b0a3 4ab49d50 b09d49b3
924fb198 49af964e b29553b1 8e50b294 52b6874b b18d50b2 944eb48d 49b28a56
b3844aae 934fb485 53af884d b08356b0 814eac84 52b37754 b08650ae 7d57b081
57ae8752 ac8356a9 9150ae8a 52af7f52 ac8e51ac 8554ad8e 44ae9851 ad9c55af
9d54b095 56ae9a52 afa052ae a150aca4 51aba74c aaa34eac a453aea7 4bafa254
af9c4fac a150b29a 54aea652 af9d4db0 9e4eb195 4eaf9454 af974caf 884eb086
54a98750 ad8d51ad 8249ac85 51ab7750 ad7951ae 8453ab80 4cac8553 …
>

Now I think those are hexadecimal colors, pixel by pixel.
Together with this NSData object I also receive information like the width and height of the image.
My question is how can I create an image (NSImage, CGImageRef, etc…) from this data?  I used CGImageCreate but all I got from that is a lot of noise.
Edit
As requested in one of the comments her is the full data of an piece of paper (A8) I scanned with 6 colors on it.
Pastebin of the data and metadata.
At the bottom there is also the other information I received from the scanner.
I scanned the image in rgb with a bit depth of 8 bits and a resolution of 50ppi. Below is an image of the paper I scanned with another application:

When using this code to create a CGImageRef:
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, (__bridge const void *)([data dataBuffer]), [data dataSize], NULL);
    CGImageRef image = CGImageCreate([data fullImageWidth], [data fullImageHeight], [data bitsPerComponent], [data bitsPerPixel], [data bytesPerRow], CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrderDefault|kCGImageAlphaNone, provider, NULL, false, kCGRenderingIntentDefault);

I get a lot of noise that looks like this (for the image shown above) :

Edit
As suggested in one of the answers, the size of the data I get is the same as what the metadata says as seen in this picture:

A: I made a test bmp of 320*320px, added a Red, Green and Blue area.

Opened it in an text editor and removed meta data at the beginning.
When I used this code
NSString *imagePath = [[NSBundle mainBundle] pathForResource: @"test3" ofType: @"bmp"];

NSData *data = [NSData dataWithContentsOfFile:imagePath];
CGFloat width = 320.0;
CGFloat height = 320.0;

NSUInteger bitPerByte = 8;
NSUInteger bytePerColor = 3;
NSUInteger len = [data length];

Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
                                                          byteData,
                                                          width*height*bytePerColor,
                                                          NULL);

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;

CGImageRef imageRef = CGImageCreate(width,
                                    height,
                                    bitPerByte,
                                    bytePerColor*bitPerByte,
                                    bytePerColor*width,colorSpaceRef,
                                    bitmapInfo,
                                    provider,NULL,NO,0);

Red and Blue where switched

The data looking like this
<… 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000
ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff
0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00
00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000
ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff
0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00
00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000
ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff
0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ff0000ff 0000ff00 00ff0000 ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff …>

BTW: the groping of 8 bytes has nothing to do with the number of color components in the image. NSData doesn't know which data it contains. this is just the way it's description method displays the data.
One solution would be to create a BGR colorspace, but I did't have this option, as I decided to create an iOS app, as I am not very familiar with Mac Cocoa.
Instead I exchanged red and blue values manually
// on ios i cannot create a BGR colorspace, there for I swap red and blue values
for (NSUInteger i =2; i < len; i+=3) {
    Byte l = byteData[i-2];
    Byte r = byteData[i];
    byteData[i] = l;
    byteData[i-2] = r;
}

giving me following code
NSString *imagePath = [[NSBundle mainBundle] pathForResource: @"test3" ofType: @"bmp"];

NSData *data = [NSData dataWithContentsOfFile:imagePath];
CGFloat width = 320.0;
CGFloat height = 320.0;

NSUInteger bitPerByte = 8;
NSUInteger bytePerColor = 3;
NSUInteger len = [data length];

Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

// on ios i cannot create a BGR colorspace, there for I swap red and blue values
for (NSUInteger i =2; i < len; i+=3) {
    Byte l = byteData[i-2];
    Byte r = byteData[i];
    byteData[i] = l;
    byteData[i-2] = r;
}

CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
                                                          byteData,
                                                          width*height*bytePerColor,
                                                          NULL);

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;

CGImageRef imageRef = CGImageCreate(width,
                                    height,
                                    bitPerByte,
                                    bytePerColor*bitPerByte,
                                    bytePerColor*width,colorSpaceRef,
                                    bitmapInfo,
                                    provider,NULL,NO,0);

and this result:

So as you haven't provided a sample data set yet, you may have to adjust certain things, mainly bitPerByte and bytePerColor. you also have to check, if the scanner adds some meta data.

I don't know why, but that raw data array has exactly twice as much bytes as told by the metada, 89352 istead of 44676.
with this code
NSData *data = [NSData dataWithContentsOfFile:imagePath];
CGFloat width = 146.0;
CGFloat height = 102.0;

NSUInteger bitPerByte = 8;
NSUInteger bytePerColor = 2*3;
NSUInteger len = [data length];

Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
                                                          byteData,
                                                          width*height*bytePerColor,
                                                          NULL);

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGBitmapInfo bitmapInfo = kCGBitmapByteOrder16Big;

CGImageRef imageRef = CGImageCreate(width,
                                    height,
                                    bitPerByte * 2,
                                    bytePerColor*bitPerByte ,
                                    bytePerColor*width ,
                                    colorSpaceRef,
                                    bitmapInfo,
                                    provider,NULL,NO,0);

I am able to display

A: With the help of the above answer I managed to make it work, this is the code I used:
- (void)scannerDevice:(ICScannerDevice *)scanner didScanToBandData:(ICScannerBandData *)data {
    CGColorSpaceRef color = CGColorSpaceCreateDeviceGray();
    if ([data pixelDataType] == ICScannerPixelDataTypeRGB) color = CGColorSpaceCreateDeviceRGB();
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(CFDataCreate(NULL, [[data dataBuffer] bytes], [data dataSize]));
    CGImageRef image = CGImageCreate([data fullImageWidth], [data fullImageHeight], [data bitsPerComponent], [data bitsPerPixel], [data bytesPerRow], color, kCGBitmapByteOrderDefault|kCGImageAlphaNone, provider, NULL, false, kCGRenderingIntentDefault);

    NSImage *finImage = [[NSImage alloc] initWithCGImage:image size:NSMakeSize([data fullImageWidth], [data fullImageHeight])];
    CGImageRelease(image);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(color);
}

The problem was that I'm putting the NSData object straight into the data provider. This gives the data provider other data in your memory than the actual raw image data, so that's the noise in the picture.


text:
Q: Why does the tool offer to change the code - just because it can? Resharper (or is it Visual Studio - it's a yellow light bulb with a tiny red filament in it) offers to "invert if" on this code:
if (tItems >= 0)
{
    return tItems;
}
SetTotalItemsAndTotalAmt();

...and if I allow it to, it becomes this:
if (tItems < 0)
{
    SetTotalItemsAndTotalAmt();
}
return tItems;

...but then it offers to "invert if" again, and if I gullibly take the bait, it sets it back to its former glory.
If one way is considered better (more grokkable, I guess) than the other, why would it also allow a reverse inversion? And if it's a case of "six of one and half a dozen of the other," why does it even bother to offer a change?
UPDATE
Actually, come to think of it, one of those ways is not even valid, for it says, "WorkFiles.getAmount()': not all code paths return a value" unless it has the return statement outside the if condition.
My guess is this is not Resharper doing this; those Urquell-powered cats wouldn't do such a thing, methinks.

A: It's ReSharper that's offering this, and it offers it because it can.  There can be many good reasons to let it do so.  I frequently use this when refactoring code like:
if (cond1) {
   if (cond2) {
      if (cond3) {
         DoSomething();
      } else {
         throw "Error 3";
      }
   } else {
      throw "Error 2";
   }
} else {
   throw "Error 1";
}
return;

into:
if (!cond1) throw "Error 1";
if (!cond2) throw "Error 2";
if (!cond3) throw "Error 3";
DoSomething();
return;

It's especially useful when those ifs run on for several screens of code.  And yes, I see code like this often.


text:
Q: Create models after callback using ember-data ember I'd like to get my model from an api and passing my current position so I can get the 10 closest.
The server does the calculation and limits to 10 already.
What would be the best approach to load the data while passing the location params. knowing that I would like the application not waiting for the geolocation to starts displaying the interface. Then when geolocation is done inject the models.
What url scheme should I use?
Should I still use the rest adapter form ember-data or not?

A: Assuming location is a property of the model you want to load, and Place is the name of your model, have you tried something like this:
App.Place.find({location: "foo"});

This would issue a request in the form:
myhost.com/places?location=foo

Hope it helps.


text:
Q: React Native How to filter sectionlist data on the basis of id this is the get api of sectionlist data
const getAllMatches = async () => {
await fetch(APIS?.Matches, {
  method: 'GET',
  headers: {
    Authorization: user,
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
})
  .then(response => response.json())
  .then(({matches}) => {
    setAllMatches(matches);
  })
  .catch(error => {
    return console.error(error);
  });

};

A: just in your code when setting matches use:
setAllMatches(matches.filter((item,index)=>item.category=="fruits");
in this case we are putting matches with the category fruits, you can adjust accordingly


text:
Q: VBA to rearch email ID in another excel sheet I have a simple VBA code with search email ID in another excel sheet and provide cell address. I am getting error that

"Object variable or With block variable not set".

Here is my code so far:
Dim cell As Range
Set cell = ws0.Range("AA2:AA1048576").Find(email0, LookAt:=xlWhole)
MsgBox cell.Address

Updated code (from a comment below):
Dim myFileNameDir0 As String
Dim ws0 As Worksheet
Dim cell0 As Range
Dim email0 As String

email0 = ws4.Range("D" & 2)
myFileNameDir0 = TextBox1.Value
Workbooks.Open Filename:=myFileNameDir0, ReadOnly:=True, UpdateLinks:=0
Set ws0 = Worksheets(1)
ws0.Activate

Dim cell As Range
Set cell = ws0.Range("AA2:AA1048576").Find(email0, LookAt:=xlWhole)
MsgBox cell.Address

Any help welcome.

A: Looks like the problem might be in the worksheet identifier.
What happens if you change it to read;
Set cell =  sheets("NAME").Range("AA2:AA1048576").Find(email0, LookAt:=xlWhole)

Also, what is email0? Is it a variable or a string?
What have you dimmed email0 to be as, if it is a variable?