text:
Q: Is it possible to implement a shared state management for CLI applications without the need for an external database? I want to create a CLI application and I think this question is not about a specific technology but for the sake of reproduction purposes I'm using Node with command-line-commands ( but I know there are plenty others, e.g. commander ).
Given the following sample code
#!/usr/bin/env node

'use strict';

const commandLineArgs = require('command-line-args');
const commandLineCommands = require('command-line-commands');
const commandLineUsage = require('command-line-usage');

let isRunning = false; // global state

let commandResult;

try {
    commandResult = commandLineCommands([ 'start', 'info', 'help' ]);
} catch (error) {
    console.error('Invalid command.');
    process.exit(1);
}

if (commandResult.command === null || commandResult.command === 'help') {
    const commandInfo = commandLineUsage([
        { header: 'start', content: 'Sets the value to true' },
        { header: 'info', content: 'Gets the current value' },
    ]);

    console.log(commandInfo);
    process.exit(0);
}

let options;

try {
    options = commandLineArgs([], { argv: commandResult.argv });
} catch (error) {
    console.error('Invalid argument.');
    process.exit(1);
}

if (commandResult.command === 'start') {
    isRunning = true;
} else if (commandResult.command === 'info') {
    console.info({ isRunning });
}

The boolean isRunning indicates a shared state. Calling the start command sets its value to true. But calling the info command obviously starts a new process and prints a new variable isRunning with its initial falsy value.
What is the prefered technology to keep such state? Must the CLI use an external database ( e.g. local filesystem) or are there some ways to keep the information in memory until shutdown?
Generating my own file on the system and storing this variable to it feels like an overkill to me.

A: An old cross-platform hack is to open a known TCP port. The first process able to open the port will get the port. All other processes trying to open the port will get an EADDRINUSE error:
const net = require('net');

const s = net.createServer();

s.on('error',() => {
    console.log('Program is already running!');

    // handle what to do here
});

s.listen(5123,'127.0.0.1',() => {
    console.log('OK');

    // run your main function here
});

This works in any language on any OS. There is only one thing you need to be careful of - some other program may be accidentally using the port you are using.
I originally came across this technique on the Tcl wiki: https://wiki.tcl-lang.org/page/singleton+application.

A: One way would be to use a local web server.
index.js
const commandLineArgs = require('command-line-args');
const commandLineCommands = require('command-line-commands');
const commandLineUsage = require('command-line-usage');
var http = require('http');

let globalState = {
    isRunning: false
}

let commandResult;

try {
    commandResult = commandLineCommands([ 'start', 'info', 'help' ]);
} catch (error) {
    console.error('Invalid command.');
    process.exit(1);
}

if (commandResult.command === null || commandResult.command === 'help') {
    const commandInfo = commandLineUsage([
        { header: 'start', content: 'Sets the value to true' },
        { header: 'info', content: 'Gets the current value' },
    ]);

    console.log(commandInfo);
    process.exit(0);
}

let options;

try {
    options = commandLineArgs([], { argv: commandResult.argv });
} catch (error) {
    console.error('Invalid argument.');
    process.exit(1);
}

if (commandResult.command === 'start') {
    globalState.isRunning = true;
    http.createServer(function (req, res) {
        res.write(JSON.stringify(globalState));
        res.end();
    }).listen(9615);
} else if (commandResult.command === 'info') {
    console.info({ globalState });
}

index2.js
var http = require('http');

var req = http.request({ host: "localhost", port: 9615, path: "/" }, (response) => {
    var responseData = "";

    response.on("data", (chunk) => {
        responseData += chunk;
    });

    response.on("end", () => {
        console.log(JSON.parse(responseData));
    });
});

req.end();
req.on("error", (e) => {
    console.error(e);
});

Here the index.js is a program that holds the "shared / global state" as well as creates a web server to communicate with. Other programs such as index2.js here can make a http request and ask for the global state. You could also let other programs change the state by having index.js listen to some specific request and act accordingly.
This doesn't have to be done with http like this, you could also use something like node-rpc or node-ipc. I thought the easiest working example would be to do it with a local http client and server.
Either way, I think the word for what you are looking for is Inter Process Communication (IPC) or Remote Procedure Call (RPC). I don't see why one couldn't also utilize websockets as well. Child processes probably won't work here, even if you could implement some kind of parent-child process communication, because only the child processes spawned by the main process could use that.
EDIT
After reading your question more carefully, I think that this is just a matter of "keeping" the "console session" after start command and setting the isRunning variable.
Check this out:
const commandLineArgs = require('command-line-args');
const commandLineCommands = require('command-line-commands');
const commandLineUsage = require('command-line-usage');
const prompt = require('prompt-sync')();

let globalState = {
    isRunning: false
}

let commandResult;

try {
    commandResult = commandLineCommands([ 'start', 'info', 'help' ]);
} catch (error) {
    console.error('Invalid command.');
    process.exit(1);
}

if (commandResult.command === null || commandResult.command === 'help') {
    const commandInfo = commandLineUsage([
        { header: 'start', content: 'Sets the value to true' },
        { header: 'info', content: 'Gets the current value' },
    ]);

    console.log(commandInfo);
    process.exit(0);
}

let options;

try {
    options = commandLineArgs([], { argv: commandResult.argv });
} catch (error) {
    console.error('Invalid argument.');
    process.exit(1);
}

if (commandResult.command === 'start') {
    globalState.isRunning = true;

    while(globalState.isRunning)
    {
        let cmd = prompt(">");

        if(cmd === "exit")
            process.exit(0);
        if(cmd === "info")
            console.info({ globalState });
    }

} else if (commandResult.command === 'info') {
    console.info({ globalState });
}

Here I am using prompt-sync library inside a loop when the program is called with a start command. The "console session" is kept indefinitely until the user types exit. I also added and example for in case the user types info.
Example:

A: Another old hack for this is to try and create a symlink.
Creating symlinks are generally guaranteed to be atomic by most Unix and Unix-like OSes. Therefore there is no issue with potential race conditions using this technique (unlike creating a regular file). I presume it is also atomic on Windows (as per POSIX spec) but I'm not entirely sure:
const fs = require('fs');

const scriptName = process.argv[1];
const lockFile = '/tmp/my-program.lock';

try {
    fs.symlinkSync(lockFile, scriptName);

    // run your main function here

    fs.unlinkSync(lockFile);
}
catch (err) {
    console.log('Program already running');

    // handle what to do here
}

Note: While creating symlinks are atomic, other operations on symlinks are not guaranteed to be atomic. Specifically be very careful of assuming that updating a symlink is atomic - it is NOT. Updating symlinks involve two operations: deleting the link and then creating the link. A second process may execute its delete operation after your process creates a symlink causing two processes to think that they're the only ones running. In the example above we delete the link after creating it, not before.


text:
Q: Text is jumbled in custom cell I'm trying to read data from CoreData into a custom cell. This is just a test app before I try moving to the real app that I've been working on. The data is there - I can print it to the console and see it. For some reason, even with constraints, all of the data is laid on top of each other in the cell. Can anyone see what's going on with this?
I've created constraints to keep the cells where they should be, but when the data is loaded from my 'show data' button, the data is laid on top of each other.
Here is my custom cell class:

import UIKit

class CustomCellClass: UITableViewCell {

    @IBOutlet weak var txtNameLabel: UILabel!
    @IBOutlet weak var txtAgeLabel: UILabel!

}

Here is the ShowData class: (partial)

class ShowData: UIViewController, NSFetchedResultsControllerDelegate {

    @IBOutlet weak var personTableView: UITableView!

    let appDelegate = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    var personData = [Person]()

    // Read the data

    override func viewDidLoad() {
        super.viewDidLoad()
        personTableView.delegate = self
        personTableView.dataSource = self

        loadItems()
    }

  func loadItems() {
        let request : NSFetchRequest<Person> = Person.fetchRequest()
        do {
           personData = try appDelegate.fetch(request)
        } catch {
            print("couldn't load")
        }

    }

}

extension ShowData : UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personData.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "personNameAge", for: indexPath) as! CustomCellClass

        cell.txtNameLabel?.text = person.name
        cell.txtAgeLabel?.text = String(person.age)

        return cell

    }

Here is a screenshot of the tableview while running:

Edit:
I just deleted the app from the simulator and tried to rerun - now there isn't any data in the cells.

A: Just to clarify for other readers, as can be seen in your screenshot, the rows in your table are separated as expected but the different fields in each cell, what one might call the columns, are on top of one another.
You say that you have created constraints to keep the cells where they should be, I'm not sure what you mean by that.  What you need is constraints for the fields within each cell – what I call intra-cell constraints.  Either you have not added these constraints, or there is a mistake in them which causes all fields to be drawn at the left.
To show you what I mean, let's use the example of a little workout app of mine which has, in each table cell, from left to right, a Perform button, an Edit button, a Name field and a Duration field.  The screenshot below shows, in the big yellow box, the intra-cell constraints.  If you are using a storyboard, the problem with your app must be in that area.  If you are not using a storyboard, the problem must be in the equivalent code (or lack of it).

A: Just to let everyone know. The issue is resolved. I removed the table view cell from the project, readded, and readded the constraints. Everything is working now. I'm not sure where the problem was, but I noticed I had weird wrapping happening. I moved one of the labels to the other side of the cell and constrained it to the right side, and the other to the left side. When I ran the app, the text appeared to word wrap. I decided to delete the cell and readd and relink my outlets. It worked the first time...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Options -Indexes not working in .htaccess file in Docker container I have the following .htaccess file used in the web home of Apache2 in a Docker container:
# allows HTML files to be interpretted as PHP files
AddType application/x-httpd-php .html

# allows redirect to *.html files without using the extension
# e.g., http://example.com/foo will show http://example.com/foo.html
<IfModule mod_rewrite.c>
    Options All
    RewriteEngine   on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    #RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
    RewriteRule !.*\.html$ %{REQUEST_URI}.html [L]

# causes redirect from HTTP to HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>

Options -Indexes

# environament variables
SetEnv DBL "mysql:dbname=roars;host=foo;port=3306"
SetEnv DB_USER "bar"
SetEnv DB_PASS "glorp"

