text:
Q: Most pythonic way of function with no return? A I couldn't find anything concerning in the PEP 8. I'm interested in your thoughts about the most pythonic syntax of function which have no return?
Are there any reason to prevent functions without a return line(example 3)?
Example 1:
def foo():
   print 'foo'
   return None

Example 2:
def foo():
   print 'foo'
   pass

Example 3:
def foo():
   print 'foo'

A: If you function returns a value, that may be None is some case, return None is good.
If you function doesn't return a value, but you want to return early, use return without any parameter. On the last line, you can omit it.
pass does nothing, and is only useful when a statement is needed to avoir a syntax error (in an empty class, for example)

A: Keep it simple. Example 3 is the most pythonic way.
>>> import this

The Zen of Python, by Tim Peters

...
Simple is better than complex.
...

A: There are two use cases:

*

*a function that never returns anything (a.k.a "procedure"). You should omit return altogether.

*a function that returns None for some inputs. I personally prefer to put return None there, because otherwise it might slightly confuse the reader:

example:
 def find_user(name):
     if database.is_ready():
        return database.find_user_by_name(name)
     else:
        return None

Technically, you can drop the else part, but that would make the function look confusing.

A: The PEP8 has a recommendation on this topic:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable).

Yes:
def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:
def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

A: As others have stated Option 3 is by far the best.
Even more of a reason Option 3 is a good idea is that many people are of the opinion that None (aka null in other languages) should generally never be returned and that you should throw an exception or use the Null Object pattern. While I don't entirely agree with that I think there is some valid point of avoiding using None particularly explicitly when it doesn't semantically make sense and is ambiguous.
I'm not saying you should never return None but in general I don't think its a good idea.
You can even see this in Python today where blah['DOESNOTEXIST'] will throw an exception where in Java map.get("DOESNOTEXIST") will return null.


text:
Q: Weka Explorer isn't working I am using Weka Explorer to do a SMOTE oversampling of my training data. The file format is libsvm compatible. It's loaded. Everything looks fine. But when I select filter->supervised learning->SMOTE, and choose the default settings. Then I should press "apply" to start sampling, but the problem is that the "apply" button is gray, disabled. I can't do it.
What might cause this? Really thanks for any information.
The data format I loaded in Weka Exlporer is this:
-1 1:-1.0 2:-1.0 3:-1.0 4:-1.0 5:-1.0 6:-1.0 7:0.5 8:0.0043 9:0.0063 10:1.0
1 1:-1.0 2:-1.0 3:1.0 4:-1.0 5:-1.0 6:1.0 7:0.5 8:0.0028 9:0.0028 10:3.0
This is the format LIBSVM accepts. Wekta allows libsvm format. Right?

redpajama_set_name: RedPajamaStackExchange


text:
Q: box-shadow CSS property not working properly on iOS

function getLocation(parameter) {
    const queryString = new URLSearchParams(window.location.search);
    const queryStringParam = queryString.get(parameter);
    return queryStringParam;
};

function fillServiceItemContent(parameter, element, infoArray, elementTitle) {
    const locationParam = getLocation(parameter);
    const info = infoArray[locationParam].info;
    const title = infoArray[locationParam].title;
    const video = infoArray[locationParam].video;

    if (elementTitle === undefined && element.tagName === 'VIDEO') {
        element.innerHTML = '';
        element.setAttribute('src', video);
        element.setAttribute('type', 'video/mp4');
        return;
    } else if(elementTitle === undefined) {
        element.innerHTML = info;
        return;
    }
        element.innerHTML = info;
        elementTitle.innerHTML = title;
};
.service-items .service-video video {
    height: 80vh;
    border-radius: 1em;
        -webkit-border-radius: 1em;
        -moz-border-radius: 1em;
    box-shadow: -15px 14px 23px -16px #000;
        -webkit-box-shadow: -15px 14px 23px -16px #000;
        -moz-box-shadow: -15px 14px 23px -16px #000;
    -webkit-appearance: none;
}

  <video id="service-video-source" autoplay loop muted playsinline></video>

I have a problem with the box-shadow rendering on a video tag on iOS. It's not working properly neither on Safari or Chrome. I have tested it on iPhone X. It's pushing the video to the right, and the box-shadow is invisible. On desktop or Android is working properly. Is there a solution for this?


text:
Q: kubernetes: AWS ELB not working I have set up a front-end service via the following svc and deployment:
Deployment
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ui-deployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        els-pod: ui
    spec:
      containers:
      - image: pkaramol/the-ui
        name: ui
        ports:
        - containerPort: 80
      restartPolicy: Always

Service
apiVersion: v1
kind: Service
metadata:
  name: ui
spec:
  ports:
  - name: ui-port
    port: 8080
    targetPort: 80
  selector:
    els-pod: ui

When exposing via an AWS ELB as follows:
kubectl expose  deployment ui-deployment --type=LoadBalancer --port=80 --target-port=8080 --name=k8s-elb

I get an empty page when accessing ELB's dns name.
Furthermore, the instances behind the elb seem unhealthy:

Also, does the following port mapping make sense?

A: You may need some additions to your service yaml file -

*

*Add loalbalancer Ip and type in Service yaml
loadBalancerIP: <Public Ip>
type: LoadBalancer

*ELB routing

*

*If you are hitting with HTTP or https directly with URL without specifying any port, then you need 80 and 443 both to Port on which service is running like 30001  ex - http://ip or https://ip

*If you want to hit open Ip say 8180, then add Rule to forward 8180 to 30001
ex - http://IP:8180/

