text:
Q: Has anyone tried oracle export : EXPDP on the remote machine? I am trying to export a dump file and log file on a remote machine using oracle expdp.
However i am getting the following error :
Connected to: Oracle Database 11g
Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing
options
ORA-39002: invalid operation
ORA-39070: Unable to open the log file.
ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation

Command run on remote machine  host-name 'Local' using oracle client are :
SQL> create directory expdp_dir as '/vault2/expdp_dir';
SQL> grant read,write on directory expdp_dir to dbuser;
expdp dbuser/dbpwd@SID SCHEMAS=dbuser DIRECTORY=expdp_dir DUMPFILE=testDB24NOV17.dmp logfile=testDB24NOV17.log EXCLUDE=STATISTICS

Note vault 2 is mounted on a remote machine with hostname 'Local'. The database is on a machine with hostname TestDB.
The OS is RHEL6.
Any thoughts /ideas on making this operation successful would be appreciated.

A: Please check this one:
as per Oracle Doc.ID Doc ID 1305166.1
The errors can have multiple causes. Known causes are listed below.

*

*One of the usual reasons for this problem to occur is when the listener process has not been started under the same account as the database instance service. The listener forks the new server process and when this runs under a different security context as the database, then access to directories and files are likely impacted.

Please verify the following information:
1) the output of:
ps -ef | grep SMON
2) the output of:
ps -ef | grep tnslsnr
3) the output of:
ps -ef|grep LIST
4) the output of:
ls -ld
Note:
When using ASM, the listener may have been started from the ASM Home instead of the RDBMS Home. Depending on your security settings, this may give to this issue.
One more:
4. Directory path/folder exists but create directory is executed by a different user in the database and the import is run by a different user.
Solution:
1. Make sure the listener and instance services are started from the same account.

*Make sure that the directory are shared between nodes so that the directory can be accessed on any instance, or, create a folder similar to the other nodes locally, if there is already a folder created locally on the all the node with the same file directory path structure check if the permission are correct.

*Make sure the folder exist has specified in during creation in the "CREATE DIRECTORY" syntax command.

*Grant the required permission to the importing user to use the directory.
grant read, write on directory  to ;
If above 4 possible causes and solutions are not applicable at your end, please check if the user has proper permission to export to run utl_file package.
Hope it helps.


text:
Q: How to get custom logging working in CherryPy? (Rewritten slightly following code modifications at my end plus answers given so far. Thanks to Andrew for the sample code which gave me the starting point for demonstrating that custom error logging works and then how I can break it!)
I'm trying to get custom logging working in CherryPy. I also would like to have log file rotation so I've followed the instructions in the documentation to replace the log handlers.
script_dir is set earlier on in my code to the directory where the script is running from.
cherrypy.config.update({'server.socket_host': '0.0.0.0',
                        'server.socket_port': 1234,
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': script_dir,
                        'log.access_file': "access1.log",
                        'log.error_file': "error1.log",
                        'log.screen': False,
                        'tools.sessions.on': True,
                       })

config = {'/':
             {
                  'tools.staticdir.on': True,
                  'tools.staticdir.dir': script_dir,
                  'log.access_file': "access2.log",
                  'log.error_file': "error2.log",
                  'log.screen': False,
                  'tools.sessions.on': True,
             }
         }

application = cherrypy.tree.mount(MyApp(), "/", config)

log = application.log

# Make a new RotatingFileHandler for the error log.
fname = getattr(log, "rot_error_file", "error.log")
h = handlers.TimedRotatingFileHandler(fname, when='midnight')
h.setLevel(logging.DEBUG)
h.setFormatter(_cplogging.logfmt)
log.error_file = ""
log.error_log.addHandler(h)

# Make a new RotatingFileHandler for the access log.
fname = getattr(log, "rot_access_file", "access.log")
h = handlers.TimedRotatingFileHandler(fname, when='midnight')
h.setLevel(logging.DEBUG)
h.setFormatter(_cplogging.logfmt)
log.access_file = ""
log.access_log.addHandler(h)

With the script running, logging happens as follows:

*

*Standard access logging goes to BOTH access1.log (defined at the global level) and access.log (defined at the app level)

*Error logging only goes to error1.log (defined at the global level)

*Nothing gets logged to *2.log (as expected)

So, it looks like CherryPy has a problem with error logging going to app-specific config. Generally that wouldn't worry me except that I do want to use the rotating log file handler but I don't know how to modify the logging sessions at the global level as I have done for the app-specific level.
Thanks.

A: To answer my question about how to set up the log handlers for the global log instead of the app-level log, here are the changes:
cherrypy.config.update({'server.socket_host': '0.0.0.0',
                        'server.socket_port': 1234,
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': script_dir,
                        'log.access_file': "access1.log",
                        'log.error_file': "error1.log",
                        'log.screen': True,
                        'tools.sessions.on': True,
                       })

config = {'/':
             {
             }
         }

application = cherrypy.tree.mount(HealthCheck(script_dir, service_fqdn, my_ip), "/", config)

logscope = cherrypy.log

# Make a new RotatingFileHandler for the error log.
fname = getattr(logscope, "rot_error_file", "error.log")
h = handlers.TimedRotatingFileHandler(fname, when='midnight')
h.setLevel(logging.DEBUG)
h.setFormatter(_cplogging.logfmt)
logscope.error_file = ""
logscope.error_log.addHandler(h)

# Make a new RotatingFileHandler for the access log.
fname = getattr(logscope, "rot_access_file", "access.log")
h = handlers.TimedRotatingFileHandler(fname, when='midnight')
h.setLevel(logging.DEBUG)
h.setFormatter(_cplogging.logfmt)
logscope.access_file = ""
logscope.access_log.addHandler(h)

or, in a nutshell:

*

*leave the application config empty. I'm only defining it so that CherryPy starts quietly.

*change the log scope from application.log to cherrypy.log

To be slightly more tidy, the references to access1.log and error1.log can change to access.log and error.log but I left them like that to confirm that I was overwriting the global settings.

A: Use something like this...
import cherrypy
from cherrypy import log

class MyApp(object):
    def index(self):
        log.error(msg='This is My Error ', context='HTTP', severity=20, traceback=True)
        return "Hello World!"
    index.exposed = True

cherrypy.tree.mount(MyApp(), "/")

cherrypy.config.update({'tools.staticdir.on': True,
    'tools.staticdir.dir': 'C:\\Documents and Settings\\d\\My Documents\\Aptana Studio 3 Workspace\\ScratchPad',
    'log.access_file' : "access.log",
    'log.error_file' : "error.log",
    'log.screen' : False,
    'tools.sessions.on': True,
    })

cherrypy.engine.start()
cherrypy.engine.block()

This will log the error.  I believe there's an issue loading the config in your code.  I also think static dirs needs to be turned.
Hope this helps and Happy Coding!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use dynamic require in Remix? In a Remix action, I use a dynamic require to retrieve different JSON files:
export async function action({ request }: { request: Request }) {
  const body = await request.formData();
  const country = body.get("country");

  const cities = require(`~/cities_by_country/${country}.json`);

  return cities;
}

This produces and "Application Error": Error: Cannot find module '~/cities_by_country/Afghanistan.json'
It turns out that the dynamic require is the issue. Hardcoding the country like this works:
const cities = require(`~/cities_by_country/Afghanistan.json`);

I read that adding "module": esnext (or es2020 or es2022) to tsconfig.json would enable dynamic imports, at least for React. I tried it but got the same results.
I've read these docs as well to no avail:

*

*asset url imports

*data-loading

*resource routes
What am I missing?


text:
Q: Pandas Populate all rows that match with index of another dataframe Consider a data frame
Major = Date, Sales Cost, Sales Channel
There are multiple types of Sales Channels.
There is another data frame
Minor = Date, Agent Type, Agent Id
For a given date there will be multiple columns in Major.
However, only one column corresponding to a date in Minor.
Two new columns need to be added to Major, based on Date.
Here is what I have tried
Major.join(Minor.set_index('Date'), on='Date')
print(Major.columns)

This does not add new columns to Major, based on those that are present in Minor.
To simplify : For all date in a larger dataframe, add new columns from a smaller data frame, when date is matching.
Major
Date    Sales Cost  Sales Channel
01/12/2020  5000    Alpha
01/12/2020  10000   Alpha
01/13/2020  13000   Beta
01/14/2020  23000   Beta
01/15/2020  24000   Gamma
01/16/2020  1200    Alpha

Minor
Date    Agent Type  Agent Id
01/12/2020  Online  1234
01/12/2020  Offline 1233
01/13/2020  Online  1245
01/14/2020  Online  1232
01/15/2020  Offline 1256
01/16/2020  Offline 1234

Merged for first date
Date    Sales Cost  Sales Channel   Agent Type  Agent Id
01/12/2020  5000    Alpha   Online  1234
01/12/2020  5000    Alpha   Online  1234
01/12/2020  5000    Alpha   Offline 1233
01/12/2020  5000    Alpha   Offline 1233

A: Just merge the datasets:
result = Major.merge('Minor', on='Date', how='left')
result.set_index('Date')