The Options -Indexes directive is not keeping us from being able to view directories. All of the other directives work properly and when I use this .htaccess file outside of a Docker container it works appropriately by disallowing the viewing of a directory.
Have I done something wrong, or is this particular to Docker containers?

A: I found the issue in the default configuration file for Apache2 in the Docker container:
<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    ServerName dev.f0o.com
    DocumentRoot /home/foo/src/www-server/

    #ErrorLog ${APACHE_LOG_DIR}/error.log
    #CustomLog ${APACHE_LOG_DIR}/access.log combined
    ErrorLog /var/log/apache2/error.log
    CustomLog /var/log/apache2/access.log combined

</VirtualHost>

<Directory /home/foo/src/www-server/>
    # allow .htaccess overrides to work
    AllowOverride All
    DirectoryIndex login.html index.html index.php
</Directory>

# this matches a link to any device directory to the physical webui directory
#AliasMatch ^/projects/([-\w]*)/css/(.*)$ /home/foo/src/www-server/static/css/$2
#AliasMatch ^/projects/([-\w]*)/fonts/(.*)$ /home/foo/src/www-server/static/fonts/$2
#AliasMatch ^/projects/([-\w]*)/images/(.*)$ /home/foo/src/www-server/static/images/$2
#AliasMatch ^/projects/([-\w]*)/lib/(.*)$ /home/foo/src/www-server/static/lib/$2
#AliasMatch ^/projects/([-\w]*)/scripts/(.*)$ /home/foo/src/www-server/static/scripts/$2

AliasMatch ^/projects/([-\w]*)/(.*)$ /home/foo/src/www-server/client/$2

<Directory /home/foo/src/www-server/client>
    DirectoryIndex home.html
    Options All
    AllowOverride All
    Require all granted
</Directory>

Solution 1 - The issue was first noticed in /home/foo/src/www-server/client which has its own specific set of overrides at the end of the default configuration file. the directory listing was allowed because Options is set to All. Changing it to Options -Indexes fixed the issue.

Solution 2 - As an experiment I commented out the line starting with Options and the results were what I wanted, likely because the .htaccess file was allowed to perform its job without conflict from the default configuration file.

Because I am not, typically, a person who configures web servers I am sure there might be better ways to solve the issue given the set of known's we have now. Those with more expertise in Apache web server configuration may have more elegant solutions.


text:
Q: Modifying Mac OS terminal colours does not work. Possibly due to bash_profile modifications of anaconda? I am on Mac OS. There are all sorts of tutorials to modify the terminal font with colours, etc., to make it more readable. I followed this one here in trying to enable colours for the ls command, but I failed. I copy pasted the extra lines into the .bash_profile, but it did not have an effect, even after closing and opening terminal again.
First of all: Is there an easier way, other than modifying the .bash_profile? For example, in the terminal preferences I checked the hook at Display ANSI-colors, but it did not seem to have an effect either.
If not, then: This is just a suspicion, but I suspect it might have something to do with my anaconda installation, which added some lines to the .bash_profile. (Another user experiencing a similar issue has posted here.) Since my anaconda installation my temrinal prompt also looks a bit different:
(base) <username>@macbook ~ %

It has now that (base) added in front, and I think the ending ~ % was also different before.
Anyway, the content of my .bash_profile (without the extra lines for colouring the ls output) is:
# added by Anaconda3 2019.10 installer
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/Users/<username>/opt/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
    \eval "$__conda_setup"
else
    if [ -f "/Users/<username>/opt/anaconda3/etc/profile.d/conda.sh" ]; then
# . "/Users/<username>/opt/anaconda3/etc/profile.d/conda.sh"  # commented out by conda initialize
        CONDA_CHANGEPS1=false conda activate base
    else
        \export PATH="/Users/<username>/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda init <<<

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/<username>/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/Users/<username>/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/Users/<username>/opt/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/Users/<username>/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

I am unfortunately not well read enough in bash to realise what is going on here

A: you can try to follow this:
https://www.cyberciti.biz/faq/apple-mac-osx-terminal-color-ls-output-option/
instead of using .bash_profile, or similar, try to change the
~/.zshrc
Greetings!


text:
Q: Is there a canonical book on x86 assembly? There are lots of books on assembly. However, they usually deal with ISAs about which I don't care, such as MIPS or ARM. I don't deal with these architectures; there's no reason for me to try to learn them.
But x86 assembly books seem... nonexistent.
Let's say for example I'm trying to build a toy compiler generating Windows Portable Executable files.
Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on x86 assembly? What about that book makes it special?

A: The Art of Assembly Programming is an excellent resource that has quite a bit about x86 programming.
x64 ABI documentation is also useful. I was trying to find a link to the version that was on AMDs website, but I can't seem to find it anymore, so I guess this one will have to do.
Something that can help quite [a bit] while learning is, instead of trying to write a complete app from scratch in assembly, instead write most of it in C (or any other compiled language really) and then call a chunk of assembly code from that. Once you've done that, reverse it, write an assembly program, and call some C functions from that.
Edit: Fixed a typo.

A: A very good book for learning x86 Assembly is Pentium Processor Optimization Tools.  While the book's main focus is the optimization of assembly code, it teaches Pentium assembly along the way, and is a good reference book as well.
It is long out of print but is not hard to find used.
It comes with a floppy disk containing an "assembly code optimizer".  It does not actually optimize your code, but instead produces a commented listing that points out where inefficiencies such as pipeline stalls lie.
The tool that comes with a book is a limited version of a more featureful product that the author's company used to sell, but for reasons I am unfamiliar with they are long out of business.  I don't know why - I would think such a tool would sell like hotcakes.
x86 in general is a very complex topic as there are many variants that are supported by different models of microprocessors.  Once you know the basics you will want to consult Intel's or AMD's databooks for the precise chip you are targeting.  Unfortunately code that runs fast on one model of CPU may not be as fast on a different chip.

A: I used Assembly Language for x86 Processors as a textbook when I was in college and found it very easy to understand. I have the older fourth edition and compared it to the sixth edition and didn't notice much change, so you could probably pick up an older copy cheap. People complain about his use of his own library for I/O, but he tells you how to do it the "hard" way in latter chapters.

A: The obvious place to go is Intel's website, where you can find programming and reference manuals for download that contain everything there is to know about the x86 architecture.
Here: Intel® 64 and IA-32 Architectures Software Developer's Manuals

A: Why not try the wikibook - http://en.wikibooks.org/wiki/X86_Assembly.  It gives a good introductory start to assembly language.
The hard bit about assembly is realising how simple it is, and that you need to stay with that simplicity.


text:
Q: STL-compliant memory allocator library I need to use a map, with keys as uint32_t and values as Meshes. I want the meshes to be layed out in contigous memory for performance, as they will be accessed very often in succession.
I am wondering what memory-allocator libraries are available that provides the following aswell;

*

*Allocates to contigous memory space

*Preferably handles fragmentation of said memory space

*As fast as possible and as little additional features as possible besides what I mentioned

I've looked at boost, but it dosn't seem to provide what I'm looking for.
(Reason I'm not using vector is that the container will grow and shrink alot, and I prefer to have a uint32_t as the identifier for a mesh)
Thanks

A: Deque
http://www.cplusplus.com/reference/deque/deque/
Nothing else much to say.  Go read about it.


text:
Q: Injecting third party classes without creating factories Lets say I have the following code in C#:
public class AppleTree
{
   public AppleTree()
   {
   }

   public string GetApple
   {
      return new Fruit("Apple").ToString();
   }
}

where Fruit is a third party class that does not have an interface.
I want to create a unit test for the AppleTree class but I do not want to run the Fruit class. Instead I would like to inject the Fruit class so that I can mock it in the tests.
How should I go about doing this? I can create a factory that creates apples and then add an interface to this factory like:
public class FruitFactory : IFruitFactory
{
   Fruit CreateApple()
   {
      return new Fruit("Apple");
   }
}

Now I can inject IFruitFactory into the AppleTree and use the CreateApple instead of new Fruit as:
public class AppleTree
{
   private readonly IFruitFactory _fruitFactory;

   public AppleTree(IFruitFactory fruitFactory)
   {
      _fruitFactory = fruitFactory
   }

   public string GetApple
   {
      return  _fruitFactory.CreateApple().ToString();
   }
}

Now to my question: Is there a good way of doing this without having to create the factory? Can I for example use a dependency injector famework like Ninject in some way?

A: You can mock out implemented types. The product that I know of that does this pretty well is Typemock. Microsoft has a product called Moles but I haven't met anyone who actually uses it. I don't have a lot of input into it's usefulness.
You can also register COM interfaces with the runtime to intercept object creation to inject your own. That's how these products work. These are the least amount of code change to get where you want.
Long term I would lean towards abstracting Fruit out with factories or the like. But tools like Typemock or Moles will get you there faster in the short term. It will just be less friction moving forward if everything is behind an interface.

A: Maybe, most simple, implement your own abstract FruitBase class, with virtual methods/properties. Then make implementation that wraps real Fruit class - FruitWrapper. Same logic as HttpContextBase, HttpContextWrapper and HttpContext in System.Web.
Then you can easily mock everything without any vendor-specific dark-magic testing framework.
public class AppleTree
{
    private readonly Func<FruitBase> _constructor;
    public AppleTree(Func<FruitBase> constructor)
    {
        _constructor = constructor;
    }

    public string GetApple()
    {
        return new _constructor().ToString();
    }
}

And you can swap functions in constructor: () => new FruitMock() and () => new Fruit("Apple").

A: Rather than the factory you would typically have Fruit implement an IFruit interface and inject that instead:
public class AppleTree
{
    private readonly IFruit _apple;

    public AppleTree(IFruit apple)
    {
        _apple = apple;
    }

    public string GetApple()
    {
        return _apple.ToString();
    }
}

With this kind of implementation you can instantiate either:

*

*new AppleTree(new Fruit("Apple")) or you could have an IoC container like NInject or StructureMap do it for you

*new AppleTree(mockApple) where mockApple is a mock IFruit object you've created for unit testing

A: If you couldn't program to IFruit interface, then I think Abstract Factory is the way to go.
As to unit testing, if you are using Visual Studio 2012, you may try Microsoft Fakes. The following code is just for fun (it works of course). Maybe it's overkill for your case.
using Microsoft.QualityTools.Testing.Fakes;
using MyLib;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            using (ShimsContext.Create())
            {
                MyLib.Fakes.ShimFruit.ConstructorString = delegate(Fruit f, string s)
                {
                    var shimFruit = new MyLib.Fakes.ShimFruit(f);
                    shimFruit.ToString = () =>
                    {
                        return "Orange";
                    };
                };
                AppleTree tree = new AppleTree();
                string expected = "Orange";
                Assert.AreEqual(expected, tree.GetApple());
            }
        }
    }
}

