text:
Q: Translate sentence into FOL expression, confused about constants and quantifiers Translate the following statements into FOL sentances
1) Alex likes John
Likes(alex, john) - I know this is correct
2) Each person is either a man or woman
AxAy( man(x) v woman(y) )
EDIT: Is this better??: Az(Person(z) -> man(x) v woman(y))
OR EDIT: Is this better??: Ax(Person(x) -> man(x) v woman(x))
3) No one is both man and woman
Ex( (man(x) ^ ¬woman(x)) v (¬man(x) ^ woman(x)) )
4) Alex likes a man who likes a woman
AxEy(Likes( man(x), woman(y) ) -> Likes(alex, man(x) ))
Thanks
Here is a screenshot of the background info
EDIT: For number 3, I have found this online
"The exclusive disjunction of p and q asserts that either p is true or q is true but not both. The natural, but long-winded, way to express exclusive disjunction, then, is (p | q) & ~(p & q)."
If this can apply, then I assume the correct answer is Ax( (man(x) v woman(x)) ^ ¬(man(x) & woman(x)) )
But now I am getting confused as to how 2 and 3 are different...

A:
Hey I just wanted to know if these were correct

1. Testing the Correctness of Translation
One of the ways to test if a first order sentence agrees with an informal specification is to use a model.
To perform a test you need:

*

*To determine how many relations are there in your first order sentence and list them. This list would play the role of the logical signature of your model.

*Now take a set of individuals large enough to have all interesting combinations of properties assigned to at least one individual.

*Assign the properties to individuals according to your understanding of the meaning of relations in your first order sentence.

*Finally for each universally quantified variable try different assignments of individuals to variables and check if the property holds.
Consider one of the examples from the post.
Informal specification: Alex likes a man who likes a woman
We have

*

*one constant symbol: Alex

*two unary relations: Man(x) and Woman(x)

*a binary relation: Likes(x,y)
1.1 Structure No. 1
Now consider a structure where we have an individual for Alex, an individual for a man who is not Alex, and an individual for a woman who is not Alex.
Let's start with three: p1, p2, p3.

*

*Alex is p1

*Man(p2)

*Woman(p3)

*Woman(p1)

*Likes (p2,p3)

*Likes (p1,p2)

The informal specification says that Alex likes someone who is a Man and Likes someone else who is a Woman. Our model satisfies this specification.
Now consider the following statement taken from the OP:
AxEy(Likes( man(x), woman(y) ) -> Likes(alex, man(x) ))

This statement is from a different language. Here man(x) and woman(y) are unary functions instead of unary relations, so we cannot check this sentence.
I would not speculate any further on the subject of woman(y) or man(x) being a function (Pun intended). Instead I would consider a different sentence.
AxEy(Man(x) & Woman(y) & Likes( x, y ) -> Likes(alex, x ))

Let's see what happens if x=p2 and y=p1. In our model the premise
Man(p2) & Woman(p3) & Likes( p2, p3 )

holds, and the conclusion
Likes(p1,p2)

also holds, therefore the formula is true under this variable assignment.
1.2 Structure No. 2
Now consider a different model. This time with four individuals: p1,p2,p3,p4.

*

*Alex is p1

*Man(p2)

*Man(p4)

*Woman(p3)

*Woman(p1)

*Likes (p2,p3)

*Likes (p1,p2)

*Likes (p4,p3)

This model also satisfies our informal specification as Alex likes p2 who is a Man and likes p3 who is a Woman.
Consider the assignment x=p4 and y=p3.
Once again the premise holds in our model
 Man(p4) & Woman(p3) & Likes( p4, p3 )

however the conclusion
 Likes(p1,p4)

does not hold in our model. Since x is universally quantified this might be a problem as the formula does not hold under this assignment, however y is under an existential quantifier. Let's see if we can find an assignment for y that would turn our formula into a true statement with x=p4.
This is indeed possible. Let y=p2.
 Man(p4) & Woman(p2) & Likes( p4, p2 )

does not hold, therefore the formula
 Man(p4) & Woman(p2) & Likes( p4, p2 ) -> Likes(p1,p4)

is true. This sounds better yet to satisfy the formula we took an assignment that is far from the intended meaning of the informal specification. The original specification clearly was not speaking about a man who likes another man. So we are not done yet.
1.3 Structure No. 3
Consider a model with just two individuals: p1 and p2.

*

*Alex is p1

*Man(p2)

*Woman(p1)

The informal specification does not hold in this model, so our sentence also should be false. There are four possible assignments of variables

*

*x=p1,y=p2

*x=p1,y=p1

*x=p2,y=p1

*x=p2,y=p2

Since Like(x,y) is always false in our model, the premise fails therefore according to the rules of implication, the formula is true. So our sentence is also true in a model where it should not hold. Once again, our first-order formalization does not hold against the informal specification.
This seems to be a very complex process that we have taken to test the translation. It assumes a certain skill of finding counterexamples and always keeping in mind the intended meaning of the informal specification.
2. How to Come up with a Correct Translation
Let's look back at our informal specification
Informal specification: Alex likes a man who likes a woman
and reformulate it in a way that is easier to translate
There exists a man whom Alex likes, and this man likes some woman
There are two parts in this sentence connected with an and

*

*Ex (Man(x) & Likes(Alex,x))

*Ey (Woman(y) & Likes(x,y))

So we have
Ex (Man(x) & Likes(Alex,x) & Ey (Woman(y) & Likes(x,y))).
You like prenex normal forms where all quantifiers are collected in one quantifier prefix. We can apply logical equivalence to get
ExEy (Man(x) & Likes(Alex,x) & Woman(y) & Likes(x,y)).
Now let's check if this statement agrees with the specification in each of the structures from the previous section.
2.1 Structure 1
Since the variables are existentially quantified and the specification holds, we need to find only one satisfying assignment for the formula.
Consider

*

*Alex is p1

*x = p2

*y = p3

The conjunction holds under this assignment.
2.2 Structure 2
The same assignment as in the previous subsection can be used. In fact
Structure 1 is an substructure of Structure 2. For an existentially quantified statement we know that if it is true in a substructure, it is also true in the whole structure.
2.3 Structure 3
Since there is no pair of elements (x,y) such that Likes(x,y) in our structure, the conjunction
 Man(x) & Likes(Alex,x) & Woman(y) & Likes(x,y)

cannot be true, so the statement is false. We also know that Structure 3 does not satisfy our informal specification, so our formula has passed our tests.
Our testing procedure is by no means complete. However it gives us some assurance that the translation is indeed correct.


text:
Q: Little Icons and Font Size is coming little small JMeter icons and text is coming too small. Tried with 2 versions 5.4.1 & 5.2.1 as well.
Text font size is smaller wants little bigger so that it can be readable easily.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter out null value from array in React I want to skip all null value from array in React
This is a part of my code.
I've added filter before map function but it looks not working.
componentDidMount(){
        client.getEntries({content_type:'formRequest'}).then(response => {
            this.setState({qoutes: response.items});
        }).catch(e => {
        console.log(e);
        });
    }