text:
Q: Getting started with Exchange Web Services 2010 I've been tasked with writing a SOAP web-service in .Net to be middleware between EWS2010 and an application server that previously used WebDAV to connect to Exchange. (As I understand it, WebDAV is going away with EWS2010, so the application server will no longer be able to connect as it previously did, and it is exponentially harder to connect to EWS without WebDAV. The theory is that doing it in .Net should be easier than anything else... Right?!)
My end goal is to be able to get and create/update email, calendar items, contacts, and to-do list items for a specified Exchange account. (Deleting is not currently necessary, but I may build it in for future consideration, if it's easy enough).
I was originally given some sample code, which did in fact work, but I quickly realized that it was outdated. The types and classes used appear nowhere in the current documentation.
For example, the method used to create a connection to the Exchange server was:
ExchangeService svc = new ExchangeService();
svc.Credentials = new WebCredentials(AuthEmailAddress, AuthEmailPassword);
svc.AutodiscoverUrl(AutoDiscoverEmailAddress);

For what it's worth, this was using an assembly that came with the sample code: Microsoft.Exchange.WebServices.dll ("MEWS").
Before I realized that this wasn't the current standard way to accomplish the connection, and it worked, I tried to build on it and add a method to create calendar items, which I copied from here:
static void CreateAppointment(ExchangeServiceBinding esb)
{
    // Create the appointment.
    CalendarItemType appointment = new CalendarItemType();

    ...
}

Right away, I'm confronted with the difference between ExchangeService and ExchangeServiceBinding ("ESB"); so I started Googling to try and figure out how to get an ESB definition so that the CreateAppointment method will compile. I found this blog post that explains how to generate a proxy class from a WSDL, which I did.
Unfortunately, this caused some conflicts where types that were defined in the original Assembly, Microsoft.Exchange.WebServices.dll (that came with the sample code) overlapped with Types in my new EWS.dll assembly (which I compiled from the code generated from the services.wsdl provided by the Exchange server).
I excluded the MEWS assembly, which only made things worse. I went from a handful of errors and warnings to 25 errors and 2,510 warnings. All kinds of types and methods were not found. Something is clearly wrong, here.
So I went back on the hunt. I found instructions on adding service references and web references (i.e. the extra steps it takes in VS2008), and I think I'm back on the right track.
I removed (actually, for now, just excluded) all previous assemblies I had been trying; and I added a service reference for https://my.exchange-server.com/ews/services.wsdl
Now I'm down to just 1 error and 1 warning.

Warning:
  The element 'transport' cannot contain child element 'extendedProtectionPolicy' because the parent element's content model is empty.

This is in reference to a change that was made to web.config when I added the service reference; and I just found a fix for that here on SO. I've commented that section out as indicated, and it did make the warning go away, so woot for that.
The error hasn't been so easy to get around, though:

Error:
  The type or namespace name 'ExchangeService' could not be found (are you missing a using directive or an assembly reference?)

This is in reference to the function I was using to create the EWS connection, called by each of the web methods:
private ExchangeService getService(String AutoDiscoverEmailAddress, String AuthEmailAddress, String AuthEmailPassword)
{
    ExchangeService svc = new ExchangeService();
    svc.Credentials = new WebCredentials(AuthEmailAddress, AuthEmailPassword);
    svc.AutodiscoverUrl(AutoDiscoverEmailAddress);
    return svc;
}

This function worked perfectly with the MEWS assembly from the sample code, but the ExchangeService type is no longer available. (Nor is ExchangeServiceBinding, that was the first thing I checked.)
At this point, since I'm not following any directions from the documentation (I couldn't find anywhere in the documentation that said to add a service reference to your Exchange server's services.wsdl -- but that does seem to be the best/farthest I've gotten so far), I feel like I'm flying blind.
I know I need to figure out whatever it is that should replace ExchangeService / ExchangeServiceBinding, implement that, and then work through whatever errors crop up as a result of that switch...
But I have no idea how to do that, or where to look for how to do it. Googling "ExchangeService" and "ExchangeServiceBinding" only seem to lead back to outdated blog posts and MSDN, neither of which has proven terribly helpful thus far.
What should I replace ExchangeService / ExchangeServiceBinding with? Is there some other location that documents working with EWS that is better than MSDN?

A: I would recommend moving to the Managed EWS API.  It's much easier to use than trying to cobble everything together yourself.  It supports both Exchange 2007 SP1 and Exchange 2010.  I think you'll find it much easier to use and will probably eliminate your issues.
Version 1:
Here is the download from Microsoft.
And here are the MSDN docs.
For Version 2 (thanks @ruffin!)
Download - MSDN Docs

Added by question asker:
Additional links that proved helpful:

*

*Setting the service URL (manually or via Autodiscover)

*Working with the EWS Managed API - some basic documentation on common tasks

*Download for EWS Managed API installer - same download as above; also includes a little bit of documentation and intellisense data for visual studio.


text:
Q: Java 8 sort list of objects I am trying to sort my list of objects like this:
List<UsersDataFoundTo> mergedUsers = mergeUsersFound(ldapUsers, foundUsers);
return mergedUsers.sort((UsersDataFoundTo h1, UsersDataFoundTo h2) -> h1.getLastName().compareTo(h2.getLastName()));

and on the return statement I get an error:
Incompatible types.
Required: java.util.List<UsersDataFoundTo>
Found:void

What do I do wrong then?

A: Much easier would be to write is as:
mergedUsers.sort(Comparator.comparing(UsersDataFoundTo::getLastName))

And sort has a void return type, so basically do a :
return mergedUsers;

A: For reusable, I think the class UsersDataFoundTo should implements Comparable and override compareTo function.
class UsersDataFoundTo implements Comparable<UsersDataFoundTo> {
    private String lastNam;

    public String getLastNam() {
        return lastNam;
    }

    public void setLastNam(String lastNam) {
        this.lastNam = lastNam;
    }

    @Override
    public int compareTo(UsersDataFoundTo other) {
        return getLastNam().compareTo(other.getLastNam());
    }
}

Then you can use a collection utility to sort it like this:
List<UsersDataFoundTo> mergedUsers = //...
java.util.Collections.sort(mergedUsers);

I hope this help.


text:
Q: How can I download only the first kilobyte of content of a URL with PowerShell? My main goal is to periodically poll a file hosted by a PaaS provider (Azure) to prevent it from becoming cold. It is a 600K+ pdf, so if I poll it once a minute, this could generate a significant amount of data (more than 20GB) per month.
The two methods I tried both perform full download of the data:

*

*Invoke-WebRequest -Uri https://app.whatever.com/docs/staywarm.pdf

*((New-Object Net.WebClient).DownloadString('https://app.whatever.com/staywarm.pdf'))
I'd like to only get the first 1K, or even just the first 100 bytes. My theory that even that should keep that file warm.

I have the "Always on" turned on already. So it's interesting that the PDF still often takes 20 seconds to start downloading. The named PDF BTW is a Terms of Service PDF which has to be accepted by the user before login. So when it has to download the application itself should be warm already, since all the files (HTML, CSS, JS) related to the login page had to be served to the browser. So I thought that individual files like that big PDF can remain cold, although the app itself is warm?

A: You may turn on the Always On option:

It will prevent your app from being idled out due to inactivity

If you still want to use your way, you may just program to make your web app response a empty string to a specific path. For example: in .NET web application, you can directly response one OK action result for path '/check'.

A: Currently I have this script I execute:
$wc = (New-Object Net.WebClient).OpenRead('https://app.whatever.com/docs/staywarm.pdf')
$tr = New-Object -TypeName System.IO.StreamReader -ArgumentList $wc
$tr.ReadLine()
$tr.Close()


text:
Q: I want a file value or name when I upload a file in html javascript? <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <input type="file" name="" id="filee">
    <button onclick= "ftn()" id="btn">Choose a File</button>

This is my code. I'm getting value when i clicked button 2nd time. I want a value in span tag of my file when i click on button and open it. This giving value when i clicked again a button and show me previous value of file. Thanks if you get my point

A: You'll want to know the name of the file whenever you've uploaded it to the browser. That means that you have to listen for  the change event on the file input.

let file = document.getElementById('filee');
let btn = document.getElementById("btn");
let filename = document.getElementById("filename");

file.addEventListener('change', event => {
  const [file] = event.target.files
  filename.innerText = file.name;
});

btn.addEventListener('click', () => {
  file.click();
});
#filee {
  clip: rect(0 0 0 0);
  clip-path: inset(50%);
  height: 1px;
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
  width: 1px;
}
<input type="file" name="" id="filee">
<button type="button" id="btn">Choose a File</button>


text:
Q: Scala: generate Java annotation with parameter using Scala macros I have simple Java annotation with one parameter:
public @interface Annot {
   String value();
}

Also I have Java annotation that takes array of Annot as parameter:
public @interface Annotations {
    Annot[] value();
}

I want to generate Annot with paramter "value" using Scala macro like this:
object MyAnnotations {

  def MyAnnotation: Annot = macro myAnnotationMacro

  def myAnnotationMacro(c: whitebox.Context): c.Expr[Annot] = {
    import c.universe._
    c.Expr(q"""new Annot("value")""")
  }
}

While this works:
@Annotations(Array(
  new Annot("value")
))
trait T

This doesn't work:
@Annotations(Array(
  MyAnnotations.MyAnnotation
)) // too many arguments for constructor Annot: ()Annot
trait T

Why? And how can I generate Annot?

A: I'm afraid that you can't do what you want with macros.
Typechecking of Java annotations is implemented in a very weird way that is significantly different from the rest of the typechecker. While everything else is typechecked from Tree to Tree, arguments to Java annotations are typechecked from Tree to ClassfileAnnotArg (with the latter not being trees). Your macro expands into a Tree, whereas the typechecker expects ClassfileAnnotArg, so things don't work (and the error message is quite misleading).
I think that it would be possible to change the typechecker to work in your case, but that will require patching the compiler. No idea how to do that from within a macro.


text:
Q: typedef с рекурсией в си Коллеги, подскажите pls, можно ли в компиляторах gcc, clang объявить содержащий рекурсию тип?
Например, без рекурсии чудесно проходит, а с ней - нет:
struct {
    int a;
    char *b;
    my_t *next;
} typedef my_t;

Заранее признателен за подсказку.

A: Либо
typedef struct my_t {
  int a;
  char *b;
  struct my_t *next;
} my_t;

либо
typedef struct my_t my_t;

struct my_t {
  int a;
  char *b;
  my_t *next; // или `struct my_t *next;`
};

либо
struct my_t {
  int a;
  char *b;
  struct my_t *next;
};

typedef struct my_t my_t;

Ключевое слово typedef можно порекомендовать ставить первым в typedef-объявлении, а не запихивать его в середину.

Другими словами проблема "рекурсивного определения" решается путем назначения struct-типу непустого тэга и использования полного имени типа struct <tag> при объявлении внутреннего указателя
struct my_t {
  int a;
  char *b;
  struct my_t *next;
};

а куда при этом вы поставите ваш
typedef struct my_t my_t;

(до объявления струкутры, после объявления струкутры, сольете в одно объявление или вообще не будете делать typedef) - это уже вопрос посторонний.

A: struct myt;
typedef struct myt my_t;

struct myt
{
    int a;
    char *b;
    my_t *next;
};


text:
Q: Exclude images from lightbox in "Photo Swipe Masonry" i am using the "Photo Swipe Masonry" plugin (version 1.0.6) on wordpress 4.3.1.
It works perfect so far.
But, i have some images which have a custom link to an external url(instead of the stadard to the image).  If i click one of these images, it opens the url in a new window. That works like expected.
Now, when i click on an standard image(no external url), the lightbox opens and the image is displayed like expected.
But now, when i use the prev/next buttons to navigate through the images and i reach an image with a custom link, i got the errormessage:
"The image could not be loaded" (in the lightbox).
So, my question is, how to exclude images from being added to the lightbox?
Maybe by a unique class ?
Any help is highly appreciated.
Many thanks in advance to all of you for your time.
Regards,
Joe

A: I'm the developer of this plugin. Sorry for missing this post. There is no function built in for this sorry. You would need to edit the photoswipe code.


text:
Q: Synchronous http interface with javascript I have a synchronous API to invoke a server (HTTP GET) currently implemented with XMLHttpRequest.
The API does caching and will, if cache isn't deemed too old, return from the cache and invoke the server asynchronous to refresh cache.
Sometimes cache isn't available or too old, and then the API will synchronous call the server to fetch an accurate value before returning result to caller.
Result will contain a boolean success flag along with payload and clients handles result accordingly by looking at this flag.
There are two problems I can see with doing like this;
When cache isn't available and server isn't reachable or answering slow I would like to bring up a spinner so that the user is aware we are waiting for server.
In addition I would like to set a timeout value where we abort server request and handle the error accordingly.
Seems like I should be able to use setTimout operations but I have not been successful.
Preferably I would like to keep clients intact (not change the API to asynchronous).
Is there a way to achieve this?