A: See Ninject.Extensions.Factory - with it, you have Func<T> ctor  arguments and the Abstract Factory is generated behind the scenes (a la @Nenad's +1'd answer)
(You can also define an Abstract Factory interface and have Ninject.Extensions.Factory implement it.


text:
Q: Safe to use Single KieSession instance in multithreading environment? I and creating a rule engine with the help of drools. What I have done till now is that on server boot I have created singleton instance of KieSession using the drl file. I want to use this same instance for multiple rule evaluation in multithreaded  environment.
So what I am doing is that, after my fact is ready I will insert the fact in kieSession, Fire rules and post that I will delete the fact from the kieSession.
ExamplePojo examplePojo = new ExamplePojo();
FactHandle insertedFact = kieSession.insert(examplePojo);
kieSession.fireAllRules();
kieSession.delete(insertedFact);

As per the KieSession.delete JavaDoc -
Retracts the fact for which the given FactHandle was assigned regardless if it has been explicitly or logically inserted.

Things I know -

*

*In multithreaded scenario kieSession.fireAllRules() can be called multiple times even when the fact from other thread is still in working memory

*I have tested that calling kieSession.fireAllRules() multiple times does not execute rules again on the already inserted facts if there are no explicit changes in rules in between the two fires

*kieSession.delete(insertedFact) is compulsory from memory leak point of view

*At any point of time there can be facts from multiple threads in the working memory at the same time

Questions I have -

*

*Will this scenario can cause malfunctioning in rule execution through some execution interference?

*Can this cause any sort if memory leaks the way I am using it?

Experts your advises are welcome. I am new to Drools and not aware of such use cases.


text:
Q: Can we disallow the use of "belongs-on-xxxxxxx" and "not-programming-related" tags? With the new migration features I believe the tags:

*

*belongs-on-serverfault

*belongs-on-superuser

*belongs-on-meta

*belongs-on-stackoverflow

*not-programming-related
are no longer necessary. All they do is add useless clutter to the tagging system. We know a question belongs on superuser.com because it was migrated there. Let the close system handle this.
I used to believe these tags were necessary for those with less reputation to "alert" those with enough rep to close, but there are enough with close privileges to handle this now.

A: If you see a question with one of these newly-added, remove it, and flag the question for moderator review. Then leave a comment noting that the use of the flag feature is more useful.
Exception: if the question author added the tag themselves, then they will be unable to flag the question. Instead, also post a link to this question.

A: Add another to the list, namely, [not-a-question].
This one in particular smacks of rudeness and is extremely unhelpful.
If the question is not a valid question, then it should be flagged or at least a comment left to try and get the asker to reword and fix up their question. The tagging system should not be manhandled and rogered like this.
If they have enough rep to edit the tags, then they have enough rep to leave a comment pointing out that it is in need of serious rewording. Or, shiver their timbers, flag the question as invalid.
As it stands now, there are 67 questions abuse-tagged with this in particular. That means someone has won a Taxonimist badge for being a jerk on the back of this.

A: I previously suggested a Tagging Black List here to manage this. I have now added a bounty to get a better idea of the viability of the idea.


text:
Q: how to import with full database with split export files My client uses the following script to take backup with export datapump:
expdp system/******** logfile=exp_pdco1mob00_full_12232013.txt directory=ABC
 dumpfile=exp_pdco1mob00_full_1_12232013.dmp,exp_pdco1mob00_full_2_12232013.dmp,exp_pdco1mob00_full_3_12232013.dmp,exp_pdco1mob00_full_4_12232013.dmp
full=y exclude=statistics filesize=5g

They give me backup and I have to import full backup on a new machine to debug the error. Can anyone help me how to import full database with impdp?
Thanks in advance

A: The export was taken using datapump and has been split into 4 files, each file is 5GB or less.

To perform the import on the new machine you will have to do the following:

*

*Copy the files to the target machine.

*Since the export is done using datapump, you will need to create a directory on the database.

Create directory statement, replace PATH with the location of copied files
SQL> Create or Replace Directory ABC as 'PATH';

*

*Use the below command to import the full backup/dump.
As the dump files are made split, you will have to specify all files under dumpfile parameter

Import command
IMPDP directory=ABC dumpfile=exp_pdco1mob00_full_1_12232013.dmp,
exp_pdco1mob00_full_2_12232013.dmp,
exp_pdco1mob00_full_3_12232013.dmp,
exp_pdco1mob00_full_4_12232013.dmp
logfile=IMPORT_DUMP full=y


text:
Q: magento jQuery click not working in Firefox & IE I have added custom js in page.xml file.
<action method="addItem">
    <type>skin_js</type>
    <name>js/custom_function.js</name>
    <params/>
</action>

that js contain code for click:
jQuery(".search_img").click(function () {
    var d = jQuery("#search").css("display");
    var value = jQuery("#search").val();
    if (d == "none") {
        jQuery("#search").show();
    }

    if (d == "block") {
        if (value == "") {
            jQuery("#search").hide();
        }
    }
});

Its working in Chrome and Safari but not working in FF & IE.

A: try this before apply this you have add jquery file  and then write your code in .ready()
$(document).ready(function(){
    jQuery(".search_img").on("click",function(e){
    e.preventDefault();
    var d=jQuery("#search").css("display");
    var value=jQuery("#search").val();
    if(jQuery("#search").is(":hidden"))
    {
    jQuery("#search").show();
    }
    else
    {
        if(value=="")
        {
        jQuery("#search").hide();
        }
    }

    });
});


text:
Q: hiding INC directories from cpan, so as to install ALL dependencies of a module in a directory I come across requirements to package a perl module with all its dependent modules, for systems where one cannot run cpan install (internet connectivity issues on production).
However, from the linux system i can do cpan install, already have these modules installed. Is there a way i can mask the @INC directories from cpan command, and provide just one directory to look for all perl modules, so that it downloads all dependencies into that local directory.
Thanks in advance!!

A: Take a look at lib::core::only and local::lib - the first excludes all non-core paths from @INC, the second makes it easy to set up a local perl module directory.
The combination should solve the problem.


text:
Q: Fatal error: Maximum execution time of 30 seconds exceeded on line 64 What i am trying to do is style a text retrieven from sql. But when i try to preview it i get *Fatal error: Maximum execution time of 30 seconds exceeded on line 64 *. I tryed puting ini_set('max_execution_time', 300); but still same problem. here is the code:
    <?php
ini_set('max_execution_time', 300);
        $info="
Τεχνικά Χαρακτηριστικά
";
        $sql_1 = mysql_query("SELECT * FROM info WHERE parent = '$id'")or trigger_error(mysql_error());
        $counter = mysql_num_rows($sql_1);
        if($counter > 0){
            while ($row_1 = mysql_fetch_array($sql_1)){
                $temp = $row_1['add_info'] ."
";
                $temp = str_split($temp);
                for($i=0; $i <= sizeof($temp); $i++){
                    if($temp[$i] == ":"){
                            break;
                    }
                }
                $temp_1="";
                for($w=0; $w < sizeof($temp); $w++){
                    if($w < $i+1){
                        $temp_1 .= $temp[$w];
                    }else if($w = $i+1){
                        $temp_1 .="";
                    }else{//this is line 64
                        $temp_1 .= $temp[$w];
                    }
                }
                $info .= $temp_1 . "
";
            }
        }
?>

A: You are probably entering an infinite loop with line }else if($w = $i+1){, change that to }else if($w == $i+1){ or }else if($w === $i+1){.


text:
Q: What is purpose of type on the constructor side of Java collection creation? What is purpose of re-specifying the type on the right / constructor side of a Java Collection declaration + instantiation?
For example, how is
List<MyClass> a = new ArrayList<MyClass>();

different / better / worse than
List<MyClass> a = new ArrayList<>();

My understanding is the the second form became legal in Java 7, but I still see a lot of examples in Java 7 and 8 where the first form is used.

A: It is not worse or different. It is the same.
A new and easy way introduced by compiler to reduce human effort of defining of type.


text:
Q: Set Up C++ project with Atom I'm trying set up cpp project with Atom. My project (Picture below). My code (Snippets below). I get error undefined reference to hashCustom::Hash(std::__cxx11::basic_string, std::allocator >)
collect2: error: ld returned 1 exit status. I did everything from tutorial, in one difference, that tutor used Visual Studio, but it doesn't support Linux. How I can rid error?
hash.h
#include <iostream>
#include <string>
using namespace std;

#ifndef HASH_H
#define HASH_H

class hashCustom {
  public:
  int Hash(string key);
};

#endif

hash.cpp
#include <iostream>
#include <string>
#include "../Header Files/hash.h"
using namespace std;

int hashCustom::Hash(string key) {
  int index;
  index = key.length();
  return index;
}

main.cpp
#include <iostream>
#include <string>
#include "../Header Files/hash.h"
using namespace std;

int main() {

  hashCustom hashObj;
  cout << hashObj.Hash("Number") << endl;
  return 0;
}

A: From the error message you posted, it seems that the linker can't resolve that symbol. You should compile both main.cpp and hash.cpp together, with a command like (using gcc):
$ g++ -o test main.cpp hash.cpp

Working example: https://wandbox.org/permlink/PIK8kF4eINcLjEYc
Otherwise, you get the same error: https://wandbox.org/permlink/K8nmaUmJZhlS8Wml


text:
Q: Question concerning -ing ending in a sentence. I am trying to understand why there is an -ing ending in amazing when used in a sentence like, "different countries have proven equally amazing".
Is it because amaze is a present participle verb or is it functioning as an adjective and the adverb is modifying the adjective?
Any help is appreciated.

A: When you inflect a verb so as to make it a participle you are turning it into an adjective—that is what a participle essentially is. Sometimes participles even come to be used as nouns (as many adjectives do), and even come full circle to wind up as verbs again, and those verbs in turn get to have participles of their own, like parenting. It's the functional-shift Circle of Life.


text:
Q: detect extra attributes in frombody post payload I'm looking for a way to detect extra attributes delivered on a WebAPI post payload that do not match the POCO I expect.  For example, here's an input object:
public class Input
{
    public string Name { get; set; }
}

And a controller method:
public void Post([FromBody]Input value)

If a client sends the following post payload:
{
    "Name" : "Foo",
    "Description" : "Bar"
}

This will trigger the Post method on my controller and Name will be populated.  I'd like to be aware that Description was sent but ignored, so I can either log that event server side or inform the client through a response header that they're sending extra data.

A: I think this is possible but you'd have to go without Model Binding and use reflection if you want a general solution:
Class:
public class Input
{
    public string Name { get; set; }
}

Payload:
{
    "Name" : "Foo",
    "Description" : "Bar"
}

Controller Method:
public async void Post()
{
    //Read the content to a string
    var content = await Request.Content.ReadAsStringAsync();

    //Get the Input object you wanted
    var input = JsonConvert.DeserializeObject<Input>(content);

    //Get a Dictionary containing all the content sent
    var allContent = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);

    //Get the property names of the wanted object
    var props = input.GetType().GetProperties().Select(a => a.Name);

    //See which properties are extra
    var extraContent = allContent.Keys.Except(props);
}

For the above example extraContent would be a list containing "Description". If you want the value just use the dictionary object.


text:
Q: trying to get this jquery code working in my rails app, function not being called I have some code which works fine as a html and js document. The function in the js script file is called correctly from the html doc. But when I transfer the same code to my rails, the function isn't called. If anyone could offer some advice, that would be great.
I have //= require autocomplete in my application.js file and I'm not getting any errors in my console. The page I yield to from application.html.erb is:

remote data

Cities worldwide

After you enter at least three characters the autocomplete function will show all possible matches.

I see 'test1' in console but 'test2' doesn't appear. And neither do test3 and test4, from autocomplete.js. My autocomplete.js is:
function initialize_autocomplete() {
    console.log("test3");
    $( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
        console.log("test4");
        var $ul = $( this ),
            $input = $( data.input ),
            value = $input.val(),
            html = "";
        $ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "

" );
            $ul.listview( "refresh" );
            $.ajax({
                url: "http://gd.geobytes.com/AutoCompleteCity",
                dataType: "jsonp",
                crossDomain: true,
                data: {
                    q: $input.val()
                }
            })
            .then( function ( response ) {
                $.each( response, function ( i, val ) {
                    html += "
" + val + "
";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
            });
        }
    });
}

Thanks for any help.

A: In my application.html.erb the order was:

  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>

I changed this to:
  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>

and now it works. Is that normal behaviour? I've been reading a bit about javascript_include_tag but if someone could put it in layman's terms I'd be grateful.

A: Try to wrap your code with:
   $(document).ready(function () {
     // your functions defined here
    });


text:
Q: Conditional Probability on the Intersection Property I know the next formula:
$P\left(A\cap B \cap C \right)=P\left( A\right) P\left( B\mid A\right) P\left(C\mid B\cap A\right)   $
How could we define the next probabilities?
a) $P\left( A\cap B\mid C\right) $
b) $P\left( A\mid B\cap C\right) $
Thank you this would help me a lot.

A: Sorry, just figured my own question:
$P\left( A\cap B|C\right) = \dfrac{P\left(A\cap B \cap C \right)}{P\left( C\right) }$
$P\left( A|B\cap C\right) = \dfrac{P\left(A\cap B \cap C \right)}{P\left( B\cap C\right) }$


text:
Q: log() from .utils output location I'm using/editing a module that uses a log() function from utils imported using:
from .utils import log

and then used as
    if settings.use_cache:
    if response_json is None:
        log('Saved nothing to cache because response_json is None')

in the utils docs, .log() is there as a method
 classmethod log(lvl, msg, *args, **kwargs)

Log 'msg % args' with the integer severity 'level' on the root logger

but isn't it being used as a function here?
my questions are, where is the documentation I'm looking for, and how can I read all of the output to log after I've executed some code?

A: Found that the package had a utils.py file that defined log() which was why the docs for python_utils.log() wasn't matching the usage/behavior I saw in the code.
I think I could have known this because log() was imported from .utils not utils where the period indicates a local file


text:
Q: Open API Maven Plugin: how to generate code for File upload I'm unable to generate an open api generated Feign client for File upload.
This is a snippet of the open api requestBodies component I'm trying to use to upload an array of files
requestBodies:
    FilesRequestBody:
      description: Array of files
      content:
        multipart/form-data:
          schema:
            type: object
            properties:
              files:
                type: array
                items:
                  type: file

my pom file contains the following plugin settings
                <groupId>org.openapitools</groupId>
                <artifactId>openapi-generator-maven-plugin</artifactId>
                <version>4.2.3</version>
                <executions>
                    <execution>
                        <id>generate-feign-client</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <inputSpec>${project.build.directory}/contract/api.yaml</inputSpec>
                            <language>java</language>
                            <output>${project.build.directory}/generated-sources</output>
                            <library>feign</library>
                            <typeMappings>
                                <mapping>file=File</mapping>
                            </typeMappings>
                        </configuration>
                    </execution>

notice the typeMappings configuration - which doesn't work.
Ideally I'd like a generated Feign client which looks something like..
import feign.Param;
import feign.RequestLine;

import java.io.File;

public interface ImagesApi {

    @RequestLine("POST /api/images")
    @Headers({
            "Content-Type: multipart/form-data",
            "Accept: application/json"
    })
    List<Image> uploadImages(@Param("config") List<File> files);

}

However, this is generated, which obviously doesn't compile
    @RequestLine("POST /api/images")
    @Headers({
        "Content-Type: multipart/form-data",
        "Accept: application/json",
    })
    List<Image> uploadImages(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE);

any ideas how I can make the maven plugin use a Java Type like java.io.File ?

A: The issue has been fixed in OpenAPI Generator v6.0.0 release: https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.0.0. Please give it a try.

A: Seems like there is be a bug in the openapi generator. It can't handle
     $ref '#/components/requestBodies/FilesRequestBody'

So to make it work, don't use a components reference.. inline the request body
  /api/images:
    post:
      tags:
        - image
      summary: uploadImage
      operationId: uploadImage
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file_list:
                  type: array
                  items:
                    type: string
                    format: binary
      responses:
        "201":
          $ref: '#/components/responses/ImagesResponse'
        default:
          $ref: '#/components/responses/ErrorResponse'


text:
Q: python - cProfile not running I was trying to run a performance test of my code using cProfile, but sadly no matter how I tried cProfile refused to function properly.
Here's what I did:
import cProfile
cProfile.run('addNum()')  # addNum() is a very simple function that adds a bunch of
                          # numbers into a dictionary

and here's what I got:
Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Python27\Lib\cProfile.py", line 36, in run
result = prof.print_stats(sort)
File "C:\Python27\Lib\cProfile.py", line 81, in print_stats
pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
File "C:\Python27\Lib\pstats.py", line 81, in __init__
self.init(arg)
File "C:\Python27\Lib\pstats.py", line 95, in init
self.load_stats(arg)
File "C:\Python27\Lib\pstats.py", line 124, in load_stats
self.__class__, arg)
TypeError: Cannot create or construct a <class pstats.Stats at 0x01AE9CA8> object from '<cProfile.Profile object at 0x01ACC470>''

Can someone help me debug this, and hopefully provide a solution?
I'm running Python 2.7.3 on Wing IDE 101 ver4.1.
Thank you!!!

A: This seems like a problem with the pStats module and not the cProfile.
can you try doing
import pstats

If this says cannot import pstats, then try installing the python-profiler again. It comes with python itself but that might be messed up in your case IF pstats is not there.
It's a simple apt-get on linux, so I am assuming windows would have a separate binary for python-profiler too.
Hope this helps!

A: I've had the same problem with Python 3.5.2 today:
What ended up working was replacing the call which I want to profile like this, then running the whole program:
import cProfile
# myObject.myFunc()
cProfile.runctx('myObject.myFunc()', globals(), locals(), 'myFunc.stat')

Finally, in an interactive python3 running separately, I did:
>>> import pstats
>>> p = pstats.Stats('myFunc.stat')
>>> p.strip_dirs().sort_stats(-1).print_stats()
Wed Feb 20 17:10:05 2019    myFunc.stat

         10218759 function calls (3916491 primitive calls) in 16.519 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   16.519   16.519 <string>:1(<module>)
   ... the really useful stats followed here ...

The cProfile.runctx(...), globals(), locals() were necessary to fix a NameError I ran into; the TypeError which you asked about was fixed by specifying a file name to store the stats into, which is also available via the normal cProfile.run(...)


text:
Q: Read .tar.gz file in R I have compressed file like  cat.txt.tar.gz, I just need to load into R and process as follows

zip <-("cat.txt.tar.gz")
data <- read.delim(file=(untar(zip,"cat.txt")),sep="\t")

but "data" is empty while running the code.Is there any way to read a file from .tar.gz

A: Are you sure your file is named correctly?
Usually compressed files are named cat.tar.gz, excluding the .txt.
Second, try the following code:
tarfile <- "cat.txt.tar.gz" # Or "cat.tar.gz" if that is right
data <- read.delim(file = untar(tarfile,compressed="gzip"),sep="\t")

If this doesn't work, you might need to extract the file first, and then read the extracted file.

A: To read in a particular csv or txt within a gz archive without having to UNZIP it first one can use library(archive) :
library(archive)
library(readr)
read_csv(archive_read("cat.txt.tar.gz", file = 1), col_types = cols(), sep="\t")

should work.


text:
Q: Implement this java-script in joomla 3 (Uncaught TypeError: undefined is not a function (anonymous function) I found this great piece of code here on stackoverflow and this could be my long searched solution but I can`t get it to run on my joomla 3.
Java-Script:
$('#showVideo').click(function() {
$('#video').show().html('<iframe src="http://player.vimeo.com/video/48459576?title=0&byline=0&portrait=0&color=d01e2f&autoplay=1" width="400" height="225" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>');
$('#showVideo').hide().html;})

See on http://jsfiddle.net/1tszLnhx/2/
After loading the script in the header after all the jquery I get the following error when I click on the actual "Click to start Video"-Link:
Uncaught TypeError: undefined is not a function (anonymous function)
What am I doing wrong? Can anybody can help me out with this?

A: First try replacing $ with jQuery in the above snippet.
Generally in your actual implementation of the fiddle code in your website try to be more specific regarding the elements' selectors e.g. classnames and ids.
Wrap it around a
jQuery( document ).ready(function() { //the above snippet here});
and change the part
jQuery('img').attr('data-video')
to this jQuery('#yourimageid').attr('data-video')


text:
Q: Stretching a div to fit absolutely positioned content Is there a way to do this with just css and no scripting?  I have a div with a min-width, and inside of it is an absolutely positioned inner div with dynamically generated content of variable width.  Sometimes the content extends beyond the containing div, but since its absolutely positioned it won't stretch the containing div.  How do i get it to stretch the containing div?  Thanks

A: If your content element has position: absolute, it is not possible. However, sometimes you can avoid the absolute positioning and yet obtain the desired result by using a floating element instead. See this answer to a very similar question for an example.

A: Try referencing this JSfiddle i made. http://jsfiddle.net/gA7mB/
If I read it right that is basicly what you are looking for.
HTML

I am Content i can be as long as you wish. t is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

CSS
.container{
    width: 500px;
}

.relative{
    position: relative;
    background: #666;
    min-width: 200px;
    min-height: 200px;
}

.absolute{
    position: absolute;
    background: #999;
    top: 20px;  /* not important, just to show absolute position */
    left: 20px; /* not important, just to show absolute position */
}

