text:
Q: ERR_CONNECTION_REFUSED Mean app with nginx I have 2 web apps which run on XX.XX.XX.XX/ and XX.XX.XX.XX/harvin, one of them is only node-express and another one is a MEAN stack app respectively. They are configured with nginx as below
nginx.conf
# node-express
location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
}

# MEAN app
location /harvin {
        rewrite ^/harvin/(.*)$ /$1 break;
        proxy_pass http://localhost:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
}

This question is about the 'Harvin' app (MEAN app).
Here is my app.js file with CORS (Cross-Origin Resource Sharing) configuration.
app.js
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
var app = express();

var whitelist = ["http://localhost:4200", "XX.XX.XX.XX"];

app.use(
    cors({
        origin(origin, callback) {
            if (whitelist.indexOf(origin) !== -1) {
                callback(null, true);
            } else {
                callback(new Error("Not allowed by CORS"));
            }
        },
        methods: ["PUT, GET, POST, DELETE, OPTIONS"],
        allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
        credentials: true
    })
);

//some middlewares

app.get("/api/login", (req, res) => {
    console.log("login route");
    // login the user
});

// Connect server to Angular 2 Index.html
app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname + "/public/index.html"));
});

//some more routes

module.exports = app;

The problem
The problem I am facing is that when I make any kind of request (like login or signup etc.) on localhost:8081/api/login from the client side of Harvin (MEAN app) then the console shows ERR_CONNECTION_REFUSED.

Even morgan is not logging any kind of login request.

Exception  Homepage of Harvin is loading successfully without any error.

Expected behavior
No ERR_CONNECTION_REFUSED in the console when any kind of http request is made from the client side.
P.S.
This Harvin app is working perfectly on my local machine.

A: I had a similar problem.
I was serving static files from node with sendFile which included some javascript that sent a fetch request to http://localhost:8081/api but would always return ERR_CONNECTION_REFUSED. Solved it by setting up a reverse proxy with Nginx exactly the way you did.
Now any fetch request that doesn't have a host in its url is automatically forwarded to the localhost:8081 socket. So, my requests now fetch from just /api which is interpreted as http://localhost:8081/api.


text:
Q: how to load a function when a page load react native I'm using react-native with hooks, and I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens  This JSON contains information on what my states should be set to.
How can I call a function that runs every time this screen is opened?
i know that without hooks this should be done with useEffect, but when i put my api call there it makes an error
this is my code
useEffect(() => {
const getKind = () => {
    ForceApi.post(`/GetKindPensionController.php`)
      .then(res => {
        setpPensionKind(res.data.pension);
    })
  }

}, []);

A: You are missing call the getKind, and it should be a async function! For a better code try something like:
useEffect(() => {
    async function getKind() {
       const { data } = await ForceApi.post(`/GetKindPensionController.php`)
       setpPensionKind(data.pension);
    }

    getKind();
}, []);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can subordinate user ID be used to grant file system permissions? Suppose I have user "myuser" with uid/gid "1001", and files "/etc/subuid" & "/etc/subgid" with the following content:
myuser:100000:65536

Can this setup somehow be used to allow user "myuser" to access files with owner "100000"?

A: Yes with the help of the setuid root utilities newuidmap and newgidmap working along with /etc/subuid and /etc/subgid.
Tools like podman, docker, or LXC all require these setuid root utilities installed to work in rootless/unprivileged mode with a normal user. Without these tools there are not enough rights available to bootstrap this.
All the lengthy explanations are in the user namespaces manpage that should be read to understand how the features can be used. In short, once the user namespace is created (with an unprivileged operation), the specific pseudo-files /proc/<PID>/{uid,gid}_map can be written once and only once to set the mappings. With correct (host) privileges, spare uid/gid ranges, as allowed in /etc/sub{uid,gid}, can then be mapped in the user namespace.
The user myuser itself (without the assistance of any special command) can write to those pseudo-files, but:

*

*is allowed only to have itself (host uid 1001) mapped into one uid in the user namespace (the obvious possibly useful choices being itself again or 0 for root). This has to be done anyway from an other process, since the new process is temporarily without mapping in the newly created user namespace. As any non-mapped uid gets translated to the overflow uid (by default 65534 aka nobody) until "resolved", it thus can't write to its own /proc/<PID>/uid_map file. Even if it becomes root in this namespace, as it can affect only root which is host uid 1001, this is useless. System calls (and commands using them) are all made to not allow rights escalation. In addition to failing with EPERM etc. they can also fail with EINVAL when trying to alter a mapped uid (ie: host uid 1001) into a non-mapped uid.

*same for groups, with the additional restriction that it must first forfeit the ability to use setgroups before being able to write in /proc/<PID>/gid_map (that's to avoid being able to remove oneself from a group to evade restrictions to files added by being part of this group).
So uid 100000 would of course not be reachable: setuid root tools are required.
The goal here is to map the normal user myuser with uid 1001 (allowed in mappings by newuidmap in addition to the subordinate ids) as the root user (uid 0), as well as also map at least the host uid 100000 inside the user namespace: this allows to change one to the other by (the user namespace's) root when needed. Here I'll just map just the additional 100000 to ... 100000 again. I'll do the same with gid, assuming /etc/subgid is a mirror of /etc/subuid.
Here's a practical example on how to do, using newuidmap and newgidmap, all from initial host user myuser. As explained above, this requires two processes, so here two shells in two terminals. The actions of these setuid root commands could be replaced with correctly crafted echo (or printf etc.) commands run from the (host) root user.
term1:
$ unshare --user sh
$ id -u; id -un ; id -g; id -gn; echo pid:$$
65534
nobody
65534
nogroup
pid:13273

term2 (reusing previous pid value in the commands):
$ newuidmap 13273 0 1001 1 100000 100000 1
$ newgidmap 13273 0 1001 1 100000 100000 1

term1 again (exec sh just to have the shell display the "resolved" and "upgraded" status):
$ id -u; id -un ; id -g; id -gn
0
root
0
root
$ exec sh
#

# touch mytest
# chown 100000:100000 mytest

term2 (which here displays the same as in term1, since the mapping was chosen with the same values):
$ ls -l mytest
-rw-r--r--. 1 100000 100000 0 Apr 21 18:00 mytest
$ touch mytest
touch: cannot touch 'mytest': Permission denied

term1:
# chown 100001:100001 mytest
chown: changing ownership of 'mytest': Invalid argument
# chown root:root mytest

term2:
$ ls -l mytest
-rw-r--r--. 1 myuser myuser 0 Apr 21 18:00 mytest

Any sub process from term1 will now have control over uid 100000, including filesystem operations.
Bigger ranges or smarter mappings could be used, as allowed in /etc/subuid to affect more things or things more easily (eg: mapping 100000 to myuser instead, with newuidmap 13273 0 1001 1 1001 100000 1 would have allowed to simply run su myuser in term1, which should succeed despite a few non-fatal errors). This would also allow for example to access/rescue/backup (at the filesystem level only, not other features like network) an user LXC instance which would refuse to start due to some unrelated issue.


text:
Q: Which IDE support LESS (Dynamic Stylesheet Language)? If someone here knows which IDE support LESS? There are many problems when I'm working on it.
If I make a mistake, the JavaScript won't render my LESS CSS; that why I need IDE to correct some of my errors.

A: IntelliJ, the best IDE in the business, supports LESS CSS with a plugin:
http://plugins.jetbrains.com/plugin?pr=idea&pluginId=7059

A: Scott Guthrie just announced that there is now first class support for LESS in Visual Studio 2012.
I haven't tried it, so I'm not sure what "first class support" means.

A: Intellij IDEA with plugin LESS
and another plugin "LESS CSS Compiler"
you can compile CSS in real time
when you edit LESS file ,the CSS is already output.


text:
Q: Google Sheets Query / Date formula issue Would really appreciate some help with this Google Sheets formula.
I'm trying to pull up events that occur on `=Today() using a query formula, but it just isn't working. The purpose for this is to have a kind of calendar on my dashboard.
AO is the column that holds the dates for events. BG is the client's name.
=QUERY(clients,"SELECT BG, AP, AQ, AR WHERE AO = date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0)

A: Issue
The problem lies with the optional argument in QUERY function which is set to 1 in your current formula. Setting it to 1 will force the query to return a value, thus, having the first row in the data set as the result.
Solution
You should set the said optional argument to 0. Apply to both TODAY and TOMORROW tables. Please see formula below:
=QUERY(courtdates,"SELECT BV, AR, BO WHERE BN = date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0)


text:
Q: Substring with string, returning values between two words in a string I am getting from a Telnet buffer a string like the following:
"<CONNECTED><SENDING_VIDEO_LIST><START_VIDEO_LIST>test.mp4|test_3.mp4|test_2.mp4|<END_VIDEO_LIST><PLAYING_test.mp4_STARTED>"

I want to select everything between the two indicators <START_VIDEO_LIST> and <END_VIDEO_LIST> which is in this case euqal to:
test.mp4|test_3.mp4|test_2.mp4|
Is there an efficient way without manipulating the whole string?

A: Well, if you want, you can use a regex:
<START_VIDEO_LIST>([^<]*)<END_VIDEO_LIST>

and the first captured group (\1) is what you want.

A: Without regex (can be a less eficient) you can use String.SubString and String.IndexOf methods like;
string s = "<CONNECTED><SENDING_VIDEO_LIST><START_VIDEO_LIST>test.mp4|test_3.mp4|test_2.mp4|<END_VIDEO_LIST><PLAYING_test.mp4_STARTED>";
string start = "<START_VIDEO_LIST>";
string end = "<END_VIDEO_LIST>";
int i1 = s.IndexOf(start);
int i2 = s.IndexOf(end);
string result = s.Substring(i1 + start.Length, i2 - i1 - start.Length);
Console.WriteLine(result);

Output will be;
test.mp4|test_3.mp4|test_2.mp4|

Here a demonstration.

A: Here's a non-regex option:
string GetContents(string full, string start, string end)
{
    int s = full.IndexOf(start) + start.Length;
    int e = full.IndexOf(end);
    int length = e - s;

    //validate the index and length to ensure Substring wont throw an error (unless you want that of course)
    if (s < 0 || length > full.Length - s)
            return null;

    return full.Substring(s, length);
}

which you can call like so:
string result = GetContents(input, "<START_VIDEO_LIST>", "<END_VIDEO_LIST>");

NOTE: It would be wise to valid your input!


text:
Q: How to get custom tab visibility in controller based on user profile? I have a custom tab name 'Payments' and i need to provide a short cut access link to this tab from other pages. I know how to control the visibility based on object level settings, However, in this scenario I need to check if the tab is visible by that profile/user, then only show the output link.
Can anyone please point me into right direction.
Thank you.

A: create two layout
one layout contain link  and oher layout without link and share 1 layout with your profile

A: Parul,
One option is to use Permission sets to give access to the custom tab and add this permission set to the users profile [instead of using the object settings under the profile]
then in your controller, you can check if the users profile has this permission set assigned or not to find out if the tab is accessible to the user or not
here's a related post which has details on how to use permission sets to control tab visiblity
Can you show/hide a custom tab on a per user basis?

A: In Apex, you can check only Object/Field permissions and not tab visibility. To do that, we need to use Metadata API.

*

*Go to https://github.com/financialforcedev/apex-mdapi and click on "Deploy to Salesforce". This is the Apex wrapper for Salesforce Metadata API because Apex does not support Metadata API natively

*Add your Salesforce instance URL in remote site settings for the Metadata API to work

*Once deployed, you can use the below class to get tab visibility for any Profile. Invoke the method "ProfileTabSettings.getTabSettings();"
public with sharing class ProfileTabSettings{
public static MetadataService.MetadataPort createService()
{
    MetadataService.MetadataPort service = new MetadataService.MetadataPort();
    service.SessionHeader = new MetadataService.SessionHeader_element();
    service.SessionHeader.sessionId = UserInfo.getSessionId();
    return service;
}
public static void getTabSettings(){
    MetadataService.MetadataPort service = createService();
    MetadataService.Profile admin = (MetadataService.Profile) service.readMetadata('Profile', new String[] { 'Admin' }).getRecords()[0];
    for(MetadataService.ProfileTabVisibility ptv : admin.tabVisibilities){
        system.debug('tab name = ' + ptv.tab + ' & ' + 'visibility = ' + ptv.visibility);
    }
}

}

*Sample debug logs showing tab visibility for both standard and custom tabs

USER_DEBUG|[16]|DEBUG|tab name = CObject1__c & visibility = DefaultOn
          20:10:29.561 (2561238677)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561249923)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561263176)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561284914)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561294050)|USER_DEBUG|[16]|DEBUG|tab name = CObject2__c & visibility = DefaultOn
          20:10:29.561 (2561300614)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561308910)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561320450)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561339471)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561347746)|USER_DEBUG|[16]|DEBUG|tab name = SSOContact__c & visibility = DefaultOn
          20:10:29.561 (2561354395)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561362436)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561373417)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561392222)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561400516)|USER_DEBUG|[16]|DEBUG|tab name = SyncKA & visibility = DefaultOn
          20:10:29.561 (2561406905)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561414831)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561425759)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561443722)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561451901)|USER_DEBUG|[16]|DEBUG|tab name = Test_web_tab & visibility = DefaultOn
          20:10:29.561 (2561458116)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561466018)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561477020)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561494590)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561502603)|USER_DEBUG|[16]|DEBUG|tab name = redirect_tab & visibility = DefaultOn
          20:10:29.561 (2561508755)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561516962)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561527993)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561545912)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561553946)|USER_DEBUG|[16]|DEBUG|tab name = standard-Account & visibility = DefaultOn
          20:10:29.561 (2561560253)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY)
          20:10:29.561 (2561568218)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561580360)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
          20:10:29.561 (2561598330)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
          20:10:29.561 (2561606555)|USER_DEBUG|[16]|DEBUG|tab name = standard-AppLauncher & visibility = DefaultOn 20:10:29.561
  (2561612953)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY) 20:10:29.561
  (2561621031)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
  20:10:29.561
  (2561631931)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
  20:10:29.561 (2561649871)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
  20:10:29.561 (2561658460)|USER_DEBUG|[16]|DEBUG|tab name =
  standard-Campaign & visibility = DefaultOn 20:10:29.561
  (2561664893)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY) 20:10:29.561
  (2561672589)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
  20:10:29.561
  (2561683484)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
  20:10:29.561 (2561701822)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
  20:10:29.561 (2561709911)|USER_DEBUG|[16]|DEBUG|tab name =
  standard-Case & visibility = DefaultOn 20:10:29.561
  (2561716253)|SYSTEM_METHOD_EXIT|[16]|System.debug(ANY) 20:10:29.561
  (2561723972)|SYSTEM_METHOD_ENTRY|[15]|system.ListIterator.hasNext()
  20:10:29.561
  (2561734972)|SYSTEM_METHOD_EXIT|[15]|system.ListIterator.hasNext()
  20:10:29.561 (2561753048)|SYSTEM_METHOD_ENTRY|[16]|System.debug(ANY)
  20:10:29.561 (2561760836)|USER_DEBUG|[16]|DEBUG|tab name =
  standard-Chatter & visibility = DefaultOn