render(){

        const user = "name";
        const qoutes = this.state.qoutes
        .filter(i => i !== null)
        .map((qoute, i) =>
        user === qoute.fields.user || user === qoute.fields.company ?
        <QoutesListItem id={i} key={i} qoute={qoute} />
        : null)

        return(<div>{qoutes}<div>)

I tried to make function like this, but it does not work as well
const qoutes = this.state.qoutes.filter((qoutes)=>{
    if(qoutes !== null ) {
      return qoutes;
    }}).map((qoute, i) =>

How can I avoid null value and get available data (in my case only three objects)

A: Do both conditional checks in a single reduce pass. If the quote is truthy and the fields has a match user or company for user, push the JSX into result array.
const qoutes = this.state.qoutes.reduce(
  (quotes, quote, i) => {
    if (
      quote &&
      quote.fields &&
      (user === quote.fields.user || user === quote.fields.company)
    ) {
      quotes.push(<QoutesListItem id={i} key={i} qoute={quote} />);
    }
    return quotes;
  },
  [] // initial empty quotes result array
);

const quotes = [null, null, null, {
  fields: {
    user: 'name'
  }
}, null, {
  fields: {
    company: 'name'
  }
}];

const user = "name";

const quotesRes = quotes.reduce(
  (quotes, quote, i) => {
    if (
      quote &&
      quote.fields &&
      (user === quote.fields.user || user === quote.fields.company)
    ) {
      quotes.push(`<QoutesListItem id={${i}} key={${i}} qoute={${quote.fields.user || quote.fields.company}} />`);
    }
    return quotes;
  }, [] // initial empty quotes result array
);

console.log(quotesRes);

FYI, anytime you see map/filter or filter/map should be a good indication to use a reduce function.

A: Filter the results again to remove the null elements from the second map:
render(){
  const user = "name";
  const qoutes = this.state.qoutes
    .filter(q => !!q)
    .map((qoute, i) =>
        user === qoute.fields.user || user === qoute.fields.company ?
          <QoutesListItem id={i} key={i} qoute={qoute} />
          :
          null)
    .filter(q => !!q) // Filter falsy values

  return(<div>{qoutes}<div>)


text:
Q: withMemoryRebound in Swift 3 is not working for an Objective-C struct pointer I've been trying to interface to an Objective-C library that only exposed the pointer to a C struct array and the count of in that array.
I've used withMemoryRebound to the struct and set the capacity as I've seen in other posts here and elsewhere. However, the array I get in Swift has garbage data. As a workaround, I have added an accessor method to the library. But I would really prefer to not modify the library.
Here are the components of a test app that demonstrates the problem followed by the expected results:
Circle.h:
#import <Foundation/Foundation.h>

typedef struct {
    float x, y;         /**< Position in pixels. */
    float radius;       /**< Radius in pixels. */
} circle;

@interface CircleGenerator : NSObject {
}

@property (nonatomic)      size_t              numCircles;
@property (nonatomic, readonly) const circle*  circles;

- (id)init;
// Added as a workaround:
- (void)fetchCircle:(size_t) i circle:(circle *) c;

@end

Circle.m:
#import "Circle.h"

@interface CircleGenerator ()

@end

const circle myCircles[] = {
    {.x=2467.38184, .y=338.520477, .radius=140.096466},
    {.x=438.689453, .y=1879.302, .radius=116.18354}
};

@implementation CircleGenerator

- (id)init {
    _numCircles = 2;
    _circles = myCircles;
    return self;
}

// Added as a workaround:
- (void)fetchCircle:(size_t) i circle:(circle *) c {
    *c = _circles[i];
}

@end

ViewController.swift:
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let circleGen = CircleGenerator()!

        var circlesPtr = UnsafePointer(circleGen.circles)
        withUnsafePointer(to: &circlesPtr) {
            $0.withMemoryRebound(to: circle.self, capacity: circleGen.numCircles, {
                for i in 0..<circleGen.numCircles {
                    print($0[i])
                }
            })
        }
        print("\nShould be:")
        var nextCircle:circle = circle(x: 0, y: 0, radius: 0)
        for i in 0..<circleGen.numCircles {
            circleGen.fetchCircle(i, circle: &nextCircle)
            print(nextCircle)
        }
    }
}

Output:
circle(x: 6.70394638e-38, y: 1.40129846e-45, radius: 2.47778904e+18)
circle(x: 4.59163468e-41, y: 6.7002974e-38, radius: 1.40129846e-45)

Should be:
circle(x: 2467.38184, y: 338.520477, radius: 140.096466)
circle(x: 438.689453, y: 1879.302, radius: 116.18354)

Also, $0.pointee and $.pointee.x, etc. show the incorrect values of the first element.
Do I have a bug, or should I report this to Apple?

A: circleGen.circles is already a typed pointer (UnsafePointer<circle>), there is no need to use  withUnsafePointer():
for i in 0..<circleGen.numCircles {
    let circle = circleGen.circles[i]
    print(circle)
}

Output:
circle(x: 2467.38184, y: 338.520477, radius: 140.096466)
circle(x: 438.689453, y: 1879.302, radius: 116.18354)

Or create a UnsafeBufferPointer which is a "array-like" collection:
let circles = UnsafeBufferPointer(start: circleGen.circles, count: circleGen.numCircles)
for circle in circles {
    print(circle)
}

But if you are curious why your code does not work:
You are rebinding the pointer to the circlesPtr variable itself,
not the pointer stored in that variable.
You would get the correct result with
let circlesPtr = UnsafePointer(circleGen.circles)!
circlesPtr.withMemoryRebound(to: circle.self, capacity: circleGen.numCircles, {
    for i in 0..<circleGen.numCircles {
        print($0[i])
    }
})


text:
Q: VSCODE : get error after install php_codesniffer I have Laravel project always get error message from vscode about phpcs ,I searched for solving ,I found to excecute this line command :
 composer global require squizlabs/php_codesniffer

after I did I get errors in my controllers and api pages :

I removed php_codesniffer again but not solved


text:
Q: How to make a "webhook"? I need the "WinForm" application for correspondence in viber.
 "Webhook" is planned to receive data (events) from viber, then the data will be used in the application "WinForm".
I did:

*

*created the project "ASP.NET Web Application (.NET Framework)";

*chose a template - "Empty" + "MVC" + "API";

*added controller "Controller MVC 5 - empty". Controller name "HookController";

*I run the application "Postman";

*"Postman". I set the request "POST";

*"Postman". I set the link http://localhost:44836/Hook;

*"Postman". Click "SEND";

*The result, see the picture "- = RESULT = -";

If I understand the theory correctly, then after performing the "Postman" action. I click "SEND", the ViberProcess (HttpContext context) method should be executed in the HookController.cs controller and the code should stop at the breakpoint.
This is not happening.
Documentation Viber REST API - link
Question.
How to make a Webhook?
Code HookController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using System.Web;
using System.Web.Mvc;

//
using System.Runtime.Remoting.Contexts;

namespace WebAppl1.Controllers
{
    public class HookController : Controller
    {
        // GET: Hook
        //public ActionResult Index()
        //{
        //    return View();
        //}

         [HttpPost]
        // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void ViberProcess(HttpContext context)
        {
            try
            {
                Stream s = context.Request.InputStream;
                // Stream s = Context.Request.InputStream;
                // or  Stream s  =  HttpContext.Current.Request.InputStream;
                s.Position = 0;
                StreamReader reader = new StreamReader(s);
                string jsonText = reader.ReadToEnd();

                // Other code that converts json text to classes
            }
            catch (Exception e)
            {
                // .....
            }
        }

    }

}

7. "Postman". Click "SEND";

8. The result, see the picture "- = RESULT = -";

Server error in application '/'.
Could not find this resource.
Description: HTTP 404. The resource (or one of its dependencies) may have been deleted, received a different name, or may be temporarily unavailable. Review the following URL and verify that it is correct.
Requested URL: / Hook
Version Information: Microsoft .NET Framework Version 4.0.30319; ASP.NET version: 4.7.3062.0
Update_1
I use the link http://localhost:44836/api/Hook
The code does not stop at breakpoint.
Result:
{
"Message": "Could not find the HTTP resource corresponding to the request URI \" http://localhost:44836/api/Hook\ ".",
"MessageDetail": "Could not find the type corresponding to the controller \" Hook \ " . "
}
I use the link http://localhost:44836/Hook/ViberProcess
The code does not stop at breakpoint.
Result
Server error in application '/'.
For this object, no parameterless constructors are defined.
Description: An unhandled exception occurred during the execution of the current web request.
Examine the stack trace for more information about this error and the code snippet that caused it.
Exception Details: System.MissingMethodException: No parameter-less constructors are defined for this object.
Source Error:
An unhandled exception occurred during the execution of the current web request.
Information on the origin and location of the exception can be obtained using the following exception stack trace.

A: Just remove the HttpContext context in your ViberProcess action.
So, the method will become
public IActionResult ViberProcess()
{
    Stream s = HttpContext.Current.Request.InputStream;

    //... continue your code from here.
}

The reason behind this is, You have mention HttpContext context as an Argument of ViberProcess but while you are sending request it will search with the Exact schema.
So, in your request, you can not pass the HttpContext from anywhere. So, this request will never be found.
Here is the screenshot:

Try this an let me know if you still have an issue.


text:
Q: Vim in terminal is slow I'm using vim in the terminal a log and I'm getting frustrated with its slow performance. I'm on Debian Jessie using Gnome.
If I open a file in vim do a block select and I to insert on multiple lines there is always a delay from when I press esc to when the change is inserted.
If I do the the same thing in gvim the change is imidiate.
I have tried adding
set ttyfast
set lazyredraw

In my ~/.vimrc but that does not make any noticeable difference.
$ vim --verion
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Nov 20 2015  15:31:14)
Included patches: 1-930

A: This is completely normal.
In Vim, some special keys (like the cursor keys) are implemented as <Esc> followed by some other character. Therefore, Vim waits a bit after your press <Esc> to determine if you actually wanted <Esc> or if you wanted something else like <Esc>A (<Up>).
See :help 'timeout', :help 'timeoutlen', :help 'ttimeout', and :help 'ttimeoutlen'.


text:
Q: Como fazer RequestContext thread-safe? Em um projeto estou utilizando o componente "demoiselle-scheduler-quartz". Neste projeto várias threads são disparadas e executadas concorrentemente.
O componente "demoiselle-scheduler-quartz" injeta os contextos do Demoiselle (RequestContext, SessionContext, ViewContext, ConversationContext), ativa-os, invoca a execução da tarefa e desativa-os. Mas esporadicamente ocorre ContextNotActiveException.
Olhando o código fonte do Demoiselle observei a classe br.gov.frameworkdemoiselle.internal.context.AbstractCustomContext:
public abstract class AbstractCustomContext implements CustomContext {

    private boolean active;
    ...
}

e comparei com a classe org.jboss.weld.context.AbstractManagedContext:
public abstract class AbstractManagedContext extends AbstractContext implements ManagedContext {

    private final ThreadLocal<Boolean> active;
    ...
}

Não sei se a implementação foi intencional ou um bug, mas existe alguma forma de tornar a RequestContext thread-safe?
Tentei implementar uma @Alternative RequestContext, mas sempre é injetada a br.gov.frameworkdemoiselle.internal.context.TemporaryRequestContextImpl.
Também tentei definir um método @Produces RequestContext, mas também não funcionou.

A: Não ficou claro para mim qual a questão da concorrência. Por isso não vou entrar nesse mérito.
Pelo que entendi você quer criar uma implementação alternativa de RequestContext que não apresentaria esse problema. Assim, para injetar sua implementação alternativa, além de usar a tag @Alternative na classe você tem que colocar no seu beans.xml que você quer usar aquela implementação.
<beans ... >
...
    <alternatives>
        <class>meu.pacote.MeuContextoAlternativo</class>
    </alternatives>
...
</beans>


text:
Q: How mount application log folder in docker? I'm trying to use docker for my flask application & here is my application structure
Application Files
I just want my logs folder to mount to a different location.
how can I achieve this using docker?
I tried the below command but it's not working for me.
docker run -v /d/DockerData:/app -p 5001:5000 temp
Below is the my Dockerfile
# Pull python Image
FROM python:3.7.6-stretch

# Update Pip
RUN pip install pip --upgrade

# update & install requried packages
RUN apt-get update -y && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    sshpass

# Copy Requirement.txt for installation all python packages
COPY requirements.txt .

# Let's install Python Packages
RUN pip install -r ./requirements.txt

WORKDIR /app

COPY . /app

ENTRYPOINT ["python"]
CMD ["app.py"]

A: If you just want to access your logs directory, you can volume the logs directory anywhere you want, by runnings this:
docker run -v /my/absolute/path/in/host:/app/logs -p 5001:5000 temp

But for log aggregation, I suggest printing logs in stdout and aggregate them with the proper tools ( like fluentbit etc. )


text:
Q: What is the best way to store an array of objects with cocoa? I have an NSMutableArray with many objects in it. Some are NSStrings, others are NSMutableArrays, others are NSNumbers. What is the best way to store this data so that the app could use it again?
The array needs to stay in order as well.
I'm thinking a plist or NSUserDefaults?
Many thanks

A: Consider using NSKeyedArchiver.
// Archive
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:theArray];
NSString *path = @"/Users/Anne/Desktop/archive.dat";
[data writeToFile:path options:NSDataWritingAtomic error:nil];

// Unarchive
NSString *path = @"/Users/Anne/Desktop/archive.dat";
NSMutableArray *theArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

It works great, especially in case the array contains more then strings and numbers.
This way you can be sure the unarchived array is identical to the original.