A: The trick is to set the absolute div to have full width and height:
position: absolute;
bottom: 0;
left: 0;
transform: translateY(100%);
width: 100vw;
height: 100vh;

(You can reduce the width and height to prevent the element from overflowing the page.)
Then you can just put a children's div into the absolute positioned div and it will grow as much as it needs.
To prevent the children's div to fit the parent div, you can add this to the absolute positioned div:
display: flex;
align-items: flex-start;

Then the children will minimize its width while still being able to grow.

A: An alternative would be using Grid instead of position: "absolute".
this will ensure the container  fits the area you want to position your content.
.container {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
}

later you assign the content to the area like so. If you use position relative, you can still use the top, left, right, bottom properties; they will behave absolutely to the container and the container will fit the content;
.child {
    grid-column: 1;
    grid-row: 1;

    position: relative;
    top: 20px;
}


text:
Q: Ubuntu 22.04 LTS how to set all hdd drives always on - prevent from sleeping or spin down On a pretty large system with 1000+ hdd drives I have a problem where hdd drives are going to sleep | spinning down (if you find it more accurate).
The system is running on Ubuntu 22.04 LTS, as stated in title, but I think it is a more general question to linux.
In the server I have a mix of SATA and SAS drives, connected through HBA's and JBOD's - I don't think the capacity will matter here.
So how can I prevent these drives from spinning down?
Finding out how to do this per drive is obviously my goal, but maybe there is a global system wide solution?
I've already tried sudo hdparm -S 254 /dev/sdXX or with 0, but I'am getting errors in all these cases like this:
SG_IO: bad/missing sense data, sb[]:  70 00 05 00 00 00 00 0a 00 00 00 00 20 00 01 cf 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