*And I think you don`t need to expose deployment. Running Service yaml will work.

*Make sure you are providing correct ports. You may leave target port also. It will be taken same as of Port that is 8080 in your case

Refrence - https://cloud.google.com/kubernetes-engine/docs/tutorials/configuring-domain-name-static-ip

A: Set your service type to LoadBalancer: https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#external-load-balancer-providers
apiVersion: v1
kind: Service
metadata:
  name: ui
spec:
  type: LoadBalancer
  ports:
  - name: ui-port
    port: 8080
    targetPort: 80
  selector:
    els-pod: ui

You do not need to set a load balancer IP.


text:
Q: redirecting folder to file using htaccess A friend wants me to implement basic file security on his site that he can look after himself.
I think the simplest option is to put a .htaccess file into the folder he wants to protect and that will redirect all requests to a php file in the root.
The php file will then check if the user is logged in and serve the file or request a fixed shared login password.
It's going ok so far except for two problems.
Firstly I can't get the htaccess file work based on the directory it is located in - I can only manage it by hard coding the directory into the htaccess file.
Secondly, I can get the php file to know the url of the file that was requested.
Any help and pointers would be great!

A: It sounds like what you are wanting to do can be done a little more easily with an .htpasswd setup.
You will just place this in an .htaccess of the directory you are trying to protect and all of the sub-directories will be protected as well.
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

And then create an .htpasswd file and use a tool like this to generate the credentials.
Alternatively, the way you are suggesting to do it will require the use of either cookies or sessions and here is another question that should help a bit more with setting that up.


text:
Q: How to use "of which" to refer to a percentage Please help me with the use "of which" in the following context:
Original sentence:

A and B caused the problem for 50% and 23% of the elderly people in
  England respectively.

Rewrite (option 1):

A and B cause the problem for almost three quarters (73%) of the
  elderly people in England, of which 50% being affected by A and 23%
  being a result of B.

Rewrite (option 2):

A and B cause the problem for almost three quarters (73%) of the
  elderly people in England, of which around two thirds being affected
  by A and a third being a result of B.

Also, I'm not so sure whether "of which" in this case refers to "almost three quarters (73%) of the elderly people in England", or it refers to England only.

A: I think that the biggest difference between your two options, which virmaior doesn't seem to have considered (or at least didn't mention) is what the percentages add up to. Let's make the numbers smaller, so it's more noticeable:

Every day, up to 12% of British people accidentally punch themselves in the face, of which 9% use their right hand, and 3% use their left hand.

versus:

Every day, up to 12% of British people accidentally punch themselves in the face, of which 75% use their right hand, and 25% use their left hand.

Should the percentages in the "of which" part add up to the previous 12%, or add up to 100%. Convention seems to be that they should add up to 100%; i.e. the latter option.
Also, when referring to people you should probably use "of whom" rather than "of which". It's one of the few uses of "whom" where you're unlikely to get accused of being pretentious!

A: I would go with the following:

A and B cause the problem for almost three quarters (73%) of the elderly people in England, of which 50% are affected by A and 23% of cases are a result of B.

This is different from your option A in that I am preferring the construction that makes both of the sections that follow of which into subordinate clauses with verbs in normal conjugation rather than "being" clauses.


text:
Q: Container goes underneath fixed element when min-width is applied I am trying to complete a freecodecamp project. I have a sidebar nav along with a section-container. When I set min-width: 600px; to the section-container, it works as expected, but when I minimize my window below 600px and click on the navbar links, the section-container goes underneath the navbar despite there being a margin-left applied to it. This doesn't happen when min-width is not applied.
Why is this happening, and how do I fix it?

@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  line-height: 1.4;
  font-size: 1.25rem;
}

.container #main-doc #navbar header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container #main-doc #navbar header h1 {
  margin-left: 0.625rem;
  margin-right: 0.625rem;
}

.container #main-doc nav {
  position: fixed;
  border-right: 2px solid black;
  height: 100%;
}

.container #main-doc nav ul:first-of-type {
  list-style: none;
}

.container #main-doc nav ul:first-of-type li{
  margin-bottom: 0.625rem;
  padding-right: 0.625rem;
  border-bottom: 2px solid black;
}

.container #main-doc nav ul:first-of-type li a {
  text-decoration: none;
  color: black;
  display: block;
  margin-left: 1.25rem;
}

.container #main-doc #section-container {
/*   padding: 2.5rem 2.5rem; */
  margin-left: 370px;
  min-width: 600px;
}

.container #main-doc #section-container .main-section header {
  font-size: 1.5rem;
  font-family: 'Noto Sans', sans-serif;
  font-weight: 700;
  margin-bottom: 0.625rem;
}

.container #main-doc #section-container .main-section {
  margin-bottom: 2.5rem;
}

.container #main-doc #section-container .main-section p {
  margin-left: 1.25rem;
}

.container #main-doc #section-container .main-section ul {
  margin-left: 5rem;
}

Semantic Elements

New Semantic Tags Added by HTML5

The header element

The main element

The nav element

The article element

The section element

The aside element

The address element

The footer element

      New Semantic Tags Added by HTML5

In this brief tutorial we'll touch on all of the new tags added as part of HTML5 to define the structure and content of a web page. The elements we're going to cover in this guide include:

header

main

nav

article

section

aside

address

footer

Using these elements isn't as complicated as it might appear at first glance, and most are fairly self-explanatory. We'll make a quick pass over each new element, and then draw up an HTML template you can use these new tags to add rich semantic meaning to your markup.

      The header element

The header element is used to contain the content that appears at the top of every page of your website: the logo, tagline, search prompt, and possibly a navigational menu. In most cases, the header element is best positioned as a direct descendant of the body element, but it's also ok to place it inside the main element if you prefer.

      The main element

Use the main element between header and footer elements to contain the primary content of your web page. The main element cannot be a descendant of an article, aside, header, footer, or nav element. Instead, it should be a direct descendant of the body element. Think of it as the direct replacement for the div id="main" you've used in the past to wrap up your entire page contents.

It's also ok to use more than one main element on a webpage. For example, if your blog homepage includes your five most recent posts, it would be appropriate to wrap each post in it's own main element – or you could wrap each in article tags.

       The nav element

Navigational menus are commonly placed at the top of a web page, in a sidebar, or in the page footer. Wherever you happen to place a navigational menu, wrap it in nav tags. Note that you don't need to use nav tags for every link, just for blocks of links that provide either sitewide navigation or navigation for a specific part of a website.

      The article element

If your website includes blog posts, articles, or any other content that could just as well appear on another website as syndicated content, wrap that content in an article post. You can use an article element just about anywhere other than nested within an address element, but in most cases an article element will be a direct descendant of a main element or of a section element that is a direct descendant of a main element..

      The section element

Navigational menus are commonly placed at the top of a web page, in a sidebar, or in the page footer. Wherever you happen to place a navigational menu, wrap it in nav tags. Note that you don't need to use nav tags for every link, just for blocks of links that provide either sitewide navigation or navigation for a specific part of a website.

        The aside element

If your website contains information that isn't directly related to the main content of the page, it would be appropriate to wrap that information in aside tags. For example, if you write a post that includes some technical terms, and you add definitions for those terms in a sidebar, it would make sense to wrap those definitions in aside tags. It is also common for the entire sidebar of a blog-type website to be wrapped in aside tags to make it clear that the sidebar is not part of the primary content of the page.

        The address element

The address element provides contact information for the nearest parent article or body element that contains it. Use the address element inside an article to provide contact information for the article's author. Use it outside of an article in the main or footer elements, or as a direct descendant of the body element, to provide contact information for the website's owner.

        The footer element

The footer appears at the bottom of a section of a document. Typically, the footer is a direct descendant of the body element, but it can also be used within a main element, a section, or an article. The most common use of the footer element is to place it at the bottom of an HTML document to contain things like a copyright notice, links to related content, address information about the owner of the website, and links to administrative things like privacy policies and website's terms of service.

You may also use the footer element within an article to provide metadata about that particular article. For example, if article tags have been used to wrap a forum post, it would be appropriate to wrap copyright information and the date and time the post was made in a footer element and place it at the bottom of the article.

       Source

A: Below I put the min-width:70%; and I put the nav's width:30%;. Doing this will have a responsive design where it will always be 70% and 30%. When you do min-width: 600px; you're telling CSS that no matter the screen size, always take up 600px of space.
Also, I put in a overflow-y:scroll; in the nav section so that the nav bar's content can be scrolled through if the viewport is not tall enough.

@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  line-height: 1.4;
  font-size: 1.25rem;
}

.container #main-doc #navbar header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container #main-doc #navbar header h1 {
  margin-left: 0.625rem;
  margin-right: 0.625rem;
}

.container #main-doc nav {
  position: fixed;
  border-right: 2px solid black;
  height: 100%;
  width: 30%;
  overflow-y: scroll;
}

.container #main-doc nav ul:first-of-type {
  list-style: none;
}

.container #main-doc nav ul:first-of-type li{
  margin-bottom: 0.625rem;
  padding-right: 0.625rem;
  border-bottom: 2px solid black;
}

.container #main-doc nav ul:first-of-type li a {
  text-decoration: none;
  color: black;
  display: block;
  margin-left: 1.25rem;
}

.container #main-doc #section-container {
/*   padding: 2.5rem 2.5rem; */
  margin-left: 30%;
  min-width: 70%;
}

.container #main-doc #section-container .main-section header {
  font-size: 1.5rem;
  font-family: 'Noto Sans', sans-serif;
  font-weight: 700;
  margin-bottom: 0.625rem;
}

.container #main-doc #section-container .main-section {
  margin-bottom: 2.5rem;
}

.container #main-doc #section-container .main-section p {
  margin-left: 1.25rem;
}

.container #main-doc #section-container .main-section ul {
  margin-left: 5rem;
}

Semantic Elements

New Semantic Tags Added by HTML5

The header element

The main element

The nav element

The article element

The section element

The aside element

The address element

The footer element

      New Semantic Tags Added by HTML5

In this brief tutorial we'll touch on all of the new tags added as part of HTML5 to define the structure and content of a web page. The elements we're going to cover in this guide include:

header

main

nav

article

section

aside

address

footer

Using these elements isn't as complicated as it might appear at first glance, and most are fairly self-explanatory. We'll make a quick pass over each new element, and then draw up an HTML template you can use these new tags to add rich semantic meaning to your markup.

      The header element

The header element is used to contain the content that appears at the top of every page of your website: the logo, tagline, search prompt, and possibly a navigational menu. In most cases, the header element is best positioned as a direct descendant of the body element, but it's also ok to place it inside the main element if you prefer.

      The main element

Use the main element between header and footer elements to contain the primary content of your web page. The main element cannot be a descendant of an article, aside, header, footer, or nav element. Instead, it should be a direct descendant of the body element. Think of it as the direct replacement for the div id="main" you've used in the past to wrap up your entire page contents.

It's also ok to use more than one main element on a webpage. For example, if your blog homepage includes your five most recent posts, it would be appropriate to wrap each post in it's own main element – or you could wrap each in article tags.

       The nav element

Navigational menus are commonly placed at the top of a web page, in a sidebar, or in the page footer. Wherever you happen to place a navigational menu, wrap it in nav tags. Note that you don't need to use nav tags for every link, just for blocks of links that provide either sitewide navigation or navigation for a specific part of a website.

      The article element

If your website includes blog posts, articles, or any other content that could just as well appear on another website as syndicated content, wrap that content in an article post. You can use an article element just about anywhere other than nested within an address element, but in most cases an article element will be a direct descendant of a main element or of a section element that is a direct descendant of a main element..

      The section element

Navigational menus are commonly placed at the top of a web page, in a sidebar, or in the page footer. Wherever you happen to place a navigational menu, wrap it in nav tags. Note that you don't need to use nav tags for every link, just for blocks of links that provide either sitewide navigation or navigation for a specific part of a website.

        The aside element

If your website contains information that isn't directly related to the main content of the page, it would be appropriate to wrap that information in aside tags. For example, if you write a post that includes some technical terms, and you add definitions for those terms in a sidebar, it would make sense to wrap those definitions in aside tags. It is also common for the entire sidebar of a blog-type website to be wrapped in aside tags to make it clear that the sidebar is not part of the primary content of the page.

        The address element

The address element provides contact information for the nearest parent article or body element that contains it. Use the address element inside an article to provide contact information for the article's author. Use it outside of an article in the main or footer elements, or as a direct descendant of the body element, to provide contact information for the website's owner.

        The footer element

The footer appears at the bottom of a section of a document. Typically, the footer is a direct descendant of the body element, but it can also be used within a main element, a section, or an article. The most common use of the footer element is to place it at the bottom of an HTML document to contain things like a copyright notice, links to related content, address information about the owner of the website, and links to administrative things like privacy policies and website's terms of service.

You may also use the footer element within an article to provide metadata about that particular article. For example, if article tags have been used to wrap a forum post, it would be appropriate to wrap copyright information and the date and time the post was made in a footer element and place it at the bottom of the article.

       Source


text:
Q: ParquetIO.readFiles(jsonSchema) giving NoSuchMethodError: 'org.apache.beam.sdk.coders.AvroCoder AvroCoder.of(org.apache.avro.Schema)' I am trying to read a Parquet file in Apache Beam using import org.apache.beam.sdk.io.parquet.ParquetIO;
The code I used to do that is shown below
    public static void main(String[] args) {
        PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
        Pipeline p = Pipeline.create(options);
//    final String filePattern = "/home/ismael/test/*.xml";
//        final String filePattern = "file:///home/ismael/test/*.xml";

        final String filePattern = "file-path";

        PCollection<FileIO.ReadableFile> files = p.apply("MatchFiles", FileIO.match().filepattern(filePattern))
                .apply(
                        MapElements.via(
                                new SimpleFunction<MatchResult.Metadata, MatchResult.Metadata>() {
                                    public MatchResult.Metadata apply(MatchResult.Metadata metadata) {
                                        ResourceId resourceId = metadata.resourceId();
                                        System.out.println(resourceId.getScheme() + "://" + resourceId.getCurrentDirectory() + resourceId.getFilename());
                                        return metadata;
                                    }
                                }))
                .apply(FileIO.readMatches());

        Schema jsonSchema = new Schema.Parser().parse(schemaString);
        PCollection<GenericRecord> output = files.apply(ParquetIO.readFiles(jsonSchema))   // <-- error causing line
                .setCoder(AvroCoder.of(GenericRecord.class, jsonSchema));
        p.run();

    }

but it's throwing error
Exception in thread "main" java.lang.NoSuchMethodError: 'org.apache.beam.sdk.coders.AvroCoder org.apache.beam.sdk.coders.AvroCoder.of(org.apache.avro.Schema)'
    at org.apache.beam.sdk.io.parquet.ParquetIO$ReadFiles.expand(ParquetIO.java:195)
    at org.apache.beam.sdk.io.parquet.ParquetIO$ReadFiles.expand(ParquetIO.java:178)
    at org.apache.beam.sdk.Pipeline.applyInternal(Pipeline.java:548)
    at org.apache.beam.sdk.Pipeline.applyTransform(Pipeline.java:482)
    at org.apache.beam.sdk.values.PCollection.apply(PCollection.java:363)

due to line files.apply(ParquetIO.readFiles(jsonSchema))
Can anybody help me with this?


text:
Q: Converting 3 RGB ints to one 0-1 double I'm creating a GUI that has a double slidePos from 0-1 that needs to dictate the color of a setting. The resulting color should always be at full saturation and 50% brightness. I need to convert the number from 0 to 1 into any color(i.e. three ints), where 0 is red, 0.333 is green, and 0.666 is blue. I would also need the reverse operation, taking three integers and turning them into a double from 0-1. How would I go about the math to make this work?

A: What you are looking for is simply a conversion from HSL to RGB and backwards. Take a look at the answer here. For your case, s=1 and l=0.5.


text:
Q: QRegularExpression count number of occurrences I have a QString and I want to count 2 things in QString:
a) Number of special chars
b) Number of consecutive 2 chars
For first one I tried this:
QRegularExpression var1("[$&+,:;=?@#|'<>.^*()%!-]");
myString.count(var1);

Which I don't know how to also count backslash and slash chars and I'm not sure if this is the way to check for ALL special chars.
For second one I tried this:
QRegularExpression var2("([a-z\\d])\\1\\1");
myString.count(var2);

and also this:
QRegularExpression var2("([a-zA-Z0-9\\d])\\1\\1");
myString.count(var2);

Which doesn't work at all.
Please advice, I need number of consecutive chars and number of special chars in QString.

A: For first one. Please try this.
  QRegularExpression var1("[$&+,:;=?@#|'<>.^*()%!-/\\\\]");

You can count slash by just 1 slash like other char.
To cound backslash char, You need 4 backslashs. In regular expression, you need to escape backslash char  to match backslash char(\\). And in C++, you also need to escape those 2 backslashs. As a result, you need 4 backslashes.
For second one, you need just one \\1 to match consecutive 2 chars. \\1 means the same char of first matched group so your regex actually matches consecutive 3 chars.
  QRegularExpression var2("([a-z\\d])\\1");


text:
Q: Rounding milliseconds SQL Server 2000 In Microsoft SQL Server 2000, I have this data.
1900-01-01 00:10:10.830
1900-01-01 00:10:10.430

From the above column, I want to select the datetime and round off the milliseconds, in order to get the below output
1900-01-01 00:10:11
1900-01-01 00:10:10

Thanks in advance

A: For SQL Server 2008 and above, you can do use DATETIME2. DATETIME2 is available in SQL Server 2008 and above - for more info see here:
SELECT CAST('1900-01-01 00:10:10.830' AS DATETIME2(0));
SELECT CAST('1900-01-01 00:10:10.430' AS DATETIME2(0));

Confirmed Output
For earlier version of SQL Sever, for example SQL Server 2000. You can do something like this:
SELECT DATEADD(ms, -DATEPART(ms, DATEADD(ms, 500, CAST('1900-01-01 00:10:10.830' AS DATETIME))) , DATEADD(ms, 500, CAST('1900-01-01 00:10:10.830' AS DATETIME)));
SELECT DATEADD(ms, -DATEPART(ms, DATEADD(ms, 500, CAST('1900-01-01 00:10:10.430' AS DATETIME))) , DATEADD(ms, 500, CAST('1900-01-01 00:10:10.430' AS DATETIME)));

A: SELECT *
     , DateAdd(ss, rounded_second, round_down_seconds) As result
FROM   (
        SELECT *
             , Round(nanoseconds / 1000.0, 0) As rounded_second
        FROM   (
                SELECT the_date
                     , DatePart(ms, the_date) As nanoseconds
                     , DateAdd(ss, DateDiff(ss, 0, the_date), 0) As round_down_seconds
                FROM   (
                        SELECT '1900-01-01 00:10:10.830' As the_date
                        UNION ALL
                        SELECT '1900-01-01 00:10:10.430'
                       ) As x
               ) As y
       ) As z

I've split out each step to be as clear as possible.
If you want a single liner:
SELECT the_date
     , DateAdd(ss, Round(DatePart(ms, the_date) / 1000.0, 0), DateAdd(ss, DateDiff(ss, 0, the_date), 0)) As result
FROM   (
        SELECT '1900-01-01 00:10:10.830' As the_date
        UNION ALL
        SELECT '1900-01-01 00:10:10.430'
       ) As x


text:
Q: Find list with entries which have max version of this entries I have some entities which uses a slowly changing versioning by version-number without a current-version-flag. My entity looks like:
@Entity
public class MyEntity {
  @Id
  private long id;
  private long functionalKey;
  private String name;
  private int version;
}

There are entries like:

*

*{ id = 1, functionalKey = 1, name = "Test1", version = 1 }

*{ id = 2, functionalKey = 18, name = "Test2", version = 1 }

*{ id = 32, functionalKey = 18, name = "New Test 2", version = 2 }

How can I use Spring data to find all entries (by functionalKey) with the highest version number?
To find a single entry I can use something like MyEntity findFirstByFunctionalKeyOrderByVersionDesc(long functionalKey) or write a suitable expression statement. But I want all entities not only one! I search for something like List<MyEntity> findAllWithHighestVersionGroupedByFunctionalKey.
How is this possible?
Thanks for your support!

A: You cannot do that. Here is the list of things you can achieve with query methods https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation . You should use JPQL.


text:
Q: List Git commit SHAs from a specific branch without cloning the repository Is there a way to get all the commit IDs for a particular branch without cloning the repository or using the API's?
I'm looking for something like this. Unfortunately the below command works only within the repository (i.e., git directory). I want to able to do it without cloning the repo.
git rev-list --remotes=*master

For example, the below command brings all the branches and it's last commit ID (Note: the command works without having to clone the repo.)
git ls-remote -h http://user:password@example.gitlab.com/ProjectA/example.git

Sample output:
82cd0dcc9d1005b44bdc799034b706f9ad2b1e0e    refs/heads/master
afacc961fedf49a84c09ab91e67633b02921dd07    refs/heads/projects/myproject
b6d954ec86750dcfd35c1c3fba4f40449abeb6ed    refs/heads/releases/production
e891a0b29847d0d7dfc5bc7e5ad45f718918f67f    refs/heads/releases/ready_for_prod
7b0282004a6f72c5803ddf19172c16a0b3124038    refs/heads/releases/test

A: This isn't possible using regular Git commands, but you've tagged your question with both github and gitlab, both of which have APIs that let you do it:

*

*GitHub: GET /repos/:owner/:repo/commits and provide a parameter sha containing the name of the branch whose commits you wish to list

*GitLab: GET /projects/:id/repository/commits and provide a parameter ref_name containing the name of the branch whose commits you wish to list

You may need to be using GitLab Enterprise Edition to use its API. (The version hosted at GitLab.com should support it.)

A: Yes, to interact with a repository you will need to clone it first.
Once cloned, run:
git rev-list branch/name

A: To get the output you asked for, a for-each-ref would be easier to format :
git for-each-ref --format="%(objectname) %(refname)" refs/heads/


text:
Q: I need help getting my JavaScript file to work on wordpress through child theme? I asked this question on css-tricks but only got one response which I implemented in my child functions file , but its still not working, you can see the thread here : http://css-tricks.com/forums/topic/i-need-help-getting-my-javascript-file-to-work-on-wordpress-through-child-theme/#post-160138
Inside my wordpress page which you can see here towards the bottom : http://izaguirre.me/contact/
I have this in html :

These Are Radom Letters To Test The Connection Of the JAVA File DSFDFSFSDFF

And in my myscript.js file in my child theme the only code I have inside is this :
document.getElementById('myDiv').style.background = "black";

But I see no reflection of the JS working since there is no visible background change on the example I put at the end of the  izaguirre.me/contact/ page ?

A: Have you tried to put after the

  These Are Radom Letters To Test The Connection Of the JAVA File DSFDFSFSDFF

this

I think it will work.

A: The js-file couldn't get loaded (404). You uploaded it to your child theme's folder (http://izaguirre.me/wp-content/themes/selfy-child/myscript.js),
but the page actually tries to load it from the parent themes folder
(http://izaguirre.me/wp-content/themes/selfy/js/myscript.js).


text:
Q: how to run the code before the app.run() in flask? I'm new on flask.I configured a server with flask+gunicorn.
the code file called test.py like this:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    return aa+"world!"

if __name__ == '__main__':
    aa = "hello"
    app.run()

run it using:gunicorn -b 0.0.0.0:8080 test:app
I got a mistake:NameError: name 'aa' is not defined.
I want some codes like variable aa runing before gunicorn.
How to do that?

A: Put in a small block just before your @app.route and you dont need the last block in the question
 @app.before_first_request
 def _declareStuff():
     global aa
     aa='hello'

A: Just declare aa outside of "__main__", in the global scope of the file.
from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    return aa+"world!"

aa = "hello"

if __name__ == '__main__':
    app.run()

The code in the if __name__ == '__main__': block executes only if the Python code is run as a script, e.g., from the command line. Gunicorn imports the file, so in that case the code in __main__ will not be executed.

Note that if it is your intention to modify the value of aa then different requests can produce different results depending on how many requests each gunicorn worker process has handled. e.g.:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    global counter
    counter += 1
    return "{} world! {}".format('aa', counter)

counter = 0

if __name__ == '__main__':
    app.run()

Run the above script with more than one worker (gunicorn -w 2 ...) and make several requests to the URL. You should see that the counter is not always contiguous.

A: As of Flask 2.2, the @app.before_first_request decorator suggested by Vipluv in their answer is deprecated and will be removed in 2.3.

Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup code when creating the application instead.

The equivalent can be done by manually pushing the app context, as suggested by Enkum :
# In place of something like this
@app.before_first_request
def create_tables():
    db.create_all()
    ...

# USE THIS INSTEAD
with app.app_context():
    db.create_all()


text:
Q: Laravel make a dynamic dropdown using ajax I'm using laravel 5.6 and my User table have a foreign key of f_code for Faculty and i have 2 dropdown select Faculty and Programme. The faculty dropdown would be automatically selected based on the login by using Auth::user()->f-code while the programme dropdown would only display programme based on the faculty (I have already done the relationship between the 2 table). I am trying to use ajax to return the p_code and p_name and append them in my Programme dropdown select but it isn't displaying any programme in the dropdown select. Anyone able to help me? Sorry if my question is slightly confusing i'm not sure how do i explain in words properly hope my codes can explain better.
Any help would be appreciated thank you in advance.
Blade View

<select id="Faculty" class="form-control Faculty">
    <option value="0" disabled selected>Select Faculty</option>
    @foreach($FacultyList as $fac)
        <option value="{{$fac->f_code}}">{{$fac->f_name}}</option>
    @endforeach
</select>

<select id="Programme" class="form-control Programme">
    <option value="0" disabled selected>Select Programme</option>
</select>

Controller
function index()
{

    $FacultyList = Faculty::all();
    return View::make('generateqr',compact('FacultyList'));
}

function findProgramme(Request $request)
{
    $data = Programme::select('p_code','programme_name')->where('faculty_id',$request->id)->take(100)->get();

    return response()->json($data);
}

A: SOLVED
instead of dynamically using ajax i select the Programme data inside my controller and pass it into the view and use a loop to display all the programmes
Blade View

<select id="Faculty" class="form-control Faculty">
    <option value="0" disabled selected>Select Faculty</option>
    @foreach($FacultyList as $fac)
        <option value="{{$fac->f_code}}">{{$fac->f_name}}</option>
    @endforeach
</select>

<select id="Programme" class="form-control Programme">
    <option value="0" disabled selected>Select Programme</option>
    @foreach($ProgrammeList as $prog)
        <option value="{{$prog->p_code}}">{{$prog->programme_name}}</option>
    @endforeach
</select>

Controller
function index()
{

    $FacultyList = Faculty::all();
    $ProgrammeList = Programme::select('p_code','programme_name')->where('faculty_id',Auth::user()->f_code)->take(100)->get();
    return View::make('generateqr',compact('FacultyList','ProgrammeList'));
}

function findProgramme(Request $request)
{
    $data = Programme::select('p_code','programme_name')->where('faculty_id',$request->id)->take(100)->get();

    return response()->json($data);
}


text:
Q: Invalid Total error with Dwolla Server to Server checkout method I'm following the docs for Dwolla for the Server to Server method, and making a post request to the URL in the docs with the following json data in the body:
{
   "Key":"Fake_Key",
   "Secret":"Fake_Secret",
   "PurchaseOrder":{
      "DestinationId":"Fake_Destination_id",
      "Discount":0,
      "OrderItems":[
      {
            "Description":"a product",
            "Name":"lol",
            "Price":19.99,
            "Quantity":20
         }
      ]
   },
   "Shipping":0,
   "Tax":0,
   "Total":399.8,
   "Test":true
}

Unfortunately, while the data seems valid to me, their server is responding with the error message:
{
    "Result":"Failure",
    "Message":"Total cannot be less than $1."
}

While the error tells me that the problem is that the "Total" is less than $1, it very clearly isn't.
-- Further Information
Here's the php I'm  using to make the request:
$result = file_get_contents('https://www.dwolla.com/payment/request', null, stream_context_create(array(
    'http' => array(
    'method' => 'POST',
    'header' => 'Content-Type: application/json' . "\r\n" .
        'Content-Length: ' . strlen(json_encode($body)) . "\r\n",
        'content' => json_encode($body),
    ),
)));

When I commend out the Content-Type, I get "Invalid Application Credentials" as the error.

A: It might not be completely clear from the server-to-server request docs, but the "Shipping", "Tax", and "Total" parameters, should all be nested within the "PurchaseOrder" object parameter. So, to get your request to work, you'll need to change the position of those parameters, as such:
{
   "Key":"Fake_Key",
   "Secret":"Fake_Secret",
   "PurchaseOrder":{
      "DestinationId":"Fake_Destination_id",
      "Discount":0,
      "OrderItems":[
      {
            "Description":"a product",
            "Name":"lol",
            "Price":19.99,
            "Quantity":20
         }
      ],
      "Shipping":0,
      "Tax":0,
      "Total":399.8
   },
   "Test":true
}


text:
Q: Consider the boundary value problem $-u''=x, u(0)=u(1)=0$. Find solution, write down a minimization problem and the value of the quadratic functional I am working on problem 9.3.1 from Introduction to Differential Equations bij Peter J. Olver. I have just been introduced to self-adjointness and positive (semi) definiteness but I find it quite hard to understand. The problem is as follows:
Consider the boundary value problem $$-u''=x, u(0)=u(1)=0.$$
Now I need to
(a) find the solution
(b) write down a minimization principle that characterizes the solution
(c) find the value of the minized quadratic functional on the solution
(d) write down at least two other functions that satisfy the boundary conditions and check they produce larger values for the energy,
and honestly I have no clue where to even start.
(a) I suppose we can use the underlying differential operator $S= D^{*} \circ D = - D^{2}$ which is self-adjoint since we have Dirichlet boundary conditions. Now we can also use the fact that if $L$ is a linear operator between inner product spaces with adjoint $L^{*}$ and we assume the kernel just consists of the zero function, we then know
$$Q[u] = \frac{1}{2} ||| L[u] |||^{2} - \langle f,u \rangle,$$
for $-u''=f(x)$,  where the triple brackets indicate $\langle\langle \cdot, \cdot \rangle\rangle$ (i.e. the inner product of $L^{*}$) has a unique minimizer $u_{*}$. which is a solution to S[u]=f.
In our case this would then become
$$Q[u] = \frac{1}{2} ||| u' |||^{2} - \langle x,u \rangle = \int_{a}^{b} \left[ \frac{1}{2} u'(x)^{2} - xu(x) \right] dx.$$
Is this correct and if so: how to proceed?

A: Firstly let's solve the ODE. Integrating twice and inserting the boundary conditions we get that:
$$u_0(x)=\frac16 x- \frac16 x^3 $$
Next we see that the ODE is a Euler-Lagrange equation associated with (for instance) the functional $Q[u] = \int_0^1 \left(\frac12 u'(x)^2 -xu(x) \right)dx$.
Inserting our solution we get that $Q[u_0]=-\frac{1}{90}$.
Lastly we need to calculate $Q$ for two functions that satisfy the boundary conditions. Let's take the functions $u_1(x)=x(1-x)$ and $u_2(x)=\sin(\pi x)$. Inserting into $Q$ we get:
$$Q[u_1]=\frac{1}{12} $$
$$Q[u_2] = \frac{\pi^3-4}{4\pi}\approx 2.15 $$
Finally we note that $Q[u_0]<Q[u_1]<Q[u_2]$ as expected.


text:
Q: regex - negative lookahead to exclude strings I am trying to find (and replace with something else) in a text all parts which

*

*start with '/'

*ends with '/'

*between the two /'s there can be anything, except the strings '.' and '..'.

(For your info, I am searching for and replacing directory and file names, hence the '.' and '..' should be excluded.)
This is the regular expression I came up with:
/(?!\.|\.\.)([^/]+)/

The second part
([^/]+)

matches every sequence of characters, '/' excluded. There are no character restrictions required, I am simply interpreting the input.
The first part
(?!\.|\.\.)

uses the negative lookahead assertion to exclude the strings '.' and '..'.
However, this doesn't seem to work in PHP with mb_ereg_replace().
Can somebody help me out? I fail to see what's wrong with my regex.
Thank you.

A: POSIX regex probably don't have support for negative lookaheads. (I may be wrong though)
Anyway since PCRE regex are usually faster than POSIX I think you can use PCRE version of the same function since PCRE supports utf8 as well using u flag.
Consider this code as a substitute:
preg_replace('~/(?!\.|\.\.)([^/]+)/~u', "", $str);

EDIT: Even better is to use:
preg_replace('~/(?!\.)([^/]+)/~u', "", $str);

A: This is a little verbose, but it definitely does work:
#/((\.[^./][^/]*)|(\.\.[^/]+)|([^.][^/]*))/#
^  |------------| |---------| |---------|
|        |             |               |
|        |        text starting with   |
|        |        two dots, that isn't |
|        |             "." or ".."     |
|  text starting with                  |
|  a dot, that isn't                text not starting
|  "." or ".."                         with a dot
|
delimiter

Does not match:

*

*hi

*//

*/./

*/../
Does match:

*

*/hi/

*/.hi/

*/..hi/

*/.../

Have a play around with it on http://regexpal.com/.
I wasn't sure whether or not you wanted to allow //. If you do, stick * before the last /.

A: I'm not against regex, but I would have done this instead:
function simplify_path($path, $directory_separator = "/", $equivalent = true){
  $path = trim($path);
  // if it's absolute, it stays absolute:
  $prepend = (substr($path,0,1) == $directory_separator)?$directory_separator:"";
  $path_array = explode($directory_separator, $path);
  if($prepend) array_shift($path_array);
  $output = array();
  foreach($path_array as $val){
    if($val != '..' || ((empty($output) || $last == '..') && $equivalent)) {
      if($val != '' && $val != '.'){
        array_push($output, $val);
        $last = $val;
      }
    } elseif(!empty($output)) {
        array_pop($output);
    }
  }
  return $prepend.implode($directory_separator,$output);
}

Tests:
echo(simplify_path("../../../one/no/no/../../two/no/../three"));
// =>  ../../../one/two/three
echo(simplify_path("/../../one/no/no/../../two/no/../three"));
// =>  /../../one/two/three
echo(simplify_path("/one/no/no/../../two/no/../three"));
// =>  /one/two/three
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three"));
// =>  ../../../one/two/three
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/"));
// =>  ../../../one/two/three

I thought that it would be better to return an equivalent string, so I respected the ocurrences of .. at the begining of the string.
If you dont want them, you can call it with the third parameter $equivalent = false:
echo(simplify_path("../../../one/no/no/../../two/no/../three", "/", false));
// =>  one/two/three
echo(simplify_path("/../../one/no/no/../../two/no/../three", "/", false));
// =>  /one/two/three
echo(simplify_path("/one/no/no/../../two/no/../three", "/", false));
// =>  /one/two/three
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three", "/", false));
// =>  one/two/three
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/", "/", false));
// =>  one/two/three

A: /(?!(\.|\.\.)/)([^/]+)/
This will allow ... as a valid name.


text:
Q: Determine a basis for $\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5})/\mathbb{Q}$.
Given a basis for $\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5})/\mathbb{Q}$.

Considering $\mathbb{Q}(\sqrt{2},\sqrt{3})/\mathbb{Q}$ then, $\lbrace 1, \sqrt{2}, \sqrt{3}, \sqrt{6} \rbrace$ is a basis.
But $\lbrace 1, \sqrt{2}, \sqrt{3}, \sqrt{5}, \sqrt{6}, \sqrt{10}, \sqrt{15} \rbrace$ is not a basis for $\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5})/\mathbb{Q}$. I Know that $[\mathbb{Q}(\sqrt{2},\sqrt{3},\sqrt{5}):\mathbb{Q}]=8$.
I would like some help. My difficulty is not to prove that a given set is a basis, I can not find a basis.


text:
Q: How do I write to a file from new Linux system call in a loop from a Kthread I am using a kthread as a worker to write to a file. I want the kthread to keep writing once the initial system call has terminated. The thread is writing data from a buffer. I open the file and the kthread like this:
f = filp_open(file, O_RDWR | O_APPEND, 0);
if (!f)
{
    return -1;
}
running_thread = kthread_run(write_to_disk_thread, (void*)&thread_args, "write_to_disk");

I then run this code in a loop on the thread. text_to_append is the next char* to be written from the buffer. It is created by kmalloc() and then the data is coppied into it on each loop. popped_length is its length.
loff_t pos = f->f_pos;
__kernel_write(f, text_to_append, popped_length, &pos);
pos += popped_length;
set_fs(KERNEL_DS);
__fput_sync(f);
f->f_pos = pos;
vfs_fsync_range(f, pos-popped_length, pos, 1);
set_fs(old_fs);`