text:
Q: Issues accessing Ubuntu through vnc I have installed through a SSH console into my Ubuntu server a service called vncserver and I ran it. This is the output:
New 'X' desktop is ubuntu-s-4vcpu-8gb-fra1-01:3

Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/ubuntu-s-4vcpu-8gb-fra1-01:3.log

When I try connecting remotely on my Mac through the screen sharing app, I use the link vnc://xxx.xxx.xxx.xxx:5903 but the connection won't establish. (Where xxx.xxx.xxx.xxx is the server's public IP). Any help?


text:
Q: Mysql: ALTER TABLE without locking the table? I want to add column to an existing table.
Is there a manner to alter the table without locking it?

A: No, that's not possible.
However, adding a nullable column or a not null column with a constant (immutable) default value is merely a catalog change and only takes a very short time (typically "milliseconds" if the lock can be obtained). But during that time, the exclusive lock can't be avoided.


text:
Q: QLPreviewController is under the navbar and tabbar How do I make it so that I can see everything, the contents of the QLPreviewController is under the navbar.

The document looks like this in TextEdit.

I'm loading things with this code:
@implementation TextViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.preview = [[QLPreviewController alloc] init];
    self.preview.dataSource = self;
    self.preview.delegate = self;
    [self addChildViewController:self.preview];

    [self.view addSubview:self.preview.view];
    [self.preview didMoveToParentViewController:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [self.preview refreshCurrentPreviewItem];
}

- (void) loadData: (NSString *)name;
{
    assert(![name isEqualToString:@""]);

    // Load the plist
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString *path = [resourcePath stringByAppendingPathComponent:name];
    self.info = [[NSDictionary alloc] initWithContentsOfFile:path];

    NSString *rtfPath = [resourcePath stringByAppendingPathComponent:[self.info valueForKey:@"transcript"]];
    self.url = [NSURL fileURLWithPath:rtfPath];
    [self.preview refreshCurrentPreviewItem];
}

- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index
{
    if ([QLPreviewController canPreviewItem:self.url]) {
        return self.url; // This always returns
    }

    return nil; // This line is never executed
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

@end

How do I go about making the QLPreviewController take the navbar into account?

A: Do something like this before inserting as child view.
CGFloat w= self.view.frame.size.width;
CGFloat h= self.view.frame.size.height;
self.preview.view.frame = CGRectMake(0, 0,w, h);


text:
Q: Do you add public/assets in version control? In rails 3.1, when you precompile the assets, rails create public/assets directory and add files there.
Do you version-control public/assets/*?

A: I was looking for an answer to this too.  I found the official Rails Guide has some thoughts on this:
http://guides.rubyonrails.org/asset_pipeline.html#local-precompilation
Here's a quote of the relevant section (emphasis added):

There are several reasons why you might want to precompile your assets locally. Among them are:

*

*You may not have write access to your production file system.

*You may be deploying to more than one server, and want to avoid duplication of work.

*You may be doing frequent deploys that do not include asset changes.

  Local compilation allows you to commit the compiled files into source control, and deploy as normal.
There are three caveats:

*

*You must not run the Capistrano deployment task that precompiles assets.

*You must ensure any necessary compressors or minifiers are available on your development system.

*You must change the following application configuration setting:

  In config/environments/development.rb, place the following line:
config.assets.prefix = "/dev-assets"

The prefix change makes Sprockets use a different URL for serving assets in development mode, and pass all requests to Sprockets. The prefix is still set to /assets in the production environment. Without this change, the application would serve the precompiled assets from /assets in development, and you would not see any local changes until you compile assets again.
In practice, this will allow you to precompile locally, have those files in your working tree, and commit those files to source control when needed. Development mode will work as expected.

So, it looks like it might be a good idea to put precompiled assets into VCS on occasion.

A: I use Capistrano to deploy. The last step is compiling the assets. Nothing like that gets checked into version control.
https://github.com/capistrano/capistrano/wiki/Documentation-v2.x
Checking in compiled assets, .gz files/etc, will just clutter up version control.


text:
Q: Hilbert Theorem of zeros Use the Hilbert Nullstellensatz Theorem to prove the following result:

Given $F_1, F_2, F_3 \in \mathbb{C} [X_1,\dots,X_n]$ polynomials checking the following conditions:

*

*$F_1$ is irreducible;

*$F_2$ is not a multiple of $F_1$;

*For every element $ x \in \mathbb{C}^n \text{ if } F_1 (x) = 0 \text{ and } F_3 (x) \neq 0,\text{ then } F_2 (x) = 0$.

  Show that $F_3$ is a multiple of $F_1$.

A: If the condition $3.$ states (as @JeffTolliver suggested in his comment) that $F_1(x)=0$ implies $F_2(x)F_3(x)=0$, then all is easy: this condition means $\mathcal V(F_1)\subset\mathcal V(F_2F_3)$ and then $\mathcal I(\mathcal V(F_2F_3))\subseteq\mathcal I(\mathcal V(F_1))$, that is, $\sqrt{(F_2F_3)}\subseteq\sqrt{(F_1)}$. Since $F_1$ is irreducible the ideal $(F_1)$ is prime, and thus $F_2F_3\in (F_1)$. It follows that $F_1\mid F_2F_3$, and from the condition $2.$ we get $F_1\mid F_3$.


text:
Q: How to Calculate a Date in Swift 3 let date1 = "2017-02-09 11:51:07"
let date2 = **I need now time code**

How to Calculate this?
looks like "10 minutes ago", "1 hours ago", " 1 day ago"
Anyone help me please~

A: Check out this playground
//: Playground - noun: a place where people can play

import Cocoa

// Given a date as a string
let dateString = "2017-02-09 11:51:07"

// To turn it into a date we can use a date formatter
let dateFormatter = DateFormatter()

// Make sure the formatter is using the correct format for your date string
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

// Attempt to create a date from the string using our date formatter
guard let date = dateFormatter.date(from: dateString) else {
    fatalError("Unable to create date from string \(dateString) with format \(dateFormatter.dateFormat)")
}

// Calendar can do all kinds of things with dates
let calendar = Calendar(identifier: .gregorian)

// Date() By itself will give us "now" date
let now = Date()

// We can ask the calendar to give us the hours and minutes between now and the date we parsed
let components = calendar.dateComponents([.hour, .minute], from: date, to: now)

// If getting the hours was succesful we can use them
if let hours = components.hour {
    print("\(hours) hours ago")
}

// same with minutes
if let minutes = components.minute {
    print("\(minutes) minutes ago")
}

// you can also try using DateComponentsFormatter

let componentsFormatter = DateComponentsFormatter()
componentsFormatter.allowedUnits = [.day, .minute, .hour]
componentsFormatter.maximumUnitCount = 2
componentsFormatter.unitsStyle = .full

if let fromString = componentsFormatter.string(from: date, to: now) {
    print("Parsed date was \(fromString) ago.")
}

Using the Date, DateFormatter, Calendar, DateComponentsFormatter, and DateComponents APIs you should be able to pull this off.


text:
Q: WPF Image with loading animation I'm trying to make Image control in WPF to animate while loading source.
I have found a solution, bu prepared for Windows 8 Metro development and it contains ImageOpened event, which does not exist in normal WPF Image control.
Do you know any solution for making Image show loading animation while loading?
Maybe there are some libraries with that kind of Image Control?
Here's that ImageLoader control I have found for Win 8 dev:
<Grid>
    <Image x:Name="imgDisplay" Source="{Binding ElementName=parent,Path=Source}"
           ImageFailed="OnImageFailed"
           ImageOpened="OnImageOpened" />
    <ContentControl
        Visibility="{Binding ElementName=parent,Path=IsLoading,Converter={StaticResource converter}}"
        Content="{Binding ElementName=parent,Path=LoadingContent}"
        VerticalContentAlignment="Stretch"
        HorizontalContentAlignment="Stretch" />
    <ContentControl Visibility="{Binding ElementName=parent,Path=IsFailed,Converter={StaticResource converter}}"
                    Content="{Binding ElementName=parent,Path=FailedContent}"
                    VerticalContentAlignment="Stretch"
                    HorizontalContentAlignment="Stretch" />
</Grid>

And here's missing event handler:
void OnImageOpened(object sender, RoutedEventArgs e)
{
    this.IsLoading = false;
    this.IsLoaded = true;
}

A: Simle solution: Position the Image control on top of the control that displays the loading animation (e.g. by putting both inside the same Grid). As long as the image hasn't fully loaded it's transparent, letting the loading animation shine through, and after it has finished loading it automatically hides the animation.


text:
Q: Spring.NET WebServiceExporter and WCF I've modified my original question (hope that's allowed)...
I have used WCF to expose my Spring Service layer. I have created a WCF project, and for each service interface (IOrderService, ICustomerService etc) in my application, I have created an SVC file and added the appropriate config in web.config. This all works well, and Spring's dependency injection is working too.
I expect that Spring's ServiceExporter class can make the process even simpler. But what does it give me that I don't already have? Does it allow me to achieve the same thing without needing the WCF project? The reason I ask is that most examples I have seen also mention 'editing .svc files', which are in the WCF project.
Since the ASMX WebServiceExporter allows me to create a webservice from just my interface(s) and a bit of XML config, I was thinking ServiceExporter would be similar.
OPTIONAL: as an aside, wouldn't it be better to have just one WebServiceExporter class in Spring and have a property e.g. exportAs="WCF | ASMX"?
Thanks

A: First, read this:
http://www.springframework.net/docs/1.2.0-M1/reference/html/wcf-quickstart.html

I expect that Spring's ServiceExporter class can make the process even
  simpler. But what does it give me that I don't already have?

well, The Host have to reference the exporter object :
<object id="OpcServiceHost"
type="Spring.ServiceModel.Activation.ServiceHostFactoryObject,Spring.Services">
<property name="TargetName" value="OpcServiceExporter" />
</object>

Does it allow me to achieve the same thing without needing the WCF project?

Are you referring to the service interface project? if so - spring.net example shows that Spring specific implementation of the WCF interfaces is used within the server project, and are not used in an interface project of it's own. Also note that the basic WCF service interfaces (System.ServiceModel.Dispatcher.IInstanceProvider and System.ServiceModel.Description.IServiceBehavior ) are encapsulated by Spring.
The example given in the link shows that you don't need such a project, however the interface is defined within the server project.

as an aside, wouldn't it be better to have just one WebServiceExporter class in Spring and have a property e.g. exportAs="WCF | ASMX"?

Not an option - You can, however, try to use GenerateProxy method of ServiceExporter class:
http://www.springframework.net/docs/1.3.2/api/net-2.0/html/topic16729.html


text:
Q: How do I convert byte values into decimals? I'm trying to load some decimal values from a file but I can't work out the correct way to take the raw values and convert them into decimals.
I've read the file out into a byte array, and each chunk of four bytes is supposed to represent one decimal value. To help figure it out, I've constructed a table of how the decimal values 1 through to 46 are represented as four byte chunks.
For instance, the number 1 appears as 0,0,128,63 the number 2 as 0,0,0,64 and so on up to 46, which is 0,0,56,66. The full table is available here.
There is also another series of numbers which go to three decimal places and include negatives, which is here.
The only documentation I have states
They are stored least significant byte first:  1's,  256's,  65536's,  16777216's.  This makes the hex sequence 01 01 00 00 into the number 257 (decimal).  In C/C++, to read e.g. a float, do:   float x;   fread(&x, sizeof(float), 1, fileptr);
However I'm using .NET's File.ReadAllBytes method so this isn't much help. If anyone can spare a few minutes to look at the examples files and see if they can spot a way to convert the values to decimals I'd be most grateful.

A: You can use BitConverter.ToSingle to read a float value from a byte array, so to get a sequence of floats, you could do something like this:
byte[] data = File.ReadAllBytes(fileName);
int count = data.Length / 4;
Debug.Assert(data.Length % 4 == 0);

IEnumerable<float> values = Enumerable.Range(0, count)
    .Select(i => BitConverter.ToSingle(data, i*4));

A: Have you looked into using the BitConverter class?  It converts between byte arrays and various types.
Edit:
MSDN has a helpful comment on the documentation for BitConverter at http://msdn.microsoft.com/en-us/library/system.bitconverter_methods(v=vs.85).aspx:
public static decimal ToDecimal(byte[] bytes)
{
  int[] bits = new int[4];
  bits[0] = ((bytes[0] | (bytes[1] << 8)) | (bytes[2] << 0x10)) | (bytes[3] << 0x18); //lo
  bits[1] = ((bytes[4] | (bytes[5] << 8)) | (bytes[6] << 0x10)) | (bytes[7] << 0x18); //mid
  bits[2] = ((bytes[8] | (bytes[9] << 8)) | (bytes[10] << 0x10)) | (bytes[11] << 0x18); //hi
  bits[3] = ((bytes[12] | (bytes[13] << 8)) | (bytes[14] << 0x10)) | (bytes[15] << 0x18); //flags

  return new decimal(bits);
}

public static byte[] GetBytes(decimal d)
{
  byte[] bytes = new byte[16];

  int[] bits = decimal.GetBits(d);
  int lo = bits[0];
  int mid = bits[1];
  int hi = bits[2];
  int flags = bits[3];

  bytes[0] = (byte)lo;
  bytes[1] = (byte)(lo >> 8);
  bytes[2] = (byte)(lo >> 0x10);
  bytes[3] = (byte)(lo >> 0x18);
  bytes[4] = (byte)mid;
  bytes[5] = (byte)(mid >> 8);
  bytes[6] = (byte)(mid >> 0x10);
  bytes[7] = (byte)(mid >> 0x18);
  bytes[8] = (byte)hi;
  bytes[9] = (byte)(hi >> 8);
  bytes[10] = (byte)(hi >> 0x10);
  bytes[11] = (byte)(hi >> 0x18);
  bytes[12] = (byte)flags;
  bytes[13] = (byte)(flags >> 8);
  bytes[14] = (byte)(flags >> 0x10);
  bytes[15] = (byte)(flags >> 0x18);

  return bytes;
}

A: The .NET library implemented Decimal.GetBytes() method internally.
I've used the decompiled .NET library to create a simple conversion methods between decimal and byte arrary - you can find it here:
https://gist.github.com/eranbetzalel/5384006#file-decimalbytesconvertor-cs
EDIT : Here is the full source code from my link.
public decimal BytesToDecimal(byte[] buffer, int offset = 0)
{
  var decimalBits = new int[4];

  decimalBits[0] = buffer[offset + 0] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24);
  decimalBits[1] = buffer[offset + 4] | (buffer[offset + 5] << 8) | (buffer[offset + 6] << 16) | (buffer[offset + 7] << 24);
  decimalBits[2] = buffer[offset + 8] | (buffer[offset + 9] << 8) | (buffer[offset + 10] << 16) | (buffer[offset + 11] << 24);
  decimalBits[3] = buffer[offset + 12] | (buffer[offset + 13] << 8) | (buffer[offset + 14] << 16) | (buffer[offset + 15] << 24);

  return new Decimal(decimalBits);
}

public byte[] DecimalToBytes(decimal number)
{
  var decimalBuffer = new byte[16];

  var decimalBits = Decimal.GetBits(number);

  var lo = decimalBits.Value[0];
  var mid = decimalBits.Value[1];
  var hi = decimalBits.Value[2];
  var flags = decimalBits.Value[3];

  decimalBuffer[0] = (byte)lo;
  decimalBuffer[1] = (byte)(lo >> 8);
  decimalBuffer[2] = (byte)(lo >> 16);
  decimalBuffer[3] = (byte)(lo >> 24);

  decimalBuffer[4] = (byte)mid;
  decimalBuffer[5] = (byte)(mid >> 8);
  decimalBuffer[6] = (byte)(mid >> 16);
  decimalBuffer[7] = (byte)(mid >> 24);

  decimalBuffer[8] = (byte)hi;
  decimalBuffer[9] = (byte)(hi >> 8);
  decimalBuffer[10] = (byte)(hi >> 16);
  decimalBuffer[11] = (byte)(hi >> 24);

  decimalBuffer[12] = (byte)flags;
  decimalBuffer[13] = (byte)(flags >> 8);
  decimalBuffer[14] = (byte)(flags >> 16);
  decimalBuffer[15] = (byte)(flags >> 24);

  return decimalBuffer;
}

A: As others have mentioned, use the BitConverter class, see the example below:
     byte[] bytez = new byte[] { 0x00, 0x00, 0x80, 0x3F };
     float flt = BitConverter.ToSingle(bytez, 0); // 1.0

     bytez = new byte[] { 0x00, 0x00, 0x00, 0x40 };
     flt = BitConverter.ToSingle(bytez, 0); // 2.0

     bytez = new byte[] { 0, 0, 192, 190 };
     flt = BitConverter.ToSingle(bytez, 0); // -0.375


text:
Q: TitledBorder for QLabel? I'm new here and german, so excuse me for my english^^
I'm now working on a C++ Project with Qt-library 4.7 for university and I want to add some QLabels to a QGridLayout.
In Java it's possible to set a TitledBorder to a JLabel to get a title for a JLabel.
Is there a way to add some kind of TitledBorder to a QLabel?

A: Indeed there is. Use a QGroupBox.
This is the appearance

From https://qt-project.org/doc/qt-4.7/qgroupbox.html


text:
Q: Call to undefined function FOS\UserBundle\Util\mb_convert_case() I'm getting error
Call to undefined function FOS\UserBundle\Util\mb_convert_case() app_path/vendor/bundles/FOS/UserBundle/Util/Canonicalizer.php on line 18

It occurs when I try to load fixtures.
First step was to install mbstring.so ext, so I compiled php with
--enable-mbstring

than successfully copiled mbstring ext
phpize
./configure
make
make install

and added
extension=mbstring.so

to my php.ini file. Unfortunately I still got that error and php -m doesn't display mbstring as loaded extension. What's wrong?
Any help will be greatly appreciated.
PHP 5.4.7, Debian Lenny
from php check.php output
[[WARNING]] Checking that the mb_strlen() function is available: FAILED
            *** Install and enable the mbstring extension ***

A: on CentOS, for example, you will need to install this php module:
yum install php-mbstring

as written on https://stackoverflow.com/a/1216284/2071028

A: On debian, install the module php-mbstring
apt-get install php-mbstring

If necessary restart apache2
service apache2 restart

A: If you are using Windows try to set the extension in php.ini with full path e.g: extension="/FULL/PATH/mbstring.so". In other case you need to put mbstring.so file inside your modules directory (where all others .so are located).


text:
Q: How to Copy file ONLY NEW FILES from Google Cloud Bucket Storage using GSUTIL I have some automate project would like to sending files from my google cloud bucket to sftp server. But to do that, everyday i must maintain the name files generated by some cloud function that i want to send.
I'm using gsutil to copy the files from bucket to my server using jenkins automation.

*

*Is that possible to copy only NEW FILES using gsutil?

*or is that any prefix or sort by date or time on gsutil to that?
Copy only new files from google cloud bucket with gsutil using sorting like date or prefix


text:
Q: iOS:How to set the color of the text view's modal mail compose controller's navigation bar? When the user long presses email link in UITextView, and selects new message option, system presents mail compose controller. I would like to change its navigation bar color (or appearance).
Any easy way to do it?

A: Using RGB:
UINavigationBar *bar = [self.navigationController navigationBar];
[bar setTintColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0]];

A: MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
[[mailer navigationBar] setTintColor:[UIColor whiteColor]];


text:
Q: Azure Function Fixed Delay Retry locking up function I have been testing out the FixedDelayRetry mechanism of Azure Functions but I am running into an scenario where the function wont process the next message until the function consumes all of the remaining retries and the message ends up in the deadletter queue.
I am using .NetCore 3.1 and the Functions SDK 3.0
This is a very boiled down version of my function where I am able to reproduce the issue
[FunctionName("Function1")]
[FixedDelayRetry(5, "00:01:00")]
public void Run(
    [ServiceBusTrigger("SomeTopic", "SomeSubscription", Connection = "ServiceBusConnectionString")] string item,
    ExecutionContext context,
    ILogger log
)
{
    log.LogInformation($"Function executed at: {DateTime.Now}");

    throw new System.Exception("Error Happened!!");
}

A: throw new System.Exception("Error Happened!!");

You are throwing the exception in the code execution so that you're seeing this behavior like

A scenario where the function won't process the next message until the function consumes all of the remaining retries and the message ends up in the dead letter queue.

To not encounter the retries, throw the exception in the catch block.
Function Code:
[FunctionName("FixedDelayRetryTest")]
[FixedDelayRetry(5, "00:01:00")]
public void Run([ServiceBusTrigger("Topic", "Subscription", Connection = "ServiceBusConnString")] string item, ExecutionContext context, ILogger log)
{
    try
    {  log.LogInformation($"Function executed at {DateTime.Now}");  }
    catch
    {  throw new System.Exception("Error Happened!!");  }
}


text:
Q: How to parse a Python module from file I saw this SO question and tried using it by creating a .py file with 2 methods and trying to read it.
The file:
def f1(a):
    print "hello", a
    return 1

def f2(a,b):
    print "hello",a,", hello",b

Trying to read it:
>>> r = open('ToParse.py','r')
>>> t = ast.parse(r.read)

Exception thrown:
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python26\lib\ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
TypeError: expected a readable buffer object

What am I doing wrong?
My goal is to get a python module and be able to parse it using Python - expose its classes and methods.

A: If you want to expose your classes and methods dynamically, then you probably need to use eval along with compile.
In this case you may do it like the following.
Create a file:
#test.py
def hello():
    print "hello"

And you can call it like this:
#main.py
testContent = open("test.py").read()
#evaluate a content
eval(compile(testContent, "<string>", 'exec'))
#call function
hello() #prints hello

EDIT: there is another way to evaluate file:
#main.py
#evaluate a content
eval(compile("import test", "<string>", 'exec')) #test.py
#check list of methods
dir(test) # ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
#call function
hello() #prints hello

I do realize, that eval may be not that good choice, but I don't know other way. I'd glad to see other solution

A: Use:
t = ast.parse(r.read()) # () is needed

Source: http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

A: You are trying to parse the function read on the file.
You want
t = ast.parse(r.read())

or (to more closely follow the example)
text = r.read()
ast.parse(text)

not
t = ast.parse(r.read)

A: You need to call read. So your line
t = ast.parse(r.read)

Should be
t = ast.parse(r.read())

See here for info on files and here for info on ast.parse


text:
Q: mysql service status doesn't show started when it is started by monit I installed monit on my Ubuntu 14.04 server and configured it to monitor mysql with the below config in monitrc.
 check process mysqld with pidfile /var/run/mysqld/mysqld.pid
 start program = "/etc/init.d/mysql start"
 stop program = "/etc/init.d/mysql stop"

Now to test I shutdown mysql user
 service mysql stop

Monit does restart the server but the issue is that when I service status on mysql like below
 service mysql status

It shows
 mysql stop/waiting

But when I do
 ps -e | grep "mysql"

I see the mysqld service running.
Any ideas why service mysql status wont show me running?
Thanks!


text:
Q: How to display all items from a javascript array in html with commas in between them except the last item I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward? Below I have the code that prints all items in the array except the last one.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="coffee.css" />
    <title>Coffee</title>

Drinks of the Month

A: Just use join() method of array.
Example
const foo = ['tea', 'coffee', 'soda'];

console.log(foo.join('-'));
console.log(foo.join(', ');

You can read more about Array.join() here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

A: This will do it:
var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
]

drinks.join(', ')

Will output:
Chai Tea, Sweet Cream Cold Brew, Caramel Macchiato, Vanilla Latte

A: You can also do it like this
while (i < drinks.length) {
  if(i != drinks.length-1){
    drinksOfMonth += drinks[i] + ", "}
  else{
    drinksOfMonth += drinks[i]}
 i++
}

A: I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward ?
Why you want to use for or while loop as you can easily achieve this requirement with Array.join() method with a single line of code.
Demo :

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
];

console.log(drinks.join(', '));

A: Just add the last item after the while loop:
drinksOfMonth += drinks[drinks.length-1];


text:
Q: Accord .Net Read .mat file wrong data type or value I am using Accord .Net c# library to read a .mat file:
        string fileName = Path.Combine("MYLOCALPATH", "training_f_r1_1.mat");
        FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        Debug.WriteLine(fileName);
        var reader = new MatReader(fStream);

        var node = reader["training_f_r1_1"];
        double[,] value = node.Value as double[,];
        Debug.WriteLine("*****");
        Debug.WriteLine(value[0,0]);
        Debug.WriteLine(value[0,1]);
        Debug.WriteLine(value[0,2]);
        Debug.WriteLine("*****");

My matlab ".mat" file is a double matrix and has values:
33.338652248163450, 0.447357298679056, 5.207437835743190
               ...,               ...,               ...

But the above code gives me:
    3500.4784339099424, -1.6283030973451347E+138, 2.4840536969417093E-208

I know double in Matlab should be Single in c# I tried that too but it didn't work. Any ideas why the values are different?

A: You have to set the lazy parameter to false when initing the reader.
var reader = new MatReader(new BinaryReader(new FileStream("file.mat", FileMode.Open)), false, false);


text:
Q: SQLite : How to populate a boolean field on a pojo, from a subQuery I want to return a list of posts like.
@Query("SELECT * FROM posts")
List<Post> getPosts()

I have a pojo.
post {
   name:String
   id :String
   postUid:String
   userHasNewContent:Boolean
}

Now, I want every post in the list to have the userHasNewContent:Boolean, populated by checking if the user who owns this post has new content(Not older than a week)
So I tried.
@Query("SELECT *,
       (SELECT content_uid FROM content WHERE content_uid = postUid AND
        contentTime < :aWeekAgo)AS userHasNewContent
      FROM posts")
List<Post> getPosts(String aWeekAgo)

WHERE content is:
   content{
       contentTime:Long //Unix Timestamp
       id:String
   }
AND
public static Long aWeekAgo() {
        long day = (1000 * 60) * 60 * 24;
        return System.currentTimeMillis() - day * 7;
    }

This doesn't seem to work as expected, am I doing this the way?
Edit
Ok, after writting the question, it's now clear what I want to do. Here's the short version.
//Get all posts
@Query("SELECT * FROM posts")
List<Post> getPosts()

//Then loop through them.
@Query("SELECT count(*) FROM content WHERE contentId :contentUID AND soundTime < : aWeekAgo")
int checkIfUserHasNewContent(String uid, long aWeekAgo);

List<Post> postsWithNewContentIndicator = new ArrayList<>();
for (Post post : postsFromDb) {
    post.userHasNewContent(checkIfUserHasNewContent(post.getUid()) > 0);
    postsWithNewContentIndicator.add(post);
}

So, but I want to do this with a single query and not use this loop.

A: You need to rewrite the query as the following
SELECT
  *,
  (
    (
      SELECT
        COUNT(*)
      FROM
        (
          SELECT
            content_uid
          FROM
            content
          WHERE
            content_uid = postUid
            AND contentTime > : aWeekAgo
        )
    )> 0
  ) AS userHasNewContent
FROM
  posts

A: Your sub-query should be written as a case:
SELECT CASE WHEN EXISTS (
   SELECT content_uid FROM content WHERE content_uid = postUid AND
       contentTime < :aWeekAgo
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

A: Assume post and user is 1 to 1, you can do it with a join.
SELECT posts.name, posts.uid, posts.postUid,
  (content.contentTime < :aWeekAgo) as userHasNewContent
FROM posts inner join content on content.uid = post.uid

If user to posts are 1 to n, you will need to use group and having too.


text:
Q: check for 'item not in mylist' causes python to crash Good evening,
I am trying to build a list of backpointers. In there, I want to avoid duplicates. As far as i know i cant use a dict or set, because the items to be stored are not hashable. I implented the following code:
while k in range(limit):
    try:
        if path not in path_backp:
            path_backp.append(path)
            continue
        else:
            Log.Message(path.Item[k].Text)
            path = path.Item[k].Items
            limit = path.Count
            scan(path, path_backp, e, 0)
            k = k +1
    except AttributeError:
        path = path_backp.pop()
        limit = path.Count
        k = k + 1

the part to avoid double entities of course is:
if path not in path_backp:
     path_backp.append(path)
     continue
else:
     [...]

Im running python inside TestComplete, which has (limited) debugging functions.
When I enable the debugger and track what is happening, the first check works. The if-routine gets executed, and because path_backp is an empty dict, path gets appended, so that afterwards path_backp[0] equals path and I get back to to the while-routine.
But when the if-routine gets executed the 2nd time (so when path_backp is no empty dict anymore), the debugger freezes for what seems an infinite amount of time.
same happens, by the way, when I implemented:
if path not in path_backp:
    path_backp.append(path)

without any continue or else.
Can anyone explain to me why this is happening and how I can handle the situation?
Many thanks,
b.


text:
Q: Analysis/Inequality question about proving an infinite product greater than 0 This is from David Williams' book Probability using Martingales. I'm self-studying.
Question
Prove that if $$0\leq p_n < 1 \quad\text{ and }\quad S:=\sum p_n < \infty$$ then $$\prod (1-p_n) > 0$$ Hint: First show that if $S<1$, then $\prod (1-p_n)\geq 1-S$.
I was able to prove the hint using induction. Assume $\prod\limits_{n=1}^N (1-p_n) \geq 1-\sum\limits_{n=1}^N p_n$. Consider $\prod\limits_{n=1}^{N+1}(1-p_n) \geq (1-\sum\limits_{n=1}^N p_n)(1-p_{N+1})=1-\sum\limits_{n=1}^{N+1}p_n+p_{N+1}\sum\limits_{n=1}^{N}p_n \geq 1-\sum\limits_{n=1}^{N+1}p_n$.
But I'm unable to use this to prove the general result for arbitrary $S$. Any guidance would be appreciated. I'm also surprised that he asks this question after stating the 2nd Borel Cantelli lemma, I don't see the connection.

A: If $\sum_{n=1}^\infty p_n<\infty$, then you can find for each $\epsilon>0$ some index $N$ such that $\sum_{n=N}^\infty p_n<\epsilon$. In particular, you can do this for some $0<\epsilon<1$. By what you have shown, $$\prod_{n=N}^M (1-p_n)>1-\epsilon>0,$$ and since $\prod_{n=N}^M (1-p_n)$ converges as $M\to\infty$ (it is a decreasing sequence bounded below), we have $$\prod_{n=N}^\infty (1-p_n)\geq 1-\epsilon>0.$$
Clearly, $\prod_{n=1}^{N-1}(1-p_n)>0$. Now $$\prod_{n=1}^\infty(1-p_n)=\prod_{n=1}^{N-1}(1-p_n) \prod_{n=N}^\infty (1-p_n)\geq (1-\epsilon)\prod_{n=1}^{N-1}(1-p_n)> 0.$$

Here is the connection to the second Borel-Cantelli lemma. The lemma says that if $(E_n)$ is a sequence of independent events satisfying $\sum_{n=1}^\infty p_n=\infty$ with $p_n=P(E_n)$, then a random point in the sample space lies with probability $1$ in infinitely many of the $E_n$. This exercise shows that this automatically fails if $\sum_{n=1}^\infty p_n<\infty$, since $\prod_{n=1}^\infty (1-p_n)$ is the probability that an element lies in none of the $E_n$.

A: Without loss of generality we can take $0<p_n<1$, and by the condition $\sum p_n<\infty$ follows that $p_n\to 0$. Denote
$$p=\prod_{n=1}^{\infty} (1-p_n)\in[\,0,1).$$
Since
$$\lim_{n\to\infty}\frac{\log(1-p_n)}{-p_n}=1,$$
then the series $\sum\log(1-p_n)>-\infty$ converges as $\sum p_n$ converges and hence
$$\log p=\lim_{N\to\infty}\sum_{n=1}^N \log (1-p_n)=\sum_{n=1}^{\infty}\log (1-p_n)>-\infty.$$
Thus we  get $$-\infty<\log p<0,$$
which implies $p>0.$


text:
Q: How can i assign the return value of a power shell script to a variable while being used in a post build event I have a Powershell script that reads the Assembly version from a dll, I want to store this return value in a variable, I am running the ps1 script from a post-build event:
When i execute the script:
powershell -NoProfile -ExecutionPolicy RemoteSigned -file $(SolutionDir)GetAssemblyVersion.ps1 $(TargetPath)

The post build event produces this:
1>1.0.8146.38525

I want to assign this value to a variable to be able to use it later in another operation, unfortunately, it has not worked
A=(powershell -NoProfile -ExecutionPolicy RemoteSigned -file $(SolutionDir)GetAssemblyVersion.ps1 $(TargetPath))

I have also tried this:
A=$(powershell -NoProfile -ExecutionPolicy RemoteSigned -file $(SolutionDir)GetAssemblyVersion.ps1 $(TargetPath))

None of these two solutions is working.
My Powershell script is the following one:
$strPath = $args[0]
$Assembly = [Reflection.Assembly]::Loadfile($strPath)
$AssemblyName = $Assembly.GetName()
$Assemblyversion = $AssemblyName.version
$Assemblyversion.ToString()

I appreciate your comments and suggestions


text:
Q: Passing a cookie into a fetch call I am currently obtaining cookies from a specific url as follows:
const cookies = driver.manage().getCookies()

Note: driver is from Selenium WebDriver
My aim is to be able to pass these cookies in a fetch method. Perhaps with this kind of approach below
fetch(url, {
    credentials: "include",
    headers: cookies
});

The actual cookies being passed in above is an array that looks like this - below (with some obfuscation for privacy reasons):
[ { domain: 'somedomain.com',
    expiry: 12345434,
    httpOnly: false,
    name: 'JSESSIONID',
    path: '/',
    secure: false,
    value: '5766ti65ruir65e5uey454343' },
  { domain: 'somedomain.com',
    httpOnly: false,
    name: 'JSESSIONID',
    path: '/extra',
    secure: false,
    value: '5766ti65ruir65e5uey454343' } ]

Nothing seems to work however. Any ideas what the best way do this is?

A: The cookies need to be like this
{cookie: 'name=value; name1=value1;'}

try
let heads = {'cookie' : ''};
cookies.forEach(c => heads['cookie'] += `${c['name']}=${c['value']};`)

fetch(url, {
    credentials: "include",
    headers: heads
});


text:
Q: TextInputEditText needs 2 taps to fire the associated listener I have a view with some input fields, one of those is a TextInputEditText with a datepicker associated which shows up when the field is selected. The problem is that at the first tap, the TextInputEditText field gets the focus and it is required a second tap do show the datepicker.
This is how the field is defined
<android.support.design.widget.TextInputLayout
    android:id="@+id/wExpiresAt"
    style="@style/AppTheme.TextInputLayout"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:errorTextAppearance="@style/AppTheme.Text.ErrorText"
    app:hintTextAppearance="@style/AppTheme.Text.HintText"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/wMessage">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/tvExpiresAt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/tv_pick_date_ph"
        android:imeOptions="actionNext"
        android:textSize="18sp" />

</android.support.design.widget.TextInputLayout>

While inside the activity:
val mExpiresAt: TextInputEditText = findViewById(R.id.tvExpiresAt)

mExpiresAt!!.setOnClickListener {
    val cal   = Calendar.getInstance()
    val year  = cal.get(Calendar.YEAR)
    val month = cal.get(Calendar.MONTH)
    val day   = cal.get(Calendar.DAY_OF_MONTH)

    val dialog = DatePickerDialog(
            this@NewMessageActivity,
            android.R.style.Theme_Material_Light_Dialog_MinWidth,
            mDateSetListener,
            year, month, day)
    dialog.show()
}

My guess is that the problem is caused by the TextInputLayout which wraps the TextInputEditText, the first tap fires the animation which moves the hint string from the text field to its top and gives the focus to the field itself, the second tap fires the listener associated to the text field and the datepicker appears. How can I get all the events on the first tap?

A: Just set for editText. It allows for a view to handle click and focus at the same time!
android:focusableInTouchMode="false"


text:
Q: How to monitor consecutive exceptions in Azure? (Kusto) I want to monitor consecutive exceptions.
For example if I get 'X' amount of '500' exceptions in a row, I want it to trigger an action group.
How to write this in Kusto?
I know how to monitor amount of exceptions over a 1min period but I'm a bit stuck on how to monitor consecutive exceptions.

A: You are looking for setting up a custom log alert on AppInsights
Here is the step by step guide on how to setup
You can use the following query with Summarize Operator
exceptions
| where timestamp >= datetime('2019-01-01')
| summarize min(timestamp) by operation_Id

A: Please use the query like below:
Exceptions
| summarize count() by xxx

For more details about summarize operator, refer to this article.


text:
Q: How can I reduce my repeated jquery codes jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
  if (jQuery(this).val() == 0) {
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('input, select, textarea').val('');
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-one').nextUntil('.form-actions').find('select').trigger("chosen:updated");
  } else if (jQuery(this).val() == 1) {
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('input, select, textarea').val('');
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-two').nextUntil('.form-actions').find('select').trigger("chosen:updated");
  } else if (jQuery(this).val() == 2) {
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('input, select, textarea').val('');
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
    jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings('#edit-field-beneficial-owner-three').nextUntil('.form-actions').find('select').trigger("chosen:updated");
  }
});

A: As was pointed out, the main thing to simplify your code is storing intermediate steps in variables. I want to add encapsulating conditional checks in a data-structure:
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
    const $this = jQuery(this);
    const labels = ['one', 'two', 'three'];
    const target = $this.parent()
        .parent('#edit-field-number-of-beneficial-owner')
        .siblings(`#edit-field-beneficial-owner-${labels[+$this.val()]}`)
        .nextUntil('.form-actions');

    target
        .find('input, select, textarea')
        .val('');

    target
        .find('input:checkbox')
        .attr('checked', false);

    target
        .find('select')
        .trigger('chosen:updated');
});

A: Use a local variable for the result of the "base" of all of the things you're working with. Then, you can make a function to handle the steps you were typing out repeatedly.
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
  let numOwner = jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner');
  let handle = function(sibs) {
    sibs.nextUntil('.form-actions').find('input, select, textarea').val('');
    sibs.nextUntil('.form-actions').find('input:checkbox').attr('checked', false);
    sibs.nextUntil('.form-actions').find('select').trigger("chosen:updated");
  }

  if (jQuery(this).val() == 0) {
    handle(numOwner.siblings('#edit-field-beneficial-owner-one'))
  } else if (jQuery(this).val() == 1) {
    handle(numOwner.siblings('#edit-field-beneficial-owner-two'))
  } else if (jQuery(this).val() == 2) {
    handle(numOwner.siblings('#edit-field-beneficial-owner-three'))
  }
});

A: There are numerous ways you could handle this. Here is one example.
Map your value 0-2 into the string equivalent. Use the value as the index into the array to get the string (notice the back-ticks that allow you to use template literals ). Store the long series of jQuery calls into a variable, and use that variable for the find() calls.
jQuery('#edit-field-number-of-beneficial-owner-und').change(function() {
  let ownerMap = ['one', 'two', 'three']
  let owner = jQuery(this).val()

  let formAction = jQuery(this).parent().parent('#edit-field-number-of-beneficial-owner').siblings(`#edit-field-beneficial-owner-${ownerMap[owner]}`).nextUntil('.form-actions')
  formAction.find('input, select, textarea').val('');
  formAction.find('input:checkbox').attr('checked', false)
  formAction.find('select').trigger("chosen:updated")
});


text:
Q: How many patterns of length 3? I asked another question that I guess is too hard to be answered, so I have to change the problem:
how many patterns with length three we can draw on an android device?

A: For the solution of this problem, a clear definition of the pathways that are allowed and not allowed is necessary. I interpreted the question according to the following:

*

*we have to determine what is the number of all possible patterns characterized by three consecutive lines of total length 3, where "length 1" is defined as any line that directly connects two points without crossing another point. For example, calling 1,2,3 the three points in the upper horizontal row from left to right, 4,5,6 those in the middle row, and 7,8,9 those in the lower row, if I start from point 1, we have the following lines of "length 1": 1-2, 1-4, 1-5, 1-6, 1-8;

*we can have consecutive lines of length 1 that are aligned (e.g., the line 1-7 is considered of length 2, resulting from the sequence of lines of unitary length 1-4 and 4-7);

*the pattern can be "closed", that is to say that the initial and the final point can be the same (e.g., the path 1-4-2-1 is allowed);

*coming back over a line already drawn is not allowed (e.g., the path 1-2-1-4-5-3, albeit finally resulting of length 3, is not allowed);

*crossing between lines is allowed (e.g., the path 7-2-5-4 is allowed).
Based on these assumptions, the simplest way to solve this interesting problem is to divide the 9 points in 3 types: the 4 angles (we will call them A-points), the other 4 points  placed in the middle of each side of the 3x3 square (M-points), and the central point (C-point).
Let us start by considering the second line of our pattern, which connects the second and the third point of our path with length 1. Consider the type of the second point:

*

*Case 1 - if it is one of the four A-points, it can be connected to another point by lines of unitary length in five ways (4 towards a M-point, 1 towards the C-point);

*Case 2 - if it is one of the four M-points, it can be connected in seven ways (4 towards an A-point, 2 towards a M-point, and 1 towards the C-point);

*Case 3 - lastly, if it is the C-point, it can be connected in eight ways (4 towards an A-point, 4 towards a M-point).
Now reconsider these possible connections, which refer to the second line of our path, by taking into account the first line. The first line can be of seven types: writing the two letters of the first and second point we have CA, MA (referring to case 1 of the list above); CM, AM, MM (referring to case 2); AC, MC (referring to case 3). In rewriting the possible second lines, we have to take into account that the first point of our path must be excluded from the possible endpoints of the second line. For example, let us consider  the case of first line CA. There are clearly 4 possible first lines CA. In this case, among all possible second lines described in point 1 of the list above, we have to eliminate the connection from the A-point towards the C-point, so that there remain only 4 possible connections towards a M-point; thus we can write $4CA\rightarrow{4AM}$, indicating that each of the four possible first lines CA can continue only with 4 possible second lines AM. We can procede in the same way, by rewriting all possible second lines for each  type of first line (and also counting the possibilities for that type of first line). The following scheme is obtained:
1.1 - There are 4 possible first lines CA. We have $4CA\rightarrow{4AM}$;
1.2 - There are 16 possible first lines MA. We have $16MA\rightarrow{3AM,1AC}$;
2.1 - There are 4 possible first lines CM. We have $4CM\rightarrow{4MA,2MM}$;
2.2 - There are 16 possible first lines AM. We have $16AM\rightarrow{3MA,2MM,1MC}$;
2.3 - There are 8 possible first lines MM. We have $8MM\rightarrow{4MA,1MM,1MC}$;
3.1 - There are 4 possible first lines AC. We have $4AC\rightarrow{3CA,4CM}$;
3.2 - There are 4 possible first lines MC. We have $4MC\rightarrow{4CA,3CM}$.
Following this scheme, it is not difficult to check that all possible sequences for the first two lines can be grouped in fifteen different types: 16 CAM, 48 MAM, 16 MAC, 16 CMA, 8 CMM, 48 AMA, 32 AMM, 16 AMC, 32 MMA, 8 MMM, 8 MMC, 12 ACA, 16 ACM, 16 MCA, 12 MCM.
Lastly, we have to consider the third line. Note that the last scheme, applied to count all possible second lines for each type of first line, can be "shifted" and also applied to count all possible third lines for each type of second line. This is because the first point of the path is now available for possible connections (we have predefined that closed paths are allowed) and therefore we have only to exclude the second point among the possible endpoints of the third line. For example, for the case  CAM, where the first line is CA and the second line is AM, for the successive third line we have to consider the number of possible connections stated in point 2.2 above, because the second line is AM. Therefore we can write $16CAM\rightarrow{\times6}$. The scheme, grouped for each of the fifteen initial sequences above, then becomes:

*

*$16CAM\rightarrow{\times6}=96$;

*$48MAM\rightarrow{\times6}=288$;

*$16MAC\rightarrow{\times7}=112$;

*$16CMA\rightarrow{\times4}=64$;

*$8CMM\rightarrow{\times6}=48$;

*$48AMA\rightarrow{\times4}=192$;

*$32AMM\rightarrow{\times6}=192$;

*$16AMC\rightarrow{\times7}=112$;

*$32MMA\rightarrow{\times4}=128$;

*$8MMM\rightarrow{\times6}=64$;

*$8MMC\rightarrow{\times7}=56$;

*$12ACA\rightarrow{\times4}=48$;

*$16ACM\rightarrow{\times6}=96$;

*$16MCA\rightarrow{\times4}=64$.

*$12MCM\rightarrow{\times6}=72$;
The sum of these numbers gives the final answer of $1632$ total possibilities for a path of length 3.


text:
Q: Calling SWI-Prolog via C based on a DLL again I need help. I try to call SWI-Prolog via C based on a dll on windows.
In my C progam I want to use the function "consult_cooco". The C code looks like
#include "consult_cooco.h"
#include <SWI-Prolog.h>

int consult_cooco( char** strInput )
{
    char *program = "consult_cooco";
    char *plav[2];
    int rval;

    char* xmlstring;
    term_t av;
    predicate_t p;

    /* make the argument vector for Prolog */
    plav[0] = program;
    plav[1] = NULL;

    putenv("SWI_HOME_DIR=C:\\Program Files (x86)\\swipl");
    if ( !PL_initialise(1, plav ) )
        PL_halt(1);

    av = PL_new_term_refs(2);
    p = PL_predicate("start_dialog", 2, "user");

    printf("consult_cooco:: input >> %s\n",*strInput);

    // Prolog call: start_dialog('ohne Zitrone, mit Joghurt, Butter',XML).
    av = PL_new_term_refs(2);
    PL_put_atom_chars(av, *strInput);

    if ( PL_call_predicate(NULL, PL_Q_NORMAL, p, av) )
    {
        rval = PL_get_atom_chars(av+1, &xmlstring);
        printf(" >> xmlstring of %s is \n\n%s (returned %i)\n",*strInput,xmlstring,rval);
    }
    else
    {
        printf(" >> no answer found\n");
    }

    PL_halt(1);

    return 0;
}