I would be more than glad, if anyone from the superuser community, could guide me towards the proper solution.


text:
Q: iOS: Is it possible to override the locale set on the phone and make it use a strings for a different locale? In iOS, is it possible to override the locale currently set on the phone and make it use a strings for a different locale in my app?

A: In short: Yes.
The NSLocalizedString is a macro, which you can replace with your own macro and do the language loading yourself. This might require setting most of the strings in code though and you will not be able to use them in Storyboards.
However, changing the locale manually in NSUserDefaults works if you want to change the locale.
The answers below explain more on this topic:

*

*Custom NSLocalizedString?

*change locale programmatically

*Change app language programmatically

*iOS: How to change app language programmatically WITHOUT restarting the app?


text:
Q: How does recursion work internally in python (source code of recursion)? I would like to understand the internal work of recursion. Can I write my own recursion for python?
For example, now we have following function:
def fact(n):
    return n*fact(n)

How can I change the return command and change the functionality of it, like the following:
def fact(n):
    my_return  n*fact(n)

In this case, I want to change the internal work of return and use my_returne, and also with this, I want to control stack differently.

A: If you want to understand the guts of how Python works, I highly recommend reading the documentation for the built-in modules under the "Language Services" heading, particularly the ast and dis modules. Python exposes, as importable and Python-runnable modules, all of its parsing capabilities. You can see, use, and tinker with its parsing of code, how it generates bytecode, and its core execution.
I'm not sure if this really helps, but RETURN_VALUE is its own opcode in Python's bytecode, so aside from creating your own bytecode manually or screwing with the parser results, there's probably no other way to get the return keyword's behavior. The actual implementation of how that behaves is going to be implementation-dependent (CPython might do it differently from Pypy, for example), so you'd need to be more specific in your question, or just dig into their source code for that opcode.
That said, there's nothing stopping you from creating your own stack as a list and pushing/popping stack frames to/from it yourself, besides the sheer insanity of the act. E.g.,
stack = []

def my_pseudo_func():
    global stack
    args, kwargs = stack[-1]
    x, = args
    # do some stuff
    my_return_result = x + 5
    ###
    stack.pop()
    stack.append(my_return_result)

stack.append(((3,), {}))
my_pseudo_func()
result = stack.pop()
assert result == 8


text:
Q: Input Button of type="image" is not working with href in IE 11
    <input name="Plus" type="image" src="~/GHAimages/129.png" id="btnAddRule" title="Add New Rule"/>

By Clicking this Button it will open a new page. Button is basically a image button (Iconic which helps user to understand what they are doing exactly). Working fine in Firefox and Chrome. But in IE 11 it is not working. when I am changing its type from type="image" to type="button", it starts working, but it is not showing the image.
Also have tried with the following code, by putting it inside  tag.
onclick="window.location=this.parentNode.href;

Now, Image is showing on the button, button is working also and page is also opening but in the back side the window from which it has been invoked.
Any help is welcome..

A: You can use  an  tag instead of an input tag.

Also, I don't think you need a tilde in your path, try replacing src="~/GHAimages/129.png" with src="/GHAimages/129.png". I would try this before using the image tag.

A: There is no valid reason to wrap an  tag around an input[type="image"].
Have you considered just using an ?


text:
Q: Xcode 4: List Methods By Name? Is there any way to navigate the structure of an Objective-C file by alpha order for the methods? The combobox (in the Jump Bar) that shows all the methods is not much more helpful than looking through the file.

A: As per the Jump Bar Help Page:

"Tip: Hold down the Command key when selecting a level in the path menu to view its items alphabetically."

A: If it's a file implementing a class then in the Symbol Navigator (CMD+2) you can expand the class you're interested in and the class's member variables and methods are listed in alphabetical order.


text:
Q: easy_install in windows XP with error "Not a recognized archive type" This error "Not a recognized archive type" happens on one Windows XP machine but Never happen on another one. It's so weird!
My python is 2.5, did I miss something in my windows?

A: there is a good chance you have a file or directory in your path that has the same name with the package you are trying to install, like:
easy_install ali
# Processing ali
# error: Not a recognized archive type: ali

this is because I have an ./ali in the same directory or on the path that I am running the easy_install command from

A: This has happened to me when I've accidentally renamed the setuptools egg after or during downloading ... Downloading and reinstalling has always fixed it. :)
Instructions here: http://pypi.python.org/pypi/setuptools


text:
Q: "unreachable statement" when trying to compile a "while" statement I'm new to Java and working through some coursework. However, on the following piece of code I'm getting the error "Unreachable statement" when trying to compile. Any pointers as to what I'm doing wrong?
public String getDeliveredList() {
   int count = 0;
   while (count < deliveredList.size()){
       return ("Order # " + count + deliveredList.get(count).getAsString());
       count++;
   }
}

A: Once you've returned from the function, logically it can no longer execute anything after that point -- the count++ statement will never be reached.
while (count < deliveredList.size()){

   // function always ends and returns value here
   return ("Order # " + count + deliveredList.get(count).getAsString());

   // this will never get run
   count++;
}

A: If you have returned from a function then any statement after the point from where the function returned are basically unreachable statements and the compiler will issue an error on such statements.
However the following code will not issue an error inspite of statements written after return
void max(int a,int b)
{
    if(a>b)
    {
        System.out.println(a+" is greater");
        return;
    }

    System.out.println(b+" is greater");
    return;
}

This is because the first return statement is written within a nested scope and not immediately visible in the function scope. The program execution will only pass through first return statement when a>b. If it is not so then that block of codes is never executed. So in spite of having statements after return, the code is compile-able;


text:
Q: Align DataFrames in pandas so that data matches in rows I want to align my data
I currently have it like this:
Yan     TNSeq   Kato    Eco-GeneOrth    Essential

accA    accA    accA        accA        accA
accB    accB    accB        accB        accB
accC    accC    accC        accC        accC
accD    accD    accD        accD        accD
aceF    acpP    acpP        alaS        aceF
acpP    acpS    acpS        argA        acpP
acpS    adk     adk         argB        acpS

What I want is this:
Yan     TNSeq   Kato    Eco-GeneOrth    Essential

accA    accA    accA        accA        accA
accB    accB    accB        accB        accB
accC    accC    accC        accC        accC
accD    accD    accD        accD        accD
aceF    NaN     NaN         Nan         aceF
acpP    NaN     Nan         acpP        acpP
NaN     acpS    NaN         NaN         acpS

I've tried with reindex and sort, but no luck
I'm clueless
Basically what I want is to align or sort the first 4 columns with the Essential column, so that the data in the rows matches.