When I run my code I get a null pointer bug but only on the second iteration of the loop.


text:
Q: Well-ordering principle and theorem Could somebody clearly explain the difference between the well-ordering principle and the well-ordering theorem? Is one of these related to the Principle of Mathematical Induction, and the other to the Axiom of Choice? Thanks.

A: The "well-ordering theorem" is the statement that for any set $X$, there is a relation $<$ on $X$ which is a well-ordering.  This statement is equivalent to the axiom of choice.
The "well-ordering principle" has (at least) two different meanings.  The first meaning is just another name for the well-ordering theorem.  The second meaning is the statement that the usual relation $<$ on the set $\mathbb{N}$ is a well-ordering.  This statement is equivalent to the statement that ordinary induction on the natural numbers works.


text:
Q: Some Activity is not opening : java.lang.IllegalStateException: Could not execute method of the activity I am trying to open activities on button click "Categories Activity" is opening but study activity is not opening. please me to open study activity. thanks in advance
{
  //  Main Activity

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void categories (View categories)
    {
        Intent intent = new Intent(this, Study.class);
        startActivity(intent);

    }

    public void study (View view)
    {
         Intent intent = new Intent(this, Study.class);
        startActivity(intent);

    }
}
}

 Main xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.itcheeta.englishverformsmaster.MainActivity" >