I created the dll by
swipl-ld -shared -dll -o consult_cooco -goal true consult_cooco.c dialog.pl -DLIKES_EXPORTS -v

I linked C sources by
gcc CooCoServer.o -static-libgcc -lws2_32 -L. -lconsult_cooco -I. -o startcoocoserver

Begin of my Prolog file dialog.pl looks like
start_dialog( InputString, XMLResult ) :-
    create_individual_filename('dialog_','.debug',Filename),
    tell(Filename),
    process_input( InputString, WordList ),
    do(WordList, XMLResult ),
    told.

Without
putenv("SWI_HOME_DIR=C:\\Program Files (x86)\\swipl");

I got the error
[FATAL ERROR: Could not find system resources]

as described in SWI Prolog manual.
But still Prolog predicates can not be found, the error description is
ERROR: '$c_call_prolog'/0: Undefined procedure: start_dialog/2

start_dialog is defined in dialog.pl, see above.
My assumption is that plav[0] = "consult_cooco"; is wrong and no link to the Prolog file is found.
When using an exe file starting from a C main file by changing
int consult_cooco( char** strInput )
{
    char *program = "consult_cooco";

to
int main( int argc, char** argv )
{
    char *program = argv[0];

it works. It works also with
int main( int argc, char** argv )
{
    char *program = "call_cooco";

What do I wrong when using the dll? What must be put into char *program?
Would appreciate your help very much.

A: Sorry for that, the answer is already given here:
I have to set
plav[0] = (char*)"startcoocoserver.exe";
plav[1] = (char*)"-x";
plav[2] = (char*)"dialog.exe";

and to use then
if(!PL_initialise(3, plav))

An additional building step is necessary
swipl --goal=true --stand_alone=true -o dialog -c dialog.pl

before doing the other steps. Then it works :)
PS: I did not found how to delete a question - admin, please do...


text:
Q: How to multiply points on elliptic curve? I am learning about elliptic curves.
Consider the elliptic curve $y^2=x^3+2$ over $\mathbb Q$. Then $P=(-1,1)$ is a point on it.
I want to find its multiples i.e., $2P,3P, \cdots$
The addition of two points $P=(x_1,y_1),~Q=(x_2,y_2)$ is obtained by intersecting the line $\bar{PQ}$ intersecting the elliptic curve, i.e., if $R=(x_3,y_3)$ be the addition of $P$ and $Q$, then it is given by
\begin{align} x_3&=\lambda^2-x_1-x_2 \\
y_3&=\lambda(x_1-x_3)-y_1, \\
\lambda&=\frac{y_2-y_1}{x_2-x_1} \end{align}
But when we double a point, the slope $\lambda$ will be as follows: $$\lambda=\frac{3x_1^2+2}{2y_1}.$$
So in our case $\lambda=\frac{5}{2}$. Hence:
$$x_3=25/4+1+1=33/4, ~y_3=5/2(-1-33/4)-1=-193/8.$$
So $2P=(\frac{33}{4},-\frac{193}{8})$.
Is it correct ?
Is it the only way ?
Edit: I already got the answer as mentioned in the folloing comment sections. But I couldn't understand why my approach didn't work ?  Are the formulas that I used correct ?

A: Basically, your slope calculation was not correct.
Let $P=(-1,1)$
$$\lambda=\frac{3 x_1^2+2}{2y_1} = \frac{3\cdot 1^2+0}{2}= \color{red}{\frac{3}{2}}$$
The formula is
$$x_e = \lambda^2 - 2x_1$$
$$x_3=(9/4) - 2(-1) = 17/4$$
For $y_3$ formula is
$$y_3 = \lambda(x_1 − x_3 ) − y_1$$
\begin{align}
y_3&=\left[(3/2)(-1-17/4)\right]-1\\
   &=\left[(3/2)(-21/4)\right]-1\\
   &=(-63/8)-1\\
   &=(-63/8)-1\\
   &=-71/8\\
\end{align}
Verifacation with SageMath on the SageMathCell
A = 0
B = 2
E = EllipticCurve([A,B])

P = E(-1,1)
2*P

outputs
(17/4 : -71/8 : 1)


text:
Q: How to always keep browser on focus When I click radio button or navigate through tabs my geckofx web browser loose focus. I can get back to focus by using browser.Focus() it works well but if there is for example two tabs 1tab and 2tab. On 2tab is my webbrowser. When I go to tab1 my browser in tab2 loose focus and command browser.Focus() wont work. Its really annoying that everytime I do some stuff on my UI gecko loose focus. Is there any way how I could keep it ALWAYS on focus?
Thanks.
Edit:
I thinked about making UI elements not to focus on them so browser wont loose its focus.
enter link description here
Found this, used that class and it works with buttons. Ill try to do this on tabs.

A: It's simple. First add this code on Form_load :
private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.TabIndex = 0;
            webBrowser1.Focus();
        }

Then make all other controls' Tabstop property to false. And on every controls clicking event add this code : webBrowser1.Focus();
For example I use this code for Button and RadioButton.
private void radioButton1_Click(object sender, EventArgs e)
    {
        radioButton1.TabStop = false;
        webBrowser1.Focus();
        webBrowser1.LostFocus += webBrowser1_LostFocus;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button1.TabStop = false;
        webBrowser1.Focus();
        webBrowser1.LostFocus += webBrowser1_LostFocus;
    }

Do this for all other controls in your form. You also need to define webBrowser1_LostFocus void for that.
void webBrowser1_LostFocus(object sender, EventArgs e)
    {
        webBrowser1.Focus();
    }

Update : You can also make a void for focusing. Then use this void in everywhere you want. Try this :
public void SetFocus(Control webbrowser)
{
 // Set focus to the control.
   if(webbrowser.CanFocus)
   {
      webbrowser.Focus();
   }
}


text:
Q: Building HTML table in javascript, getting "ReferenceError: invalid assignment left-hand side" I hope someone can help me out with this.  I'm trying to dynamically build an HTML table in javascript/jquery based on iterating over an array built by earlier code.  I am getting an error on the referenced line below as soon as the page loads:
function BuildForm (allFields) {
    var dyndata = "";
    var formstart = "<form>\n<fieldset class='fieldset-js'>\n<legend>Choose A Parent</legend>\n
\n
\nID	\nName	\nDOB	\nPhone	\n
\n
";
    $('#PickAParent-Form').append(formstart);
    $.each(allFields, function (index, value) {
        if ((index + 5) % 5 == 0) {
            dyndata = "
\n<input type='radio' name='pid' value='" = index + "'>" + value + "	\n";
     error here---------^
            $('#PickAParent-Form').append(dyndata);
        } elseif ((index +1 ) % 5 == 0) {
            dyndata = "" + value + "	\n
\n";
            $('#PickAParent-Form').append(dyndata);
        } else {
            dyndata = "" + value + "	\n";
            $('#PickAParent-Form').append(dyndata);
        }
    });
    DisplayForm;
}

I have been all over Google and SO this AM but can't figure this one out.  Any help is MUCH appreciated!!

A: Change it to:
dyndata = "
\n<input type='radio' name='pid' value='" + index + "'>" + value + "	\n";

Note:
value='" + index + "'

Instead of:
value='" = index + "'

A: This line:
dyndata = "
\n<input type='radio' name='pid' value='" = index + "'>" + value + "	\n";

should be:
dyndata = "
\n<input type='radio' name='pid' value='" + index + "'>" + value + "	\n";

Looks like you had an equals sign instead of a plus sign for variable to string conversion


text:
Q: When a SensorEvent is reused by the system, does it allocate a new values array? I'm using android sensors, and I don't want my code to produce a new object for each sensor event. For now, I'm copying the values contained in the array SensorEvent.values to my own Sample class values array.
I know SensorEvents are reused by the system and cannot be kept, but I was wondering if SensorEvent.values was also reused or if a new array was allocated. Indeed, there is no point in copying the array into mine if a new is created anyway (I'd better replace my own array by SensorEvent.values directly).
I've been looking at different posts like post 1 and post 2 but they deal with SensorEvent objects and not the values field itself.

A: To clarify for future readers, the array SensorEvent.values is reused as well as the SensorEvent object. Therefore, one should not keep any reference to it, and should instead copy each value.

A: As shown here, it is declared as
public final float[] values;

So the array is not reallocated, it is just reused -- you'll have to clone it.


text:
Q: Contact Form; ASP.NET, C# This should be simple, but there is something I'm not getting. The user fills out info and the btnClick does the code.
I would think the msgToAdd would be who the e-mail is going to. (Testing as my email.)
And that the msgFromAdd would be who the message is from, which is input by the person browsing. (Testing as my wife's email.)
Then the credentials I put in my email/password. (Which in reality, anything "mine" would be x company. So I would need to code in the company email password? :-/)
Anyway, I successfully send email to my address, but it says it's coming from my address and I need it to come from whatever address the user input.
I've searched everywhere, but all the code is the same and it makes no sense to me. Thanks.
        SmtpClient smtpClient = new SmtpClient();

        MailMessage mailMsg = new MailMessage();

        MailAddress msgToAdd = new MailAddress("myemail@gmail.com");
        MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text);

        mailMsg.To.Add(msgToAdd);
        mailMsg.From = msgFromAdd;
        mailMsg.Subject = ddlEmail.SelectedValue;
        mailMsg.IsBodyHtml = true;
        mailMsg.Body = tbxEmail.Text;

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");
        smtp.EnableSsl = true;
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.Send(mailMsg);

So even with the overkill below, it still doesn't show the real sender's address.
        MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text);

        mailMsg.From = msgFromAdd;
        mailMsg.ReplyToList.Add(msgFromAdd);
        mailMsg.ReplyTo = msgFromAdd;
        mailMsg.Sender = msgFromAdd;

Also, the following DOES make the name show up. Still no email address though!
MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text, "NAME");