A: Assuming the other arrays also contain only numbers, strings, and arrays (or other property list types), a plist would be a great way to store your data. It will keep it's order, and is simple to use.
To write an array to a plist file, use writeToFile:atomically:.
[myArray writeToFile:@"path/to/file.plist" atomically:YES];

To read it, use initWithContentsOfFile:.
myArray = [[NSMutableArray alloc] initWithContentsOfFile:@"path/to/file.plist"];

However, that will create a mutable array with non-mutable contents. To create an array with mutable contents, you can use CFPropertyListCreateDeepCopy.
NSArray *temp = [[NSArray alloc] initWithContentsOfFile:@"path/to/file.plist"];
myArray = (NSMutableArray*) CFPropertyListCreateDeepCopy(kCFAllocatorDefault,(CFArrayRef)temp,kCFPropertyListMutableContainers);
[temp release];


text:
Q: How to define a functional that produces at runtime a function by evaluating selected parts in its definition? Consider the following functional as an example:
ClearAll[urlModifier];
urlModifier[url_]:=ReplaceAll[Function@Evaluate[
    Inactive[URLBuild][
        URLParse[url]/.{"slot"->Inactive[StringReplace][Slot[]," "->"_"]}
    ]
],{Inactive[x_]:>x}];

If I evaluate it using the following command:
urlModifier["https://www.somewebsite.com/path/slot"]["hello world!"]

It fails probably because the Slot[] is not aligning with the Function.
But if I do in-place evaluation of urlModifier["https://www.somewebsite.com/path/slot"] and use the result as input:
URLBuild[<|"Scheme"->"https","User"->None,"Domain"->"www.somewebsite.com","Port"->None,"Path"->{"","path",StringReplace[Slot[]," "->"_"]},"Query"->{},"Fragment"->None|>]&["hello world!"]

It works fine.
What should I do to urlModifier to make it accept the Slot[] for its Function that it creates?