A: The synchronous API was made responsive by maintaining a cache that was pulled from server asynchronous.
The cache was protected by a grace period under which we do not pull new value from server to avoid hammering the server.
For the most cases this was enough to assert there was always a cached value that could be provided to the client.
For a few cases where we have to pull new data the best solution would be to go fully asynchronous, that is also update client code.
Currently that is not an option, so in addition to above a heartbeat mechanism was put in place that toggles online/offline status to prevent trying synchronous pulls when offline.


text:
Q: How to enable dotenv variables for a file inside the /public folder in a Vue project? I have very little experience with configuring Webpack, and I'am a bit overwhelmed by this issue.
I've been working on a Vue2 project built on top of this boilerplate. The project has a folder called public which contains the entry point file index.html. Inside that index.html file I can normally access .env environment variables (e.g. process.env.VUE_APP_PAGE_TITLE).
I've included an HTML fragment inside the public folder, navbar.html, because I want it to be available for other applications via https://example.com/public/navbar.html. However, I cannot seem to get my environment variables working inside ./public/navbar.html even though they work just fine in ./public/index.html. I assume this is a problem with my webpack config.
I know I can edit my Webpack config by editing a file in my project root called vue.config.js. This file contains a configureWebpack object, but I have no idea how to make it enable environment variables inside ./public/navbar.html. Any help would be appreciated.

EDIT:
Here's my vue.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');

function resolveClientEnv() {
  const env = {};
  Object.keys(process.env).forEach((key) => {
    env[key] = process.env[key];
  });
  env.BASE_URL = '/';
  return env;
}

module.exports = {
  configureWebpack: {
    plugins: [
      new HtmlWebpackPlugin({
        // This is the generated file from the build, which ends up in public/navbar.html
        filename: 'navbar.html',
        // This is the source file you edit.
        template: 'public/navbar.html',
        templateParameters: (compilation, assets, pluginOptions) => {
          let stats;
          return Object.assign({
            // make stats lazy as it is expensive
            get webpack() {
              return stats || (stats = compilation.getStats().toJson());
            },
            compilation,
            webpackConfig: compilation.options,
            htmlWebpackPlugin: {
              files: assets,
              options: pluginOptions,
            },
          }, resolveClientEnv());
        },
      }),
    ],
  },
};

This is what my custom HTMLWebpackPlugin adds to the configuration according to vue inspect:
{
  options: {
    template: 'public/navbar.html',
    templateContent: false,
    templateParameters: function () { /* omitted long function */ },
    filename: 'navbar.html',
    hash: false,
    inject: true,
    compile: true,
    favicon: false,
    minify: 'auto',
    cache: true,
    showErrors: true,
    chunks: 'all',
    excludeChunks: [],
    chunksSortMode: 'auto',
    meta: {},
    base: false,
    title: 'Webpack App',
    xhtml: false
  },
  childCompilerHash: undefined,
  childCompilationOutputName: undefined,
  assetJson: undefined,
  hash: undefined,
  version: 4
}

A: Use this standard plugin to generate navbar.html. https://github.com/jantimon/html-webpack-plugin.
If you read the docs, the templateParameters option is what you pass env variables to. Those variables will be available in navbar.html.
This is the same plugin that vue-cli uses for index.html. If you run the vue inspect command, you can see what options they provide to the plugin. You'll need to read the source code for resolveClientEnv() to see how it works.
Example:
    /* config.plugin('html-portal') */
    new HtmlWebpackPlugin(
      {
        templateParameters: (compilation, assets, pluginOptions) => {
                // enhance html-webpack-plugin's built in template params
                let stats
                return Object.assign({
                  // make stats lazy as it is expensive
                  get webpack () {
                    return stats || (stats = compilation.getStats().toJson())
                  },
                  compilation: compilation,
                  webpackConfig: compilation.options,
                  htmlWebpackPlugin: {
                    files: assets,
                    options: pluginOptions
                  }
                }, resolveClientEnv(options, true /* raw */))
              },
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeAttributeQuotes: true,
          collapseBooleanAttributes: true,
          removeScriptTypeAttributes: true
        },
        chunks: [
          'chunk-vendors',
          'chunk-common',
          'portal'
        ],
        template: 'C:\\Users\\Eric\\workspace\\arc-core\\portal\\client\\templates\\portal.html',
        filename: 'portal.html',
        title: 'Arc Portal'
      }
    ),

That's a bit much, a minimal example would be:
new HtmlWebpackPlugin({
    // This is the generated file from the build, which ends up in public/navbar.html
    filename: 'navbar.html',
    // This is the source file you edit.
    template: 'templates/navbar.html',
    templateParameters: {
        MY_VAR: 'myVar'
    }
}),


text:
Q: How to hide the Text Area in the Post Edit screen Is there a way to hide the text area box in my custom post edit screen? All entry is done through taxonomy check boxes and a couple custom fields. I want no entry in the text area.
As an alternative, how can I place a "Enter Nothing Here" text message within the text area?
I know this is a little bizarre, but is it possible?
Thanks -- Mike

A: In your functions.php file where the custom post type is registered do you see:
'supports' => array('title','editor','thumbnail')

or something similar? If so remove 'editor'


text:
Q: My first python program: can you tell me what I'm doing wrong? I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.
I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.
This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions:

*

*My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements.

*Am I using the correct libraries? Am I using them correctly?

*Am I using the correct datatypes? Am I using them correctly?

I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when).
The source (one file, 92 lines of code)
http://code.google.com/p/floep/source/browse/trunk/floep

A: Before unloading any criticism, first let me say congratulations on getting your first Python program working.  Moving from one language to another can be a chore, constantly fumbling around with syntax issues and hunting through unfamiliar libraries.
The most quoted style guideline is PEP-8, but that's only a guide, and at least some part of it is ignored...no, I mean deemed not applicable to some specific situation with all due respect to the guideline authors and contributors :-).
I can't compare it to PHP, but compared to other Python applications it is pretty clear that you are following style conventions from other languages.  I didn't always agree with many things that other developers said you must do, but over time I recognized why using conventions helps communicate what the application is doing and will help other developers help you.

Raise exceptions, not strings.

raise 'Server or group ' + sectionname + ' not found in ' + configfile
becomes
raise RuntimeError('Server or group ' + sectionname + ' not found in ' + configfile)

No space before the ':' at the end of an 'if' or 'for', and don't put multiple statements on the same line, and be consistent about putting spaces around operators.  Use variable names for objects and stick with i and j for loop index variables (like our masterful FORTRAN forefathers):

for i in grouplist : servers+=getServers(i)
becomes:
for section in grouplist:
    servers += getServers(section)

Containers can be tested for contents without getting their length:

while len(threadlist) > 0 :
becomes
while threadlist:
and
if command.strip() == "" :
becomes
if command.strip():

Splitting a tuple is usually not put in parenthesis on the left hand side of a statement, and the command logic is a bit convoluted.  If there are no args then the " ".join(...) is going to be an empty string:

(options,args) = parser.parse_args()

if options.verbose : print "floep 0.1"

command = " ".join(args)

if command.strip() == "" : parser.error('no command given')

becomes

options, args = parser.parse_args()
if options.verbose:
    print "floep 0.1"

if not args:
    parser.error('no command given')
command = " ".join(args)

A python for loop has an unusual 'else' clause which is executed if the loop goes through all of the elements without a 'break':

    for server in threadlist :
        foundOne = False
        if not server.isAlive() :
            ...snip...
            foundOne = True

        if not foundOne :
            time.sleep(0.010)

becomes

    for server in threadlist:
        if not server.isAlive():
            ...snip...
            break
    else:
        time.sleep(0.010)

Getting a list of lines and then joining them back together is a bit long winded:

        result = proc.readlines()
        strresult = ''
        for line in result : strresult+=line
        self.result = strresult

becomes

        self.result = proc.read()

Your library use is good, check out the subprocess module, it's a little more up-to-date.

Your datatypes are fine.
And you'll get lots of other anwsers :-)

A: String exceptions are deprecated in Python, so this line:
if not config.has_section(sectionname):
    raise 'Server or group ' + sectionname + ' not found in ' + configfile

should be reworked into something like this:
if not config.has_section(sectionname):
    raise ConfigNotFoundError(
        "Server or group" + sectionname + "not found in" + configfile)

class ConfigNotFoundError(Exception):
    pass

[Edited to reflect the suggestion of dangph in the comments]
It's more lines of code, but it's better for future upgrades.
For readability's sake, something like this:
parser.add_option('-q','--quiet',action="store_false", help="Display only server output", dest="verbose", default=True)

Can be rewritten like this:
parser.add_option('-q',
                  '--quiet',
                  action="store_false",
                  help="Display only server output",
                  dest="verbose",
                  default=True)

You might prefer another method of splitting the method call up, but the idea is that long lines can be hard to read.
You should also read PEP 8 to get a sense of Python style.

A: Often, for reuse purposes, we do the following, starting at about line 48 in your program
def main():
    config = ConfigParser.RawConfigParser()
    etc.

if __name__ == "__main__":
    main()

This is just a starting point.
Once you've done this, you realize that main() is really two parts: parsing the command-line interface and doing the work.  You then want to refactor things to look like this.
def serverWork(group,...):
    servers = getServers(group)
    etc.

def main():
    config = ConfigParser.RawConfigParser()

    if command.strip() == "":
        parser.error('no command given')
    else:
        serverWork( options.group, options.etc., ... )

Now, you have elevated the real work to a function within this module.  Your serverWork function can now be reused easily by other programs or scripts.

A: Usually is preferred that what follows after the end of sentence : is in a separate line (also don't add a space before it)
if options.verbose:
  print ""

instead of
if options.verbose : print ""

You don't need to check the len of a list if you are going to iterate over it
if len(threadlist) > 0 :
  for server in threadlist :
    ...

is redundant, a more 'readable' is (python is smart enough to not iterate over an empty list):
for server in threadlist:
  ...

Also a more 'pythonistic' is to use list's comprehensions (but certainly is a debatable opinion)
server = []
for i in grouplist : servers+=getServers(i)

can be shortened to
server = [getServers(i) for i in grouplist]


text:
Q: Intellij IDEA code coverage doesn't work When I'm trying to run my JUnit tests with coverage I receive the following error
FATAL ERROR in native method: processing of -javaagent failed
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:382)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:397)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.coverage.main.CoveragePremain.premain(CoveragePremain.java:50)
    ... 6 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
    at com.intellij.rt.coverage.instrumentation.Instrumentator.premain(Instrumentator.java:40)
    ... 11 more
Exception in thread "main"
Process finished with exit code 1

Can anybody help to fix it?

A: Take a look here:
https://youtrack.jetbrains.com/issue/IDEABKL-5941
You can add -Djava.io.tmpdir param to idea's launching script or replace TMP system property.
Also probably you will have to change idea.config.path and idea.system.path in idea.properties in installation directory.