I'm seriously losing it.

A: Sounds like google don't let you mess with the "from" header?  You might want to try using the "Sender" property, doesn't always render nice in all email clients tho.
MailMessage, difference between Sender and From properties

A: I would check your web.config (if you have one). There may be a setting like:
<system.net>
    <mailSettings>
      <smtp from="your address here">
        <network host="localhost" password="" userName=""/>
      </smtp>
    </mailSettings>
 </system.net>

that could be overriding your settings.

A: you're sending email with your smtp credential, so the "from" should be your email. the "From" property in MailMessage is just an optional choise in case you're using an open smtp that needn't credentials.


text:
Q: Android ParseQueryAdapter notifyDataSetChanged does not work Using latest Parse library v1.5.1
Thanks to the update now I can do:
ParseQueryAdapter<ParseObject> mAdapter = new ParseQueryAdapter<ParseObject>(MainActivity.this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
    @Override
    public ParseQuery<ParseObject> create() {

        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(ParseObject.class);
        query.fromLocalDatastore();

        return query;
    }
});
mListView.setAdapter(mAdapter);

Now I have some pinned objects and they appear correctly, but when I unpin them like so:
//Some ParseObject in the above adapter
object.unpinInBackground(new DeleteCallback() {
    @Override
    public void done(ParseException e) {
        if(e == null) {
            //I beleive this would be the correct approach.
            mAdapter.notifyDataSetChanged();
        }
    }
});