A: fixspace = StringReplace[#, " " -> "_"] &;
slotfiller[url_] := StringTemplate[StringReplace[url, "slot" -> "``"]]
urlModifier02[url_] := URLBuild@URLParse@slotfiller[url][fixspace@#] &;

A: Summary
The root cause of the surprising behaviour is that Function does not recognize Slot[] when it appears within an association object (as opposed to an association constructor).  To fix it, we must either "unwrap" the association object returned by URLParse or use a different approach altogether.
The Problem: Association Objects vs. Association Constructors
We can demonstrate the problem with a simpler example:
f = With[{assoc = <| "a" -> #1 |>}, assoc &]
(* <|"a" -> #1|> & *)

The function definition looks okay.  But it will not work:
f["hello world!"]
(* <|"a" -> #1|> *)

We can see the structural difference between an association constructor and an association object using TreeForm:
Function[<| "a" -> # |>] // TreeForm    (* constructor *)

Function[Evaluate[<| "a" -> # |>]] // TreeForm    (* object *)

More discussion on this distinction can be found in (148095).  See the section labelled Ambiguity of Association.
Fixing the Original Definition
We can change the original definition to unwrap the association object during the initial evaluation and to recreate it upon use.  We do that using Normal@URLParse[...] and Inactive[URLBuild@*Association].  The updated definition looks like this:
ClearAll[urlModifier];
urlModifier[url_]:=ReplaceAll[Function@Evaluate[
    Inactive[URLBuild@*Association][
        Normal@URLParse[url]/.{"slot"->Inactive[StringReplace][Slot[1]," "->"_"]}
    ]
],{Inactive[x_]:>x}];

... so then:
urlModifier["https://www.somewebsite.com/path/slot"]["hello world!"]

(* "https://www.somewebsite.com/path/hello_world%21" *)

Alternative Definitions
There are simpler ways to express this operation.
For example, we could define the urlModifier operator like this:
ClearAll[urlModifier]

urlModifier[url_] :=
  URLBuild[URLParse[url] /. {"slot" -> StringReplace[#, " "->"_"]}] &

We could also define it explicitly as a "curried form":
ClearAll[urlModifier]

urlModifier[url_][s_] :=
  URLBuild[URLParse[url] /. { "slot" -> StringReplace[s," "->"_"]}]

The Function form offers an advantage over the curried form in that, if desired, we could perform the initial URL-parsing at the moment of creation instead of every time the generated function is used:
ClearAll[urlModifier]

urlModifier[url_] :=
  With[{parsedUrl = URLParse[url]}
  , URLBuild[parsedUrl /. {"slot" -> StringReplace[#, " "->"_"]}] &
  ]

All of these definitions give the same results as the corrected original.


text:
Q: 'Connection reset by peer' error with web scraping I am trying to get HTML data using urllib but I keep getting Connection reset by peer error.
I have tried to use header option to circumvent proxy related issue, but seems like it is not working. Any help would be highly appreciated
import urllib.request
url = "https://wolt.com/az/aze/baku/restaurant/qutabxana"
hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36' }

req = urllib.request.Request(url, headers=hdr)
response = urllib.request.urlopen(req)
response.read()

Error response:
---------------------------------------------------------------------------

File /opt/conda/envs/bifrost/lib/python3.8/ssl.py:1309, in SSLSocket.do_handshake(self, block)
   1308         self.settimeout(None)
-> 1309     self._sslobj.do_handshake()
   1310 finally:

ConnectionResetError: [Errno 104] Connection reset by peer

A: Use direct requests module along with .get() method
import requests
res= requests.get('https://wolt.com/az/aze/baku/restaurant/qutabxana')
print(res)

Output:
<Response [200]>
Full working code with an example:
from bs4 import BeautifulSoup
import requests
res= requests.get('https://wolt.com/az/aze/baku/restaurant/qutabxana')

soup = BeautifulSoup(res.text,'lxml')
for title in soup.select('[class="MenuItem-module__content___mNrbB"] p'):
    print(title.text)

Output:
Qarın Qutabı
Qarın, qursaq, iç piyi, duz, istiot
Göy Qutabı
İspanaq, keşniş, cincilim, gicitkən, turşəng, kəvər, soğan göy
Pendirli Göy Qutabı
Ağ pendir, göyərtilər
Pendir Qutabı
Ağ pendir
Ət Qutabı
Ət, quyruq, duz istiot
Kartof Qutabı
Kartof pure
Sarı Noxud Qutabı
Noxud puresi
Pendirli (Holland) Qutab
Holland pendiri
Ətli və Holland Pendiri ilə Qutab
Ət ve holland pendiri
Kartoflu Pirojki
Kartof pure
Ciyər ilə Pirojki
Ağ və qara ciyər
Ətli Pirojki
Ət
Sarı Noxud ilə Pirojki
Noxud
Cemli Ponçik
Alma cemi
Ətli Blinçik
Ət, düyü
Kəsmikli Blinçik
Kəsmik
Kartoflu Blinçik
Kartof
Acika
Tomat, duz, istiot
Ayran Ev Sayağı
Fanta® 500 ml
Pepsi® 500 ml
Coca-Cola® 500 ml

A: Use requests module and for parsing use Beautiful soap package for python.
https://beautiful-soup-4.readthedocs.io/en/latest/
Here is the example for web scraper
https://realpython.com/beautiful-soup-web-scraper-python/


text:
Q: what are the steps tomcat follows to open homepage(Ex:Index.jsp) in browser when we click on "Run on Server" option in Ecclips Actually i heard that some build.XML reading takes place,really i don't no
exactly,so any one tell what are the steps tomcat follows to open
homepage(Ex:Index.jsp)
in browser when we click on "Run on Server" option in Eclipse.

A: When you click "Run on server", Eclipse deploys the application in Tomcat, opens a new browser window to the URL of the JSP in the deployed webapp.
So an HTTP request is sent to Tomcat by the browser. Since the URL of the HTTP request points to a .jsp file, Tomcat loads the corresponding JSP file in the webapp, transforms it into a Java source file containing a class which extends HttpServlet, then invokes the Java compiler to compile this Java source file into a class file.
Then the class file is loaded by the Tomcat classloader associated with the webapp, an instance of the JSP servlet is constructed and initialized, and its service method is called.
The service method generates HTML and writes it to the servlet's response writer, which is in fact a writer wrapping the socket output stream which sends the bytes to the browser.
The browser interprets the HTML and generates text and graphics to be shown in the browser window.
Of course, if a second request is sent to the same JSP, Tomcat reuses the servlet instance it has created to serve the first request, and just reinvokes the service method of this servlet. That's why the first request is generally slow, and the subsequent ones are blazingly fast.


text:
Q: Conditions for linearly ordered groups One standard definition of a linearly ordered group is that the order $\leq$ obeys the law

(1) $a\leq b\implies ac\leq bc$.

Suppose (1) only holds for positive c. Must it also hold for negative c?
I've been able to show that (1) holds if

(2) $a\leq 1\implies a^{-1}\geq 1$

but I can't prove (2) knowing (1) only for positive c. However, I can't think of a counter-example, and it seems weird to have (2) not be true.

A: Consider the multiplication group $(\mathbb{R}-\{0\},\times)$, the order is the usual one. Then $a<b$ implies $ac<bc$ for $c>1$ but $ac>bc$ for $c<0$ (note the meaning of negative is now <1).

A: Let $G=\{0,1\}$ under addition modulo 2 (So $G=\mathbb{Z}_2$). Let $\leq$ be defind by $1\leq 0$, $1\leq 1$, $0\leq 0$. This is a perfectly good linear ordering on the set $G$.
This satisfies your condition (1) for all positive $c$ because $0$ is the only positive element in this group and it is the identity. $1$ is its own inverse and so $1^{-1}\leq 0$. It follows that your condition (2) does not follow from condition (1) for all positive $c$.
Taken to the extreme, we can just make an arbitrary ordering of any non-trivial group $G$ as long as $g\leq e$ for all $g\in G$ where $e$ is the identity of $G$. Such an ordering will trivially satisfy your condition (1) for all positive elements $c$ and will never saitisfy your condition (2).


text:
Q: code is working for the few testcases but it not workinng for the testcase solve(10.25,17,5) def solve(meal_cost, tip_percent, tax_percent):
    meal_cost=float(input(""))
    tip_percent=int(input(""))
    tax_percent=int(input(""))
    x=(meal_cost*tip_percent)/100
    y=(meal_cost*tax_percent)/100
    total_cost=meal_cost+x+y
    print(int(total_cost))
solve(12.00,20,8)
solve(10.25,17,5)

the error is
Traceback (most recent call last):
  File "solution.py", line 18, in <module>
    solve(10.25,17,5)
  File "solution.py", line 10, in solve
    meal_cost=float(input(""))
EOFError


text:
Q: SOP-4 Package Footprint Standard I've got a  TCMT1102 Vishay optocoupler. Its a 4-pin SMD part but there is no standard package type associated on the datasheet - i.e SOP, SSOP, TSSOP etc. Vishay has a footprint document that describes this footprint as a "SOP-4 miniflat" according to the dimensions. Based on the footprint doc I assumed its a SOP-4. But when looking at the IPC-7351 standard, section 9 there is no description for a "SOP-4." The lowest SOP pin count is SOP-8. And when referencing this package classifications document there is no description for a SOP-4, SSOP-4, or TSOP-4.
Additionally, the linked CAD Model for the TCMT1102 Digikey page is not in alignment with the datasheets dimensions.
Is SOP-4 a non-standard footprint? Where can I get this footprint?

A: Many IC manufacturers use non-standard footprints - or make up their own.
Whether or not SOP-4, or any package for that mater, is a multi-manufacturer standard package is somewhat irrelevant. You should always follow the manufacturers datasheet and recommended footprint, even for more standard packages.
As to where to get the footprint, you either need to make it yourself for whichever tool you use (for something this simple, you could probably duplicate and modify an existing package), or find a CAD footprint from the manufacturer or tools such as UltraLibrarian.
If you find a CAD footprint from a secondary source such as vendor (e.g. Digikey), always double check that it matches the parts datasheet. If there are discrepancies, trust the parts datasheet.


text:
Q: Incorrect Syntax near Keyword 'Order' I am getting and error Incorrect syntax near keyword 'Order'.
protected void btnSubmit_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("Insert INTO Order (Cust_Num, Sale_Num) VALUES (@cust_num, @sale_num))", conn);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@cust_num", txtBxCustNum.Text);
    cmd.Parameters.AddWithValue("@sale_num", txtBxSaleNum.Text);

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

A: Order is a key word used in Order by
Correct like this
SqlCommand cmd = new SqlCommand("Insert INTO [Order] (Cust_Num, Sale_Num) VALUES (@cust_num, @sale_num))", conn);

Use [] to escape keywords that appear in table or column names.

A: Order is a reserved word, and as such IMHO a bad name for a table. Nonetheless, you need to escape the name by wrapping it in square brackets:
SqlCommand cmd = new SqlCommand("Insert INTO [Order] (Cust_Num, Sale_Num) VALUES (@cust_num, @sale_num))", conn);


text:
Q: How to only keep BMP in the utf-8 text file? This is the content of a text file, and I want to only keep BMP.
这是无效的字符
这是正常的字符  哈

In the How to remove non UTF-8 characters from text file
, I find there is a solution, but it doesn't work here.
iconv -f utf-8 -t utf-8 -c test.txt

The utf-8 of  is F0A19B82 (located in CJK Unified Ideographs Extension B), utf-8 of 哈 is E59388(located in CJK Unified Ideographs).
If I want to delete all characters(the size greater than 3 Bytes) like  in text file , how to do it?

A: Pass it through a charset that doesn't support the Supplementary Multilingual Plane, such as UCS-2.
$ iconv -f utf-8 -t ucs-2 -c input.txt | iconv -f ucs-2 -t utf-8
这是无效的字符
这是正常的字符  哈

A: Without resorting to tricks, perl is able to do exactly what you ask for:
$ perl -Mopen=locale -ne 's/[^\x{1}-\x{FFFF}]//g; print' infile
这是无效的字符
这是正常的字符  哈

Please take a look at this answer for additional solutions.


text:
Q: Sort and group objects alphabetically by first letter Javascript Im trying to create a collection like this in order to use in a react component:
let data = [
    {
        group : 'A',
        children : [
            { name : 'Animals', id : 22 },
            ...
        ]
    },
    {
        group : 'B', children : [
            { name : 'Batteries', id : 7},
            { name : 'Baggage', id : 12 },
            ...
        ]
    },
    {
        group : 'C', children : [
            { name : 'Cake', id : 7},
            ...
        ]
    },
]

 I've already sort my data like this :
let rawData = [
    { name : 'Animals', id : 10},
    { name : 'Batteries', id : 7},
    { name : 'Baggage', id : 12 },
    { name : 'Cake', id : 7},
    ...
]

Also I used this sorting method but the problem is, it's returning an Object with A, B, C keys with children as values. But I have to turn it into array like above in order to use that.
Here is what i've tried so far :
let data = rawData.reduce(function(prevVal, newVal){
    char = newVal.name[0].toUpperCase();
    return { group: char, children :{name : newVal.name, id : newVal.id}};
},[])

A: You can create object with reduce and then use Object.values on that object.

let rawData = [
  { name : 'Animals', id : 10},
  { name : 'Batteries', id : 7},
  { name : 'Baggage', id : 12 },
  { name : 'Cake', id : 7},
]

let data = rawData.reduce((r, e) => {
  // get first letter of name of current element
  let group = e.name[0];
  // if there is no property in accumulator with this letter create it
  if(!r[group]) r[group] = {group, children: [e]}
  // if there is push current element to children array for that letter
  else r[group].children.push(e);
  // return accumulator
  return r;
}, {})

// since data at this point is an object, to get array of values
// we use Object.values method
let result = Object.values(data)

console.log(result)

A: in answer to @hakkikonu, for typescript add the type of outputed reducer when calling .reduce
 let data = rawData.reduce((r: any, e) => {
  let group = e.name[0];
  if (!r[group]) r[group] = { group, children: [e] }
  else r[group].children.push(e);
  return r;
}, {} );


text:
Q: Difference between Session Storage, Local Storage and Cookies in AngularJS I would like to dig down into Angular, and for that i would like to know the difference between Session Storage, Local Storage and Cookies.
Problem Questions ---
1) $windows.sessionStorage can be used to store user session but the problem with it is, when you open something in a new tab  it again ask the user to login.
2) Will Local Storage would be a solution to problem question 1 ? and if so, does that mean i need local storage and session storage both in my app or local storage will act as session storage as well.
3) I am also working on Remember me on my login form - is it safe to store password and email of the user in the local storage for this, if not what is best way to do remember me in angular
4) Cookies are great, but does corporate companies allow them on there browser?
Hoping to find decent answers
Thanks

A: localstorage will work across tabs:
There is a demo here:
http://www.undefinednull.com/2014/02/25/angularjs-real-time-model-persistence-using-local-storage/

A: 1) It is correct that sessionStorage is temporary, and it has been designed to do so.
2) Local storage will solve the issue of the login going away with a new browser session being opened or after waiting a long time, but no, localStorage will not act as a session cookie for browser requests.
3) Many different server side applications support encryption and tamper-resistant cookie support for applications. That being said, it is always best not to store user passwords in the client, maybe a token perhaps that your server will recognize and be able to decrypt/decode and look up the correct user record.
4) I would say nowadays yes, cookies are generally accepted to be safe, however that is always a possibility, and depending on your clients or audience you may have an issue there. Also sessions won't work if cookies are disabled in the browser. (Though my outlook on this is speculation on a general population, ie: don't quote me on that)
My recommendation for your needs is to set a session variable when the user encounters the page. Then store the result in localStorage or with a cookie, and then when the user returns to the application after the session has died, have some architecture set up to re-authenticate and re-assign the session automatically.
Hope this helps!
Edit: Session Cookies are shared between browser tabs within the same window. However Session Storage has been pointed out not to be.


text:
Q: Compare format string to actual string python I have the following format, as a string variable
format = '$<amount> has been received from <user>'

How would I check if another string fits the format, for example:
message = '$50 has been received from Hugh'

I'd like to check that the message exactly fits the format, and save the data, in this case 50 and Hugh in two separate variables.
I checked RegEx on a few websites such as W3Schools and PyPi, but couldn't find anything that fits what it is I'm trying to do.

A: message = '$50 has been received from Hugh'

import re
regex = re.compile(r'\$(\d+) has been received from (\w+)')
amount, user = regex.findall(message)[0]
print(amount, user) # 50, Hugh


text:
Q: DC boost converter and Ohm's Law A circuit has a resistance of 1 Ohm, a DC power supply rated at 9W is delivering power to the circuit. Using a DC boost-converter that takes in an input of 9W can it output different voltages? Even if the resistance is 1 ohm?
If the resistance is 1 Ohm and the power is 9W, from ohms law voltage is 3V and current is 3A, but can I use a DC boost converter to increase voltage to higher voltages?
EDIT: The location of the resistor is between power supply and the load, if a converter or constant current was added, the resistor will be after the converter/constant current source and before the load.

A: The text below is only valid for an ideal resistor (e.g. one without parasitic effects, which should be good enough for the considerations below)
For the answer below I interpreted the question as to ask for information on this schematic:

simulate this circuit – Schematic created using CircuitLab
Since you did not mention any voltages, I'll answer a little bit more generic:
It is not possible is to have a resistor that does not adhere to Ohms law (R=U/I). A simple resistor will adhere to this law/equation at all times, therefore:
If you want to build a boost converter that outputs e.g. 5V into a 1 Ohm load, it will have to deliver 25W of power. (P = U^2 / R). This is certainly possible.
But: The boost converter would need to be supplied with enough energy to do that. If your boost converter has an efficiency of e.g. 85%, you would need to supply the converter with ~30W. In this case, your power supply would not be sufficient.
A DC/DC converter can not produce energy/power out of nothing. It is a tool to change the voltage of some supply to another voltage with acceptable losses, nothing more.
If you only have a 9W power supply you can never supply a resistor with a voltage higher than 3V (U = sqrt(P*R), same eq. as above, and that only if you have an efficiency of 100%), you simply do not have the power.
What will happen if you try depends on your power supply.
Some of the possibilities:

*

*The power supply might switch itself off, since your exceeded its specification

*The power supply might go into current limitation (and basically become a constant current source)

*The power supply might oscillate

*The power supply might get to hot and destroy itself (hopefully not, but many cheap and or badly designed ones do)

Regardless of that, you can not have a resistor e.g. dissipate 20W of power on a 9W supply.
Edit: Further explanation regarding "constant current mode"
Regarding your second comment, and my point about the constant current source. This was just meant as an explanation what a real-world power supply might do if you try to consume more power than the power supply can deliver. Behaving like a constant current source is one thing that can happen in that case:
Some power sources (e.g. most lab supplies) are built in a way that they have a set voltage and a set current. Whichever one is the one that is the limiting point at the moment, will be the one used. Say we set the power supply to 1V and 1A, and connect a variable resistor. When you turn the variable resistor to its maximum resistance e.g. 10k the power supply will be in constant voltage mode (voltage at 1V and current at I=U/R=100uA). If you turn the resistance down, e.g. 0.5 Ohm, the power supply will go into constant current mode (current at 1A, voltage at U=IR=500mV). But the power delivered will never exceed 1W (P=UI)

A: This is a very interesting question about the fundamentals of energy conservation, power transfer/dissipation and efficiency, in the context of boost converters.
Short answer, quoting your questions:

A circuit has a resistance of 1 Ohm, a DC power supply rated at 9W is
  delivering power to the circuit. Using a DC boost-converter that takes
  in an input of 9W can it output different voltages? Even if the
  resistance is 1 ohm?

Yes. Of course, it will depend on the specific boost converter design. However, in general, a boost converter will raise the input voltage up to an output voltage independently of its series path resistance. That's why they are also called step-up converters. As it is explained below in more detail, the series path resistance (of which your 1 Ohm resistor is now part of), will INCREASE the power losses (reduce the overall EFFICIENCY), having little impact on the capability of the boost converter to raise the output voltage.

If the resistance is 1 Ohm and the power is 9W, from ohms law voltage
  is 3V and current is 3A, but can I use a DC boost converter to
  increase voltage to higher voltages?

You are applying Ohm's law as if the boost converter was a short-circuit to ground! Your calculation of 3V/3A is right only if you put the 9W source directly on the 1Ohm resistor.
A boost converter will demand current in repetitive pulses, usually in two phases: 1) Demand of current following a linear or exponential curve, from 0 to a certain value of Amps, while using that current to "charge-up" an internal storage component (inductor or capacitor). 2) Without demanding current from the power source, the energy from the storage component is transferred to the output (load), while raising its voltage.

Long answer. First, some context and background that will be used for the reasoning below:

*

*A boost converter is a type of SMPS (Switched Mode Power Supply) where the DC output voltage is higher than the DC input voltage. It is commonly said the the input voltage is raised up to the output voltage.

*A boost converter usually works in two or more timed stages,

*

*During the first phase, some energy is captured from the external power supply (DC voltage input) and stored.

*During the second phase, the stored energy is transferred to the load while raising the output voltage.

*We will consider here a basic generic topology: the single inductor flyback boost converter operating in DCM (Discontinuous-Conduction Mode), which will serve us for arriving some conclusions without losing generalization. We could equally well arrive the same conclusions using any other well known topologies, for instance those using capacitors instead of inductors.

Now, we have a single inductor which will serve us for storing some energy during the first phase of the conversion:

*

*Let's say that the first phase lasts for \$T_{on}\$. During that time, the boost converter will connect the input voltage directly to the inductor, so that the inductor will start "charging-up" energy. An ideal inductor (no parasitic capacitance or resistance), will increase its current linearly up to its maximum allowed current (called saturation current). Let's suppose \$T_{on}\$ is short enough so that the saturation current is not reached, then:
\$I_{inductor} (t) = \frac{V_{input}}{L}.t \$, where the slope of the curve is \$\frac{V_{input}}{L}\$.

*At the end of \$T_{on}\$, the energy stored in the inductor is:
\$E_{inductor} = \frac{1}{2}L.I_{T_{on}}^2\$

*Getting to the point, now we can see that all the resistors in the series path between the input voltage and the inductor will dissipate (loss) some power (heat), according to the Ohm's Law:
\$P_{losses}(t) = R.{I(t)}^2\$

*As the current curve is approximately linear (now the effect of R in the circuit makes the current curve to actually be an exponential curve), we can integrate the energy lost in the resistor:
\$E_{losses}=\int{P_{losses}(t)}.dt=\frac{1}{3}R.I_{T_{on}}^3\$

*And we reach a rough estimation of the efficiency of our converter for the first phase of the conversion:
\$\rho=\frac{E_{inductor}}{E_{inductor}+E_{losses}}=\frac{1}{1+\frac{2}{3}\frac{R}{L}}\$

*Where in the equation above you can substitute R for the total series path resistance of your circuit: physical resistors, intrinsic resistance of the switching elements (MOSFET?) and equivalent series resistance of your inductor.

*The above is only a first order approximation (simplified) for the case of a single flyback inductor boost converter. The real, more accurate calculation will add the second phase/stage of the converter and all the devices in your circuit.

For a more in-depth introduction to the topic, you can check this article by Texas Instruments:
http://www.ti.com/lit/an/slva061/slva061.pdf

A: 9 Watt power means P=V*I but normally voltage will be constant ,but how much current we can drown from the ckt will be decided by the manufacture of the component.
Ex: 4.5v*2A=9W ,5v*1.8A=9W in this case power is same but current and voltage will varied,hence in power calculation current is measure roll, we are not take directly  1V*9A=9W  ,if in datasheet manufacture is mentioned about current means not a problem..u can boost the voltage.


text:
Q: Native query not working for write ,delete and update operation I am new to springboot and facing issue in JPQL,nativeQuery. While doing read operation native query is working
@Query(value="select * from student s where s.name= :name", nativeQuery=true)
List<Student> getStudentByName(String name);

working but its not working when doing delete operation on database
    @Query(value="delete from student s where s.name= :name",nativeQuery = true)
    void deleteStudentByName(String name);

Entity Class

    package com.example.demo.test.entity;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;

    @Entity
    public class Student {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        private String name;
        private Integer age;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }

    }

Please help. Thank you

A: Write operations need to be executed differently than read operations, you also need to annotate the repository method with a @Modifying annotation. Hence put @Modifying above the delete Query.
@Modifying
@Query(value="delete from student s where s.name= :name",nativeQuery = true)
void deleteStudentByName(String name);

I suggest you to not write nativeQuery and learn JPQL because

*

*Pagination of native query results requires an extra step.

*Spring Data JPA doesn't support dynamic sorting for native SQL statements.

A: Use can use the JPQL Query like void deleteByName(String name);

A: Just try to use this code inside your repo
   @Modifying
   @Transactional
   @Query(value="delete from student s where s.name= ?1",nativeQuery = true)
   void deleteStudentByName(String name);

A: You can try this query
@Query("DELETE FROM Student c WHERE c.name = ?1")
    void deleteStudentByName(String name);

And I suggest you learn how to write  JPQL queries: https://www.javatpoint.com/jpa-jpql-introduction


text:
Q: How to take a pathname string with wildcards and resolve the glob with pathlib? If I'm given a path as a string, such as "~/pythoncode/*.py" what is the best way to glob it in pathlib?
Using pathlib, there is a way of appending to a path using a glob:
p = pathlib.Path('~/pythoncode/').expanduser().glob('*.py')

but this, for example, does not work because the user isn't expanded:
p = pathlib.Path().glob('~/pythoncode/*.py')

and this is generates an exception because I'm providing no arguments to glob():
p = pathlib.Path('~/pythoncode/*.py').expanduser().glob()

Is there a way to do this in pathlib, or must I parse the string first?

A: pathlib.Path.glob does not support absolute (non-relative) path patterns, but glob.glob does:
from glob import glob
from pathlib import Path

paths = [Path(p) for p in glob('/foo/*/bar')]

Or in connection with Path.expanduser:
paths = [Path(p) for p in glob(str(Path('~/.bash*').expanduser()))]

A: If you're starting from the string "~/pythoncode/*.py" and you'd like to expand and glob, you will need to split the path first. Luckily pathlib provides .name and .parent to help you out:
def expandpath(path_pattern) -> Iterable[Path]:
    p = Path(path_pattern)
    return Path(p.parent).expanduser().glob(p.name)

expandpath("~/pythonpath/*.py")

Note this simple solution will only work when only the name includes a glob, it will not work with globs in other parts of the path, like: ~/python*/*.py. A more general solution that is a bit more complex:
def expandpath(path_pattern) -> Iterable[Path]:
    p = Path(path_pattern).expanduser()
    parts = p.parts[p.is_absolute():]
    return Path(p.root).glob(str(Path(*parts)))

expandpath("~/python*/*.py")

note-2: the above function fails (IndexError: tuple index out of range) with these degenerate paths: '', '.', '/'

A: I found that I really wanted the inline expansion.  It wasn't as easy as I thought it'd be.
Anyhow, here's what I've got.  Only trivialy tested, but let me know where it falls down for you and I'll edit it.
def expand_pathglobs(pathparts, basepaths=None):
    # Logic:
    # 0. Argue with a Path(str).parts and optional ['/start','/dirs'].
    # 1. for each basepath, expand out pathparts[0] into "expandedpaths"
    # 2. If there are no more pathparts, expandedpaths is the result.
    # 3. Otherwise, recurse with expandedpaths and the remaining pathparts.
    # eg: expand_pathglobs('/tmp/a*/b*')
    #   --> /tmp/a1/b1
    #   --> /tmp/a2/b2

    if isinstance(pathparts, str) or isinstance(pathparts, Path):
        pathparts = Path(pathparts).parts

    if basepaths == None:
        return expand_pathglobs(pathparts[1:], [Path(pathparts[0])])
    else:
        assert pathparts[0] != '/'

    expandedpaths = []
    for p in basepaths:
        assert isinstance(p, Path)
        globs = p.glob(pathparts[0])
        for g in globs:
            expandedpaths.append(g)

    if len(pathparts) > 1:
        return expand_pathglobs(pathparts[1:], expandedpaths)

    return expandedpaths


text:
Q: Prevent word from updating all fields when inserting a caption When I insert a caption, depending on the document's size, it could take several seconds because Word is updating all fields and it's annoying.
How to prevent word from updating all fields when inserting a caption?

A: Word doesn't seem to have this function, how about unlinking with Ctrl+Shift+F9?


text:
Q: 18.04 - Failing to shutdown/power off after upgrade Kernel 4.15.0.108.96 to 4.15.0.111.99 or 5.3.0.61.114 to 5.3.0-62.56 I use an Acer Notebook with a fresh installation of Ubunto 18.04.
Till the last upgrade everything works as expected.
The last upgrade brings two new kernel versions (as mentioned above).
Now the system stucks at the very end of the power down sequence.
Because I use Systemback, I timeshift to the previrious system and then install package by package to see what will bring in the problem.
If I install any of the mentioned kernel updates the probem will show up.
I found a lot of similar problems by searching the web, but none is related to this combination.
Please indicated what information I should provide for fixing this.
Something I found today:
Even when I block the above mentioned kernels (via APT pinning) the problem ocours after "apt upgrade".
It seams, that I must block linux-firmware too.
(Installed was 1.173.18 upgrade to 1.173.19 will result in the problem)
I am not shure if I do it right (APT pinning).
I currently create a file /etc/apt/prefereces.d/kernel. After doing so "apt list --upgradeable" will not list the packages in question.
I add an entry for every of the following packages to block the newest version (Pin-Priority: -1):
linux-generic, linux-image-generic, linux-image-4.15.0-111-generic, linux-generic-hwe-18.04, linux-headers-generic, linux-headers-generic-hwe-18.04, linux-image-generic-hwe-18.04, linux-modules-nvidia-440-generic, linux-modules-nvidia-440-generic-hwe-18.04, linux-firmware

A: BIOS
Aspire E5-771G-0884
You have BIOS v1.15.
There's a newer BIOS available which may solve your problem. It's v1.23, and can be downloaded here.
Note: Confirm that I have the correct web page for your model #.
Note: Have good backups before updating the BIOS.


text:
Q: Debug has an indirect dependency on Android API level X, but minSdkVersion for variant 'debug' is API level Y I have a Android project created with Android Studio.  I have added some third party dependencies to the project, but when I try to compile in Android Studio I hit the following error:
Error:Execution failed for task ':app:prepareDebugDependencies'.
> ERROR: Debug has an indirect dependency on Android API level 14, \
  but minSdkVersion for variant 'debug' is API level 8

Compiling on the command line with ./gradlew works fine.
What does this error mean?
How do I fix it?
Many thanks.

UPDATE:
My top level build.gradle file:
[snowch@laptop MyApplication]$ cat build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
        mavenCentral()
        maven { url "http://maven.restlet.org" }
    }
}

The application module's build.gradle:
[snowch@laptop MyApplication]$ cat app/build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.snowch.myapplication"
        minSdkVersion 8
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'net.christophersnow:sync-android-p2p:0.0.1-SNAPSHOT'

    compile("org.restlet.jse:org.restlet:2.1-M7") {
        exclude group: 'org.osgi', module: 'org.osgi.core'
    }
    compile("org.restlet.jse:org.restlet.ext.simple:2.1-M7")

}