A: UPDATE:
In [120]: df[df.apply(lambda x: x['Essential'] == x, axis=1)]
Out[120]:
    Yan TNSeq  Kato Eco-GeneOrth Essential
0  accA  accA  accA         accA      accA
1  accB  accB  accB         accB      accB
2  accC  accC  accC         accC      accC
3  accD  accD  accD         accD      accD
4  aceF   NaN   NaN          NaN      aceF
5  acpP   NaN   NaN          NaN      acpP
6  acpS   NaN   NaN          NaN      acpS

try this:
In [86]: df[df.apply(lambda x: x[0] == x, axis=1)]
Out[86]:
    Yan TNSeq  Kato Eco-GeneOrth Essential
0  accA  accA  accA         accA      accA
1  accB  accB  accB         accB      accB
2  accC  accC  accC         accC      accC
3  accD  accD  accD         accD      accD
4  aceF   NaN   NaN          NaN      aceF
5  acpP   NaN   NaN          NaN      acpP
6  acpS   NaN   NaN          NaN      acpS

data:
In [87]: df
Out[87]:
    Yan TNSeq  Kato Eco-GeneOrth Essential
0  accA  accA  accA         accA      accA
1  accB  accB  accB         accB      accB
2  accC  accC  accC         accC      accC
3  accD  accD  accD         accD      accD
4  aceF  acpP  acpP         alaS      aceF
5  acpP  acpS  acpS         argA      acpP
6  acpS   adk   adk         argB      acpS

A: IIUC use eq and pass your column with arg axis=0 to create a boolean mask of your entire df against that column:
In [49]:
df[df.eq(df['Essential'],axis=0)]

Out[49]:
    Yan TNSeq  Kato Eco-GeneOrth Essential
0  accA  accA  accA         accA      accA
1  accB  accB  accB         accB      accB
2  accC  accC  accC         accC      accC
3  accD  accD  accD         accD      accD
4  aceF   NaN   NaN          NaN      aceF
5  acpP   NaN   NaN          NaN      acpP
6  acpS   NaN   NaN          NaN      acpS


text:
Q: Populate User/People field in CSOM using Azure AD user ID Ok so i've got access to MS Graph app that retrieves users. I already tested it and i can get back a lot of user info from which i have email, ID and others.
Does anyone know of a way to populate a People Picker field in a list using information from MS Graph? I know its doable, but i have no idea how.
AFAIK you can set that field by using lookupid for users that are in a specific site collection, but what i want is a bit general (to be able to set any user in the active directory, which i am retrieving with msgraph).
Can anyone share a code snippet regarding this ? Thanks!

A: I'm literally getting into the bad habbit of answering my own questions ffs....
Anyway, the fix is simple, you need to use the username ex :
                    var managerField = FieldUserValue.FromUser(newItem.Manager);

Where newItem.Manager is actually the username (john@something.com) ->
                    var managerField = FieldUserValue.FromUser("john");

Tested it with security groups aswell and it works.


text:
Q: How to add an icon to a QTabWidget (not for each tab)? I would like to add an icon at the top left of the QTabWidget. I don't want to add an icon for each tab. How to do that using a stylesheet or programmatically in C++?

A: Stylesheet below will add an image to the left of all tabs, but not to individual tabs. However, it is very likely that you'll need to tweak other attributes in the CSS to polish the final result.
QTabWidget > QTabBar {
  background: url(url-to-your-corner-image);
  background-repeat: norepeat;
  margin-top: 10px; /* whatever needed to center the image vertically */
}
QTabWidget > QTabBar::tab:first {
  margin-left: 10px; /* at least the width of your image */
}

A: You can add a first tab with a fixed stylesheet : TabWidget stylesheet example


text:
Q: How to use WS with Node.js + Cloudflare + Nginx I would like to create a websocket using ws.
I use Nginx.
In my Nginx configuration that redirects "gateway.example.com" to "http://127.0.0.1:3006".
In my Cloudflare configuration (DNS), there is gateway to SERVER_IP.
// For "generate" the websocket. There are the Cloudflare key & cert.
const server = require("https").createServer({
    cert: require("fs").readFileSync('./src/router/api/v1/cert.pem'),
    key: require("fs").readFileSync('./src/router/api/v1/key.pem')
});
server.listen(3006)

const wss = new WebSocket.Server({
  server
});

A: It was a problem with nginx. We need a special configuration for ws (upgrade).


text:
Q: Java Class Path issue with Randoop I'm using Randoop, the automatic test generator for Java.
However, when running Randoop from the commandline, I can't seem to figure out how to properly specify the classpath.
I read through this question: Java Classpath error-cannot find my class in detail but my setup seems a bit different.
I'm running on a Windows machine.
The overall project structure looks like this:
cse331/
    bin/
        hw5/
            GraphNode.class
    src/
        hw5/
            GraphNode.java
    randoop-2.1.4.jar