Naturally I want that item to disappear from the corresponding ListView, but it doesn't. But say I go back to a different activity and revisit this activity, the ListView is displayed properly without the recently unpinned object.
Is this a bug? If not what am I doing wrong?

A: I have the same problem) I solve it with invoke method ParseQueryAdapter.loadObjects().

A: You can try mAdapter.remove(object) before calling notifyDataSetChanged();
unpinInBackground removes the object from the database. Probably the adapter has a local copy of the object.
Looks like there is no remove method in ParseQueryAdapter.
Here is an response from official source:

Since a ParseQueryAdapter is designed to always show the results of a
  ParseQuery, you would need to use an API request to reload the query.

https://www.parse.com/questions/delete-a-object-using-parsequeryadapter


text:
Q: Flexbox drop down menu position and movement I'm trying to design a header with 3 items:
----------
   LOGO
----------  hidden navigation bar
----------
  BUTTON
----------

Which then grows to:
----------
   LOGO
----------
li
li
li
li
----------
  BUTTON
----------

I'd like the logo and the button to remain vertically centered and for all growth/movement to happen downwards from the top of the button/bottom of the logo-container. I've managed this without flexbox, but I'd like to use it so that I can get a better understanding of why this isn't working.
At the moment - unless I put a large height for the logo container - which feels a bit hacky - the menu grows upwards as well as down. I'd ideally like to use justify-content: space-around but obviously that attributes some space to the hidden menu.
I feel like flex-shrink might be a solution, but I'm very much a novice at all this, and can't get it to work. Here's what I've got so far:
https://codepen.io/nwoodward/pen/RMrRVZ