<Button
            android:id="@+id/categories"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Categories"
           android:onClick="categories" />

<Button
    android:id="@+id/study"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/categories"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:text="study"
    android:onClick="study" />

Study Activity
import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;

public class Study extends Activity {
    private ScrollView layMain;
    private TableGenerator mTable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study);
        showTable();
    }

    private void showTable() {
        mTable = new TableGenerator(getApplicationContext());
        layMain = (ScrollView)findViewById(R.id.table);

        String[] firstRow = {"Present", "Past", "Future" };
        String[] secondRow = {"Do", "Did", "Done" };
        String[] thridRow = {"Come", "Came", "Come"};
        String[] fourthRow = {"Go", "Went", "Gone"};

        mTable.addRow(firstRow);
        mTable.addRow(secondRow);
        mTable.addRow(thridRow);
        mTable.addRow(fourthRow);

        layMain.removeAllViews();
        layMain.addView(mTable.getTable());
    }

}

Study xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/table"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ScrollView>

</LinearLayout>

Table Generator Activity
import android.content.Context;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TableGenerator {
    private final Context mContext;
    private TableLayout mTable;

    private TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams();
    private TableRow.LayoutParams colParams = new TableRow.LayoutParams();

    public TableGenerator(Context context) {
        mContext = context;
        mTable = new TableLayout(context);
        rowParams.setMargins(0, 0, 0, 1);
        colParams.setMargins(0, 0, 1, 0);

        TableLayout.LayoutParams lptable = new TableLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mTable.setLayoutParams(lptable);

        mTable.setStretchAllColumns(true);
        mTable.setBackgroundColor(mContext.getResources().getColor(
                R.color.table_background));
    }

    public void addRow(String[] data) {
        TableRow tr = new TableRow(mContext);
        tr.setBackgroundColor(mContext.getResources().getColor(
                R.color.table_background));

        tr.setLayoutParams(rowParams);

        for (int iCol = 0; iCol < data.length; iCol++) {
            TextView tvCol = new TextView(mContext);
            tvCol.setText(data[iCol]);
            tvCol.setGravity(Gravity.CENTER | Gravity.CENTER);
            tvCol.setPadding(3, 3, 3, 3);
            tvCol.setTextColor(mContext.getResources().getColor(
                    R.color.text_black));
            tvCol.setLayoutParams(colParams);
            tvCol.setBackgroundColor(mContext.getResources().getColor(
                R.color.row_background));
            tr.addView(tvCol);
        }

        mTable.addView(tr);
    }

    public TableLayout getTable() {
        return mTable;
    }
}