A: Setting the minSdkVersion to 14 in the app\build.gradle file fixed the issue for me.
Thanks to murtaza-hussain and gabriele-mariotti for the inspiration.


text:
Q: Magento2 add a cms page link to menu I have added CMS page link to the top menu by following the below tutorial:
http://www.amitbera.com/magento2-add-a-cms-page-link-to-menu/
Since one of the custom menu items would be Home, so it should be the first item in the menu.
I want to know that how can I make some custom menu item as the first item in the top menu using the code in the tutorial.
Update: Suppose, I have 2 custom menu items, say Home and Contact. I want to make Home as the first menu item and Contact as the last menu item. Is it possible with a single plugin class? or I have to write 2 different plugins to achieve this goal?
Please help.

A: There is a issue with plugin order
In default Magento already plugin define in vendor/magento/module-catalog/etc/di.xml
<type name="Magento\Theme\Block\Html\Topmenu">
    <plugin name="catalogTopmenu" type="Magento\Catalog\Plugin\Block\Topmenu" />
</type>

And we created custom plugin in app\code{VendorName}{ModuleName}\etc\di.xml
<type name="Magento\Theme\Block\Html\Topmenu">
    <plugin name="add_cms_menu" type="{VendorName}{ModuleName}\Plugin\Topmenu" sortOrder="0" />