text:
Q: swift image resize and save resolution issue I have a problem with image size.
Initially I have image with any size which I crop to square
func cropToSquare() -> NSImage? {
    let dimensions = [self.width, self.height]
    let lessValue = dimensions.min()
    let x = floor((self.width - lessValue!) / 2)
    let y = floor((self.height - lessValue!) / 2)
    let frame = NSMakeRect(x, y, lessValue!, lessValue!)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: NSSize(width: lessValue!, height: lessValue!))
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: NSMakeRect(0, 0, lessValue!, lessValue!),
                from: frame,
                operation: NSCompositingOperation.copy,
                fraction: 1.0,
                respectFlipped: false,
                hints: [:]) {
        return img
    }
    return nil
}

Next I resize image
func copyWithSize(size: NSSize) -> NSImage? {
    let frame = NSMakeRect(0, 0, size.width, size.height)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: size)
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: frame) {
        print(size, frame)
        return img
    }
    return nil
}

finally saving image to file using the png extension from this answer
Generally everything working OK ... except image size.
When I start with some size and resize to let say 100x100 my saved image has a double size (200x200).
What's wrong with my code ?

A: The image is drawing in @2x because you have a Mac with a Retina display.
Using lockFocus creates a new image for displaying on the screen, which is impractical if you want to save it to a file.
You could get the scaling factor using:
NSScreen.main.backingScaleFactor
and adjust your resize accordingly.
But the best solution is to create a NSBitmapImageRep and manually set it's size to the size you want the image.


text:
Q: console Proxy which keeps line numbers, has prefix AND respects string substitution I've created a console Proxy which right now doesn't do much more than adding a prefix on each line written to the console, and it works perfectly, even keeps line numbers intact (that is, the messages have the proper origin shown by the browser). Here is the code:
const disabledMethodsInProduction = ['debug', 'log', 'trace'];
logger = new Proxy(console, {
    get (target, method) {
        if (method in target) {
            if (!developmentMode && disabledMethodsInProduction.includes(method)) {
                return () => { /* NOP */ };
            }
            // 'loggingID' is a string, defined elsewhere.
            return target[method].bind(console, `${loggingID}:`);
        }
        throw new Error(`Method '${method}()' not implemented in console.`);
    }
});

The problem with the above code is the same that other solutions that I've investigated (and commented) here in Stack Overflow. To wit, the prefix (in this case, the loggingID string) is now the FIRST argument of the console object method, so when calling the proxy object above with a message containing string substitutions (%c for example), they won't be processed because they are now the SECOND argument instead.
The fix is easy: instead of returning the console method, a new function can be returned which traps the arguments provided and if the first one is a string and contains string substitutions, the prefix is inserted in that argument, instead of being a different argument:
return function () {
    // Do things with 'arguments' and pass it to the proper console method.
    const args = Array.from(arguments);
    // Yes, I know, first I should check args[0] to see
    // if it is a string and contains string substitutions.
    args[0] = `${loggingID}: ` + args[0];
    target[method](...args);  // THIS line number will appear in console messages, obviously.
}

Unfortunately, doing that clobbers the original line numbers, obviously.
Any solution to have both features, that is, keeping line numbers and trapping the arguments at the same time?
I can live with losing the ability of using string substitutions, as keeping line numbers is far more important for me, but I'm just curious about how to solve this, and I would love to have both features.

A: I found a way of achieving what I need but requires a set of extra parens:
const disabledMethodsInProduction = ['debug', 'log', 'trace'];
logger = new Proxy(console, {
    get (target, method) {
        if (method in target) {
            if (!developmentMode && disabledMethodsInProduction.includes(method)) {
                return () => { /* NOP */ };
            }
            return function (...args) {
                // An additional check for string subtitution chars is needed.
                if (typeof args[0] === 'string') {
                    // 'loggingID' is a string, defined elsewhere.
                    args[0] = `${loggingID}: ${args[0]}`;
                }
                return target[method].bind(console, ...args);
            };
        }
        throw new Error(`Method '${method}()' not implemented in console.`);
    }
});

// Should be used like this:
// logger.log('%cThis is bold', 'font-weight:bold')();

Notice the extra pair of parentheses when calling the proxied object method.
This solution:

*

*Preserves line numbers, showing those of the caller.

*Can selectively disabled in production.

*Honors string substitutions in the first argument.

If anyone has any idea about how getting rid of the ugly extra pair of parentheses, I'm all ears.


text:
Q: Better percentile rank for subsets of data that works like PERCENTRANK.INC() in Excel? We use PERCENTILERANK.INC() in Excel with no issues. The column below labeled "Pctl Inc" uses this formula:
=PERCENTRANK.INC($B$2:$B$6,B2,3)

I also built a formula that ranks a subset of values among the subset data based on another columns text values. My formula works just like the one in this link:
http://www.exceltactics.com/calculate-percentile-conditional-ranking-using-sumproduct/
Here is the specific formula I am referring to in that link:
=(SUMPRODUCT(($A$2:$A$6=A2)*(B2>=$B$2:$B$6)))/COUNTIF($A$2:$A$6,A2)

(Note that the site link has a typo in the formula and mine is the one you want to use to test.)
The formula above is labeled "Pctl W/in" in the data I provide below.
The column "Subset Labels" indicates the subset they should be in. More on that later. "Values to Rk" are the items being ranked in all cases.
My goal is to change only the "Pctl W/in" formula so that it returns the same values as the "Pctl Inc" column would if subsetting weren't involved. I.e. we like the behavior of the "Pctl Inc" column, but we need a formula to mimic that ranking style for a subset of the same data.
Here is the data you can use to create a "match". Note that I intentionally have all of the "Subset Labels" the same so you can match the ranks easily. The Pctl Inc and Pctl W/in value should be the same here since they all have the same Subset Labels:
Without Subsets:

*

*Subset Labels,   Values to Rk,   Pctl Inc,   Pctl W/in

*a,   100,    1,  1

*a,   0,  0.25,   0.4

*a,   6,  0.5,    0.6

*a,   -1, 0,  0.2

*a,   7,  0.75,   0.8

The "Pctl W/in" data is wrong, hence this post.The values above are what I am getting currently and I would like them to be like the "Pctl Inc" values when you take out the subset component:
With Subsets:
For the a's:

*

*Subset Labels    Values to Rk    Pctl Inc

*a,   100,    1

*a,   0,  0.5

*a,   -1, 0

For the b's:

*

*Subset Labels,   Values to Rk,   Pctl Inc

*b,   6,  0

*b,   7,  1

In other words, the ranks for all should look like this if it is working correctly:

*

*Subset Labels,   Values to Rk,   Pctl Inc,   Pctl W/in

*a,   100,    1,  1

*a,   0,  0.25,   0.5

*b,   6,  0.5,    0

*a,   -1, 0,  0

*b,   7,  0.75,   1

PS - can someone tell me how one creates good grids in stackoverflow posts?

A: Here is the answer:
=IFERROR(1-(COUNTIFS(A$2:A$6,A2,B$2:B$6,">="&B2)-1)/(COUNTIF(A$2:A$6,A2)-1),1)

Notes:

*

*An array formula could solve this more simply, but I cannot use an array formula.

*The IFERROR(...,1) wrap solves a #DIV/0 error when there is only one of any particular Subset Label (ex. many a's and only one b).

*This correctly mimics PERCENTRANK.INC() when there is a tie in ranked values.


text:
Q: selecting whole entities from SQLAlchemy subqueries If I specify mapped classes (~= database tables) in a SQLAlchemy query, then the returned rows will contain instances of those classes:
q = sess.query(table1, table2, table3.string_column)
q.first()
==> ( <instance of table1>,
      <instance of table2>,
      'string' )

However, if I select from a subquery, then the returned rows contain the individual columns rather than the class instances:
q = sess.query(table1, table2, table3.string_column)

q2 = sess.query( q.subquery() )
q2.first()
==> ( col1_of_table1, col2_of_table1, ...,
      col2_of_table2, col2_of_table2, ...,
      'string' )

Is there a way to specify that I want to preserve the row from the subquery as an instance of a mapped class?
I can't figure out how to do this without joining to a new instance of the mapped classes. The corresponding_column method allows me to refer to specific columns from the subquery, but I can't figure out how to refer to complete entities from the subquery. I've tried playing around with select_from but it doesn't give me the right behavior.
Any suggestions?

A: the query that returns entities always needs to be told about those entities - thats the things it wants to "select".  The source of rows is what it wants to select "from".   Two separate things.
so given:
q = sess.query(table1, table2, table3.string_column)
q = q.subquery()

once you call subquery(), the ORM-ness of the query is mostly gone, it's just a SELECT object.  To select entities from that you have to name them out again, and use select_entity_from (which if you are actually on 0.7, is what select_from() was back then; you'd need to be specific about "not the right behavior):
q2 = sess.query(table1, table2, table3.string_column).select_entity_from(q)

A: According to Selecting Entities from Subqueries, you can use keyword aliased()


text:
Q: How can i get past the kernel panic error? I had a problem with Ubuntu, it became slow after I got a message saying that a partition was full. So I opted to resize the partition.
So recently I installed Windows 10 in my laptop. The OS (Windows 10) ended up overwriting my ubuntu bootloader. So I created a USB bootable disk for Xubuntu, then I resized and moved the partitions I had on Ubuntu without any consideration of the messages I got saying moving a partition might corrupt a partition and make the Ubuntu OS not boot. Then I used the terminal to reinstall grub. I used:
$ sudo mount /dev/sda6 /mnt/boot \#which is where my boot partition
$ sudo grub-install --boot-directory=/mnt/boot /dev/sda

Then I restarted my computer. It brought me to the grub menu as usual but past that it stops at error:  kernel panic unable to mount the root fs.
Then tried to use boot-repair, but it did not help. The boot-repair application save its info here.


text:
Q: Let $f:[a,b]\to[f(a),f(b)]$ be monotone increasing and continuous. Prove that $f$ is a homeomorphism. (w/o IVT) I'm reading Intro to Topology by Mendelson.
The section is titled Connectedness of the Real Line, it's the section right before IVT is introduced.
I've been working on this problem, but I'm stuck on how to show that the function is onto. I know that because its monotone (strictly) increasing, that $f$ must be one-one. Intuitively, I know that the function must be onto, yet I'm having putting it down on paper.
To show the homeomorphism, I know that I have to show that either there is a continuous inverse function of $f$ or show that $f$ is a bijection and that every subset $O$ of $[a,b]$ is open if and only if $f(O)$ is open. To approach it using the second method I know that open sets in $\mathbb{R}$ are open intervals and for continuous functions the image of each interval is an interval, but do we know that an open interval maps to an open interval?
Thank you for any hints on how to approach this.