LogCat Message:
{
12-12 02:29:37.191: E/AndroidRuntime(24473): FATAL EXCEPTION: main
12-12 02:29:37.191: E/AndroidRuntime(24473): java.lang.IllegalStateException: Could not execute method of the activity
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.view.View$1.onClick(View.java:3617)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.view.View.performClick(View.java:4222)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.view.View$PerformClick.run(View.java:17620)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.os.Handler.handleCallback(Handler.java:800)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.os.Handler.dispatchMessage(Handler.java:100)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.os.Looper.loop(Looper.java:194)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.ActivityThread.main(ActivityThread.java:5391)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at java.lang.reflect.Method.invokeNative(Native Method)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at java.lang.reflect.Method.invoke(Method.java:525)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at dalvik.system.NativeStart.main(Native Method)
12-12 02:29:37.191: E/AndroidRuntime(24473): Caused by: java.lang.reflect.InvocationTargetException
12-12 02:29:37.191: E/AndroidRuntime(24473):    at java.lang.reflect.Method.invokeNative(Native Method)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at java.lang.reflect.Method.invoke(Method.java:525)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.view.View$1.onClick(View.java:3612)
12-12 02:29:37.191: E/AndroidRuntime(24473):    ... 11 more
12-12 02:29:37.191: E/AndroidRuntime(24473): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.itcheeta.englishverformsmaster/com.itcheeta.englishverformsmaster.Study}; have you declared this activity in your AndroidManifest.xml?
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1693)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1492)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Activity.startActivityForResult(Activity.java:3388)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Activity.startActivityForResult(Activity.java:3349)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Activity.startActivity(Activity.java:3584)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at android.app.Activity.startActivity(Activity.java:3552)
12-12 02:29:37.191: E/AndroidRuntime(24473):    at com.itcheeta.englishverformsmaster.MainActivity.study(MainActivity.java:32)
}

A: You should declare any activity in the AndroidManifest.xml file before you can start it. before the </application> add this:
<activity android:name=".Study"/>

A: Declare Study Actvity inside your AndroidManifest.xml, your LogCat message is indicating the Exception:

Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.itcheeta.englishverformsmaster/com.itcheeta.englishverformsmaster.Study}; have you declared this activity in your AndroidManifest.xml?

example:
 <activity
            android:name=".Study"
            android:label="Study" >


text:
Q: Elements of quotient ring $\mathbb{Z}_3[x]/I$ being represented as $ax^2 + bx + c + I$ by Euclidean Algorithm? I came upon this problem in http://sites.millersville.edu/bikenaga/abstract-algebra-1/quotient-rings-of-polynomial-rings/quotient-rings-of-polynomial-rings.pdf, but I don't understand how he applied the Euclidean Algorithm to arrive at the $ax^2 + bx + c + I$ form for the elements in this quotient ring. Could anyone elaborate a little more? No need for the specific steps, just enough to get me started. Thanks very much!

A: Divide by $x^3 + 2x + 1$ using the division algorithm. It's part of the statement of the theorem that the remainder has degree less than $3$ (i.e. less than the degree of the thing you are dividing by), hence it is of the form $r(x) = ax^2 + bx + c$.


text:
Q: JavaScript dynamic object scope Is it possible to use created objects in another scope?
var iZ = 0;
var pcs = {};
function Pc(_name, _os) //Constructor
{
   this.name = _name; // Pc Name
   this.os = _os;    //Pc Os
   this.ausgabe = function()
   {
   //Do something
   }; iZ++;
}
//Creating a new object
document.getElementById("pc_create").addEventListener("click", function()
{
      pcs['pc' + iZ] = new Pc('Pc '+ iZ , os);
      pcs['pc' + iZ].ausgabe();
});
//Using object in another scope
document.getElementById("run").addEventListener("click", function()
{
      pcs['pc' + iZ].name = "test"; // Doesnt work
});

Is there another way to use solve this ?

A: Use,
this.name = _name;

Instead of,
var name = _name;

If you don't assign the name to the current object, then that will become local variable to that constructor. This is applicable for os also.
Also the main error is, whenever you are creating an instance you are updating one variable by increment its count. So if you have created 2 instances, then your 2 objects will be stored like 'pc0' and 'pc1' respectively. But the count iZ will be 2. Now if you access 'pc2' at that time, it will not be fetched, since it was not created. So you could fix it by rewriting your code like below,
 pcs['pc' + (iZ-1)].name = "test";

A: This works now:
document.getElementById("run").addEventListener("click", function()
{
      pcs['pc' + iZ].name = "test"; // Now work
});


text:
Q: Cocos2d IPhone sprite problem The problem is - when i load game on iphone some sprites are shown, some are not, plus CCBitmapFontAtlas labels and CCMenu button are also not visible and when i tap on the place where button have to be - there is no effect. At simulator it worked just fine. What is the reason of such strange situation?
IPad aslo works ok.

A: Hard to say without more detail, but it could be some issue with your build.  Try cleaning your targets and republishing to make sure that your iPhone device has the exact files you want it to have.  The behavior you describe could come from older versions of image files being used (say, an Atlas sprite going to a frame that used to be blank but has content in the new version).


text:
Q: Hide admin bar on all pages except homepage I am trying to hide WordPress admin bar from all pages except the home page.
I added the following CODE in the theme's functions.php file, but it hides the admin bar on all pages:
if ( ! is_single() ) {
   add_filter( 'show_admin_bar', '__return_false' );
}

I want it to appear only on the homepage and to be hidden everywhere else.

A: You should use conditional tag inside function hooked to show_admin_bar filter.
add_filter( 'show_admin_bar', 'show_adminbar_on_homepage_only', 20 );
function show_adminbar_on_homepage_only()
{
     return is_user_logged_in() && is_front_page();
}

A: Could be a priority issue, meaning that some plugin / theme function is overriding the admin bar behaviour. Try something like this:
if (!is_home() && !is_front_page()){
   add_filter('show_admin_bar', '__return_false', 999);
}