</type>

That means core and custom plugin, both are same exist with same sort order.
If you want to display custom menu just before category menu, sort order required minimum values to core value.
Use below code for plugin and check you custom menu
<type name="Magento\Theme\Block\Html\Topmenu">
    <plugin name="add_cms_menu" type="{VendorName}{ModuleName}\Plugin\Topmenu" sortOrder="-1" />
</type>

I hope it will be useful for you. Let me know if not working


text:
Q: Google Maps API key not found Trying to use Google Maps v2 API for Android and it keeps telling me my API key is not found. I have tried suggestions from other posts but nothing worked. I just created a new API key to verify that the key wasn't defective. I also used the code specified in the Google set up docs and still cannot get it to work. Below are all the relevant files. Thanks.
02-25 11:16:30.890: E/AndroidRuntime(2260): FATAL EXCEPTION: main
02-25 11:16:30.890: E/AndroidRuntime(2260): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.echofriendly/com.example.echofriendly.MainMapFragment}:     android.view.InflateException: Binary XML file line #2: Error inflating class fragment
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.os.Looper.loop(Looper.java:137)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread.main(ActivityThread.java:4745)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at java.lang.reflect.Method.invokeNative(Native Method)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at java.lang.reflect.Method.invoke(Method.java:511)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at dalvik.system.NativeStart.main(Native Method)
02-25 11:16:30.890: E/AndroidRuntime(2260): Caused by: android.view.InflateException: Binary XML  file line #2: Error inflating class fragment
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.Activity.setContentView(Activity.java:1867)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.example.echofriendly.MainMapFragment.onCreate(MainMapFragment.java:11)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.Activity.performCreate(Activity.java:5008)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
02-25 11:16:30.890: E/AndroidRuntime(2260):     ... 11 more
02-25 11:16:30.890: E/AndroidRuntime(2260): Caused by: java.lang.RuntimeException: API key not found.  Check that <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.z.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.z.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.z.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.ae.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.bu.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at maps.y.p.onCreateView(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.maps.internal.IMapFragmentDelegate$Stub.onTransact(IMapFragmentDelegate.java:107)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.os.Binder.transact(Binder.java:326)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.maps.internal.IMapFragmentDelegate$a$a.onCreateView(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.maps.MapFragment$b.onCreateView(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.internal.d$4.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.internal.d.a(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.internal.d.onCreateView(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at com.google.android.gms.maps.MapFragment.onCreateView(Unknown Source)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:807)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1013)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1112)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.app.Activity.onCreateView(Activity.java:4664)
02-25 11:16:30.890: E/AndroidRuntime(2260):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)

Activity:
package com.example.echofriendly;

import android.app.Activity;
import android.os.Bundle;

 public class MainMapFragment extends Activity {

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

}

}

XML:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

Manifest:
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<permission
    android:name="com.example.echofriendly.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.example.echofriendly.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

----
 <meta_data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="xxxxxx"/>

</application>

A: The helpful hint in the error message says:
<meta-data android:name="com.google.android.maps.v2.API_KEY"
           android:value="your API key"/>

Your code says:
<meta_data android:name="com.google.android.maps.v2.API_KEY"
           android:value="xxxxxx"/>

Spot the difference? Change your _ to a -.


text:
Q: best strategy for attaching arbitrary threads to Android JVM I find myself needing to call back into the JVM from arbitrary native
threads that may or may not be long-lived.  It's easy enough call
AttachCurrentThread prior to every Java method invocation on the
assumption that it's a (presumably fast) no op if the thread's already
attached, but I find myself wondering what the JVM does with attached
native threads when they go away somewhere in native-land without
being officially detached.  Or in other words, is this going to be a
problem?  If so, then I find myself wondering about the overhead of
attaching/detaching for each Java method invocation.  Ideally each
thread would just register itself upon startup and detach on shutdown
but again, I'm writing code that must be callable from arbitrary
threads running code that has no idea it's running inside of Android,
so that's not a realistic option in this case.
Any thoughts on the matter?

A:
I find myself wondering what the JVM does with attached native threads when they go away somewhere in native-land without being officially detached.

The regular VM shuts down when all non-daemon threads have exited.  Attaching a thread without detaching means that the VM cannot exit and has to wait for your thread to detach first. This is just a general case of VM, though. In Android it shouldn't be a problem, as apps don't really "exit". Source.
But detaching threads is highly recommended for proper memory management (see an official recommendation).

I'm writing code that must be callable from arbitrary threads running code that has no idea it's running inside of Android, so that's not a realistic option in this case.

Actually, the implementation of a self-detaching thread is quite easy. Pass "destructor" reference to pthread_key_create(destKey_, threadDestructor); and inside this "destructor" call JNI method cached_jvm->DetachCurrentThread();.
Hope that helps!


text:
Q: An equivalent to Condition that I can use anonymously when string pattern matching When I name a pattern I'm working with, that name stands for the same particular expression wherever it shows up. That's a basic precept of how the Wolfram Language's pattern-matching works. But if I want to keep the generality of some pattern, how can I avoid naming it when applying a condition? That's a little hard to articulate, so let me give a specific example.
endsWithSpaceQ[str_] := StringEndsQ[str, " "];
str1 = "abc efg 17";
str2 = "abc abc 17";

I want to test str1 and str2 to see if they match the pattern
Repeat[substring-that-satisfies-endsWithSpaceQ, {2}] ~~ "17"

It's natural to start with:
StringMatchQ[#,
   Repeated[p__ /; endsWithSpaceQ[p], {2}] ~~ "17"] & /@ {str1, str2}

However, this returns {False, True}, because since I named the pattern p__, Mathematica looks for two occurrences of a particular string that satisfy my condition. Instead, I want two substrings, not necessarily identical, that satisfy the condition. ? allows me to use pure functions so I can avoid the necessity for /; f[] to take an argument (i.e. the name of my pattern), but ? does not test an entire substring [sequence for non-string patterns] but rather its individual characters [elements of the sequence].
Is there any way I can use Condition without forcing myself to name the pattern? If not, I'm looking specifically for a way to require the anonymous pattern inside Repeated[__] to satisfy a condition.
(Help with the title is encouraged -- I can't find anything to sum this question up well)
Edit: clarification Of course, my real-life task is a little more complicated than this example. I'm hoping for a general solution or solution-strategy, because I think it'd be good to have on record here. If one isn't out there, I might post another question with my specific problem (assuming I can't hack it together myself).