(There are some other files but the not important here, I think)
I tried calling:
java -ea -classpath randoop-2.1.4.jar:bin/* randoop.main.Main gentests --testclass=GraphNode --timelimit=20

But received the error:
Error: Could not find or load main class randoop.main.Main

I've tried several variations, loading in the .java file instead of the .class file for the classpath but no option has worked so far. If I don't specify the class path at the end of randoop-2.1.4, I get an error message saying the class GraphNode cannot be found.
The setup is just the first step and I can't seem to get on the right track.

A: In the end, the solution was to remove the asterisk from bin/ and include the semi colon like Sumit suggested.
java -ea -classpath randoop-2.1.4.jar;bin/ randoop.main.Main gentests --testclass=GraphNode --timelimit=20

A: Try this one: It will surely remove this error.
java -cp cse331/bin;randoop-2.1.4.jar randoop.main.Main gentests --testclass=hw5.GraphNode --timelimit=100.
If your project is maven project, Try to include all dependencies. for downloading use this command: mvn dependency:copy-dependencies
Let me know if you have any other queries regarding randoop.


text:
Q: lambda binding upon call is causing issue in my generated code As the author of Pythonizer, I'm translating some perl code to python that defines a function FETCH in 2 different packages in the same source file, like:
package Env;
sub FETCH {...}
package Env::Array;
sub FETCH {...}

and my generated code needs to insert a special library call (perllib.tie_call) that handles the 'tie' operation at runtime.  Here is a sample of my generated code for the above:
builtins.__PACKAGE__ = "Env"
def FETCH(*_args):
    ...
Env.FETCH = lambda *_args, **_kwargs: perllib.tie_call(FETCH, _args, _kwargs)

builtins.__PACKAGE__ = "Env.Array"
def FETCH(*_args):
    ...
Env.Array.FETCH = lambda *_args, **_kwargs: perllib.tie_call(FETCH, _args, _kwargs)

What is happening, when I call Env.FETCH, it's invoking the second def FETCH, as that's the current one defined.  I need to invoke the first FETCH for Env.FETCH and the second FETCH for Env.Array.FETCH.  How can I modify my generated code to do that?  In the situation that I don't need to sneak in a perllib.tie_call, my generated code is:
builtins.__PACKAGE__ = "Env"
def FETCH(*_args):
    ...
Env.FETCH = FETCH

builtins.__PACKAGE__ = "Env.Array"
def FETCH(*_args):
    ...
Env.Array.FETCH = FETCH

which works as expected.  With the lambda, the evaluation of FETCH gets delayed and the last one defined is being picked up.  I need it to pick up the FETCH defined just above it instead.

A: Here is how I figured out how to fix it. Thanks @python_user for helping me brainstorm a solution!!  Since I'm also the author of perllib, the library for Pythonizer, I added a new function to it add_tie_call, defined as follows:
def add_tie_call(func):
    """Add a call to _tie_call for functions defined in a tie package"""
    def tie_call_func(*args, **kwargs):
        return _tie_call(func, args, kwargs)
    return tie_call_func

Then I changed lambda lines to read:
Env.FETCH = perllib.add_tie_call(FETCH)
...
Env.Array.FETCH = perllib.add_tie_call(FETCH)

and now my test case passes:
$ ./runit -P issue_s304
==================== issue_s304.pl ====================
issue_s304.pl - test passed!
issue_s304.py - test passed!
pythonizer 1 tests PASSED!


text:
Q: where is the source code of the face detection implementation on Android 4.0 Ice cream sandwich? ICS has provided new API for face detection. I traced the source code, but I cannot find how the detection implemented. I found the interface OMXCameraAdapterFillBufferDone, in which I can get how many faces have been detected. but what happened before this?
can anybody tell me where the the source code of face detection implementation is? Thanks!!!


text:
Q: Exceeded rate limits: too many table update operations for this table in Cloud Function while uploading the data from pubsub topic to BQ Let me explain the use case which I am trying to solve

*

*I am getting data to the pubsub topic on daily basis in google cloud

*I have a written a cloud function with pubsub as a trigger type to trigger and execute the
script inside the cloud function when ever the topic receives the data

*The function will trigger and uploads the data to Bigquery tables

*Right now I kept the memory of the function as 256mb and max instances to 100

*On daily basis I receive very small amount of data like 16 messages to pubsub topic

*Even the data is small I observed the cloud function is encountering the following error "too
many table update operations for this table" and I am missing some data

*I have retry option which I can use but don't want the cloud function to return any errors, Is
there any workaround for this

*sharing the sample code below

A: It appears that your code is exceeding the maximum rate of table metadata update operations per table which is 5 operations per 10 seconds. So it appears that all your Cloud Pub/Sub messages are coming at the same time (or near the same time). You can follow either of the following solutions for the same:

*

*As suggested in the comments, you can use Streaming inserts. As this limit does not apply to Streaming Inserts.

*You can insert a delay in your code for providing time between successive metadata updates. In this case I passed a timeout of 30 seconds to the result for the same. This worked for me.
I tried the second method. I published 19 messages from my publisher code at the same time. I got the same error message as yours (when executing without timeout).

But after Inserting the timeout the execution was successful. (Timeout value can be reduced further as per the requirement)
Complete Code:
import base64
from google.cloud import bigquery
import json
import io

def hello_pubsub(event, context):
   """Triggered from a message on a Cloud Pub/Sub topic.
   Args:
        event (dict): Event payload.
        context (google.cloud.functions.Context): Metadata for the event.
   """
   client = bigquery.Client()
   pubsub_message = base64.b64decode(event['data']).decode('utf-8')
   print(pubsub_message)
   message = json.loads(pubsub_message)
   result = json.dumps(message)
   source_file = io.StringIO(result)
   table_id="ProjectID.DatasetID.TableName"

   job_config = bigquery.LoadJobConfig(
    autodetect=True,
    write_disposition="WRITE_APPEND",
    source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
    )
   job = client.load_table_from_file(source_file, table_id, job_config=job_config)
   job.result(timeout=30)  #passing a timeout in the function call

Output : (All 19 rows were inserted, I did not notice any loss of data)


text:
Q: Load repetitively-named XML nodes using Linq [C#] I'm working on a program that needs to be able to load object-properties from an XML file. These properties are configurable by the user and XML makes sense to me to use.
Take the following XML document.
<?xml version="1.0" encoding="utf-8" ?>

<udpcommands>

  <command name="requser">
    <cvar name="reqchallege" value="false" />
  </command>

  <command name="reqprocs">
    <cvar name="reqchallenge" value="false" />
  </command>

</udpcommands>

I need to be able to load values from the cvars above to properties. I'm think Linq-To-XML would be good for it (I'm looking for applications of Linq so I can learn it). I've got a Linq-to-XML query done to select the right "command" based on the name.I was reading MSDN for help on this.
The following code snippet goes in a constructor that takes the parameter "string name" which identifies the correct XML <command> to pull.
I would like to have one linq statement to pull each <cvar> out of that XML given the section name, dumping everything to an IEnumerable. Or, I'm looking for a better option perhaps. I'm open for anything really. I would just like to use Linq so I can learn it better.
    XElement doc = XElement.Load("udpcommands.xml");

    IEnumerable<XElement> a = from el in doc.Elements()
                              where el.FirstAttribute.Value == name
                              select el;

    foreach (var c in a)
    {
        Console.WriteLine(c);
    }

The above code snippet outputs the following to the console:
<command name="requser">
  <cvar name="reqchallege" value="false" />
</command>

A: Something like this should do:
var result =
    doc.Elements("command")
    .Single( x => x.Attribute("name").Value == name)
    .Elements("cvar");

This will give you an IEnumerable<XElement> where each XElement represents a cvar in the specified command.
Note that if the specified command does not exist, the call to Single will cause an error. Likewise if the specified attribute is not found on the command.
EDIT As per your comments, you could do something along the lines of:
// Result will be an XElement,
// or null if the command with the specified attribute is not found
var result =
    doc.Elements("command")
    // Note the extra condition below
    .SingleOrDefault( x => x.Attribute("name")!=null && x.Attribute("name").Value == name)

if(result!=null)
{
    // results.Elements() gives IEnumerable<XElement>
    foreach(var cvar in results.Elements("cvar"))
    {
        var cvarName = cvar.Attribute("name").Value;
        var cvarValue = Convert.ToBoolean( cvar.Attribute("value").Value );
    }
}


text:
Q: If $a > b$ and $x > 2$ show $\frac{2^{a+1}-1}{2^a}\frac{x^{b+1}-1}{x^b(x-1)} > \frac{2^{b+1}-1}{2^b}\frac{x^{a+1}-1}{x^a(x-1)}$ Given integers $a > b \geq 0$ and $p>2$, show that the following inequality holds
$$\dfrac{2^{a+1}-1}{2^a}\dfrac{x^{b+1}-1}{x^b(x-1)} > \dfrac{2^{b+1}-1}{2^b}\dfrac{x^{a+1}-1}{x^a(x-1)}$$
This is trivial if $b=0$ as we'll end up with the inequality
$$\dfrac{2^{a+1}-1}{2^a} > \dfrac{x^{a+1}-1}{x^a(x-1)}$$
which can be shown using a variety of methods such as taking the derivative of both sides. I want to show that this inequality holds for all values of $a,b,x$ which I am able to plot out trivially, however I get stuck down the line.
Here is what I've tried so far:
$$\dfrac{2^{a+1}-1}{2^a}\dfrac{x^{b+1}-1}{x^b(x-1)} > \dfrac{2^{b+1}-1}{2^b}\dfrac{x^{a+1}-1}{x^a(x-1)}\equiv\dfrac{2^{a+1}-1}{2^a}\dfrac{x^{b+1}-1}{x^b} > \dfrac{2^{b+1}-1}{2^b}\dfrac{x^{a+1}-1}{x^a}$$
then we cross multiply to find
$$
\dfrac{2^b}{2^{b+1}-1}\dfrac{2^{a+1}-1}{2^a} > \dfrac{x^b}{x^{b+1}-1}\dfrac{x^{a+1}-1}{x^a} \equiv \dfrac{2^{a+b+1}-2^b}{2^{a+b+1}-2^a}>\dfrac{x^{a+b+1}-x^b}{x^{a+b+1}-x^a}
$$
but from here I find myself stuck without a direction forward. Any help would be appreciated!

A: $
f(x)=\dfrac{x^{a+b+1}-x^b}{x^{a+b+1}-x^a}=\dfrac{1-\frac{1}{x^{a+1}}}{1-\frac{1}{x^{b+1}}}\\
f'(x)=\dfrac{\frac{a+1}{x^{a+2}}-\frac{b+1}{x^{b+2}}-\frac{a-b}{x^{a+b+3}}}{\left(1-\frac{1}{x^{b+1}}\right)^2}=\dfrac{(a+1)x^{b+1}-(b+1)x^{a+1}-a+b}{x^{a+b+3}\left(1-\frac{1}{x^{b+1}}\right)^2}\\
g(x)=(a+1)x^{b+1}-(b+1)x^{a+1}-a+b\\
g(1)=0\\g'(x)=(a+1)(b+1)(x^b-x^a)\\
x>1\,\Rightarrow\,g'(x)<0\,\Rightarrow\,g(x)<0\,\Rightarrow\,f'(x)<0\,\Rightarrow\,f(2)>f(x)
$


text:
Q: When trying to use ng-transclude inside md-virtual-repeat I'm getting Illegal use of ng-transclude directive I have created a directive which uses md-virtual-repeat-container component of angular material.
angular
      .module('MyApp')
      .directive('myDirective', function() {
          var template = document.getElementById("myDirective").innerHTML;
            return {
              replace: true,
              transclude: true,
              template: template,
              controllerAs: 'ctrl',
              controller: function() {
              this.items = [];
              for (var i = 0; i < 100; i++) {
                  this.items.push(i);
              }
          }
        }
      });

My HTML

  <my-directive>
    Hello
  </my-directive>

The issue is when i am running this code i am getting

Illegal use of ngTransclude directive in the template! No parent
  directive that requires a transclusion found

Which makes sense since the ng-trasclude is becoming a part of md-virutal-repeat-container and it doesn't have trasclude property set.
What I have tried so far:

*

*I have tried creating a separate child directive of my current directive and set transclude property to true but to add that child again I need to add ng-transclude to 'myDirective' directive which brings me back to same issue.

*I tried replacing the content in prelink function but the md-virtual-repeat removes the content before prelink and I am not able to access the content where i have to replace the transcluded element. Everything is fine in compile function but i don't have access to transcluded element in compile function.
Source of virtual repeat container
I have created a codepen for this. Please play around with it and see if you can get through it.
Thanks in advance.


text:
Q: como el frontend puede comprobar la disponibilidad del backend al entrar a la pagina estoy practicando el desarrollo de un CRUD, con un backend en Spring Boot, y un front en angular. y quisiera saber como puedo hacer para que el frond me de un aviso si el backen no esta disponible por algun motivo.
algunos me dicen que se puedo hacer un endpoint de consulta y lo utilice para la comprobacion, otros me dicen que utilice "actuator". Nose si hay una manera correcta o considerado como buena practica de hacer un comprobacion de la disponibilidad del backend.


text:
Q: Dropdownlist with a list of Models I'm  trying to save multiple models but have problem with the dropdownlist of the model.
I got the following error: No information ViewData type 'IEnumerable ' with key '[0]. TypeBienId'.
Here are some files:
Controller GET:
public ActionResult RDummy()
{
    List<BI> bis = new List<BI>();
    BI bi1 = new BI();

    ViewBag.TypeBienId = new SelectList(db.TypeBiens, "TypeBienId", "cnom");
    bis.Add(bi1);
    return View(bis);
}

My View:
@model IEnumerable<SIBI.Models.BI>
@using (Html.BeginForm()) {
   @Html.EditorForModel()

      <input type="submit" value="Crear" />

}

My Template in the EditorTemplates Folder:
@model SIBI.Models.BI
@Html.DropDownList("TypeBienId", String.Empty)

@Html.ValidationMessageFor(model => model.TypeBienId)

Any ideas of what the problem is and how to resolved?

A: Try using this in your EditorTemplate:
@Html.DropDownList("TypeBienId", ViewBag.TypeBienId);


text:
Q: Sitecore with SolrCloud switch on rebuild We have recently implemented SolrCloud with Sitecore 8.0 Update 2. All works fine and good with this setup. Then we introduced patch 449298 into the mix to enable switch on rebuild functionality. Our CM server is the only one that initiates indexing. Both CM and CD use searching functionality against SolrCloud.
All works well and fine in regards to incremental updates. But when we rebuild the indexes, the CD servers do not pick up the rebuilt indexes. They still point to the previous "primary" indexes. CM works fine without issues. When we manually switch the indexes then they work fine for CDs as well.
The only issue we ever notice is pasted below but this seems like a harmless error.
9/11/2016, 11:48:55 AM  WARN    OverseerCollectionProcessor OverseerCollectionProcessor.processMessage : createalias , {
OverseerCollectionProcessor.processMessage : createalias , {
  "operation":"createalias",
  "name":"social_messages_web_alias_secondary",
  "collections":"social_messages_web_secondary"}

Is 449298 required on CDs or can we just OOTB libraries on CDs and 449298 on CM?
Any help is appreciated!

A: Based on the documentation on the release page in github it says the following:

*

*Download the Sitecore.Support.449298-7.2.6.0.zip file.

*Extract the archive to the Website folder of all Sitecore instances in the solution, overwrite existing files if any conflicts occur

So, i think you should apply it on all of Sitecore instances that you have in your environment, I have not tested this myself, But based on the documentation it seems thats the right way.


text:
Q: How to get Chrome to print webpages without some headers obscuring text There are many questions that have been answered about this kind of issue: How to get a PDF of a webpage that's searchable and has clickable hyperlinks. For example, this discussion.
What I'm addressing is a specific situation: I have vanilla Chrome and am not permitted to install add-ins or other browsers. (I also happen to prefer Chrome because its "Save as PDF" printing option creates clickable links.)
The problem is that some webpages have banners and other elements that overlay the text on the printed pages.
One solution offered in the thread cited above was to use Chrome's developer tools to set CSS rendering to "Screen." That helps a lot in some cases, but I still run into webpages where it doesn't work, and various elements continue to overlap the main text.
I have a solution that I will describe below.

A: My answer is kind of brute force and requires a little (not much) knowledge of HTML.
Instead of the rendering setting, I open the Chrome Developer Tools, then use the Select Element button:

I then select the offending element and go back to the Developer panel's HTML display, right-click on the element's HTML opening tag, and choose "Hide element."

I sometimes have to do this for a few elements, but then the Print | "Save as PDF" feature works, and I can see all the body text.


text:
Q: Date and Time function not usable anymore Good day,
I use in Automation Studio, an SQL query using functions like dateAdd() and Datediff().
Since yesterday, this activity is errored with this message : " An error occured while checking the query  syntax. Errors: The data types and time are incompatible in the add operator."
I didn't change this SQL activity since last october and it was running correctly almost every day.
Did I miss something in the releases?
here an example of my activity in SQL
Select
dateadd(minute,dum.ID-1,cast(dateadd(day,dumday.ID-1,cast([Date Debut
Campagne] as date)) as date) + cast([Heure Debut Campagne] + ':' + [Minute
Debut Campagne] as time)) as currentDate,
dateAdd(minute,dum.ID-1,cast([Heure Debut Campagne] + ':' + [Minute Debut
Campagne] as time)) as [CalcHour],
[Code Campagne SMS] as CodeCampagneSMS,
case [Concatenee] when 1 then [Nombre SMS - Minute] *2 else [Nombre SMS -
Minute]  end as NBSMSMinute,Frequence
from [Campagne] as B1

A: So, I'm posting the results of a conversation with one of our DBA's this evening.  He doesn't understand how it ever worked.  Instead, he suggests you write it like this:
SELECT dateadd(minute,dum.ID - 1, dateadd(day, dumday.ID - 1,
     dateadd(day, datediff(d, 0, [Date Debut Campagne]), cast([Heure Debut Campagne] + ':' + [Minute Debut Campagne] + ':00.000' as datetime))
   )) as currentDate,
   dateAdd(minute,dum.ID - 1,cast([Heure Debut Campagne] + ':' + [Minute Debut Campagne] as time)) as [CalcHour],
   [Code Campagne SMS] as CodeCampagneSMS,
   case [Concatenee] when 1 then [Nombre SMS - Minute] * 2
                     else [Nombre SMS - Minute]
    end as NBSMSMinute, Frequence
 from [Campagne] as B1

His notes::
datediff(d, 0, [Date Debut Campagne]) calculates the number of days from 'day zero'
cast([Heure Debut Campagne] + ':' + [Minute Debut Campagne] + ':00.000' as datetime) first builds a string in the time format "00:00:00.000', and then casts the to a datetime without specifying the date, so the date is set to 'day zero'.
The outer dateadd adds the number of days from 'day zero' the recorded event occurred to the 'day zero' time, and produces a datetime value built from the separately-recorded day, hour, and minute values.
Note: I didn't see your SQL so I cannot comment.  But I hope this helps.


text:
Q: image link which is located on my server using tomcat 8, java 8 webApp I am using tomcat 8 to run my webApp created in intellij 14 and I want to make some link to uploaded image like http://localhost:8080/images/profPic.jpeg . but I don't know how to create this link. Where do I have to save images on server to make them accessible like this ?

EDIT :

Context< docBase = "/some/path" path="some/link"/>

doesn't work. probably  they changed something in tomcat 8. Also, I know that putting files under web root makes them accessible  but in that case i need to deploy them on every change? i need to add and delete images dynamically


text:
Q: Iterate through JSON based on ID I am working on a webshop template and I need to display the correct JSON data according to every single product in the store in a modal that opens when clicking the given product. I am also using handlebars for templating and have the following code structure:
.html (button to open the modal)
<button type="button" class="quickview">Open Modal</button>

.html (modal)
<div id="quickview-modal">
 modal content that should iterate over the JSON and display one item at a time depending on the ID
</div>

.json
{
 "productID" : "1",
 "name" : "productOne"
},
{
 "productID" : "2",
 "name" : "productTwo"
}

.js
$( ".quickview" ).click(function( event ) {
  $('#quickview-modal').modal('show');
  event.stopPropagation();
  // Do something
});

Any ideas how I can tackle this? Thanks!

A: say your .json variable is data
 var data = 'your JSON';
 $.each(data,function(i,v){
     alert(v.productID); //will give you the value related to productID.
 });

updated
$( ".quickview" ).click(function( event ) {
   event.stopPropagation();
   var data = 'your JSON';
   $.each(data,function(i,v){
      $('#quickview-modal').append(v.name + " : " + v.productID);

   });
   $('#quickview-modal').modal('show');
 });


text:
Q: Access VBA Putting name of a Field as a Record I am with a little bit of a coding problem that I don't know how to solve. I want to put in the table as a record a field name of another table in the same Database.
I will give you an example:
Table1
What I have
Table 2
What I want
The table 1 is update weekly from an external source so I need to record the field name as a record in the second table using VBA language. Does anybody knows if it's possible?
Thank You in advance

A: You could do something like this
Dim db As Database
Dim fld As Field
Dim sql As String
Set db = CurrentDb

For Each fld In db.TableDefs("YourTable").Fields

    sql = "Insert into YourSummaryTable([Date], Hours) select '" & fld.Name & "', sum([" & fld.Name & "]) as s from YourTable"
    DoCmd.RunSQL sql

Next fld

Note that you've used a reserved word Date as a fieldname, which isn't best practice and requires the use of the square brackets in the query.


text:
Q: How to remove a character in json at specific index using js? I have a json code as below:
[
   [
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
         "elements":[
            {
               "type":"image",
               "source":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
         "elements":[
            {
               "type":"image",
               "source":"ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },

   ]
]

I need to remove the comma at the end of array ie. the comma before the last two characters of the json. Due to this the above json is a invalid json. I need to achieve this using JS.

A: Here is another approach, assuming your input is a string. It finds the last index of a comma in the string, and then uses string.splice to assemble a new string without that comma.

const JSON = `[
   [
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
         "elements":[
            {
               "type":"image",
               "source":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
         "elements":[
            {
               "type":"image",
               "source":"ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },

   ]
]`

lastComma = JSON.lastIndexOf(',')

const JSONnew = JSON.slice(0, lastComma) + JSON.slice(lastComma + 1, JSON.length)

console.log(JSONnew)

A: You can use eval, but know that it is dangerous, this code is valid JavaScript
const json = `[
   [
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
         "elements":[
            {
               "type":"image",
               "source":"http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },
      {
         "title":"Shirt Front",
         "thumbnail":"http://ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
         "elements":[
            {
               "type":"image",
               "source":"ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
               "title":"Base",
               "parameters":{
                  "left":325,
                  "top":329,
                  "colors":"#d59211",
                  "price":20,
                  "colorLinkGroup":"Base",
                  "fill":false
               }
            }
         ]
      },

   ]
]`

const validJsArray = eval(json)

A: JSON.stringify will clean that up for you.
var my_cool_object = [
        [
            {
                "title": "Shirt Front",
                "thumbnail": "http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
                "elements": [
                    {
                        "type": "image",
                        "source": "http://ipadd/pub/media/catalog/product//b/l/blue-back_2.jpg",
                        "title": "Base",
                        "parameters": {
                            "left": 325,
                            "top": 329,
                            "colors": "#d59211",
                            "price": 20,
                            "colorLinkGroup": "Base",
                            "fill": false
                        }
                    }
                ]
            },
            {
                "title": "Shirt Front",
                "thumbnail": "http://ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
                "elements": [
                    {
                        "type": "image",
                        "source": "ipadd/pub/media/catalog/product//b/l/blue-back_1_1.jpg",
                        "title": "Base",
                        "parameters": {
                            "left": 325,
                            "top": 329,
                            "colors": "#d59211",
                            "price": 20,
                            "colorLinkGroup": "Base",
                            "fill": false
                        }
                    }
                ]
            },
        ]
    ];
    var valid_json_string = JSON.stringify(my_cool_object);

A: var json = [ ...  ]
console.log(JSON.parse(JSON.stringify(json)));


text:
Q: Can I use a single app secret to create multiple oauth2 tokens and send emails from Gmail? We have a desktop application that needs to send emails on behalf of our clients (institutions), to our client's clients (real people).
After investigating about creating an intermediate web service that will hold our secret key, and retrieve oauth2 tokens on demand from the desktop app, then the desktop app uses that token to make google api calls to send emails.
I've come to the bulk mail guidelines
and I'm afraid the mails would get marked as spam (as they will have different senders)
We need to make something like thunderbird but only for sending notification mails.
Is there any other way to do this? How so?

A: Using Gmail for this is NOT going to go well.
Instead, as you are working on behalf of institutions you will do better to pick one of two options:

*

*Require your clients to provide credentials for their own smtp servers as part of the setup process for the application.

*Run your own smtp server (which is NOT trivial, but still doable) and require your clients to include your server's address in the appropriate places in their DNS so your server shows as legitimate sender for their domain.
As the main systems administrator at a small college, I've had to do both kinds of setup for various applications.
If you go option 2, get a real server with a real IP. I've had application vendors request to add SPF records for whole AWS ranges, and I am NOT going to approve that.