If this work, let's try to understand which plugins are and assign the right priority, like a lower 99 or whatever.

A: Here's a better way to do it that improves on the existing answers:
add_filter( 'show_admin_bar', function ( $show ) {

    if ( is_front_page() ) {
        return false;
    }

    return $show;
}, 50 );

Unlike the other code examples given, this snippet will only change the admin bar visibility if currently viewing the front page. Otherwise, it will use whatever the default is set to. This removes the need to account for different cases where the user is not logged in.

A: You should check if page is home page and/or front page.
is_front_page() returns true when viewing the site's front page (blog posts index or a static page), is_home() returns true when viewing the blog posts index.
try as below,
if (!is_home() && !is_front_page()){
   add_filter('show_admin_bar', '__return_false');
}

or
if (!is_home()){
   add_filter('show_admin_bar', '__return_false');
}


text:
Q: Website crashing / not loading on iOS 9 on iPhone 5s I'm tearing my hair out at this one.
On my iPhone 5s running iOS 7.1.1 everything regarding my web page is fine:
WEBSITE LINK REMOVED FOR SECURITY PURPOSES.
However, on iPhone 5s running iOS 9 I get the following error, that completely destroys / does not load the page, making it completely unusable:
"A problem occurred with this web page so it was reloaded"

I have searched high and low for ideas about this one but there appears to be no real direct cause.
One thing I noticed in my trial and error testing, is that if I remove the main app.min.css stylesheet, it will at the least load the page (DOM).
However, if I then load the CSS but this time with an empty file...the error appears. So it appears that it's not related to my CSS per se - just to the act of linking to it.
I've gone through and tried removing all scripts, images etc...with no luck. Removing the CSS is about as close as I have gotten to solving the issue, but even with a blank CSS file, the problem occurs. It makes no sense to me.
So to summarise what I know:

*

*This appears to be triggered by the inclusion of my app.min.css
stylesheet.

*Even if the CSS is included as a totally blank file, the error still happens.

*Removing all JS does not solve the
issue.

*It happens on any page, not just the landing page or any
particular area. Works fine on my older version of iOS but not the
newer 9+ on iPhone 5s

I'm hoping you can help. I would love to provide isolated code examples, but since this issue is so 'out there', I wouldn't know what to write up as a test case.
If there's anything obvious you can notice in dev tools I'd love to know. Thanks!
Here's a screenshot of the iOS simulator having the problem too:

A: After much debugging, I found the offending CSS that completely causes webkit browsers on iOS9 + to crash and burn (Safari and Chrome):
::-webkit-scrollbar-thumb:window-inactive {
    // Properties
}

Removing this line now removes the error and loads the page correctly.
This problem was hard to debug because the iPhone heavily caches your CSS files. To get around this, cache bust your CSS when testing by appending a random query string to the end like so (PHP):
<link rel="stylesheet" href="/path/to/css/file.css?refresh=<?php echo md5(rand()); ?>">

Remember to remove this once your debugging is done so that you can take advantage of caching.
Twitter post here for sharing: https://twitter.com/michaelpumo/status/669478677600669696
Hope this helps somebody out there. What a pain it was!

A: Seems like your website opens only on Google Chrome. Safari crashed. Opening on Mozilla Firefox shed some light.
I see this error on the console downloadable font: download not allowed (font-family: "Tiempos Regular" style:normal weight:normal stretch:normal src index:1): content blocked source: http://example.com/wp-content/themes/future-cities/dist/fonts/TiemposTextWeb-Regular.woff
which is in app.min.css.
@font-face {
    font-family: "Tiempos Regular";
    font-style: normal;
    font-weight: normal;
    src: url("../fonts/TiemposTextWeb-Regular.eot?#iefix") format("embedded-opentype"),url("../fonts/TiemposTextWeb-Regular.woff") format("woff")
}

Take that font out of css and then try it. It should work.
Hope it helps!


text:
Q: What kind of time delay switch to choose to reverse motor for just a couple of seconds I would like to know the following:
I have a motor driving a lead screw which transports a part either up or down.
When going down and something comes in the way a switch gets triggered by the obstical which stops the down movement until the obstical is removed (and the switch released). It will continue to go down until it hits an end switch which stops the whole thing.
All this works fine.
However, now I would like to reverse the motor if something gets in the way. So...if going down, something gets in the way I do not want it to just stop. I would like it to go up for 2-3 seconds and then continue to go down until it reaches the end switch which stops everything as usual.
So...I tried to find a time delay relay and noticed that there are quite a few options. A few I do understand and know I can't use them for my application. The other ones....I have to admit....I don't really understand how they work.
Could somebody be so kind telling me what kind of time delay switch/relay I have to choose and how to integrate it in to my current circuit.
BTW a programmable timer will start the down movement if in "on" mode. If timer turns off the motor reverses and the part goes up. Everything is 12V. A DPDT relay reverses the motor.
I hope I gave all necessary info necessary.
Thanks a lot!!!

A: The simplest way is to use the drive mechanism itself as the timer. Have a DPDT switch which reverses the motor when it hits an obstacle, and arrange the coupling so that the switch doesn't turn off again until the mechanism has backed off a bit. A micro switch with a long lever arm may do it.
If that doesn't provide enough delay or clearance then you will have to use a timer. This would be switched on by the obstacle detect switch, then operate a DPDT reversing relay for 2~3 seconds. Here's a suitable timer:-
Kemo 113A Time switch
Depending on how your existing relay is wired, you may be able to use it for both jobs. The timer outputs would be wired together so that the relay turns on (or off?) to reverse the motor if the obstacle timer is running or if the down timer is finished.


text:
Q: Combining effects using GLFX.js I have been playing around with GLFX.js and have been able to setup some effects.  What I am missing however is the capability to use each effect together in a sort of layering/blending.  Currently if I increase the slider for say Sepia, and then increase the value for Saturation, Sepia will reset.  I have an inclination that I somehow need to save the current value of the effect on the image each time the slider is updated but not sure how to go about doing that.  Any help would be greatly appreciated.  Thank you in advance!  Here is my Javascript code:
`
window.onload = function() {
  // try to create a WebGL canvas (will fail if WebGL isn't supported)
  try {
    var canvas = fx.canvas();
  } catch (e) {
    alert(e);
    return;
  }

  // convert the image to a texture
  var image = document.getElementById("image");
  var texture = canvas.texture(image);

  let sepiaSlider, sepiaFilter, hueSatFltr, hueSldr, satSldr;

  canvas.draw(texture).update();

  sepiaSlider = document.getElementById("sepia-slider");

  hueSldr = document.getElementById("hue-slider");

  satSldr = document.getElementById("sat-slider");

  hueSldr.addEventListener("input", function(hueVal) {
    hueVal = this.value;
    console.log(hueVal);
    canvas.draw(texture).hueSaturation(hueVal, 0).update();
  });

  satSldr.addEventListener("input", function(satVal) {
    satVal = this.value;
    canvas
      .draw(texture)
      .hueSaturation(0, satVal)
      .update();
  });

  sepiaSlider.addEventListener("input", function(sepiaValue) {
    sepiaValue = this.value;
    console.log(sepiaValue);
    canvas
      .draw(texture)
      .sepia(sepiaValue)
      .update();
  });

  // replace the image with the canvas
  image.parentNode.insertBefore(canvas, image);
  image.parentNode.removeChild(image);
};

`

A: I was talking to a colleague, and he was able to help me out with a more direct solution.  For anyone who is interested, it involves using classes.  Here is the cleaned up javascript solution:
 /*jshint esversion: 6 */

//set the intial value of canvas so it can be used throughout the program
let canvas = null;

//create a class to hold the intial values
class CurrentSettings {
  constructor(canvas, texture) {
    this.canvas = canvas;
    this.texture = texture;
    this.hue = 0;
    this.sat = 0;
    this.sepia = 0;
    this.brtness = 0;
    this.cntrst = 0;
    this.vgnteSize = 0;
    this.vgnteAmnt = 0;
    this.vbrnce = 0;
  }

  //set the initial values of each effect
  setHue(fValue) {
    this.hue = fValue;
    this.update();
  }

  setSaturation(fValue) {
    this.sat = fValue;
    this.update();
  }

  setSepia(fValue) {
    this.sepia = fValue;
    this.update();
  }

  setBrightness(fValue) {
    this.brtness = fValue;
    this.update();
  }

  setContrast(fValue) {
    this.cntrst = fValue;
    this.update();
  }

  setVignetteSize(fValue) {
    this.vgnteSize = fValue;
    this.update();
  }

  setVignetteAmt(fValue) {
    this.vgnteAmnt = fValue;
    this.update();
  }

  setVibrance(fValue) {
    this.vbrnce = fValue;
    this.update();
  }

  //update the values if the slider is modified
  update() {
    this.canvas.draw(this.texture);
    if (this.hue > 0 || this.sat > 0)
      this.canvas.hueSaturation(this.hue, this.sat);
    if (this.sepia > 0) this.canvas.sepia(this.sepia);

    if (this.brtness > 0 || this.cntrst > 0)
      this.canvas.brightnessContrast(this.brtness, this.cntrst);
    if (this.vgnteSize > 0 || this.vgnteAmnt > 0)
      this.canvas.vignette(this.vgnteSize, this.vgnteAmnt);
    if (this.vbrnce > -1.1) this.canvas.vibrance(this.vbrnce);
    this.canvas.update();
  }
}

//set the initial value of the settings
let pSettings = null;