$('#button').click(function() {
  $('.menu').toggleClass('menu--open', 700);
})
header {
  background: #808080;
  display: flex;
  flex-direction: column;
  min-height: 100px;
}

#logo-container {
  display: block;
  flex-grow: 2;
  background: red;
  width: 100%;
  height: 50px;
  text-align: center;
}

#logo-container img {
  height: 40px;
}

.menu {
  height: 0px;
  overflow: hidden;
  background-color: green;
}

.menu--open {
  height: auto;
}

#button {
  background: blue;
  width: 100%;
  height: 20px;
  text-align: center;
  cursor: pointer;
}

#rest {
  height: 500px;
  background: #000;
}

item 1

item 2

item 3

item 4

item 5

Click Me

A: I don't see any good reason to use flexbox in that case. But to answer your question, the key is the header {min-height: 100px;} setting.
With the default collapsed menu, the overall computed height of elements in the header is smaller than 100px. However it will be greater than 100px when the menu expands. Therefore, it creates the effects of pushing the menu to the top first and then to the bottom.


text:
Q: Shopify: auto-update Price when Quantity changed in Cart page? How to update Price immediately once the buyer increase or decrease the Quantity using Plus & Minus buttons?
Here is the Quantity Picker code:

-

<input type="number" name="updates[]" id="updates_{{ item.key }}" class="cart__product-qty" value="{{ item.quantity }}" min="0" data-id="{{ item.key }}">

+

Thanks


text:
Q: Internal Server Error when trying to check url I'm trying to check the string after the last trailing slash in my URL.
My code is as follows:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$data = substr($url, strrpos($url, '/') + 1);

if($data == "dashboard") {
      require_once VIEW_ROOT . '/cp/dashboard_view.php';
} else {
      echo $data;
}

Once I go to http://MYURL/dashboard/in it should show in as the $data. Instead it gives me a 500 error.

A: You can simply use explode() function to break the string... .Or else $_SERVER[REQUEST_URI] shall give you the data after the host name...
But for the data after the last '/' explode function will work the best..
This will work.
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$x = explode('/',$url);
$data = $x[sizeof($x)-1];
echo $data;

A: You should try :
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];

You need to join
http:// string with $_SERVER[HTTP_HOST] and then $_SERVER[REQUEST_URI] using .(dot).