A: I don't know of any direct solution to this problem.  I have always had to work around it, but usually I find that isn't too hard.  In this case, as I imagine you know, you could just write:
StringMatchQ[#, Repeated[__ ~~ " ", {2}] ~~ "17"] & /@ {str1, str2}

{True, True}

Further this is far more efficient as it is run in an optimized string library, rather than being done by brute force.
You could of course use multiple patterns, generated programmatically if need be:
StringMatchQ[#, (p1__ /; endsWithSpaceQ[p1]) ~~ (p2__ /; endsWithSpaceQ[p2]) ~~
    "17"] & /@ {str1, str2}

A: Okay, I think here's a way you can do virtually everything you want.
First, my original answer, which I had then moved to a comment to Mr.Wizard's answer.
You can substitute in Unique:

StringMatchQ[#, StringExpression @@ With[{each = p__ /; endsWithSpaceQ@p}, Table[each /. p -> Unique[], {2}]] ~~ "17"] & /@ {str1, str2}
(* {True, True} *)

This gives you what you want for your specific case.
But, you may want to have an arbitrarily long repeated sequence. Meaning, you don't know if it will repeat exactly 2 times or 3 times. The above doesn't do that.
Well, now, I don't know how to do it completely arbitrarily, but if you're willing to choose some maximum, then the following seems to work:

With[{each = p__ /; endsWithSpaceQ[p]},
   StringMatchQ[#,
      Table[StringExpression @@ Table[each /. p -> Unique[], {i}], {i,
         10}] ~~ "17"] & /@ {str1, str2}]

(replace the "10" in the last iterator with whatever your maximum is)
The way it works is to first create the sequence of patterns programmatically, as Mr.Wizard suggested. For that, it replicates the "p" pattern a certain i number of times and replaces it with a unique symbol each time it appears. Then, the outer table iterates i up through the maximum. A list of StringExpression's evaluates as an alternative, so as long as one of those patterns matches, it goes on.
Here's a way to see that it is really working. Let's change your function a little bit:

endsWithSpaceQn[str_, lenprespace_: 3] :=
   StringEndsQ[str, " "] && StringLength@str == lenprespace + 1

now we are looking for strings that end with a space and are of length 3 (not counting the space)
Running this:

With[{each = p__ /; endsWithSpaceQn[p, 3]},
   StringMatchQ[#,
      Table[StringExpression @@ Table[each /. p -> Unique[], {i}], {i,
         10}] ~~ "17"] & /@ {str1, str2}]

with any maximum greater than 1 in the final iterator (where the 10 is), results in the correct answer:

(* {True, True} *)

But if you replace the 10 with a 1 then you'll see it comes back as:

(* {False, False} *)

(if you had used the original endsWithSpaceQ function here, it would still come back true, because it would match eg "abc abc ")


text:
Q: duplicate of entry in database of longitude and latitude using javascript php laravel im stuck in here for 24 hours i've been trying to get different values.
i'm getting the address of each student as well as the longitude and latitude.
here is my view, i used javascript  :
    $(document).ready(function() {
    $("#dropdown").change(function() {
    var selVal = $(this).val();
    $("#textboxDiv").html('');
     $("#schoolloc").html('');

    if(selVal > 0) {
        for(var i = 1; i<= selVal; i++) {
             $("#textboxDiv").append('<input type="hidden"
    value="student'+i+'" name="stud[]" />');
             $("#schoolloc").append('<input type="text"
    name="studlocation[]" id="studlocation'+i+'" />');
        var input = document.getElementById('studlocation'+i+'');
        var autocomplete = new google.maps.places.Autocomplete(input);
    $("#slat").html('');
    $("#slng").html('');
    autocomplete.addListener('place_changed', function () {
     var place = autocomplete.getPlace();
    var lat = place.geometry.location.lat();
    var lng= place.geometry.location.lng();
     $("#slat").append('<input type="hidden" name="slat" value="'+lat+'" />');
    $("#slng").append('<input type="hidden" name="slng" value="'+lng + '" />');
       console.log(lat);
         });
                   }

               }
                });
              });

and here is my controller:
 $students = (array)$request->stud;
 $locations = (array)$request->studlocation;

 for ($i = 0; $i < count($students); $i++){

$hm = new HouseMate;

$hmid = rand();
$hm->hmid=$hmid;
$hm->rId_fk=$renterid;
$hm->person=$students[$i];
$hm->location=$locations[$i];
$hm->$lat=$request->slat;
 $hm->lng=$request->slng;

$hm->save();

}


text:
Q: Why bufferTime(5000, 10000) shows values that I created after 5000ms Code:
const source = Rx.Observable.fromEvent(document.getElementById('click'), 'click')
const example = source.bufferTime(5000,10000);
const subscribe = example.subscribe(val => console.log('Start Buffer Every 1s:', val));

jsfiddle
I don't understand two things:

*

*Why first value is returned after 5s not 10s

*After 10s (as soon as I see empty array in console) I start clicking btn. I do it for 4 seconds, and after 10s there is still empty array. But if I start clicking after 5 seconds since the appearance of an empty array in the console, there is a proper result.

I thought that it will work like "Every 10 seconds, emit the click events from the next 5 seconds". But it doesn't.

A: bufferTime(bufferTimeSpan: number, bufferCreationInterval: number, ..)
// bufferTimeSpan: The amount of time to fill each buffer array.
// bufferCreationInterval: The interval at which to start new buffers.

bufferTimeSpan < bufferCreationInterval ⟹ gaps between buffer intervals
Example 1: bufferTimer(5000, 10000)

// 1. bufferCreationInterval = 10000
//    open the buffer every 10 seconds, start with an open buffer

                      ┌ 5   ┌ 10  ┌ 15  ┌ 20  ┌ 25  ┌ 30  ┌ 35  ┌ 40  ┌ 45  ┌ 50

bufferInterval: [----- -----[----- -----[----- -----[----- -----[----- -----[---

// 2. bufferTimeSpan = 5000
//    close the buffer 5 seconds after it was opened

                      ┌ 5   ┌ 10  ┌ 15  ┌ 20  ┌ 25  ┌ 30  ┌ 35  ┌ 40  ┌ 45  ┌ 50

bufferInterval: [~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~

As soon as I see empty array in console I start clicking button, I do
  it for 4 seconds.

                       ┌┬┬┬ sounds like you click here, nothing is recorded
                       ││││
bufferInterval: [~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~

If I start clicking after 5 seconds since the appearance of an empty
  array in the console, there is a proper result.

                             ┌┬┬┬ sounds like you click here, values are buffered
                             ││││
bufferInterval: [~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~~~]-----[~~~

bufferTimeSpan > bufferCreationInterval ⟹ overlapping buffer intervals
Example 2: bufferTimer(2000, 1000)

// 1. bufferCreationInterval = 1000
//    open the buffer every 1 seconds, start with an open buffer

                               ┌ 5            ┌ 10           ┌ 15           ┌ 20

bufferInterval: (- [- {- (- [- {- (- [- {- (- [- {- (- [- {- (- [- {- (- [- {- (-

// 2. bufferTimeSpan = 2000
//    close the buffer 2 seconds after it was opened

                               ┌ 5            ┌ 10           ┌ 15           ┌ 20

bufferInterval: (~ [~){~](~}[~){~](~}[~){~](~}[~){~](~}[~){~](~}[~){~](~}[~){~](~}

// split into multiple layers for better view
layer1:         (~  ~) - (~  ~) - (~  ~) - (~  ~) - (~  ~) - (~  ~) - (~  ~) - (~
layer2:          - [~  ~] - [~  ~] - [~  ~] - [~  ~] - [~  ~] - [~  ~] - [~  ~] -
layer3:          -  - {~  ~} - {~  ~} - {~  ~} - {~  ~} - {~  ~} - {~  ~} - {~  ~}


text:
Q: Deploying configuration via Jenkinsfile to unknown amount of servers We're setting up multiple more or less static servers in AWS. These are primarily configured via Ansible and that's also the ultimate source of truth when it comes to their existence, grouping, host names and IPs. But then there's Jenkins deploying configuration files to these servers based on new commits added to a git repository.
I'm having an issue with listing the target servers directly in a Jenkinsfile. How shall I proceed? Which are the most common ways of dealing with this?
I understand this is mostly an opinion based topic. But maybe there's a particular Jenkins feature which I don't know about...?
Thank you.

A: This is very subjective. Following are a few ways to do this.

*

*Store the details somewhere accessible after the Ansible step. Possibly commit to a Github repo and retrieve these details within the Jenkins Job.

*Using AWS APIs/CLI to retrieve server details. You can either set up AWS CLI in Jenkins Agent or use something like AWS Step Plugin.

*Do an API call to Jenkins after the Ansible script is executed and update the server details in the Job itself.


text:
Q: Content negotiation using WebSharper I'm investigating whether WebSharper can be used to build a ReSTful API that supports content negotiation. I was hoping that it would support something similar to the Web API model, whereby the controller returns a resource that is subsequently converted to the correct representation based on the request's accept header. However, it appears that the header info is only available to the Router, which maps the request to an Action, and then the Controller is responsible for converting the Action into some Content (i.e. a representation). This suggests that I would need a separate Action for each representation of the resource, which feels ugly.
Am I missing something here, or is WebSharper meant to be "MVC done right" and is not intended for this use case?

A: As expected, I was missing something. The details are here.


text:
Q: Prevent pause while recording a video with intent on some Android devices Is it possible to prevent such feature in selected devices (like the HTC One)?
I am starting an intent using that code:
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    Uri fileUri = Uri.fromFile(/* path to some file */);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
    intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45); // limit the camera to 45 seconds

    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

I cannot find any flag to use for preventing "pause while recording"..
The stock Android camera (on api lvl21+ at least) there isn't any option to pause the video recording but on some devices you can.


text:
Q: Where to save JS callback function for retry after authentication? I have an action that I want to allow only to an authenticated user. If a user who hasn't yet logged in clicks this link, the Webserver will return a not-logged-in response. I then present the login form in a floating "lightbox" div. If the user successfully logs in, I want the browser to retry the action.
I'm having trouble finding a good place to store the function that I want to retry. Currently, I'm attaching it to a global object, which seems very hacky. The jQuery "deferred" pattern seems to fit here, but I would still need to retain a reference to the deferred object somewhere, and I can't see the right place to do it.
Suggestions?
Here's some simplified code (in reality, the Ajax response determines whether we show the login form or a confirmation of the action):
$(function() {
    $('li.secured').find('a').click(function() {
        var link = this;
        var action = function() {               // captures 'link'
            if(RootObj.IsAuthenticated() ) {            // already logged in
                window.location.assign( link.href );
            } else {
                // pass ourself in as a callback to be repeated after authentication
                // Yes, this seems to work even in the midst of our own definition...
                RootObj.ShowLoginForm( action );
            }
            return false;           // don't go immediately to the new url
        }
        return action();
    });
});

RootObj.ShowLoginForm = function( callback ) {
    var lb = $('#lightbox');
    if(lb.length == 0) { lb = $('

').appendTo('body'); }
    lb.load('login.html');

    RootObj.callback = callback;    // is there a better place to store this callback function?
}


text:
Q: How do I change the default 'hostname.local' apache config OS: Ubuntu 19.10
I'm playing around with Apache so I can learn how to configure it, so I installed it via apt-get and took a look at the config directories.
I also am vaguely aware that with Apache on macOS all the default addresses end with a .local TLD, so I tried navigating to my box in a web browser using its hostname and the .local TLD, i.e. http://mybox.local/. And it worked, I see the apache default page.
But looking at the apache config files and virtual host config, nowhere is this server name defined. So I looked up as best I could how this extension is configured, and I found this page saying the avahi-daemon is responsible and how to work the config.
I changed the server settings to a different TLD, eg '.blarg' and I restarted the avahi service - which doesn't work, even with an Apache service reload, yet somehow the .local TLD still works, even after a reboot.
This leads me to believe either I'm restarting the wrong service, or avahi isn't responsible for the .local extension. Anyone care to point me in the right direction?

A: There's no magic going on, really.
What you have is a fresh installation to Apache. So, by default, any request on port 80 to your machine will show you the default apache welcome page.
For example, the following would work as well:

*

*http://127.0.0.1/

*http://localhost/
If you need to add another domain, you need to point that domain to your machine. The simplest way to do that on a development machine is to edit the /etc/hosts file and a new entry.
Open the file with an editor and add the following line (change mybox.something to whatever you want):
127.0.0.1   mybox.something

After you do that, just open http://mybox.something in your browser and it should work.


text:
Q: Unable to render SurfaceView inside RecyclerView. Implementing group video calling using Agora.io My requirement is to have a bottom scrolling for all users. I have added recyclerview for this. Problem occurs when I am trying to add surfaceview provided from sdk to recycler; it renders to black color view.
I have also tried adding following properties to surfaceview
@NotNull
@Override
public UsersSurfaceViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                             int viewType) {
    LayoutInflater inflater = LayoutInflater.from(
            parent.getContext());
    View v =
            inflater.inflate(R.layout.item_cell_video_call, parent, false);
    // set the view's size, margins, paddings and layout parameters
    return new ViewHolder(v);
}

 @Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    VideoModel model = values.get(position);
    RelativeLayout.LayoutParams videoLayoutParams =
            new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
    SurfaceView surfaceView = model.getSurface();
    surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
    surfaceView.setZOrderOnTop(true);
    holder.relContainer.addView(surfaceView, videoLayoutParams);
}

Also my holder.relContainer is having fixed height and width.


text:
Q: Friend declaration not working with typedef When I write a friend declaration like this
template<typename T>
struct Foo {};

struct Bar {
    friend class Foo<Bar>;
};

everything is fine. However, when I use a typedef
template<typename T>
struct Foo {};

struct Bar {
    typedef Foo<Bar> FooBar;
    friend class FooBar;
};

gcc (4.4.7) complains with
error: using typedef-name 'Bar::FooBar' after 'class'
error: 'Bar::FooBar' has a previous declaration here
error: friend declaration does not name a class or function

I always thought a typedef behaves exactly the same as if I typed the original type.... Is it not allowed to use a typedef here? or am I just using it wrong?
PS: the template turned out to be a red herring, the following will cause the same error
struct Foo{};
struct Bar{
    typedef Foo FooBar;
    friend class FooBar;
};


text:
Q: how do i load csv into array? I am using pandas to load csv files containing questions/answers and assigning them to dict.
kids_csv_file = pd.read_csv(...) #columns Questions, SubQuestions, Answers

questions_dict = dict()

for i in ... :
_key = kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i]
questions_dict[_key] = kids_csv_file.Answers[i];

I am getting:

TypeError: must be str, not numpy.int64

A: Because kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i] is not a string.
When you type kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i]
python thinks, that string '-' must be joined with object kids_csv_file.Questions[i] and kids_csv_file.SubQuestion[i]
step 1) create string in separate line
step 2) append to dict your value

A: as mentioned before, kids_csv_file.Questions[i] is not a string, so python can't use the string's Plus operator to concatenate it to other strings. you can use the format method, though:
questions_dict['{}-{}'.format(kids_csv_file.Questions[i], kids_csv_file.SubQuestion[i])] = kids_csv_file.Answers[i];

or better yet, create the index in a different line:
index = '{}-{}'.format(kids_csv_file.Questions[i], kids_csv_file.SubQuestion[i])
questions_dict[index] = kids_csv_file.Answers[i];


text:
Q: Failed to reorder bars in R ggplot geom_bar() function by reorder I'm trying to plot a variable importance for my random forest classifier model and from the trained model I will be able to get the importance score for all my 105 feature variables for each of my 7 classes. So I want to now plot them out as simple bar graph: each bar represent a Feature variable(character variable), and the height of the bar will be its Importance score (numeric), then I can use facet to see for each Class, how the importance scores are ranked in each Class for all the features.
I want each of the Class facet plot ranks the features  from high to low importance, I think this is where my code screwed up. I don't think the reorder () did not work when I facet it. Is there anyway to fix this?
Then once I can get that graph, for simplicity, I might want a second graph just to show the top 20 features in each of the facet graph.
I think the core problem is in my data, feature A might be super important for Class A but not so much for Class B, so that confuses R? A little intuitive explanation is much appreciated.
The real data (sorry for the long list wpnt fit in the limit, so I put it on google drive)
https://drive.google.com/file/d/18-1CWvALU-ILAHIFWsz8jjcvsXnXD0WQ/view?usp=sharing
The code:
ggplot(importance_tbl,aes(x=reorder(Feature,-Importance) ,y=Importance)) +
  geom_col()+
  facet_wrap(.~Class)+
  coord_flip() +
  scale_fill_grey() +
  scale_y_discrete(guide = guide_axis(n.dodge=3))+
  theme_bw()

you see the output, x axis labels is not well ordered by importance but scattered


text:
Q: Improve naive gauss elimination, when zero elements are known I wrote naive gauss elimination without pivoting:
function [x] = NaiveGaussianElimination(A, b)
    N = length(b);
    x = zeros(N,1);
    mulDivOp = 0;
    subAddOp = 0;
    for column=1:(N-1)
        for row = (column+1):N
            mul = A(row,column)/A(column,column);
            A(row,:) = A(row,:)-mul*A(column,:);
            b(row) = b(row)-mul*b(column);
            mulDivOp = mulDivOp+N-column+2;
            subAddOp = subAddOp +N-column+1;
        end
    end

    for row=N:-1:1
        x(row) = b(row);
        for i=(row+1):N
            x(row) = x(row)-A(row,i)*x(i);
        end
        x(row) = x(row)/A(row,row);
        mulDivOp = mulDivOp + N-row + 1;
        subAddOp = subAddOp + N-row;
    end
    x = x';
    mulDivOp
    subAddOp
    return
end

but I am curious if I can reduce the number of multiplications/divisions and additions/subtractions in case I know which elements of matrix are 0:
For N = 10:
A =

    96   118     0     0     0     0     0     0     0    63
   154   -31  -258     0     0     0     0     0     0     0
     0  -168   257  -216     0     0     0     0     0     0
     0     0   202    24   308     0     0     0     0     0
     0     0     0  -262   -36  -244     0     0     0     0
     0     0     0     0   287  -308   171     0     0     0
     0     0     0     0     0   197   229  -258     0     0
     0     0     0     0     0     0   -62  -149   186     0
     0     0     0     0     0     0     0   -43   255  -198
  -147     0     0     0     0     0     0     0  -147  -220

(non-zero values are from randi). In general, non-zero elements are a_{1, N}, a_{N,1} and  a_{i,j} when abs(i-j) <= 1.

A: Probably not. There are nice algorithms for reducing tridiagonal matrices (which these aren't, but they are close) to diagonal matrices. Indeed, this is one way in which the SVD of a matrix is produced, using orthogonal similarity transformations, not Gaussian elimination.
The problem is that when you use Gaussian elimination to remove the nonzero entries in the first column, you will have introduced additional nonzero entries in the other columns. The further you proceed, the more you destroy the structure of the matrix. It may be that Gaussian elimination is simply the wrong approach for the problem you are trying to solve, at least if you are trying to exploit the structure of the matrix.


text:
Q: Having layout issues So I have a layout, everything is fine besides this annoying button.
My layout consists of three Layouts, one being the header. And the other two displaying time and date. But in the CardView, I wish to add a Button under the time (TextView). But for some reason, it keeps going to the left? I've tried dragging it around but it doesn't seem to work.

My question is, how can I make the Button lay itself under the TextView?
The code below is the layout -
<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_card" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/mybutton"
            android:text="Button" />

        <com.activelauncher.MyTextView
            android:id="@+id/time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="30sp"
            android:text="10:08 PM"
            android:textColor="#6b6b6b"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

A: Set android:orientation = "vertical" in LinearLayout
and keep Button code after Your com.activelauncher.MyTextView control code.
Check the following code.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:background="@drawable/bg_card"
    android:orientation="vertical" >

    <com.activelauncher.MyTextView
        android:id="@+id/time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="10:08 PM"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#6b6b6b"
        android:textSize="30sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/mybutton"
        android:text="Button" />

</LinearLayout>

A: // try this way,hope this will help you...
<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_card" >

        <com.activelauncher.MyTextView
            android:id="@+id/time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="30sp"
            android:text="10:08 PM"
            android:textColor="#6b6b6b"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/mybutton"
            android:layout_gravity="left|center_vertical"
            android:text="Button" />-
</FrameLayout>