//if the browser does not support webgl, return an error message
window.onload = function() {
  try {
    canvas = fx.canvas();
  } catch (e) {
    alert(e);
    return;
  }

  //gets the image from the dom
  var image = document.getElementById("image");
  //convets the image from static dom to canvas
  var texture = canvas.texture(image);

  pSettings = new CurrentSettings(canvas, texture);

  //create the variables that will hold the event listeners
  let sepiaSlider,
    hueSldr,
    satSldr,
    brtnessSldr,
    cntrstSldr,
    vgnteSizeSldr,
    vgnteAmtSldr,
    vbrnceSldr;

  //draw the image onto the canvas
  canvas.draw(texture);

  //get all of the slider values
  sepiaSlider = document.getElementById("sepia-slider");

  hueSldr = document.getElementById("hue-slider");

  satSldr = document.getElementById("sat-slider");

  brtnessSldr = document.getElementById("brt-slider");

  cntrstSldr = document.getElementById("ctrs-slider");

  vgnteSizeSldr = document.getElementById("size-vgntte-slider");

  vgnteAmtSldr = document.getElementById("amnt-vgntte-slider");

  vbrnceSldr = document.getElementById("vbrnce-slider");

  //add an event listener to the sliders
  hueSldr.addEventListener("input", function(hueVal) {
    pSettings.setHue(this.value);
  });

  satSldr.addEventListener("input", function(satVal) {
    pSettings.setSaturation(this.value);
  });

  sepiaSlider.addEventListener("input", function(sepiaValue) {
    pSettings.setSepia(this.value);
  });

  brtnessSldr.addEventListener("input", function(brtnessValue) {
    pSettings.setBrightness(this.value);
  });

  cntrstSldr.addEventListener("input", function(cntrstValue) {
    pSettings.setContrast(this.value);
  });

  vgnteSizeSldr.addEventListener("input", function(vgnteSizeValue) {
    pSettings.setVignetteSize(this.value);
  });

  vgnteAmtSldr.addEventListener("input", function(vgnteAmtValue) {
    pSettings.setVignetteAmt(this.value);
  });

  vbrnceSldr.addEventListener("input", function(vbrnceSldrValue) {
    pSettings.setVibrance(this.value);
  });

  canvas.update();

  image.parentNode.insertBefore(canvas, image);
  image.parentNode.removeChild(image);
};

A: As you probably know I can't post a runnable snippet because of cross origin security restrictions, hence I only post my source code. It works and I'm able to apply "ink" and "sepia" effects together. Notice that there is only one call to draw and update for all effects. Check by yourself and tell me whether it is helpful or not.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>glfx</title>

    <form>
      <input name="ink" type="checkbox" value="ink"> Ink
      <input name="sepia" type="checkbox" value="sepia"> Sepia
      <input type="submit">
    </form>

To make it run you need an HTTP server. Instructions for Ubuntu :
$ cd /tmp
$ wget "http://i.stack.imgur.com/VqFm1.jpg?s=328&g=1" -O image.png
$ wget http://evanw.github.io/glfx.js/glfx.js
$ head -6 demo.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>glfx</title>

$ python -m SimpleHTTPServer

Finally, open you web browser and type "localhost:8000/demo.html".
Don't forget to press "Submit" :-)


text:
Q: Set Language on speech recognition plugin How can i change the default Language in SpeechRecognitionPlugin :
https://github.com/macdonst/SpeechRecognitionPlugin
I didn't find any documentation on it.
Thank you for your answers.

A: Find it : recognition.lang = "es-ES";


text:
Q: Can't get push notifications to go through Firebase I am trying to enable push notifications on my app. I have done this process at least 30 times with no luck. I will list out the exact steps I took.

*

*Under capabilities in my xcode project I went ahead and enabled push notifications which automatically created an app id. I also enabled background modes and remote notifications.

*I went to developer.apple.com and directed to my app id page. I saw the app id that was created and saw push notifications was configurable. So I open my keychain access and request a certificate from the certificate authority. I end up with the .certSigningRequest.

*I then take that file and upload it to the development push notification SSL certificate and I am left with a .cer file which I open and saves onto keychain access. I see this Apple Development IOS Push Services: com.mybundleidentifier

*I then export that as a .p12 file and upload it to Firebase.

*I then write the code to allow for push notifications and accept it on my REAL device, not the simulator.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (granted, error) in
        print("Permission granted: \(granted)")
    }

*I go to the background i.e. my home screen. I try to send a notification....and fail don't see anything on my device.


text:
Q: How to log the "exec" command's result into log_file from an expect script I want to capture progress of my expect script with log_file command. After issuing following commands in an expect shell everything is captured in the log file.
expect1.1> log_file my.log
expect1.2> exec timedatectl status
      Local time: St 2017-04-19 17:07:10 CEST
                ⋮
 RTC in local TZ: no

But running following script leaves me with empty log.
#!/usr/bin/expect -f
log_file mylog.log
exec timedatectl status

How do I capture a log from an Expect script?
There is a similar question, the answer unfortunately does not deal with logging part.

A: You can capture the output and send it to log file explicitly:
set output [exec echo hello world]
send_log $output

I think the reason that it can automatically log the exec result to log_file is (according to man tclsh):

If invoked with no arguments then it runs interactively, reading Tcl commands from standard input and printing command results and error messages to standard output.

Sounds like log_file would capture all data written to the tty but in the script (non-interactive mode) the result of exec would not be automatically printed to tty.


text:
Q: Marathi localization does not activate at start-up for libre office When I start ubuntu, I see a list of all languages. I choose Marathi and expect to see marathi interface for libre office and other applications. The UI is still english.
I have added a bug here...
https://bugs.launchpad.net/ubuntu/+source/libreoffice/+bug/1469712
I will like to know what else can I do to fix this.

A: Marathi should work in LibreOffice. Possibly, based on your description, you haven't installed the required language support packages. The easiest way to check it out is to open System Settings -> Language Support. Then, if there are missing language support packages, you'll be prompted to install them. Just accept that.
In particular I think it's the libreoffice-l10n-mr package which needs to be installed.


text:
Q: Erros when i tried to include js libraries via requirejs I tried to include some js libraries like bootstrap, jQuery.ui etc... via requirejs method but, I encountered some errors
Here is the console errors :

Error: Script error for: jquery/jquery-storageapi

http://requirejs.org/docs/errors.html#scripterror

Error: Load timeout for modules: jquery.bootstrap

http://requirejs.org/docs/errors.html#timeout

Error: Script error for: jquery.bootstrap

Nb: for the Error: Script error for: jquery/jquery-storageapierror refer to the line require.js:166:17 and this line 166 is:
/**
     * Constructs an error with a pointer to an URL with more information.
     * @param {String} id the error ID that maps to an ID on a web page.
     * @param {String} message human readable error.
     * @param {Error} [err] the original error, if there is one.
     *
     * @returns {Error}
     */
    function makeError(id, msg, err, requireModules) {
        var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
        e.requireType = id;
        e.requireModules = requireModules;
        if (err) {
            e.originalError = err;
        }
        return e;
    }

    if (typeof define !== 'undefined') {
        //If a define is already in play via another AMD loader,
        //do not overwrite.
        return;
    }

    if (typeof requirejs !== 'undefined') {
        if (isFunction(requirejs)) {
            //Do not overwrite and existing requirejs instance.
            return;
        }
        cfg = requirejs;
        requirejs = undefined;
    }

My requirejs-config.js :
var config = {
    paths: {
        "jquery.bootstrap": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min",
        "jquery.3": "https://code.jquery.com/jquery-3.3.1.min",
        "jquery.ui": "https://code.jquery.com/ui/1.12.1/jquery-ui.min"
    },
    shim: {
        'jquery.bootstrap': {
            'deps': ['jquery']
        },
        'jquery.3': {
            'deps': ['jquery']
        },
        'jquery.ui': {
            'deps': ['jquery']
        }
    }
};

Then I call my fonction like this exemple :
<script type="text/javascript">
    requirejs(['jquery', 'jquery.3'], function (jQuery, jQuery3) {
        jQuery(function ($) {
            $('.js-toggle-menu').click(function(e){
            e.preventDefault();
            $('.mobile-header-nav').slideToggle();
            $(this).toggleClass('open');
            });
        });
    });
</script>

Screenshot
Thanks for your help.

A: Your configuration does not make any sense and indeed it should not work. In paths you have this association
"jquery.3": "https://code.jquery.com/jquery-3.3.1.min",

And then in your shim you have:
'jquery.3': {
  'deps': ['jquery']
},

That makes no sense at all. The file you get from https://code.jquery.com/jquery-3.3.1.min is jQuery, but you are setting a shim that says that jQuery is dependent on... jQuery. What??
At a minimum, you'd need to fix that problem, and use something like this:
var config = {
    paths: {
        "jquery.bootstrap": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min",
        "jquery": "https://code.jquery.com/jquery-3.3.1.min",
        "jquery.ui": "https://code.jquery.com/ui/1.12.1/jquery-ui.min"
    },
    shim: {
        'jquery.ui': {
            'deps': ['jquery']
        }
    }
};

Besides fixing the configuration for jQuery, I've also removed the shim for Bootstrap. Bootstrap 3 required a shim. Bootstrap 4 detects whether an AMD loader is present and calls define to register itself as a proper module.
Note that you'll also need to download popper and make it available to RequireJS so that Bootstrap can work because Bootstrap 4 lists it among its dependencies. If you run into issues getting popper to work, please search this site because it's been discussed quite a bit already.
I would also call Boostrap bootstrap rather than jquery.bootstrap but that's a matter of preference more than anything.


text:
Q: Credential editing in Plist if Correct In plist I have stored Credentials from that I need to check for the correct Credential  and if the correct Credential match then replace the password field with the new..for this I Have 3 UITextField . A for new email-id ,b for current password and c for new password ..if a==b means current password == email id then new password entered in the c textfield should replace in the current password field in plist

.
 - (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];