text:
Q: Need help with permalink rewrites for Custom Post Types with hierarchical relationships I'm working on a TV website that has several custom post types that are separate, but related (e.g. Series, Episodes, Videos).
There are hierarchical relationships between these post types - Episodes belong to Series, and Videos can belong to Series and/or Episodes. These relationships are set through a meta key on the child entry which identifies the parent entry.
Structurally that seems to work OK, but I'm having trouble with the permalinks.
By default, WordPress displays the URLs as follows:
Series Archive and Single Entry (OK):
domain/series/
domain/series/series-name/
Individual Episode (Not OK):
/domain/episodes/episode-name/
With this permalink, isn't clear which Series the Episode is associated with. And in some cases where episodes have the same name (e.g. "Pilot" you end up with auto-generated names like "pilot-2" and "pilot-3".
Desired URL structure for individual episode (or video)
/domain/series/series-name/episodes/episode-name/
/domain/series/series-name/videos/video-name/
I tried to piece together some code for this based on some blog posts I found online, but it's not working. Here is the code I'm currently trying:
function custom_rewrites() {
  global $wp_rewrite;

  add_rewrite_tag('%episodename%', '([^&]+)', 'episodes=');

  add_permastruct('episodes', '/series/series_placeholder/episodes/%episodename%', false);

  add_rewrite_rule('^episodes/([^/]*)/([^/]*)/?','index.php?series=$matches[1]&episodes=$matches[2]','top');
}

add_action( 'init', 'custom_rewrites', 10, 0 );

I feel like I'm kind of close, but I'm clearly missing something (or several things).
Any help would be much appreciated!

A: I think it is better to connect with taxonomy terms. Since you can add any custom fields to terms using ACF / another plugin / code, it is possible to use terms with images, full description etc.
I had similar task, this tutorial should be helpful https://rudrastyh.com/wordpress/taxonomy-slug-in-post-type-url.html. Yes, I know that there is no hierarchy but I want to show you another principle to implement your task.
Actually to add an hierarchy you just have to reorder terms from this part of the code:
$terms = wp_get_object_terms( $post->ID, $tax_name );

And add them in this part:
$permalink = str_replace( $post_type_slug, $terms[0]->slug . '/' . $terms[0]->slug, $permalink );

If you have a specific quetion - ask in comments - here or there as you want. I will try to help you.


text:
Q: AutoResetEvent doesn't work by some reason upd I've found that AutoResetEvent is works as expected. It seems I have exception somewhere inside CalculateAndNotify. So this question is not about AutoResetEvent anymore. But if you can suggest how to better calculate indexes in HFT software - comments are welcome.
==============================================================================
I add below the full listing of my class. There are two important methods. Calculate is recalculating the index value every time InstrumentUpdated is called.
class CompositeIndex : CustomIndex
{
    //private Tuple<Instrument, double>[] _instrumentsWithWeight;
    //private int[] _instrumentIds;
    //private double[] _ammounts;
    //private double[] _cachedProduct; // one thread writes here and another thread reads. so need to use "Volatile"
    //private volatile bool _initialized;

    //AutoResetEvent are = new AutoResetEvent(false);

    //public CompositeIndex(string indexId, Tuple<Instrument, double>[] instrumentsWithWeight)
    //    : base(indexId, GetInstruments(instrumentsWithWeight))
    //{
    //    _instrumentsWithWeight = instrumentsWithWeight;
    //    _instrumentIds = new int[_instrumentsWithWeight.Count()];
    //    _ammounts = new double[Commons.Constants.MAX_INSTRUMENTS_NUMBER_IN_SYSTEM];
    //    _cachedProduct = new double[Commons.Constants.MAX_INSTRUMENTS_NUMBER_IN_SYSTEM];

        Task.Factory.StartNew(() =>
                {
                    while(true)
                    {
                        if (_initialized)
                        {
                            break;
                        }
                        Thread.Sleep(1000);
                    }
                    while (true)
                    {
                        are.WaitOne();             // hangs here!
                        CalculateAndNotify();
                    }
                }
            , TaskCreationOptions.LongRunning);
    }

    //private static List<Instrument> GetInstruments(Tuple<Instrument, double>[] instrumentsWithWeight)
    //{
    //    List<Instrument> result = new List<Instrument>();
    //    for (int i = 0; i < instrumentsWithWeight.Count(); i++)
    //    {
    //        result.Add(instrumentsWithWeight[i].Item1);
    //    }
    //    return result;
    //}

    //protected override void Calculate()
    //{
    //    double result = 0;
    //    for (int i = 0; i < _instrumentIds.Count(); i++)
    //    {
    //        int instrumentId = _instrumentIds[i];
    //        // we assign 0 weself so this comparision is OK
    //        double cachedProduct = Volatile.Read(ref _cachedProduct[instrumentId]);
    //        if (cachedProduct == 0)
    //        {
    //            Value = null;
    //            return;
    //        }
    //        result += cachedProduct;
    //    }
    //    Value = result;
    //}

    //private object _initializeLock = new object();

    //private bool Initialize()
    //{
    //    lock (_initializeLock)
    //    {
    //        if (_initialized)
    //        {
    //            return true;
    //        }
    //        for (int i = 0; i < _instrumentsWithWeight.Count(); i++)
    //        {
    //            Instrument instrument = _instrumentsWithWeight[i].Item1;
    //            double weight = _instrumentsWithWeight[i].Item2;
    //            _instrumentIds[i] = instrument.Id;
    //            _ammounts[instrument.Id] = weight;
    //        }
    //        _initialized = true;
    //        return true;
    //    }
    //}

    public override void InstrumentUpdated(Instrument instrument)
    {
        //if (!_initialized)
        //{
        //    if (!Initialize())
        //    {
        //        return;
        //    }
        //}
        //int instrumentId = instrument.Id;
        //bool useSecurityInsteadOfOrderBook = instrument.GateId == 1;

        //decimal? value;
        //if  (useSecurityInsteadOfOrderBook)
        //{
        //    InstrumentInfo ii = Markets.GetInstrumentInfo(instrument);
        //    value = ii.MedianOrAskOrBid;
        //} else
        //{
        //    Glass glass = Markets.GetGlass(instrument);
        //    value = glass.MedianOrAskOrBid;
        //}

        //if (value == null)
        //{
        //    Volatile.Write(ref _cachedProduct[instrumentId], 0);
        //}
        //else
        //{
        //    Volatile.Write(ref _cachedProduct[instrumentId], ((double)value) * _ammounts[instrumentId]);
        //}
        are.Set();      // called many times!
    }

}

I've added some tracing and noticed that:
One thread hangs at are.WaitOne(). Despite of the fact that another thread call are.Set() many times the first thread is not released.
Why? What's wrong with my code?

A:  public override void InstrumentUpdated(Instrument instrument)
 {
    //your code
    // are.Set - do not need

    Task.Factory.StartNew(CalculateAndNotify, TaskCreationOptions.LongRunning);
 }

and you should change CalculateAndNotify
 protected void CalculateAndNotify()
 {
     if (Monitor.TryEnter(someObject))
     {
         try
         {
             // your code
         }
         finally
         {
             Monitor.Exit(someObject);
         }
     }
 }

that probably will do what you want


text:
Q: Does $p$-value change with sample size? I was wondering how $p$-values change with sample size or is their any relation between the two. To my knowledge, a $p$-value denotes the probability of finding observed or more extreme results than the null hypothesis claims (typically no difference). Based on the following example, let your null hypothesis be that there exists no difference in the amount of heads and tails you flip on a fair coin, that is you flip the same exact amount and your alternative be that a difference does exist. You flip a fair coin $n = 10$ times and get $7$ heads and $3$ tails, which suggests a relatively low $p$-value. But as you flip this coin more times (say $n = 100$) and now get $45$ heads and $55$ tails, your $p$-value increases - which results in you being more likely to fail to reject the null over the alternative hypothesis.
Thus, does increasing sample size, increase $p$-values in general?

A: In general, increasing the sample size changes the p-value (not necessarily increasing it). There is a lot to discuss as to why it is so and also why ''p-hacking'' is a thing, but there is a youtube video where it is explained in simple terms:
https://www.youtube.com/watch?v=42QuXLucH3Q

A: Well, the p-value can be seen as a random variable, so as you get more data, calculate the p-value anew, the value will most probably change. But I take your question to be if the distribution of the p-value changes.
Your question was not completely clear, but I take the question to be if the distribution will change under the null hypothesis. By the definition of the p-value, then, under the null hypothesis its distribution is uniform on $(0,1)$. That does not depend on the sample size $n$.  So, under the null hypothesis the answer is NO. The p-value (distribution) do not depend on $n$.
For the alternative the answer is different. If the alternative is true, we expect that with more data we will get more evidence against the null, so the p-value will be (stochastically) smaller. In that case, the p-value distribution will depend on $n$.
But there might be counterexamples, for instance, if you are using a bad (not consistent or not using the data effectively) hypothesis test, or if your data is  not really bearing on your hypothesis. But for the majority of reasonable situations, the conclusion will hold.
For the future, such questions are better asked at https://stats.stackexchange.com/, where you would have got good answers must faster than here.

A: Whether the p-value is affected by the sample size depends on: (1) whether the test statistic for the particular hypothesis test being conducted depends on the sample size, since the p-value is a probability acquired from this test statistic; and (2) whether the distribution being used also depends on the sample size, since the p-value is a probability from this distribution.
Most hypothesis tests that use the normal, student's t, chi-squared, etc. distributions have test statistics and/or distributions that depend on the sample size, so most p-values are affected by a change in n; however, this change may be unnoticeably small or surprisingly large, and is a complicated concept as per @PseudoRandom

A: "the probability of finding observed or more extreme results than the null hypothesis claims" is not right. The p-value is the probability that a result at least as extreme as that which was actually observed would occur given that the null hypothesis is true.
If the coin you're tossing is fair, that being what the null hypothesis says, then with very high probability the p-value will be large when the number of trials is large. If the null hypothesis is false, then the probability is $1$ that the p-value will approach $0$ as the sample size grows.


text:
Q: wordpress lock out as mail function not enabled I have my own website & domain. It has a wordpress blog. I forgot the password and basically now m locked out. It gives following mesage:
Possible reason: your host may have disabled the mail() function.

I checked on google, many people sAID to go to database and change password. I tried doing that too but still I am locked out. Can anyone help?

A: I fixed the problem myself by adding a new row of a user in users table and then in users _ meta table, I updated the user id to be the Id I added in users table. For example, if user id added was 2 then to give administration privileges, I updated user id 2 in user meta table. This fixed the problem.

A: create one php file and add following code in it.
<?php
define('WP_USE_THEMES', false);
require("wp-load.php");
$user = array('user_login' => 'username','user_pass' => 'password','user_email' =>
'youremail@domain.com','role' => 'administrator');
var_dump(wp_insert_user($user));

change "username" and password value to something that already not have like
 username:fscore25 and password: 123456 you can change password later on and also add another email address which is working fine for you.
upload file to root of your wordpress installtion.
it should be with file named wp-load.php
then go to your browser and execute this file using
http://yourdomain.com/yourfilename.php
hope it helps