A: Since $f$ is increasing, it is injective (proof?). One should actually prove, in my opinion, that $f([a,b])=[f(a),f(b)]$. It is clear that $f([a,b])\subseteq [f(a),f(b)]$ since $f$ is monotone. Can you prove the other inclusion? You do need the intermediate value theorem here! With this out of the way, one has a one one, onto function of the form $$f:[a,b]\to[c,d]$$
It's inverse then exists. Can you show it is continuous?

A: Surjectivity Hints:

*

*Let $y \in \lbrack f(a),f(b) \rbrack$. Let $x_1 = \sup \{x \in \lbrack a,b \rbrack : f(x) < y\}$ and $x_2 = \inf\{x \in \lbrack a,b\rbrack : f(x) > y\}$. What's true about $x_1$ and $x_2$?

*Using the answer you found to my first question and the continuity of $f$, can you prove that $f(x_1) = y$? (The easiest way to do this does not use IVT.)

*This will prove that $\lbrack f(a),f(b) \rbrack \subset f(\lbrack a,b\rbrack)$. What about the opposite containment? (It's easier.)
Continuity Hints:

*

*You now have a bijective function $f$ from $I = \lbrack a,b\rbrack$ onto another interval. Bijective $\implies$ $f^{-1}$ exists.

*Let $\epsilon > 0$ and $a \leq x_0 \leq b$. The continuity of $f$ implies there exists $\delta > 0$ such that for all $x \in \lbrack a,b\rbrack$ such that $|x-x_0| < \delta$ we have $|f(x) - f(x_0)| < \epsilon$. Rewrite these inequalities in terms of $f^{-1}(y)$ and $f^{-1}(y_0)$ where $y = f(x)$ and $y_0 = f(x_0)$. Alternatively, note that this says $f((x_0-\delta,x_0+\delta)) \subset (f(x_0)-\epsilon,f(x_0)+\epsilon)$ and reach a conclusion from that.

A: From increasing you can easily show that $f$ is injective.
Let's show that $f:[a,b]\rightarrow\left[f(a),f(b)\right]$ is onto. If it's not onto and $S=\{x\in[a,b]:[f(a),f(x)]\subseteq[f(a),f(b)]\}, T=\{x\in[a,b]:[f(x),f(b)]\subseteq[f(a),f(b)]\}$ then by considering the $\sup S$  and $\inf T$ and taking the limits of $f(x)$ as $x\to\sup S$ and $x\to\inf T$ you can derive a contradiction.


text:
Q: Google App Engine Added task goes missing When I add a task to the task queue, sometimes the task goes missing. I dont get any errors but I just dont find the tasks in my logs. Suppose I add n tasks. The computation cannot go forward without these n tasks finishing. However, I find that one or more of these n tasks just went missing after they were added and my whole algorithm stops in the middle.
What could be the reason ?
I keep a variable w to check the number of times the task was added. I observe w = n though some tasks were not created.
def addtask_whx(index,user,seqlen,vp_compress,iseq_compress):
global w
while True :
    timeout_ms = 100
    taskq_name = 'whx'+'--'+str(index[0])+'-'+str(index[1])+'-'+str(index[2])+'-'+str(index[3])+'-'+str(index[5]) + '--' + user

    try :

        taskqueue.add(name=taskq_name+str(timeout_ms),queue_name='whx',url='/whx', params={'m': index[0],'n': index[1],'o': index[2],'p': index[3],'q':0,'r':index[5],'user': user,'seqlen':seqlen,'vp':vp_compress,'iseq':iseq_compress})
        w = w+1
        break
    except DeadlineExceededError:
        taskq_name = taskq_name + str(timeout_ms)
        time.sleep(float(timeout_ms)/1000)
        timeout_ms = timeout_ms*4
        logging.error("WHX Task Queue Add Timeout Retrying")
    except TransientError:
        taskq_name = taskq_name + str(timeout_ms)
        time.sleep(float(timeout_ms)/1000)
        timeout_ms = timeout_ms*4
        logging.error("WHX Task Queue Add Transient Error Retrying")
    except TombstonedTaskError:
        logging.error("WHX Task Queue Tombstoned Error")
        break

A: Disclaimer: this is not the answer you're looking for, but I hope it will help you nonetheless.

The computation cannot go forward
  without these n tasks finishing

It sounds like you are using the task queue for something it was not designed to do. You should read: http://code.google.com/appengine/docs/java/taskqueue/overview.html#Queue_Concepts
Tasks are not guaranteed to be executed in the order they arrive, and they are not guaranteed to be executed exactly once. In some cases, a single task may be executed more than once or not at all. Further, a task can be cancelled and re-queued at the discretion of the App Engine based on available resources. For example, your timeout_ms = 100 is very low; if a new JVM has to be started, which could take several seconds, tasks n+1 and n+2 may be executed before task n.
In short, the task queue is not a reliable mechanism for performing strictly sequential computation. You've been warned.
-tjw


text:
Q: How to update by order
I have a django application with a model. I need to update the model objects according to ascending id. Something like this.
MyModel.objects.filter(my_field='value').order_by("id").update(another_field='anotheValue')

Can i be assure that the update will happen by the order according to the order by?

A: Since you already ordered the query set using id, it should update sequentially.
From the docs,

Using update() also prevents a race condition wherein something might
  change in your database in the short period of time between loading
  the object and calling save().

So I think the ordering might not matter.  However to be perfectly sure, you can iterate over the items and update them:
rows = MyModel.objects.filter(my_field='value').order_by("id")
for row in rows:
    row.another_field = 'another value'
    row.save()

However, the update method would generate one SQL query, where as the iteration would generate many. So this might be an issue with performance.


text:
Q: Jgitver maven plugin: Always calculates -SNAPSHOT versions on tagged commits Here's what I do:

*

*I commit and push something

*I go to Github and create a release-tag on the latest commit on master, say 0.0.1

Jenkins checks out branches /tags/
Checking out Revision a499.......0e (refs/tags/0.0.1)

Jgitver claims:
 [echo] Jgitver variables:
 [echo] jgitver.used_version: 0.0.1-SNAPSHOT
 [echo] jgitver.calculated_version: 0.0.1-SNAPSHOT
 [echo] jgitver.dirty: true
 [echo] jgitver.git_sha1_full: a499.......50e
 [echo] jgitver.branch_name:
 [echo] jgitver.head_tags: 0.0.1
 [echo] jgitver.head_annotated_tags:
 [echo] jgitver.head_lightweight_tags: 0.0.1
 [echo] jgitver.head_lightweight_tags: 0.0.1
 [echo] jgitver.all_tags: 0.0.1
 [echo] jgitver.all_annotated_tags:
 [echo] jgitver.all_lightweight_tags: 0.0.1
 [echo] gitver.all_version_tags: 0.0.1
 [echo] jgitver.all_version_annotated_tags:
 [echo] jgitver.all_version_lightweight_tags: 0.0.1

Jgitver config says:
<mavenLike>true</mavenLike>

<autoIncrementPatch>true</autoIncrementPatch>

<useCommitDistance>true</useCommitDistance>

<useDirty>false</useDirty>

<useGitCommitId>false</useGitCommitId>

<gitCommitIdLength>8</gitCommitIdLength>

<nonQualifierBranches>master</nonQualifierBranches>

<useDefaultBranchingPolicy>true</useDefaultBranchingPolicy>

Same happens on the master branch. It never seems to build a 0.0.1, it will always build a 0.0.1-SNAPSHOT.
I'm doing something wrong, but what is it?

A: Turns out "Releases" on Github-Enterprise are only lightweight Git tags.
Jgitver will always build SNAPSHOT versions from lightweight tags.
So in order to have Jenkins build a non-snapshot-version one needs to create an annotated tag manually.
You need to do the following:

*

*In your project's root enter:

$ git tag 0.0.1 -m "This is my first release" <optional 7 digit commit hash>
$ git push origin 0.0.1

*Go to Github Enterprise

*Click "Releases"

*Click "Tags"

*Create a release from the existing tag you just added.


text:
Q: Tell me how to fill a two-dimensional array I want to manually fill the array, but I can't understand what's wrong.
int arr[0][4]{ 1,0,0,1 },
    arr[1][4]{ 0,2,0,4 },
    arr[2][4]{ 0,0,0,6 },
    arr[3][4]{ 0,1,0,4 };

A: Here's the correct syntax for that:
int arr[4][4] {
    { 1,0,0,1 },
    { 0,2,0,4 },
    { 0,0,0,6 },
    { 0,1,0,4 }
};


text:
Q: Why some functions are uppercased and some lowercased Though PostgreSQL is case-insensitive, in the documentation some functions names shown uppercased and others lowercased. For example COALESCE(...), NULLIF(...), length(...), AGG(...), string_agg(...).
What's the reason for it?

A: Postgres is case insensitive. You can any of the function either in lower case or in upper case.
COALESCE(...) and coalesce(...) is same. Both gives the same result.
In documentation its just a format.


text:
Q: List of shipping on product page I want to display each shipping method on the product page. For example:

DPD | 10 $ DHL | 15 $ etc etc...

I used a WC() method, but it does not give the results what I want. Flat method/free delivery is not the problem, but I am also using table rate(flexible shipping) and methods don't display price.
i find something like :
https://stackoverflow.com/questions/47252728/display-shipping-methods-to-frontend-as-in-the-admin-panel/47264090#47264090
https://stackoverflow.com/questions/47409734/display-shipping-cost-on-product-page-woocommerce/47447817#47447817
Unfortunately this solution dosen't display flexible shipping prices(this is important for me).


text:
Q: Retail inventory system Mysql query optimization I'm looking to optimize the following Mysql query that is used to calculate the cost of inventory for a number of stores, I'm running the following query through a PHP loop for each distinct store and outputting the result:
Query:
SELECT

    SUM((((

    (SELECT COALESCE(SUM(facturas_fabrica.cantidad), 0)

    FROM facturas_fabrica

    INNER JOIN entradas_pedidos_productos ON
    entradas_pedidos_productos.clave = facturas_fabrica.entradas_pedidos_productos_clave

    INNER JOIN entradas_pedidos ON entradas_pedidos.clave = entradas_pedidos_productos.entradas_pedidos_clave

    WHERE entradas_pedidos_productos.producto_id = productos.id
    AND facturas_fabrica.procesado_local = 1 AND entradas_pedidos.sucursal_id = '.$row['id'].' # store id
    AND DATE(facturas_fabrica.fecha_procesada) <= DATE(NOW()))

    -

    (SELECT COALESCE(SUM(cantidad), 0)

    FROM facturas_contenido

    WHERE producto_id = productos.id AND facturas_contenido.sucursal_id = '.$row['id'].'
    AND DATE(facturas_contenido.fecha_creacion) <= DATE(NOW()))

    +

    (SELECT COALESCE(SUM(cantidad), 0)

    FROM notas_de_credito_contenido

    WHERE producto_id = productos.id AND notas_de_credito_contenido.sucursal_id = '.$row['id'].'
    AND DATE(notas_de_credito_contenido.fecha_creacion) <= DATE(NOW()))

    -

    (SELECT COALESCE(SUM(salidas_devoluciones.cantidad), 0)

    FROM salidas_devoluciones

    WHERE producto_id = productos.id AND (estado = 2 OR estado = 3) AND modulo != 2 AND salidas_devoluciones.sucursal_id = '.$row['id'].' # store id
    AND DATE(salidas_devoluciones.fecha_envio) <= DATE(NOW()))

    ) * productos.costo) / 100) ) AS "'.$row['clave'].'" # store name

FROM productos WHERE 1

(I'm only keeping fields relevant to the query)
Table 1:
CREATE TABLE `productos` (
  `id` int(10) unsigned NOT NULL,
  `costo` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `costo` (`costo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Table 2:
CREATE TABLE `facturas_fabrica` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `entradas_pedidos_productos_clave` bigint(20) unsigned NOT NULL,
  `cantidad` tinyint(3) unsigned NOT NULL,
  `procesado_local` tinyint(1) NOT NULL DEFAULT '0',
  `fecha_procesada` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_UNIQUE` (`clave`),
  KEY `fk_entradas_pedidos_productos_clave_idx` (`entradas_pedidos_productos_clave`),
  KEY `facturas_fabrica_procesado_local` (`procesado_local`),
  KEY `facturas_fabrica_cantidad` (`cantidad`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for table `facturas_fabrica`
--
ALTER TABLE `facturas_fabrica`
  ADD CONSTRAINT `fk_entradas_pedidos_productos_clave` FOREIGN KEY (`entradas_pedidos_productos_clave`) REFERENCES `entradas_pedidos_productos` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Table 3:
CREATE TABLE `entradas_pedidos_productos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `entradas_pedidos_clave` bigint(20) unsigned NOT NULL,
  `producto_id` int(10) unsigned NOT NULL,
  `cantidad` tinyint(3) unsigned NOT NULL,

  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_UNIQUE` (`clave`),
  KEY `fk_pedidos_producto_id_idx` (`producto_id`),
  KEY `fk_pedidos_productos_pedido_clave_idx` (`entradas_pedidos_clave`),
  KEY `entradas_productos_cantidad` (`cantidad`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for table `entradas_pedidos_productos`
--
ALTER TABLE `entradas_pedidos_productos`
  ADD CONSTRAINT `fk_pedidos_productos_pedido_clave` FOREIGN KEY (`entradas_pedidos_clave`) REFERENCES `entradas_pedidos` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_pedidos_productos_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Table 4:
CREATE TABLE `entradas_pedidos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `sucursal_id` tinyint(3) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_UNIQUE` (`clave`),
  KEY `clave` (`clave`),
  KEY `entradas_sucursal` (`sucursal_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for table `entradas_pedidos`
--
ALTER TABLE `entradas_pedidos`
  ADD CONSTRAINT `fk_entradas_pedidos_sucursal_is` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Table 5:
CREATE TABLE `facturas_contenido` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `sucursal_id` tinyint(3) NOT NULL,
  `producto_id` int(10) unsigned NOT NULL,
  `cantidad` tinyint(3) unsigned NOT NULL,
  `fecha_creacion` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_factura_contenido` (`clave`),
  KEY `fk_orden_contenido_producto_id_idx` (`producto_id`),
  KEY `facturas_contenido_cantidad` (`cantidad`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for table `facturas_contenido`
--
ALTER TABLE `facturas_contenido`
  ADD CONSTRAINT `fk_facturas_clave` FOREIGN KEY (`factura_clave`) REFERENCES `facturas` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_facturas_contenido_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Table 6:
CREATE TABLE `notas_de_credito_contenido` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `sucursal_id` tinyint(3) NOT NULL,
  `producto_id` int(10) unsigned NOT NULL,
  `cantidad` tinyint(3) unsigned NOT NULL,
  `fecha_creacion` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_nota_de_credito_contenido` (`clave`),
  KEY `fk_nc_clave_idx` (`nc_clave`),
  KEY `fk_ordenes_contenido_clave_idx` (`nc_facturas_contenido_clave`),
  KEY `notas_de_credito_cantidad` (`cantidad`),
  KEY `notas_de_credito_producto_id` (`producto_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `notas_de_credito_contenido`
--
ALTER TABLE `notas_de_credito_contenido`
  ADD CONSTRAINT `fk_facturas_contenido_clave` FOREIGN KEY (`nc_facturas_contenido_clave`) REFERENCES `facturas_contenido` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_nc_clave` FOREIGN KEY (`nc_clave`) REFERENCES `notas_de_credito` (`clave`) ON DELETE NO ACTION ON UPDATE NO ACTION;

Table 7:
CREATE TABLE `salidas_devoluciones` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clave` bigint(20) unsigned NOT NULL,
  `producto_id` int(10) unsigned NOT NULL,
  `cantidad` tinyint(3) unsigned NOT NULL,
  `sucursal_id` tinyint(3) NOT NULL,
  `fecha_envio` timestamp NULL DEFAULT NULL,
  `estado` tinyint(3) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `clave_UNIQUE` (`clave`),
  KEY `salidas_devoluciones_cantidad` (`cantidad`),
  KEY `fk_salidas_producto_id_idx` (`producto_id`),
  KEY `devoluciones_estado` (`estado`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

--
-- Constraints for table `salidas_devoluciones`
--
ALTER TABLE `salidas_devoluciones`
  ADD CONSTRAINT `fk_salidas_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

The problem is because of the large amount of stores and movements in each store the query is becoming increasingly heavy, and because inventory is calculated from the beginning of each store's history it only gets slower with time.
What could I do to optimize this scheme?


text:
Q: How can I reuse a variable in a different scope? I am trying to figure out how I can reuse a variable within a function, right now I have to put it in each scope for it to work.
Say I have an jQuery Event handler:
$('.button').on('click', function() {
    var btn = $(this).data('button');
    $(this).addClass(btn+'-activate');
}).on('mouseup', function() {
     var btn = $(this).data('button');
     $(this).removeClass( btn+'-activate');
}).on('mouseleave', function() {
     var btn = $(this).data('button');
     $(this).removeClass( btn+'-activate');
}

How can I reuse the variable 'btn'? When I put it in the parent scope, it doesn't recognize $(this) anymore

A: The other answers have a bit of redundancy in them. Here is how I usually handle events that are related and have common variables:
$('.button').on('click mouseup mouseleave', function(event) {
    var btn = $(this).data('button');

    switch(event.type) {
        case 'click': {
            $(this).addClass(btn+'-activate');
            break;
        }

        case 'mouseup':
        case 'mouseout':
        case 'mouseleave': {
            $(this).removeClass(btn+'-activate');
            break;
        }
    }
});

Listen to multiple events and use a switch statement to determine which event was called.

A: You can just iterate over the buttons, set the variable for each one and then use the variable inside the event handlers.
$('.button').each(function() {
    var btn = $(this).data('button');
    $(this).on('click', function() {
        $(this).addClass(btn+'-activate');
    }).on('mouseup mouseleave', function() {
        $(this).removeClass( btn+'-activate');
    });
});

But of course this is not exactly the same as your code. Here we are setting the value of btn at the time the handlers are attached while, in the code of the question, btn is set at the time the handlers are called. Therefore this is only a valid alternative if the value of .data('button') is not meant to change.

A: There's no special advantage to using a variable. You can pass a function to .removeClass() and .addClass() thereby removing the need to use a variable:
$(function() {
    $('.button').on('click', function() {
        $(this).addClass( function() {
            return $(this).data('button') + '-activate';
        });
    }).on('mouseup mouseleave', function() {
         $(this).removeClass( function() {
             return $(this).data('button') + '-activate';
         });
    });
});

    $(function() {
        $('.button').on('click', function() {
            $(this).addClass( function() {
                return $(this).data('button') + '-activate';
            });
        }).on('mouseup mouseleave', function() {
             $(this).removeClass( function() {
               return $(this).data('button') + '-activate';
             });
        });
    });
.one-activate {
  background-color:black;
  color:white;
  }
.two-activate {
  background-color:black;
  color:yellow;
  }

<button class="button" data-button="one">Man</button>

<button class="button" data-button="two">Woman</button>

BONUS:
As you can see the functions passed to .removeClass() and .addClass() are exactly identical. We could write a jQuery custom method and use it in place of the functions as follows:
$(function() {
    $('.button').on('click', function() {
        $(this).addClass( $(this).btnActivate() );
    })
    .on('mouseup mouseleave', function() {
         $(this).removeClass( $(this).btnActivate() );
    });
});

$.fn.btnActivate = function() {
    return this.data('button') + '-activate';
};

   $(function() {
        $('.button').on('click', function() {
            $(this).addClass( $(this).btnActivate() );
        })
        .on('mouseup mouseleave', function() {
             $(this).removeClass( $(this).btnActivate() );
        });
    });

    $.fn.btnActivate = function() {
        return this.data('button') + '-activate';
    };
.one-activate {
  background-color:black;
  color:white;
  }
.two-activate {
  background-color:black;
  color:yellow;
  }

<button class="button" data-button="one">Man</button>

<button class="button" data-button="two">Woman</button>


text:
Q: Can I back up to an SD card? I happy accident occurred this weekend when I left my camera's USB cable at work. I discovered that I have an SD slot in my MacBook Pro.
Can I backup to an SD card using a third party back up package? I typically do a nightly local back up as a fail safe.

A: I use an SanDisk Ultra miniDrive (64 GB) for transferable storage. However, I use an external hard drive to maintain Time Machine backups.
Of note, for compatibility with Time Machine, the SD's default format (exFat) was incompatible, and I needed to use Disk Utility to reformat to Mac OS Extended (Journaled).
For for information about SD cards, Apple provides information.


text:
Q: Regex to match certain pattern unless part of larger pattern I want to write a regex to find whenever there isn't a space after a period or comma, unless there are three periods in a row, in which case it's find to have another word character after.
E.g.
"Hello.how are you" -> Match
"Sounds good..." -> No Match
"...are you sure?" -> No Match
This is what I have so far (quotation marks after ., are fine too), but it finds a match for the third example, which I don't want.
/[.,][^\s"".]/g

How can I specify that \.\.\.\w should not match, but any other \.\w should?
(Using js)

A: I think the following regex does what you need:
(?<!\.\.)[.,](?=[^\s.])

It matches any period that isn't preceeded by two periods and that isn't followed by a period or a whitespace.


text:
Q: How to embed screenshots into Cypress 10 Mochawesome report? I am trying to implement Mochawsome report to my Cypress 10 framework. I use cypress-mochawesome-reporter plugin and set it up regarding npm package instructions https://www.npmjs.com/package/cypress-mochawesome-reporter. But the problem is that the report is generated without imbedded screenshots despite of using embeddedScreenshots: true parameter in reporterOptions object. cypress/screenshots folder contains the necessary screenshots but they are missing in the report. Could anybody advice?
P.S. I have to add important remark. Further investigation revealed that some screenshots are imbedded, but most of them are not. On the moment of publishing this request I used only few tests to check if the plugin work at all and got a report without screenshots. Now I have a big number of tests: 81 tests total, 26 failed, and only 15 of them have screenshots. Screenshots folder contains images for all failed tests


text:
Q: subdirectory on my domain gets 404 on some computers Im having a problem where this link
On some computers so far only in the state of NJ the webpage flashes goes away and a 404 error comes up
So far we have
1) Cleared the cache, cookies ect
2) Changed the subdirectory to where it has no caps, I went to norton safeweb and put a verification html up and norton doesnt recognize caps apparently, i felt it might be anti virus connected
3) so far the people having trouble have IE , i have run it on IE,Chrome,Safari,Firefox here in NJ with no isses
My next step is to physically travel to the trouble location and see if its the ISP
Does anyone have and ideas?
Below is the link which leads to a testing database which is fully functional except its a sandbox site
https://www.simplifiedchurch.net/sc/6e5aeb277a218704ef3ce9d37a211fa5cc/index.php?db=cXdkOFJsTlNSOElsUTRWN3d1WHNkRm5tYnVFZ203ZEVxcGhlMTY2dHJaYz0=
so far today it has been tested in texas, canada, north carolina and louisiana with no issues

A: just an fyi  for someone else, it looks like 1 include was not loading (missing file) I created a custom 404 that emails me $_SERVER in the event of a 404 which is  the way i tracked it down


text:
Q: I am getting this error AttributeError: 'builtin_function_or_method' object has no attribute 'title' Can I get some help guys? I am working on a dictionary which has a built in translator which works with google API. But I keep getting the AttributeError: 'builtin_function_or_method' object has no attribute 'title' As far as I know this error is caused because of not putting parentheses after defining or calling a function. I checked as best as I could but, still were not able to find anything, thus I am seeking for help.
    import tkinter as tk
import json
from difflib import get_close_matches
from googletrans import Translator
translator = Translator()

> #LIB DONE#

data = json.load(open("data.json"))
def dictionary(w):
    w = w.lower
    if w in data:
        return data[w]
    elif w.title() in data:
        return data[w.title()]
    elif len(get_close_matches(w, data.keys())) > 0:
        for widget in window.winfo_children():
            widget.destroy()
        dm = tk.Label(text = "Did you mean %s instead? Enter Y if yes, enter N if not"% get_close_matches(w, data.keys())[0])
        dm.pack()
        da = tk.Entry()
        da.pack()
        da1 = da.get()
        if da1 == "Y":
            pout1 = tk.Label(text = [get_close_matches(w, data.keys())[0]])
            pout1.pack()

        elif da1 == "N":
            pout1 = tk.Label(text = "The word is not found on our database")
            pout1.pack()
        else :
            pout1 = tk.Label(text = "The word doesn't exist, please double check it")
            pout1.pack()

window = tk.Tk()
window.geometry("300x300")

> #GUI OPENED#

def alert():
    for widget in window.winfo_children():
        widget.destroy()

> #BUTTON CLICKED#

greeting = tk.Label(text = "Welcome to the Dictionary & Translator!")
greeting.pack()
inserttext = tk.Label(text = "Enter a word: ")
inserttext.pack()
defentry = tk.Entry()
defentry.pack()
definput = defentry.get()
button = tk.Button(window, text = "Get definition!", command = alert)
button.pack()

> #DESTROYS THE FRAME AFTER GETTING THE INPUT FOR THE WORD#

output = dictionary(definput)

> #OUTPUT

if type(output) == list:
    for item in output:
        outputlab = tk.Label(text = item)
        outputlab.pack()
    alert()

> #TRANSLATE#

    def yes():
        x = 1
    def no():
        x = 0
    transq = tk.Label(text = "Do you want to translate the word to another language?")
    transq.pack()
    buttony = tk.Button(window, text = "Yes", command = yes)
    buttony.pack()
    buttonn = tk.Button(window, text = "No", command = no)
    buttonn.pack()
    if x == 1:

> #TRANSLATION PROGRESS STARTS#

        alert()
        asking = tk.Label(text = "What language do you want to translate to ?")
        asking.pack()
        answering = tk.Entry()
        answering.pack()
        answerin = answering.get()
        def translateout():
            tresult = translator.translate(definput, src = "english", dest = answerin)
            alert()
            endout = tk.Label(text = tresult.text)
            endout.pack()
        translateout()

window.mainloop()


text:
Q: Secure Copy (scp) between two Linux servers using a Win10 OpenSSH as proxy The design: multiple network security zones, some with Linux servers only, some with Windows only.
Objective: Secure Copy (scp) between two Linux servers using a Win10 OpenSSH  as proxy
linux1 (zone A) > Win10-1 (zone B) > linux2 (zone C)

[Updated: some progress] Authentication is SSH key based. I ran ssh-keygen on linux1and copied the .pub file to Win10-1, then copied the content into C:\Users\[username]\.ssh\authorized_keys and this works as intended: I can ssh from linux1 into the Win10-1passwordless.
The same procedure should work when running ssh-keygen on Win10-1; I have my key pair and copy the pub file to linux2 but logging in from Win10-1to linux2 using ssh user@linux2 fails and the Powershell prompt hangs - but if I do Start ssh user@linux2, then it works.
To test the intended connection, I did:
#linux1: ssh -J username@proxy-win10 username@target-linux2

And it gets me through just fine - but only after prompting for the login password on linux2.
I suspect that the final hurdle is that required Start ssh user@linux2 - is the OpenSSH server instance maybe broken?

A: This is actually mostly a security question.
Point 1
The only way an SSH proxy can be useful is when the target host stays behind public network, such as the following:
                                     +--- Office Computer 1
Internet <--- Router-NAT-Firewall <--+--- Office Computer 2
                                     +--- Linux Server (no port forwarding)
                                     +=== Windows Server (with SSH port forwarding)

Otherwise, your Windows server is just an actor playing in a security theater.
Point 2
SSH is a very useful transport protocol for applications, you should maximize its security by mandating users use public-key cryptography to authenticate themselves.
In "sshd_config":

*

*Use the "AllowUsers" directive to select the users allowed to login from SSH.

*Use the "Match" directive on the selected users and use "AuthenticationMethods" directive to restrict them from logging in with passwords.


text:
Q: How to extract href in sub-tags through BeautifulSoup in Python? For example:

▪美国1995年马丁·坎贝尔执导好莱坞电影

▪锦瑟华年创作都市异能小说

▪单兵便携式电脑

▪任天堂Wii主机射击类游戏《黄金眼》

▪珠宝鉴定职业

▪Rare Software制作的N64游戏

▪大鹏金翅明王小说

▪证券分析软件

▪《藏地密码》中的藏獒

First, I can extract the multi items:
multi_entry = soup.findAll('ul', attrs = {'class': 'polysemantList-wrapper cmn-clearfix'})

Then how to navigate to the href of the sub tag li? I want to get a list of all the urls in each item. The following can extract all 'li' items, but it is not necessarily from the polysemantList section.
li_items = soup.findAll('li', attrs={'class': 'item'})

A: We can find all the li with a class of item in polysemantList-wrapper cmn-clearfix with one search. Then we can iterate over the result and output the href values.
li = soup.find("ul", { "class" : "polysemantList-wrapper cmn-clearfix" }).findAll("li", attrs={'class': 'item'}, recursive=False)

for e in li:
    for x in e.findAll('a', href=True):
        print(x['href'])

Could also output a list using list comprehension
[x['href'] for e in li for x in e.findAll('a', href=True)]

Output

/item/%E9%BB%84%E9%87%91%E7%9C%BC/7822656#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/16402442#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/9585407#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/9585395#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/10704458#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/17571741#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/9585420#viewPageContent
/item/%E9%BB%84%E9%87%91%E7%9C%BC/9585384#viewPageContent


text:
Q: Publish document in umbraco Hi all from last couple of hour I am trying to publish a document and on which i am setting some custom data type value as I am saving serialized value : In umbraco data type value will be available in database and in umbraco.config file only after publishing document so In my custom document type I have a button called add user and I want to save it in db when this button is called for it I need to publish the document for that I am using :
//Get the document by it's ID
Document d = new Document(currentDocID);

//Mark it ready for publishing
d.Publish(new umbraco.BusinessLogic.User(0));

//Tell the runtime to update the document cache
umbraco.library.UpdateDocumentCache(d.Id);

//call republishing from the api:
umbraco.library.RefreshContent();

//Server.ScriptTimeout = 100000;
//umbraco.cms.businesslogic.web.Document.RePublishAll();
//umbraco.library.RefreshContent();

But it's not able to change Umbraco.config file and data base file while If do by clicking on publish in umbraco data is saved in umbraco db as well as in config file. I am not able to figure it out do i missing something..

A: The code sample looks right for save a node programmatically, all that's missing is a line to update the field that's changed, which if it was aliased as 'myField' in the document type would meaning changing to:
var myValue = "[{ serialized value that might need escaping }]";

Document d = new Document(currentDocID);
d.getProperty("myField").Value = myValue;
d.Publish(new umbraco.BusinessLogic.User(0));
umbraco.library.UpdateDocumentCache(d.Id);


text:
Q: etc folder outside root I'm currently working for a client who has a magento 1.7 version and the etc folder has been put outside the root.
Is there any reason other than security to do it? Is not safe enough to have etc folder under app?
thanks

A: As long as the .htaccess file remains in tact under app/ reading it from the web is not easily possible.

*

*https://github.com/OpenMage/magento-mirror/blob/magento-1.9/app/.htaccess
I don't see much advantage security wise other than adding unnecessary complexity, perhaps obscurity since its not standard may be the only advantage.


text:
Q: Ruby on rails get # params I am trying to do something on the backend if i get a #test in the query string but i cant seem to find that.
does any one know how to get those variables?
sample url
loocalhost:3000/#test

Thanks

A: This is called a fragment identifier.
From http://www.w3.org/Addressing/URL/uri-spec.html

A reference to a particular part of a document may, including the
  fragment identifier, look like
http://www.myu.edu/org/admin/people#andy
in which case the string "#andy" is not sent to the server, but is
  retained by the client and used when the whole object had been
  retrieved.


text:
Q: Display "burps" every 30 seconds I'm running Mint 18 on a Dell i7 and I have this annoying issue that I can't find where its coming from.
Every 30 seconds the display freezes for about 0.5 seconds. The issue is persistent and happens EXACTLY every 30 seconds (give or take 1 second).
This is particularly annoying when playing a game or watching a movie.
I couldn't isolate the process that may be causing this, but it wasn't there for the first week or so when I installed mint.
It may be worth to mention that I have another PC running Mint 17.1 that has the exact same issue (Also a Dell)
Anyone can think of a process that does something heavy and/or synchronous/blocking every 30 seconds?
I will provide any log file or additional info if anyone has any idea where should I look.
UPDATE:
This does not happen when I CTRL+ALT+F3, even when leaving all the processes alive in the graphical window.

A: EDIT: What is crossed out is only a temporary fix. The problem occurred again quickly after. Going to Settings > General > Miscellaneous Options and disabling "Enable support for indicators" fixed the issue for me. I looked in the log ~/.cinnamon/glass.log and found that one of the indicators (owncloud client) kept restarting every 30 seconds, causing the issue.
Alright I solved the issue.
Rename ~/.cinnamon to ~/.cinnamon-bak.
In my case, at least, my version of ~/.cinnamon has been around for a long time. Removing this folder (causing it to be recreated), fixed the issue, and no more lag spikes every 30 seconds!

A: Had this problem with Mint 19.1. Noticed I had 2-sec freezes, which got steadily worse with time but upon testing, it affected my account only. So I deleted ~/.cinnamon from the command line. A process list simply had too much to bother isolating the offending program but at any rate, system works perfectly now.

A: Fixed, at least for my setup, external monitor over HDMI.
I fixed it by going to Menu > Preferences > General, enabling vblank, allowing compositing for full-screen windows, logging out of cinnamon and logging back in.


text:
Q: Show that $\mathcal F=\{X\subseteq\Bbb R|X\neq\emptyset\land\forall x\forall y((x\in X\land xNot a duplicate of this or this.
This is exercise $4.4.12$ from the book How to Prove it by Velleman $($$2^{nd}$ edition$)$:
Show that $\mathcal F=\Bigr\{X\subseteq\Bbb R|X\neq\emptyset\ \text{and}\ \forall x\forall y\bigr((x\in X\land x<y)\rightarrow y\in X\bigr)\Bigr\}$ has no minimal element.
Here is my proof:
Suppose $\mathcal F$ has a minimal element called $M$. So by definition $M\neq\emptyset$, $\forall x\forall y\bigr((x\in M\land x<y)\rightarrow y\in M\bigr)$, and $\forall X\in\mathcal F(X\subseteq M\rightarrow X=M)$. Since $M$ is not empty we can choose some $m_0\in M$. Since $\forall x\forall y\bigr((x\in M\land x<y)\rightarrow y\in M\bigr)$ we can write $\{y\in\Bbb R|y\geq m_0\}\subseteq M$. Now consider the set $W$ as follows $W=\{x\in\Bbb R|x>m_0\}$. Clearly $W\in\mathcal F$ and also $W=\{x\in\Bbb R|x>m_0\}\subseteq\{y\in\Bbb R|y\geq m_0\}\subseteq M$. Since $\forall X\in\mathcal F(X\subseteq M\rightarrow X=M)$, $W=M$ which contradicts the fact that $m_0\in M$ but $m_0\notin W$ and ergo $\mathcal F$ has no minimal elements. $Q.E.D.$
Is my proof valid$?$
Thanks for your attention.

A: Yes, your proof is valid! Nicely done.
One small note: this didn't need to be a proof by contradiction. You really gave a direct proof that each element of $\mathcal{F}$ is not minimal, so it might be more elegant to structure your proof in this way. That's just a matter of taste, though.


text:
Q: Term for something that is broadly known, but in different ways? I'm trying to figure out what term to use to describe this situation:
I work in a particular field that is quite vast, and has many specialized areas. When I'm asked to evaluate someone else's abilities, I don't feel comfortable, because although I'm considered an expert on A, B, and C, someone else might be an expert in D, E, and F. That doesn't make either of us better or worse than the other, but it makes it hard to evaluate someone on the field-level as good or bad because the field or position is so ___________.
For some reason I keep wanting to say "subjective", but after reading the actual definition I don't think that's the right word I'm looking for.

A: How about specialized?
http://www.thefreedictionary.com/specialized:
specialized: requiring or having detailed training or expertise in a particular field: paleography is a very specialized field; presenting detailed information used in a particular field: a specialized glossary of computer terms.
Specialized works well in your example:

I work in a particular field that is quite vast, and has many
  specialized areas. When I'm asked to evaluate someone else's
  abilities, I don't feel comfortable, because although I'm considered
  an expert on A, B, and C, someone else might be an expert in D, E, and
  F. That doesn't make either of us better or worse than the other, but
  it makes it hard to evaluate someone on the field-level as good or bad
  because the field or position is so specialized.

By the way, in my experience, performance evaluations almost always involve some degree of subjectivity; your example makes clear one of the factors contributing to that. The simplest case is one in which the success measure is something like "number of widgets processed per day."

A: The word I would use to describe your field is diverse.That means "different in character and quality." That is to say that your field is "broad," and the pieces are all very "different."

A: Compartmentalized, maybe?
To compartmentalize, in Merriam-Webster:

to separate (something) into sections or categories

A:
multifarious -  adjective

*

*having many different parts, elements, forms, etc.

*numerous and varied; greatly diverse or manifold:

The field is multifarious.   The position, as another answer has said, is specialized.
Though if you're trying to say the field is becoming siloed, you could call it:

balkanized -
divided into small, incompatible units


text:
Q: How can I defer rendering a React component until webpack loads and applies a stylesheet I'm trying to figure out the best way to defer rendering a React component until react-scoped-css (I think it boils down to css-loader under the hood) imports and applies a sass module.
Right now I'm using polling to check document.styleSheets for the stylesheet. My code looks roughly like:
import './style.scoped.scss'
import { h, Component } from 'preact'

export default class MyComponent extends Component {
  constructor(props) {
    super(props)

    this.canRender = false
  }

  componentDidMount() {
    this.checkRender()
  }

  checkRender() {
    // Mega hack
    this.canRender = [...document.styleSheets].some(x => {
      try {
        return x.rules && [...x.rules].some(y => y.selectorText && y.selectorText.startsWith('.my-component'))
      } catch {
        return false;
      }
    })

    if (!this.canRender) {
      window.requestAnimationFrame(this.checkRender.bind(this))
    } else {
      this.forceUpdate();
    }
  }

  render() {
    return this.canRender && (

My component content

    )
  }
}

Obviously this isn't ideal. Is it possible to use import().then() or listen for a JS event or similar to be notified when the stylesheet is applied so I can get rid of the polling?


text:
Q: I can not handle error? I have method
 public static List<Transaction> getTransactions(){
 if (ShoppingSessionDao.getCurrentShoppingSession()==null){
            //what return?
        }
        return new Select().from(Transaction.class).where("shoppingSession = ?",
                    ShoppingSessionDao.getCurrentShoppingSession().getId()).execute();
    }

It return me List with data.
Then I do
private void setData() {
    transactionList = TransactionDao.getTransactions();
    baseAdapter = new BasketAdapter(transactionList);
    gridView.setAdapter(baseAdapter);
}

but sometimes (if ShoppingSession is empty) ShoppingSessionDao.getCurrentShoppingSession()return me NULL.
How can I handle this error?
solution
private void setData() {
        ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        if (shoppingSession==null){
            return;
        }
        transactionList = TransactionDao.getTransactions(shoppingSession);
        baseAdapter = new BasketAdapter(transactionList);
        gridView.setAdapter(baseAdapter);
        tvPrice.setText(calculateTotalSum());
    }

and
public static List<Transaction> getTransactions(ShoppingSession shoppingSession){
        return new Select().from(Transaction.class).where("shoppingSession = ?",
                shoppingSession.getId()).execute();
    }

A: As I see it there are two ways for you to implement this. Solution one is to surround your code with a try catch like this:
try {
        ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        transactionList = TransactionDao.getTransactions(shoppingSession);
        baseAdapter = new BasketAdapter(transactionList);
        gridView.setAdapter(baseAdapter);
        tvPrice.setText(calculateTotalSum());

    } catch (NullPointerException ex) {
        Log.e("Error: ", ex.getLocalizedMessage());
//Do error handling here
    }

Another way to do this is an extension of the current method you are using by using the following code:
ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        if (shoppingSession != null) {
            transactionList = TransactionDao.getTransactions(shoppingSession);
            baseAdapter = new BasketAdapter(transactionList);
            gridView.setAdapter(baseAdapter);
            tvPrice.setText(calculateTotalSum());
        } else {
            tvPrice.setText("Shopping session is null");
//Do error handling here
        }


text:
Q: Wait for a function to finish, before the next one executes I have a react app. In it when a user summits the form, I want to open a modal, and store the users response in state. Based on this reponse I want to preform some business logic, then post the form.
This is my onsubmit method
      async function onSubmit(submission: IPayload) {
        await handleModal();
        await submit(submission);
      }

      async function submit(submission: ICreateAdPayload) {
          await api.create({ this is where all the props go})
      }

     // Heres I set the state of the modal to open, which then chanes the open prop on another component for the modal to open.

      async function handleModal(submission: any) {
        setShowModal(true);

        // handle logic

        setShowModal(false);
  }

However my submit function is being carried out as soon as the modal opens. Any idea?

A: To be able to await handleModal(...) then that method must return a Promise which you resolve when it's work has finished - assuming it itself does not need to await anything, it does NOT need  to be marked async
function handleModal(submission: any) {
    setShowModal(true);

    return new Promise(resolve => {
        // handle logic

        setShowModal(false);

        resolve();
    });
}


text:
Q: How to upsert nested array object mongodb I have a document which looks like this
{
 _id:'asasasasa23sdsdsd',
 source:'page',
 url:[]
}

I need to upsert some values/objects to the url array. the objects that need to be upserted looks like this.
{
"type" : "blog",
"value" : "hello blog",
"id" : "1815f620-b45c-4230-85bb-7ba90ac330ed",
"datetime" : "2019-12-26 15:58:33"
}

Then it would look like this
{
 _id:'asasasasa23sdsdsd',
 source:'page',
 url:[{
    "type" : "admin",
    "value" : "hello admin",
    "id" : "1815f620-b45c-4230-85bb-7ba90ac330ed",
    "datetime" : "2019-12-26 15:58:33"
     },
   {
    "type" : "blog",
    "value" : "hello blog",
    "id" : "1815f620-b45c-4230-85bb-7ba90ac330ed",
    "datetime" : "2019-12-26 15:58:33"
   }
  ]
}

Here the id and the type fields are unique. I need to insert them if they do not exist or update them if they do.
This is the code that I have tried
db.collection(TABLE_NAME).update(
      { source: data.source },
      {
        source: data.source,
        url: [data.urls]
      },
      { upsert: true }
    );

With this, it just replaces the array object with a new object. How to upsert instead of replacing the object?

A: I think this code will help.
    let arr = [
   {
    "type" : "admin",
    "value" : "hello admin",
    "id" : "1815f620-b45c-4230-85bb-7ba90ac330ed",
    "datetime" : "2019-12-26 15:58:33"
     },
   {
    "type" : "blog",
    "value" : "hello blog",
    "id" : "1815f620-b45c-4230-85bb-7ba90ac330ed",
    "datetime" : "2019-12-26 15:58:33"
   }
    ];

    db.users.update(
      { _id: doc._id },
      {
        $set: {
          "url": arr
        }
      }
    );