for (int i = 0; i< [plistArray count]; i++)
{
    id object = [plistArray objectAtIndex:i];

    if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *objDict = (NSDictionary *)object;

        if ([[objDict objectForKey:@"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:@"title"] isEqualToString:passwordTextFeild.text])
        {

            NSLog(@"Correct credentials");
            // what should be the condition to replace current password to new password
        }
        NSLog(@"INCorrect credentials");
    } else {
         NSLog(@"Error! Not a dictionary");
    }
}
}

A: Check if this will work for you.
- (void)authenticateCredentials {

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"XYZ.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
    NSArray *plistArray = [dict objectForKey:@"title"];

    NSMutableArray *plistUpdatedArray = [NSMutableArray arrayWithArray:plistArray];

    for (int i = 0; i< [plistArray count]; i++)
    {
        id object = [plistArray objectAtIndex:i];

        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *objDict = (NSDictionary *)object;

            if ([[objDict objectForKey:@"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:@"title"] isEqualToString:passwordTextFeild.text])
            {
                NSLog(@"Correct credentials");

                NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithDictionary:objDict];
                [dict1 setObject:newPassword forKey:@"title"];

                [plistUpdatedArray replaceObjectAtIndex:i withObject:dict1];

                NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithDictionary:dict];
                [dict2 setObject:plistUpdatedArray forKey:@"title"];
                [dict2 writeToFile:documentPlistPath atomically:YES];

                return;
            }
            NSLog(@"INCorrect credentials");
        } else {
             NSLog(@"Error! Not a dictionary");
        }
    }
}

A: If your plist is in bundle you can't change the value stored in it.
So copy it to document directory before doing any change.
Answer to your question:
if([emailField.text isEqualToString:currntPwd.txt])
{
   NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
  [newDict addEntriesFromDictionary:objDict];
  [newDict setObject:@"Midhun" forKey:@"pass"];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
   NSString *docDirectory = [paths objectAtIndex:0];
   NSString *plistPath = [docDirectory stringByAppendingPathComponent:@"yourPlist.plist"];
   [[NSFileManager defaultManager] removeItemAtPath:plistPath];
   [newDict writeToFile:plistPath atomically:YES];
}


text:
Q: Change system clock by ProcessLauncher on uwp I'm trying to run a powershell script on raspberry (uwp) to change the system clock by c#.
Running the code below throw an exception 'System.UnauthorizedAccessException'.
await ProcessLauncher.RunToCompletionAsync(..."set-date.ps1", date.ToString());

set-date.ps1 file content:
function Set-Time ([string]$dateTime) {
    $newDate = Get-Date $dateTime
    Set-Date $newDate
}

I'm trying to find other way to do it or try to run ProcessLauncher inside impersonator, but i don't know how to do it on uwp.

According Microsoft: "Note, ProcessLauncher API launches executables under the current user credentials, or DefautlAccount, so apps requiring admin priviliges will fail to run properly."

Any help to change system clock?
Thank you.

A: You must be Add application with below code to add those in AllowedExecutableFilesList registry in windows Iot core , so you need use below command to add applications or files to AllowedExecutableFilesList Key in windows registry:
REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\EmbeddedMode\ProcessLauncher" /v AllowedExecutableFilesList /t REG_MULTI_SZ /d "c:\windows\system32\ipconfig.exe"\0"c:\windows\system32\tlist.exe"\0"c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe\0"

Go ahead, run the command above on your device, using SSH or PowerShell. after that you authorize to access this apps and files.

Note : ProcessLauncher API launches executables under the current user credentials, or DefautlAccount, so apps requiring admin priviliges will fail to run properly.

see this link for more details :
https://ms-iot.github.io/content/en-US/win10/samples/ProcessLauncherSample.htm

A: I don't think this is possible, out of the box, for security questions.


text:
Q: apache echart not working with pie drill down the drill down for pie isnt working that well, can you please let me know what im missing?
i want to have a drill down bar chart however, i changed it to pie as its what i need but running into some issues - wondering if someone has done this before, and/ can help find issues with my code.
this is what it looks like right now, cant add legend or get rid of those x axis.

functionality is there but just want to make it work.

json.
{
  "highLevelNumbers": [
    1269,15,54624,827,42,20895,4856
  ],
  "highLevel":
  ["Electrical Equipment",
  "Enclosures",
  "Instrument Equipment",
  "Mechanical Equipment",
  "Miscellaneous Equipment",
  "Piping and Pipeline Equipment",
  "Valve"],

  "ElectricalEquipment":
     [["earthing resistor",52],
      ["electric battery", 66],
      ["electric generator", 1],
      ["electrical control panel", 305],
      ["electrical isolator", 38],
      ["electrical switch", 43],
      ["electronic flow controller", 341],
      ["electronic level controller", 225],
      ["electronic pressure controller", 232],
      ["electronic temperature controller", 121]],

     "Enclosures":
     [["electrical control panel", 305],
      ["electrical isolator", 38],
      ["electrical switch", 43]],

     "InstrumentEquipment":
     [["electrical isolator", 38],
      ["electrical switch", 43],
      ["electronic flow controller", 341]],

     "MechanicalEquipment":
     [["earthing resistor",52],
      ["electrical control panel", 305]],

     "MiscellaneousEquipment":
     [["earthing resistor",52],

["electronic flow controller", 341]],
 "PipingandPipelineEquipment":
 [["earthing resistor",52],
  ["electronic flow controller", 341]],
 "Valve":
 [["earthing resistor",52],
  ["electrical switch", 43],
  ["electronic flow controller", 341]]

}
javascript:
function drilldownbar_Graph() {
  //values from data_import
  //fetch function
  fetch("drilldown.json")
    .then(function (u) {
      return u.json();
    })
    .then(function (json) {
      sketchingDrillDownGraph(json);
      //calling and passing json to another function data_function
    });

  //start of function
  function sketchingDrillDownGraph(data) {
    //graph
    var chartDom = document.getElementById("main6");
    var myChart = echarts.init(chartDom);
    var option;

    option = {
      title: {
        text: "Drill Down Category",
        left: "center",
        borderColor: "#796b94",
        borderWidth: 0.1,
      },
      legend: {
        show: true,
      },
      label: {
        show: true,
      },
      toolbox: {
        show: true,
        feature: {
          mark: { show: true },
          restore: { show: true },
          saveAsImage: { show: true },
        },
      },
      xAxis: {
        data: data.highLevel,
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        splitLine: {
          show: false,
        },
      },
      dataGroupId: "",
      animationDurationUpdate: 500,
      series: {
        type: "pie",
        radius: ["35%", "65%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 9,
          borderColor: "black",
          borderWidth: 0.5,
        },
        id: "jafurah",
        data: [
          {
            value: 5,
            groupId: "electricalEquipment",
          },
          {
            value: 2,
            groupId: "Enclosures",
          },
          {
            value: 4,
            groupId: "InstrumentEquipment",
          },
          {
            value: 4,
            groupId: "MechanicalEquipment",
          },
          {
            value: 4,
            groupId: "MiscellaneousEquipment",
          },
          {
            value: 4,
            groupId: "PipingandPipelineEquipment",
          },
          {
            value: 5,
            groupId: "Valve",
          },
        ],
        universalTransition: {
          enabled: true,
          divideShape: "clone",
        },
      },
    };
    const drilldownData = [
      {
        dataGroupId: "electricalEquipment",
        data: data.electricalEquipment,
      },
      {
        dataGroupId: "Enclosures",
        data: data.Enclosures,
      },
      {
        dataGroupId: "InstrumentEquipment",
        data: data.InstrumentEquipment,
      },
      {
        dataGroupId: "MechanicalEquipment",
        data: data.MechanicalEquipment,
      },
      {
        dataGroupId: "MiscellaneousEquipment",
        data: data.MiscellaneousEquipment,
      },
      {
        dataGroupId: "PipingandPipelineEquipment",
        data: data.PipingandPipelineEquipment,
      },
      {
        dataGroupId: "Valve",
        data: data.Valve,
      },
    ];
    myChart.on("click", function (event) {
      if (event.data) {
        var subData = drilldownData.find(function (data) {
          return data.dataGroupId === event.data.groupId;
        });
        if (!subData) {
          return;
        }
        myChart.setOption({
          xAxis: {
            data: subData.data.map(function (item) {
              return item[0];
            }),
          },
          series: {
            type: "pie",
            id: "jafurah",
            dataGroupId: subData.dataGroupId,
            data: subData.data.map(function (item) {
              return item[1];
            }),
            universalTransition: {
              enabled: true,
              divideShape: "clone",
            },
          },
          graphic: [
            {
              type: "text",
              left: 50,
              top: 20,
              style: {
                text: "Back",
                fontSize: 18,
              },
              onclick: function () {
                myChart.setOption(option);
              },
            },
          ],
        });
      }
    });

    option && myChart.setOption(option);

    // getting the data [docs total by day]
  }
}

A: To get rid of xAxis : just remove it in the chart options. (Both xAxis and yAxis actually, no need of that in a pie chart)
To display the legend, you have to set a name to each series.
series : {
  data: [
    {
      value: 5,
      groupId: "electricalEquipment",
      name: "electricalEquipment", // add this line to each series data
    },
  ...
  ]
}

Here is the full working code (note that I hardcoded the values instead of using your json file to make it easier for me).
I added a param (notMerge=true) in this method : myChart.setOption(option, true); (in the click event function) so that the "Back" button disappears when it cannot be used.


text:
Q: JAVA Generics Bounds Confusion I'm trying to follow the oracle documentation for generics in collection, for upper bounds and lower bounds, but it is creating confusion.. as
import java.util.ArrayList;
import java.util.List;

public class Test2 {

    public static void main(String[] args) {

       List<Dog> dogList = new ArrayList<>();
       dogList.add(new Dog());
       dogList.add(new Dog());

       List<Cat> catList = new ArrayList<>();
       catList.add(new Cat());
       catList.add(new Cat());

       List<Entity> entList = new ArrayList<>();
       entList.add(new Entity());
       entList.add(new Entity());

       print(dogList);
       print(catList);
       print1(entList);

    }

    public static  void print(List<? extends Animal> animals){

        for(Animal an : animals){
            System.out.println(an);
        }
    }

    public static  void print1(List<? super Animal> animals){
        animals.add(new Animal());
        animals.add(new Dog());
        for(Object an : animals){
            System.out.println(an);
        }
    }
}
class Entity {}
class Animal extends Entity{}
class Dog extends Animal {}
class Cat extends Animal {}

Now the confusion is , even the variable is of type List<? super Animal>, i'm allowed to add new instances of dog, like,  animals.add(new Dog()) ... why???
also, if my variable is of type List<? extends Animal> , it do not allow me to add instances of Animal, or Dog or Entity... any reasons ??

A: List<? super Animal> is a list of Animals or Entities or any Objects so you are allow to add a Dog to it. Dog is both Animal and Entity. That is
    List<Object> objList = new ArrayList<>();
    objList.add(new Dog());
    objList.add(new Animal());
    objList.add(new Entity());
    objList.add(new Object());
    print1(objList);

would compile without error or warning


text:
Q: init NSData to nil SWIFT How can I init NSData to nil ?
Because later, I need to check if this data is empty before using UIImageJPEGRepresentation.
Something like :
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

I tried data.length == 0 but I don't know why, data.length isn't equal to 0 while I haven't initialized.

A: If you want a nil NSData, then you can initialize it like this:
var data: NSData?

Then you can use:
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

If you are wanting empty data, then initialize it like this:
var data = NSData()

And to check that it is empty:
if data.length == 0 {
    data = UIImageJPEGRepresentation(image, 1)
}

A: One thing you can do is ensure your NSData property is an optional. If the NSData object has not been initialized yet, then you can perform your if nil check.
It would look like this:
var data: NSData? = nil
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

Because optionals in Swift are set to nil by default, you don't even need the initial assignment portion! You can simply do this:
var data: NSData? //No need for "= nil" here.
if data == nil {
    data = UIImageJPEGRepresentation(image, 1)
}

A: If you want to set your data variable to nil, just do data = nil. If you want to set it to be empty, then do data = NSData().