text:
Q: How to structure and parse JSON I'm creating a web RPG using HTML5 and JavaScript embedded directly into my website. The game will be a single player game against computer opponents... the design will be top-down 2D, Zelda style. It will be real time, but conversing with computer players will be scripted... they say something, and you're given some response options.
I was thinking of writing the dialog in XML, but I was told I should use JSON as it's easier to parse using JavaScript.
I saw Abstract Chaos' answer in XML...
<?xml version="1.0" encoding="UTF-8"?>
    <npcs>
      <npc name="Abstract">
        <dialogue>
          <text>Welcome #{PlayerName} to Stack Exchange, What would you like to know? </text>
          <options>
            <option action="dialogue5">Tell me about Stack Exchange?</option>
            <option action="quest1">Give me quest</option>
            <option action="object1">Give me object</option>
          </options>
        </dialogue>
        <dialogue id="5">
          <text>Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics</text>
          <text>We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise</text>
        </dialogue>
      </npc>
    </npcs>

And was wondering how I could achieve the same sort of layout in JSON...
My questions are:

*

*How can I layout RPG dialog scripts in JSON to be parsed by JavaScript?

*Can I have an example of how I could use JavaScript logic to parse JSON given certain conditions (ex: NPC asks question: "Can you help me?", JSON should have options "Yes" and "No", which could be based on if the player actually has that skill set to help).

*The JSON dialog text will be stored in a separate "dialog" folder in my project folder... so it will need to be accessed externally

The only thing I've found on how to layout and parse JSON is:
        var json = '{"result":true,"count":1}',
            obj = JSON && JSON.parse(json) || $.parseJSON(json);

        alert(obj.result);

But it doesn't have the neatness factor that XML seems to have.
Any help would be appreciated...
Thanks!

Trying to load and alert external JSON text file doesn't work:
HTML:
<html>
    <head>
        <title>Working with JSON</title>
        <script src="jquery.js"></script>
        <script>
            (function() {

            var data = "/JSON_TEXT.txt";

            var first_q = data.npcs[0].dialogs[0];
            alert(first_q.text);

            }());
        </script>

    </head>
    <body>
    </body>
</html>

JSON plain text file: JSON_TEXT.txt
'npcs': [
            {
                'name': 'Abstract',
                'dialogs': [
                    {
                        'text': 'Welcome',
                        'options': [
                            'df', 'f'
                        ]
                    }
                ]
            }
        ]

A:
How can I layout RPG dialog scripts in JSON ?

The equivalent of the XML you gave us would be (without the comments):
// you might use a top wrapper object with a property "npcs" for this array
[
    {
        "name": "Abstract",
        "dialogues": {
// I recommend on object with dialogues by id instead of an array
             "start": {
                 "texts": [
                     "Welcome #{PlayerName} to Stack Exchange, What would you like to know?"
                 ],
                 "options": [
                     {
                         "action": "dialogue 5",
                         "text": "Tell me about Stack Exchange?"
                     }, {
                         "action": "quest 1",
                         "text": "Give me quest"
                     }, {
                         "action": "object 1",
                         "text": "Give me object"
                     }
                 ]
             },
             "5": {
                 "texts": [
                      "Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics",
                      "We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise"
                 ]
             }
         }
         // further properties of the NPC like objects and quests maybe
    },
    … // further NPCs
]

How to parse JSON?

See Parse JSON in JavaScript?.

var json = {…};
var data = JSON && JSON.parse(json) || $.parseJSON(json);

Ouch, no! That's no JSON, that's just an object literal in JavaScript. You can use it like
var data = {…};

and data will be your object. You need to parse JSON only when you have it as a string, for example when you've loaded a file via ajax.

JavaScript logic to parse JSON given certain conditions

That's your game logic, with which we can't help you. But you don't need to parse JSON there, you only need to access the data which you have already parsed. See Access / process (nested) objects, arrays or JSON for that.

A: Some find JSON harder to read than XML. I think it's much cleaner and easier to use, especially if you want to parse it with JS.
That said, I'm not really sure what your question is—you already have the data in XML, so just convert it to JSON. You can use arrays ([]) for lists and objects ({}) for when you need named keys:
{
    'npcs': [
        {
            'name': 'Abstract',
            'dialogs': [
                {
                    'text': 'Welcome #{PlayerName} to Stack Exchange, What would you like to know?',
                    'options': [
                        //options here
                    ]
                },
                //next dialog object here
            ]
        },
        //next npc object here
    ]
}

So, like you said, first you'll need to parse the JSON string:
var json; //contains the json string, perhaps retrieved from a URL via AJAX
data = JSON && JSON.parse(json) || $.parseJSON(json);

You could also assign the JSON object to a JS variable in the first place (say, in a .js file somewhere) and you won't need to parse at all. Just be sure not to pollute the global scope.
After parsing, data is a normal JS object. You can access its properties just like any other object. So, to access the first question from the first NPC, do:
var first_question = data.npcs[0].dialogs[0];

Let's alert the question itself:
alert(first_question.text);

You can access its options like this:
first_question.options;

You asked about how to load the JSON data from an external file. The usual approach is to load the file's URL via AJAX. Here is a nice tutorial for making AJAX requests with vanilla JavaScript: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
But there's not much reason to hand-code AJAX requests with vanilla JavaScript. I recommend using a library like jQuery, which has handy AJAX functions such as .ajax and the shorthand function .get. Here's an example using .get:
var data;                          //will hold the parsed JSON object
var json_url = 'json.txt';         //URL of your JSON (just a plain text file)
$.get(json_url, function(json) {
    data = JSON && JSON.parse(json) || $.parseJSON(json);
});

//use data here


text:
Q: Laravel : JWT refresh token to get user data on same function I am using Tymon\JWTAuth in my app.What I want that when I am going refresh expired token it is return a new generated token but i want to get same user data in same function.
My refresh function :
public function refresh()
{
    $token      =  Auth::guard()->refresh();
    $user       = Auth::user(); // Return Null
    return response()->json([
        'status_code'       => 200,
        'token'             => $token,
        'user'              => $user
    ]);
}

Response :
{
"status_code": 200,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTkyLjE2OC41LjE1ODo4MDAwL2FwaS9hdXRoL3JlZnJlc2giLCJpYXQiOjE1MzM3OTUyOTUsImV4cCI6MTUzMzc5ODkwMSwibmJmIjoxNTMzNzk1MzAxLCJqdGkiJlMWxiamQ4c1F3UVM0TzhEIiwic3ViIjoxMiwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.vB9unghn2CCJSrzVP9V_Cna-x0Ez--0aF--D7yGfw",
"user": null
}

How can I do this ?

A: try $user = JWTAuth::setToken($token)->toUser();
where $token is the refreshed token

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic token handling of a gis application I m doing performance testing of a gis application using jmeter in which lot of map tiles load as i login to the application.each tile is a http request containing a dynamic token in its header which expires in 15 mins.I know handling of dynamic token using regex where i replace the token with a regex but problem here is that there are huge no.of map tiles so replacing each token one by one is not feasible option...can anyone suggest how do I change all the token at once or any other solution?

A: JMeter's HTTP Header Manager obeys JMeter Scoping Rules

so if you move it 1 level up (to be at the same position as your HTTP Request sampler) you will need to perform the change at one place only


text:
Q: How to find strings with * in pandas data frame using re I am trying to find a string with *A* in the data frame
df = pd.DataFrame({
    "col_1":["AAA","BBB","CCC"],
    "col_2":[4,5,6],
    "col_3":[107,800,300],
    "col_4":[1,3,5]
})

#0  1   2   3
#0  AAA 4   107 1
#1  BBB 5   800 3
#2  CCC 6   300 5

This line gives the error:
df['col_1'].str.match("*A*")

It is not working  and I am getting an error:

line 615, in _parse
source.tell() - here + len(this))
sre_constants.error: nothing to repeat at position 0

I have also following code
import pandas as pd
df = pd.DataFrame({
  "col_1":["AAA","BBB","CCC"],
  "col_2":[4,5,6],
  "col_3":[107,800,300],
  "col_4":[1,3,5]
 })

 def findItems(df, findText, colName):
    mask = df[colName].astype('str').str.match(findText)
    print("\n mask",mask)

 The above code is also not working

A: Here are some examples for you that should answer your question.
I think you might be looking for: str.match(".+A.+") which would mean any char(s) followed by A followed by any char(s), i.e if str.contains('A') doesn't help you.
Credit to all the commenters too.
import pandas as pd

# Let us create a serie as df['col'] is actually a serie.
s = pd.Series(['A','AA','AAA','aaa'])

print(s.str.contains('A').values)             # [ True  True  True False]
print(s.str.lower().str.contains('a').values) # [ True  True  True  True]
print(s.str.match(".*A.*").values)            # [ True  True  True False]
print(s.str.match(".+A.+").values)            # [False False  True False]
print(s.str.match(".+[Aa].+").values)         # [False False  True  True]


text:
Q: Media area in Finder's file selection dialog is always empty I try to select and upload files in Safari, but the Media section in the file selection dialog is empty; no photos, music or movies are ever shown in this area. The same problem happens anywhere that can open Media Browser to select files, like Mail, Twitter etc.
I checked the com.apple.iApps.plist in the ~/Library/Preferences folder, everything is normal. All databases(iTunes, Aperture, Photo Booth) are well configured.


text:
Q: how to embedded a linux command example ln -l path1 path2 in cpp im trying to create a symlink to a path /appdata/config/hello.txt to /appdata/debug/
std::string srcpath = "/appdata/config/hello.txt";
std::string debug = "/appdata/debug/";

In cpp code I have given ln -s srcpath debug
I even tried if(symlink(destPath.c_str(), DEBUG_PATH.c_str()) == 0)
But no luck.

A: You need to specify the target link name as well, e.g. like this:
std::string fileName = "hello.txt";
std::string srcpath = "/appdata/config/" + fileName;
std::string tgtpath= "/appdata/debug/" + fileName;

if (symlink(srcpath.c_str(), tgtpath.c_str()) != 0) {
  std::cerr<< strerror(errno) << std::endl; // #include <errno.h> and <cstring> for this
}

The way you've written it the program will output an "File exists" error message, because you're defining an existing directory as link target.


text:
Q: count repeated number and replace elements from last index If the count of number 1 is repeated more than or equal to 12: replace all elements with 2 after last index of number 1.
Original array contains 0,1,-1;
I tried using below it works, if there is any simpler solution please suggest and help with link to documentation for further reference.

var arr = [0, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 0, 1, 1, -1, 0, 1, 0];
var total = arr.reduce((t, i) => i == 1 ? t + i : t, 0);
if (total >= 12) {
  var startingIndex = arr.lastIndexOf(1) + 1;
  var arr = arr.map((e, i) => i >= startingIndex ? 2 : e);
}
console.log(arr);

If array is [0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0]
then resulting array should be [0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1, 2]
If given array is [-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
then resulting array should be[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,2,2,2,2]
If given array is [1,1,1,1,1,-1,1,1,1,1,1,0,1,1,1,0,-1,0]
then resulting array should be [1,1,1,1,1,-1,1,1,1,1,1,0,1,1,1,2,2,2]

A: Use filter to find how many, use fill to fill index starting from last found 1

const oneFill = arr =>
  arr.filter(x=>x===1).length >= 12 ? arr.fill(2,arr.lastIndexOf(1)+1) : arr

const array = [
[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0],
[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
]

for(const arr of array)
console.log(JSON.stringify(
  oneFill(arr)
))

optimized version using .some, breaks out immediately after finding 12th element

// fills from the 1 found at the 12th instance of 1

const oneFill = arr => {
  let count = 0
  // if equals 1 increment and check if counter reached 12, fill with 2s
  arr.some((x,i)=>x===1 && ++count >= 12 && arr.fill(2,i+1))
  return arr
}

const array = [
[0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0],
[-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]
]

for(const arr of array)
console.log(JSON.stringify(
  oneFill(arr)
))

// I don't know if you want lastIndex, or just the 12th index
// Below is a version that finds the lastIndex

const oneFill2 = arr => {
  let count = 0
  arr.some((x,i)=>x===1 && ++count >= 12) && arr.fill(2,arr.lastIndexOf(1)+1)
  return arr
}

for(const arr of array)
console.log(JSON.stringify(
  oneFill2(arr)
))

A: This is an alternate approach for @user120242 answer. This is more imperative code but uses less amount of iterations.
Idea:

*

*Create 2 variables:

*

*count: to keep count of valid cases.

*index_12: to hold index of 12th valid case.

*Now loop over the passed array and return value as:

*

*If count is less than 12 the no processing is required. Return same value/

*If count is 12, check if current index is same as index_12. If yes, this is the 12th valid case and return item instead.

*If count is greater than 12 or if its equal to 12 but index is not same as index_12, return processed value (in this case 2)

function doSomething(arr) {
  let count = 0;
  let index_12 = null;
  return arr.map((item, index) => {
    count = item === 1 ? count + 1 : count;
    index_12 = !index_12 && count === 12 ? index : index_12;
    return index === index_12 || count < 12 ? item : 2
  })
}

console.log( doSomething([0,1,1,1,1,-1,1,1,1,1,1,0,1,1,-1,0,1,0]).join() );

console.log( doSomething([-1,1,1,1,1,-1,1,1,1,1,1,1,1,1,-1,0,-1,-1]).join() );


text:
Q: How to use Mockito for AsyncTask mocking? I'm trying to improve some unit tests I've made, so I'm using mockito to mock some objects. So for now I have two questions: Should I try to mock an AsyncTask and (if yes) how can I use this mocked object to call the doInBackground() method of the mocked object?
I've tried several things but it's still not working. My test still gives me an Assertion Failure:
How the AsyncTask is executed (in the StudioActivity.java):
.....

LocationTask task = new LocationTask();
task.execute((LocationManager) this.getSystemService(Context.LOCATION_SERVICE));

My Async Task (in the StudioActivity.java):
.....

public class LocationTask extends AsyncTask<LocationManager, Void, String> {
    private LocationManager mLocationManager;

    // private TextView mLocText;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // mLocText = (TextView) findViewById(R.id.textView_location);
        // mLocText.setVisibility(View.VISIBLE);
    }

    @Override
    public String doInBackground(LocationManager... params) {
        mLocationManager = params[0];
        Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
            if (addresses.size() > 0) {
                return (addresses.get(0).getLocality() + ", " + addresses.get(0).getCountryName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        mPreviewFragment.setLocation(result);
        mLocation = result;
    }

}

This is what I've tried.
My Test Method (in the TestStudioActivity.java):
@UiThreadTest
public void testGeolocalistationLabel() throws InterruptedException, ExecutionException{
    LocationTask mockLocationTask = mock(StudioActivity.LocationTask.class);

    when(mockLocationTask.doInBackground((LocationManager[]) any())).thenReturn("JUnit, Location");

    mStudioBoastPreviewFragment.getGeoloc().performClick();
    assertEquals("JUnit, Location",mStudioBoastPreviewFragment.getGeolocTextView().getText());

    verify(mockLocationTask).doInBackground((LocationManager[]) any());
}

OR
@UiThreadTest
public void testGeolocalistationLabel() throws InterruptedException, ExecutionException{
    LocationTask mockLocationTask = mock(StudioActivity.LocationTask.class);

    when(mockLocationTask.doInBackground((LocationManager) mStudioActivity.getSystemService(Context.LOCATION_SERVICE))).thenReturn("JUnit, Location");

    mStudioBoastPreviewFragment.getGeoloc().performClick();
    assertEquals("JUnit, Location",mStudioBoastPreviewFragment.getGeolocTextView().getText());

    verify(mockLocationTask).doInBackground((LocationManager) mStudioActivity.getSystemService(Context.LOCATION_SERVICE));
}

The Failure:
junit.framework.AssertionFailedError: expected:<JUnit, Location> but was:<>
at  com.c4mprod.bhost.test.TestStudioActivity.testGeolocalistationLabel(TestStudioActivity.java:255)

Without Mocking, it's working. But the test has long time execution. That's why I wanted to use Mockito: to improve test speed and to avoid connection problems or server errors. I just want to test if the location is displayed in the mStudioBoastPreviewFragment.getGeolocTextView().
In both case I have an Assertion Failure so I wanted to know which method is the best and how could I use it to mock this doInBackground(). Or if there is another way to Mock AsyncTask.
Thanks for the help!

A: I don't know much about Android unfortunately, but I do know a bit about Mockito.
One question I must ask is:
How does your StudioBoastPreviewFragment actually obtain an instance of your LocationTask? From your test code all I can guess is that your mocked LocationTask is not injected - mStudioBoastPreviewFragment seems to be a member of your Test class, while mockLocationTask is  declared and instantiated within the method scope, so there is no way I can think of how your mStudioBoastPreviewFragment is actually using your mock.
Then there's the issue with Mocks:
I see that LocationTask inherits from AsyncTask. How does doInBackground(...) get called? Are you calling it, or is this called by the internal logic of AsyncTask (similar to Thread.run() being called by Thread.start())? Keep in mind that Mockito creates a dumb proxy object with no logic in it. So, if you rely on some internal logic of AsyncTask calling doInBackground(...), this internal logic will not exist in your mock.
In other words, if this is a Unit test, you don't care if doInBackground(...) is called in the first place, as your external client code should not depend on the internals of AsyncTask or your concrete subclass LocationTask. To come back to the Thread-example: you mock out Thread.start(), not Thread.run().
If you really want to Unit-test, you should test the two classes separately, isolating potential errors in either class. Hence, mocking out LocationTask is a good idea, if done correctly.
If on the other hand you want to test the interactions between the two components, this is not really a Unit-Test anymore and a whole different story.


text:
Q: How do I make xgettext support i18n Java? I am trying to extract the strings from a Java project using xgettext with the following line:
xgettext --lanaguage=Java C:\workspace\HelloWorldJava\src\com\Dummy.java

and I get the following error:
language 'Java' unknown

When I remove the --lanaguage=Java parameter and execute the same line I get the following:
warning:file 'C:\workspace\HelloWorldJava\src\com\Dummy.java' extension 'java' is unknown; will try C

How do I make xgettext support i18n Java?
I am running xgettext win 32 binary ("GNU gettext for WIN32") on Windows 7 64-bit from here:
http://franco-bez.4lima.de/index.php?option=com_content&view=article&id=55&Itemid=64&lang=en

A: I guess you have installed a quite old version of Gettext. By inspecting the source code of the package available on the URL you provided, Java support is not available. You should download and install a newer Gettext port for Windows.
Django's documentation includes some easy-to-follow instructions to install Gettext on Windows.


text:
Q: Evaluate $\lim_{x \to 0} \left\lfloor(1-e^x)\frac {\sin x}{|x|}\right\rfloor$
How to simplify the following limit:$$ \lim_{x \to 0} \left\lfloor(1-e^x)\frac {\sin x}{|x|}\right\rfloor,$$ where $\lfloor\cdot\rfloor$ represents the greatest integer function.

Given limit is in 0/0 form so can we apply
 LH rule to solve this problem.. or there is special approach for the same.

A: Since, when $x$ is close enough to $0$, $$\left\lfloor(1-e^x)\frac{\sin x}{\lvert x\rvert}\right\rfloor=-1,\tag1$$your limit is equal to $-1$.
The fact that $(1)$ holds when $x$ is close enough to $0$ can be deduced from these facts:

*

*if $x$ is close to $0$ and $x>0$, then $0<\frac{\sin x}x=\frac{\sin x}{\lvert x\rvert}<1$. But $-1<1-e^x<0$, and therefore $(1-e^x)\frac{\sin x}{\lvert x\rvert}\in(-1,0)$;

*if $x$ is close to $0$ and $x<0$, then $0<\frac{\sin x}x<1$, and therefore $-1<\frac{\sin x}{\lvert x\rvert}<0$. Besides, $0<1-e^x<1$, and therefore $(1-e^x)\frac{\sin x}{\lvert x\rvert}\in(-1,0)$ too.


text:
Q: How to extract text before several specified alphanumeric whole words from string in plsql How to remove all characters after specific alphanumeric value from string
for example "covid19 1st case" should be "covid19" if we remove string after 1st;
in case of "covid19 2d case" it should be "covid19" if we remove string after 2d
I am trying below query
select regexp_substr('covid19 1st case','[^1st]*') from dual;

but its giving covid as output any lead.
if we have predefine alphanumeric values can we do it in single expression
like we can remove all string after 1st and 2d.
Thanks

A: You can use
select regexp_substr('covid19 1st case','^(.*?)\s+(1st|2d)($|\W)', 1, 1, NULL, 1) from dual;
select regexp_substr('covid19 1st case','^(.*?)\s*(^|\W)(1st|2d)($|\W)', 1, 1, NULL, 1) from dual;

See the regex demo #1 and regex demo #2.
The (^|\W) and ($|\W) are used instad of word boundaries that are not supported by Oracle SQL regex engine.
Details:

*

*^ - start of string

*(.*?) - Group 1: any zero or more chars other than line break chars as few as possible

*\s* - zero or more whitespaces (\s+ matches one or more)

*(^|\W) - Group 2: start of string or a non-word char

*(1st|2d) - Group 3: either 1st or 2d

*($|\W) - Group 4: end of string or a non-word char.

Another variation is using REGEXP_REPLACE (you just need to match the rest of the string):
select regexp_replace('covid19 1st case','^(.*?)\s*(\W|^)(1st|2d)(\W|$).*', '\1') from dual;

See this regex demo, \1 refers to the Group 1 value.


text:
Q: War deployment on remote Ubuntu tomcat 8.5 not working - but working on local tomcat 8.5 I try to deploy my war file on a remote ubuntu tomcat 8.5 server, using the gui manager.
But the deployment faile and give back this error :
[org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/rest-api-0.0.1-SNAPSHOT]]]
Here is my pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org
/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.7.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.faceRecon</groupId>
<artifactId>rest-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>rest-api</name>
<description>faceRecon rest-api</description>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>com.faceRecon.restapi.Application</start-class>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

and here is my java class starting point : Application.java
package com.faceRecon.restapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import  org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder     application) {
        return application.sources(Application.class);
    }

}

A: Is this the full error message? Did you check the "catalina.log" file?
To me it looks like you could forget to provide MYSQL driver on the remote Tomcat.
Try copying the driver to the Tomcat's "lib" directory and configure it properly like in this example: Tomcat MYSQL DBCP


text:
Q: Easy68K IF-ELSE branching writing my first assembly language program for class using Easy68K.
I'm using an if-else branching to replicate the code:
IF (P > 12)
    P = P * 8 + 3
ELSE
    P = P - Q

PRINT P

But I think I have my branches wrong because without the first halt in my code the program runs through the IF branch anyway even after the CMP finds a case that P < 12. Am I missing something here or would this be a generally accepted way of doing this?
Here is my assembly code:
START:  ORG     $1000       ; Program starts at loc $1000

        MOVE    P, D1       ; [D1] <- P
        MOVE    Q, D2       ; [D2] <- Q

* Program code here

        CMP     #12, D1     ; is P > 12?
        BGT     IF          ;
        SUB     D2, D1      ; P = P - Q

        MOVE    #3, D0      ; assign read command
        TRAP    #15         ;
        SIMHALT             ; halt simulator

IF      ASL     #3, D1      ; P = P * 8
        ADD     #3, D1      ; P = P + 3
ENDIF

        MOVE    #3, D0      ; assign read command
        TRAP    #15         ;
        SIMHALT             ; halt simulator

* Data and Variables

        ORG     $2000       ; Data starts at loc $2000

P       DC.W    5           ;
Q       DC.W    7           ;

        END    START        ; last line of source

A: To do if..else, you need two jumps; one at the start, and one at the end of the first block.
While it doesn't affect correctness, it is also conventional to retain source order, which means negating the condition.
    MOVE    P, D1       ; [D1] <- P
    MOVE    Q, D2       ; [D2] <- Q

* Program code here

    CMP     #12, D1     ; is P > 12?
    BLE     ELSE        ; P is <= 12

IF
    ASL     #3, D1      ; P = P * 8
    ADD     #3, D1      ; P = P + 3
    BRA     ENDIF

ELSE
    SUB     D2, D1      ; P = P - Q
ENDIF

    MOVE    #3, D0      ; assign read command
    TRAP    #15         ;
    SIMHALT             ; halt simulator

A: EASy68K supports structured assembly.
OPT    SEX
IF.L P <GT> #12 THEN

ELSE

ENDI

Add the option SEX to expand the structured code during assembly if you wish to view the compare and branch instructions used to implement the structured code.


text:
Q: Remote options greyed out on server 2016 We've recently installed 2 new Server 2016 Virtual machines while we're awaiting the licenses. We try to connect through RDP, but we cannot connect succesfully. When looking at the RDP options, we see the remote option is enabled, but greyed out.
There's no group policy active for RDP on this domain.
I can only think that it won't work as long as the servers haven't been activated, but I cannot find any documentation on that.

A: From TechNet article Learn About Product Activation:

If activation does not occur immediately after the operating system is
  installed, Windows 7 and Windows Server 2008 R2 still provide the full
  functionality of the operating system for a limited amount of time, or
  grace period.

While the 30-day grace period has been removed since Windows 8 / Server 2012 and replaced with increased notifications and disabling personalization features, all the other features of the operating system still functions normally, so RDP even should be possible.
Licensed evaluation period of Server 2016 lasts 180 days. According to discussion on Spiceworks, a completely unactivated copy of 2008 and 2012 (& R2) runs 30 days (10 days for evaluation install) normally, and then starts shutting down once per hour. Probably 2016 does the same. However, that should be only theoretical as it doesn't take that long to get the actual licence. And it doesn't change that the OS is still otherwise fully functional.
Grayed out usually means there is a Group Policy affecting these settings. Review both your domain polixies and local group policies. I'd use Resultant Set of Policy MMC snap-in to see the affecting policy directly, regardless where the policy is set, as GPO inheritance may be complicated.
Expand Computer Configuration – Administrative Templates – Windows Components – Remote Desktop Services – Remote Desktop Session Host – Connections and check that Allow users to connect remotely using Remote Desktop Services is either Not configured or Enabled.


text:
Q: Как узнать позиции областей многострочного текста ? Есть проблема в определении нахождения элемента(<a/>): определяю с помощью .offset(), но в некоторых случах, когда ссылка находится крайне справа и имеет 2 слова, то второе слово переносится и .offset().left определяется как 0, как узнать, откуда именно начинается ссылка?
вот пример: http://jsfiddle.net/4Qbfs/
видно, что ссылки начинаются в одном месте, но из-за переноса результаты разные
A: Не знаю, есть ли обертки на jQuery, но на чистом JavaScript есть функция element.getClientRects, которая в случае многострочных элементов вернет массив областей.

$(".result").append("left of a1: " + $(".a1")[0].getClientRects()[0].left);
$(".result").append("<br/>left of a2: " + $(".a2")[0].getClientRects()[0].left);

Живой пример: http://jsfiddle.net/4JJvE/


text:
Q: Divergence of $\lim \limits_{t \to \infty}\sum_{n=1}^t b^{\ln n}$ and the Monotonic Sequence Theorem As far as I understand, the Monotonic Sequence Theorem states that if a sequence is monotonic and the individual terms are bounded, then the sequence is convergent.
My book states that $\lim \limits_{t \to \infty}\sum_{n=1}^t b^{\ln n}$ is convergent only for b $\lt$ $\frac{1}{e}$. However, is $\lim \limits_{t \to \infty}\sum_{n=1}^t 0.5^{\ln n}$, for example, not a monotonically decreasing series, whose terms are bound by 0 below and 1 above? Therefore this series meets the criteria for the MST, yet diverges, and does not share the outcome predicted by the theorem.
Why is $\lim \limits_{t \to \infty}\sum_{n=1}^t 0.5^{\ln n}$ divergent when it appears to meet the Monotonic Sequence Theorem's criteria for convergence?

A: You've confused sequence convergence (the $n$th term has a finite $n\to\infty$ limit) with series convergence (the sum of the first $n$ terms has a finite $n\to\infty$ limit).

A: $$\lim_{t\to\infty} \sum_{n=1}^\infty b^{\ln n}=\sum_{n=1}^\infty b^{\ln n}=\sum_{n=1}^\infty e^{\ln b\ln n}=\sum_{n=1}^\infty n^{\ln b}$$
This series converges iff $\ln b<-1$,i.e. when $b<1/e$.
Now, $0.5>1/e$. So, you certainly have that when $b=0.5$ this diverges.  This doesn't contradict monotonic sequence theorem, even though $ (0.5)^{\ln n}$ is bounded by $1$ for all $n$, you don't have that  $\sum_{n=1}^\infty (0.5)^{\ln n}$ is bounded for all $t$.


text:
Q: when using Aeron for Android I create client Aeron on the Android app.
Unfortunately, Aeron is using Agrona which relies on sun.misc.Unsafe. Android don't support sun.misc.Unsafe.
Log error:
I/ientapplicatio: Rejecting re-init on previously-failed class java.lang.Class<org.agrona.BufferUtil>: java.lang.NoSuchFieldError: No static field ARRAY_BYTE_BASE_OFFSET of type I in class Lsun/misc/Unsafe; or its superclasses (declaration of 'sun.misc.Unsafe' appears in /apex/com.android.art/javalib/core-oj.jar)
        at void org.agrona.UnsafeAccess.<clinit>() (UnsafeAccess.java:59)
        at void org.agrona.BufferUtil.<clinit>() (BufferUtil.java:47)
        at void org.agrona.BufferUtil.free(java.nio.ByteBuffer) (BufferUtil.java:241)
        at void io.aeron.Aeron$Context.close() (Aeron.java:1458)
        at void io.aeron.Aeron$$ExternalSyntheticLambda0.close() ((null):-1)
        at void org.agrona.CloseHelper.quietClose(java.lang.AutoCloseable) (CloseHelper.java:41)
        at void io.aeron.Aeron.<init>(io.aeron.Aeron$Context) (Aeron.java:107)
        at io.aeron.Aeron io.aeron.Aeron.connect(io.aeron.Aeron$Context) (Aeron.java:139)

Hope someone can help me.
Thank you so much.

A: Aeron is not currently supported on Android.


text:
Q: Handling errors inside Sinatra's configuration block What's an idiomatic way to handle errors inside Sinatra's configuration blocks?
For example, if an app fails to connect to the database inside the config, I would like to either communicate the error (halt) or show some specific error page (redirect)... But such methods aren't available in configure blocks.
configure do
    begin
        db = Sequel.connect ENV['HEROKU_POSTGRESQL_URL']
        db.test_connection
    rescue
        # Neither of these are available at `configure` block level
        halt 503, "Unavailable to connect to DB."
        redirect ("/custom-error-page")
    end
end

A: The configure block runs at server startup, so any client-faced operation such as halt or redirect makes no sense, because there is actually no user when that code runs.
I would just let the error bubble up and thus refuse to start the server when such things happen since it is very likely, that your application will be inherently broken when the configuration fails.


text:
Q: mouseDown, mouseup position in javascript I'm coding a small game in JavaScript, and am currently trying to change the direction of the snake using mousedown, dragging, and mouseup, using the following logic:

*

*x0 and y0, the position of mousedown

*x1 and y1, the position of mouseup

delta_x = x1 - x0
delta_y = y1 - y0

if (abs(delta_x) > abs(delta_y)) {
  if (delta_x > 0) {
    // gesture to the right
  } else {
    // gesture to the left
  }
} else if (delta_y > 0) {
  // to the down
} else {
  // … etc
}


text:
Q: How can I add multiple parameters to message.content? Need some help with my code. I started coding my first Discord bot today using Node.JS and the Discord.JS library, and others soon. I am currently using a YouTube video to guide me through Node.JS. Here's my question.
Here is my current code.
const Discord = require('discord.js');
const bot = new Discord.Client();

bot.on('message', (message) => {

    if(message.content == 'ping') {
        message.reply('pong');
    }

    if(message.content == 'xd') {
        message.reply('smh');
    }

});

This code works fine. If you go over to the second message.content, it has 'xd' written inside it. When I write the word xd in my Discord server, the bot will return smh. The problem with this is that the bot will only return smh when the capitalization is exactly like it is in xd, but I want it to work for all capitalization.
Like this.
    if(message.content == 'xd', 'xD', 'XD', 'Xd',) {
        message.reply('pong');
}

Obviously, the above code doesn't work, but is there any easy way to do this?
Cheers.

A: You can call .toLowerCase() on message.content to transform it to all lower case:
if (message.content.toLowerCase() == 'xd') {
  message.reply('pong');
}

This way the message's casing is practically ignored.

A: You need to lowercase the message.content using method toLowerCase() method then compare it with "xd string using === operator
ex:
if(message.content && message.content.toLowerCase() === 'xd') {
    message.reply("smh");
}

A: Before I answer the question, make sure hide your bot's token when sharing your source code because then people can use your bot to do some harmful stuff if it has the right permissions.
Okay so the answer:
At the very beginning, declare a variable called msg or something that stores message.content.toLowerCase();. So no matter how the person types it, it will always be lower case.
Be aware that it will only work if message.content is "xd" only so if a person type "xD something", this wouldn't work.
Additional stuff to your code:
If you want to check if a person used a certain prefix to signify a command, you can check if message.content.startsWith("prefix"); - this will return true or false.
It's always good to break down the content of the message into separate variables allowing you to easily do what you wanna do with the message, for example, a command and args variable (convert message.content into an array first).

A: There are 2 other main ways to allow for multiple parameters besides the  toLowerCase() function.
The first way would be to use the || operator or the or operator. This method allows for you to check for completely different words while being able to have the same outcome. For example:
if (message.content == "xd" || message.content == "xD" || message.content == "XD") {
     message.reply("Why would you do that");
}

The second way would be to use regular expressions like regexes. Regexes check for words inside strings by using the .test() method. For example:
let myRegex = /xd/i;
if (myRegex.test(message.content)) { //We are assuming that message.content = "XD"
   message.reply("smh");
}

This method works because the regex checks whether the word is equal to the regex it is assigned to. The i after the /xd/ means that it doesn't care about the casing so this is a shorter way to check for certain words without caring about letter case.

A: use toLowerCase on the content and then test it

if(message.content.toLowerCase() === 'xd') {
   message.reply('pong');
}

A: A better way todo this is have aliases...
//defined early on.
let commands = [
    {
        aliases:["xd","lol",":smile:"],
        run:function(msg){
            msg.send(`pong`);
        }
    },
    {
        aliases:[":("],
        run:function(msg){
            msg.send(`why the long face?`);
        }
    }
]
//later
client.on(`message`,function(msg){
    for(let i =0;i<commands;i++){
        if(commands[i].includes(msg.content.toLowerCase())){
            commands[i].run();
        }
    }
});

string.toLowerCase as answered above doesn't always work when you want multiple things to run the same command.
The code above allows aliases for every commands

A: you can use something like || to have multiple parameters.
In your case it would look like this
if(message.content == 'xd' || 'Xd' || 'xD' || 'XD') {
    message.reply('idk');
}

But in your case (because it is always the two same letters in the same order) you can simply add .toLowercase() and then the message will be treated as if it had only lowercase letters and you won't have to worry.
example:
if(message.content.toLowercase() === 'xd') {
    message.reply('idk');
}

However there's also a third option to have multiple parameters, you can simply use a constant (const)
example:
const 1 = [ "xd" , "lmao" , "lmfao" ]

if(message.content == 1) {
    message.reply('idk');
}

You can change "1" for info
Have a nice day :)
oh and thanks to the moderator that corrected me and sorry for my mistake.


text:
Q: split columns, extract numbers, and subtract difference Community! I have this following df
data = {'exp_lvl': ['5-10 yrs', '3-5 yrs', '1-3 Years']}
df = pd.DataFrame(data)

my goal is something like:

my approach is to 1. replace values , 2. split, 3. append to list, 4. build columns from the appended lists. However i'm stuck in the last step and maybe there is a easier way to approach
thansk so much!!!

A: Here is another way:
df.join(df['exp_lvl'].str.extractall(r'(\d+)')[0]
 .unstack()
 .rename({0:'first',1:'second'},axis=1)
 .astype(float)
 .assign(diff = lambda x: x['second'] - x['first']))

or
(df.join(
    df['exp_lvl'].str.extract(r'(?P<first>\d+)-(?P<second>\d+)')
    .astype(int)
    .assign(difference = lambda x: x['second'] - x['first'])))

Output:
     exp_lvl  first  second  difference
0   5-10 yrs      5      10           5
1    3-5 yrs      3       5           2
2  1-3 Years      1       3           2

A: Use pandas str.split to construct column first and second. Next, compute to get column different
df[['first', 'second']] = df.exp_lvl.str.split('-| ').str[:2].tolist()
df['difference'] = df['second'].astype(int) - df['first'].astype(int)

Out[103]:
     exp_lvl first second  difference
0   5-10 yrs     5     10           5
1    3-5 yrs     3      5           2
2  1-3 Years     1      3           2

A: Another way:
df[['first', 'second']] = df.exp_lvl.str.extract(r'(\d+)-(\d+)')
df['difference'] = df['second'].astype(int) - df['first'].astype(int)

A: This was not hard.  Just mechanical.  Did you make any effort?
data = {'exp_lvl': ['5-10 yrs', '3-5 yrs', '1-3 Years']}

data['first'] = []
data['second'] = []
data['difference'] = []
for row in data['exp_lvl']:
    parts = [int(i) for i in row.split(' ')[0].split('-')]
    data['first'].append( parts[0] )
    data['second'].append( parts[1] )
    data['difference'].append( parts[1]-parts[0] )

print(data)
import pandas as pd
df = pd.DataFrame(data)
print(df)

Output:
C:\tmp>python x.py
{'exp_lvl': ['5-10 yrs', '3-5 yrs', '1-3 Years'], 'first': [5, 3, 1], 'second': [10, 5, 3], 'difference': [5, 2, 2]}
     exp_lvl  first  second  difference
0   5-10 yrs      5      10           5
1    3-5 yrs      3       5           2
2  1-3 Years      1       3           2

C:\tmp>


text:
Q: How to override a fullscreen game with keywindow borderless window (overlay)? I've created the app which sometimes shows up an overlay with label and textbox. It works nice, but I need it to work even with other apps are in full-screen mode and active.
For overlay, I've create custom window class and overridden canBecomeKeyWindow method to let borderless window become the key window (simply returns YES).
So it works, but when I run e.g. Minecraft, and then make it full screen, my overlay can override it. But I can't type in NSTextField in the overlay. How to fix it?
I'm creating an overlay like this:
[[NSWorkspace sharedWorkspace] hideOtherApplications];
NSRect frame = [[NSScreen mainScreen] frame];
_fadedWindow = [[CustonWindow alloc] initWithContentRect:frame
                                           styleMask:NSBorderlessWindowMask
                                             backing:NSBackingStoreBuffered
                                            defer:NO];
[_fadedWindow setAcceptsMouseMovedEvents:YES];
[_fadedWindow setOpaque:NO];
[_fadedWindow setLevel:CGShieldingWindowLevel()];
[_fadedWindow setBackgroundColor:[NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.8]];
NSApplicationPresentationOptions options = NSApplicationPresentationDisableProcessSwitching + NSApplicationPresentationHideDock + NSApplicationPresentationDisableForceQuit + NSApplicationPresentationDisableSessionTermination + NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
_fadedWindow.alphaValue = 0;
[_fadedWindow orderFrontRegardless];
[[_fadedWindow animator] setAlphaValue:1];
[_fadedWindow toggleFullScreen:self];
[_fadedWindow makeKeyAndOrderFront:self];
[NSApp activateIgnoringOtherApps:YES];
[_fadedWindow orderFront:self];

But still, I can't seem to populate overlay's NSTextField with keyboard input.

A: Try this. Create a subclass for _fadedWindow. Then put this in:
-(BOOL)canBecomeKeyWindow {
    return YES;
}


text:
Q: How to send pl/sql procedure status through an email? I have scheduled a PL/SQL procedure. I want to send the status of the PL/SQL procedure (whether it is successful or has any error messages) to my email address.
I saw some ways of sending pre-defined templates of emails using UTL_MAIL. But how can I get the status of my procedure into an email?

A: Send an e-mail at the end of the scheduled stored procedure, e.g.
create or replace procedure p_your_proc as
  l_error varchar2(300);
begin
  -- do some processing

  -- if there were no errors
  utl_mail.send(sender     => 'rosh@gmail.com',
                recipients => 'rosh@gmail.com',
                cc         => null,
                bcc        => null,
                subject    => 'Procedure P_YOUR_PROC completed successfully',
                message    => null);

exception
  when others then
  l_error := sqlerrm;
  utl_mail.send(sender     => 'rosh@gmail.com',
                recipients => 'rosh@gmail.com',
                cc         => null,
                bcc        => null,
                subject    => 'Procedure P_YOUR_PROC ended with an error',
                message    => l_error);
  raise;
end;


text:
Q: Custom training phrase for Windows 7 speech recognition? Windows 7 speech recognition requires speaking the following training phrase before it can be enabled:
"Peter dictates to his computer. He prefers it to typing, and particularly prefers it to pen and paper."
I want to use Windows speech recognition to batch process a large number of MP3 files of lectures by a single individual. So what I would like to do is pick a similar phrase from these pre-existing dictations and use the phrase I choose to train it, instead of the built-in training phrase.
Mainly because I don't have a recording of the speaker saying "Peter dictates to his computer. He prefers it to typing, and particularly prefers it to pen and paper." but I have 50 hours of him saying lots of other things.
Is this possible?

A: use the api for the speech recognition tool, the person in Acoustic training using SAPI 5.3 Speech API had the same question as you, probably


text:
Q: Condition for a lattice to be distributive This is part of Exercise III.1.16(c) of Bourbaki's set theory.
Let $E$ be a lattice. The condition
$(x\vee y)\wedge(z\vee(x\wedge y))=(x\wedge y)\vee(y\wedge z)\vee(z\wedge x)$
for all $x,y,z\in E$ implies that $E$ is distributive.
I already know that
$(x\vee y)\wedge(y\vee z)\wedge(z\vee x)=(x\wedge y)\vee(y\wedge z)\vee(z\wedge x)$
implies distributivity, so it suffices to prove
$(x\vee y)\wedge(z\vee(x\wedge y))=(x\vee y)\wedge(y\vee z)\wedge(z\vee x)$.
I can't find a proof of this last statement. Either it is true in any lattice, then the proof should be so simple I must be blind not to see it, or I have to use the condition above again, but I can't imagine in what way.

A: $(x\vee y)\wedge(z\vee(x\wedge y))=(x\wedge y)\vee(y\wedge z)\vee(z\wedge x)$
implies
$x\vee((x\vee y)\wedge(z\vee(x\wedge y)))=x\vee((x\wedge y)\vee(y\wedge z)\vee(z\wedge x)).$
The right side equals $x\vee(y\wedge z)$.
For the left side, we use the condition above again, substituting $x\vee y$ for $y$ and $z\vee(x\wedge y)$ for $z$, and get
$x\vee((x\vee y)\wedge(z\vee(x\wedge y)))=(x\vee y)\wedge((z\vee(x\wedge y))\vee x)=(x\wedge y)\vee(x\wedge z).$


text:
Q: dev tools console: don't show path in the links of console messages? Is it possible to make chrome dev tool's console shorten the source code link by only showing the base file name and line number without the whole path?
--BobG


text:
Q: Activate accordion from image map I'd like to open an accordion from an image map of four internet browsers. So if someone clicks on Firefox, it opens the accordion under the Firefox section. Currently, if someone clicks on one of the four browsers in the image map, it will jump them to the link in the accordion, but it doesn't open. They then have to click on the link themselves.
I tried the first instruction on this page, but I couldn't get it to work. I'm new with javascript so it's possible it's just user error. Any help is much appreciated.
Here's the HTML

<button class="accordion">Internet Explorer</button>

Lorem ipsum dolor sit amet...

<button class="accordion">Firefox</button>

Lorem ipsum dolor sit amet...

<button class="accordion">Chrome</button>

Lorem ipsum dolor sit amet...

<button class="accordion">Safari</button>

Lorem ipsum dolor sit amet...

`

THE MAP

    <map name="Map">
    <area shape="rect" coords="13,11,82,86" href="#IE" target="_self" alt="Internet Explorer">
    <area shape="rect" coords="104,12,176,85" href="#Firefox" target="_self" alt="Firefox">
    <area shape="rect" coords="198,12,269,85" href="#Chrome" target="_self" alt="Chrome">
    <area shape="rect" coords="288,13,360,83" href="#Safari" target="_self" alt="Safari">
    </map>

THE SCRIPT

A: You can add the onclick attribute to the shapes in the image map.

    <map name="Map">
    <area onclick="activateAccordion('IE')" shape="rect" coords="13,11,82,86" href="#IE" target="_self" alt="Internet Explorer">
    <area onclick="activateAccordion('Firefox')" shape="rect" coords="104,12,176,85" href="#Firefox" target="_self" alt="Firefox">
    <area onclick="activateAccordion('Chrome')" shape="rect" coords="198,12,269,85" href="#Chrome" target="_self" alt="Chrome">
    <area onclick="activateAccordion('Safari')" shape="rect" coords="288,13,360,83" href="#Safari" target="_self" alt="Safari">
    </map>


text:
Q: Bootstrap 4 card/panel with image left of header and title I thought what I'm trying to do would be pretty easy to do but I just can't make it work.
I tried to do pull-left on bootstrap cards and panels and it's not working the way I want it to...
Here is a picture of what I'd like to acheive
Example
Heres code that almost works

        Title

Title

Description

        BUTTON

        FOOTER

A: HTML:

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

        Last updated 3 mins ago

CSS:
.card-horizontal {
  display: flex;
  flex: 1 1 auto;
}

Result:

A: There are a few different ways you could do this. Here's one way using the  flex-row and flex-wrap utility classes to change the layout of elements inside the card...
https://www.codeply.com/go/l1KAQtjjbA

Title

Description

            BUTTON

            FOOTER

Here's another approach using the grid...

Title

Description

                    BUTTON

            Footer stating cats are CUTE little animals

https://www.codeply.com/go/l1KAQtjjbA
I'm not sure why you have text-center as nothing it centered in the desired example image.

A: Keep in mind that the class pull-left is now float-left in Bootstrap version 4.


text:
Q: Use residuals of regression to calculate another regression (inside function) in R I'm using a function to calculate regressions. I need the residuals a relationship to relate to another variable.
This is because I change the facet grid several times.
This is my code:
modelregression = function(file) {
mod2 = lm(y ~ x,data=file)
mod = lm(mod2$residuals ~ anotherX,data=file)
mod_sum = summary(mod)
formula = sprintf("y= %.3f %+.3f*x",
                coef(mod)[1], coef(mod)[2])
r = mod_sum$r.squared
r2 = sprintf("r2= %.3f", r)
x  = cor.test(~mod2$residuals + anotherX,data=file)
r0 = sprintf("r= %.3f", x[4])
p1 = pf(mod_sum$fstatistic[1],mod_sum$fstatistic[2],mod_sum$fstatistic[3],lower.tail=F)
p =sprintf("p = %.3f", p1)
n0 = length(mod_sum$residual)
n1 = sprintf("N = %.f", n0)
data.frame(formula=formula, r=r0,r2=r2, p=p,n=n1, stringsAsFactors=FALSE)
}

modelregression_math = ddply(file, c("database","level"), modelregression)

The it runs without any problem, but all coefficients are zero. How can I fix this?

A: You need the residuals to reside "inside" what is specified by data=.
Thus, insert a line like the follwing before running the second regression:
file <- cbind(mod2$residuals, file)

However, this will only work if the lines in file will match the order and amount of lines in what is used for the 1st regression. If you have missing values, it gets more complicated: Use mod2$model to get exactly the data used in the regression (also in the right order) and combine that with the residuals:
data_with_residuals <- cbind(mod2$model, mod2$residuals)
mod = lm(residuals ~ anotherX, data=data_with_residuals)

(Or an approach with merge() could do the trick.)


text:
Q: How to List all the Home Screen Folder for Android I know we can get all the installed apps from packagemanager.
Is there a way to get a list of folders created by users on Home Screen?
Also, how can we know which apps in which folder?!

A:
Is there a way to get a list of folders created by users on Home Screen?

No. For starters, not all home screens have the concept of "folders".


text:
Q: Are these definitions equivalent? In the book "Essential Linear Algebra with Applications", written by Titu Andreescu, there is the following definition:

As you can see, at the bottom of the image appears the symbol $\cdot$ about which nothing is said. Since I was creating notes about the section where this definition is, I decided to "formalize" this definition by doing the following:
Let $F$ be a field. We define an binary operation $\cdot:M_{m,n}(F)\times F^n\to F^m$ such that for $A=[a_{ij}]\in M_{m,n}(F)$ and $X=[x_i]\in {F^n}$ we have that $A\cdot X=Y\in F^m$ in which $Y=[y_i]$ with $y_i=\sum_{k=1}^na_{ik}x_k$. We obtain therefore a map $F^n\to F^m$ which sends $X$ to $A\cdot X$.
Although the definition I made seems to make sense, I'm afraid that this definition does not make sense. Since I intend to continue using the definition above, I would like to know if it is equivalent to that of the book and if it is correct taking into account the already known properties of the multiplication between matrix and vector.

A: Yes, it is correct. Note that the operation mentioned by Titu Andreescu is simply the product of two matrices, in a case in which the second matrix has a single column.


text:
Q: Class not registered (Explorer.exe) on Windows Server 2008 via Remote Desktop I've got my local disks set to be accessible from remote connected Windows Server 2008.
When I open some location in the Windows Explorer, after some time or after re-connecting that location and all its contents become unavailable and when I try to navigate to a parent location I receive an error that says Class not registered.
I'm okay with that but how can I create a shortcut to that location without having to open folder by folder each time the location becomes unavailable?
I tried adding the location to favorites but it doesn't work unless I navigate to the desired folder all the way from root.

A: Actually, mapping the location as a network drive resolved the issue.


text:
Q: obiee 11g using catalog manager to extract layout and views of an analyse i am using obiee 11g and I want to extract some documentation out of the catalog manager. I explain. I have some analyse with some views I added like for example a title and a static text. I renamed those views to documentation. Now I want to extract for each analyse those two views. I thought I could do that with the catalog manager and the tool>extract report like I saw some examples here.
The problem is that I don't find how I can extract the view or compound layout with the catalog manager.

A: You can archive and unarchive  the analysses and dashboards etc..
And unarchive to anywhere or any server you have the same Model ...
Go to catalog, select your analysis, archive , and unarchive ll be at down left corner:


text:
Q: LINQ's SelectMany Equivalent in OData I have an entity called AccountAction that has property called TransactionTypes that is an ICollection of TransactionType entities.
I return a list of all the TransactionTypes that are related to all the AccountActions in a method called GetTransactionTypes. I would like to apply query options to the returned list of TransactionTypes. However, so far I have hit a wall because all of the query options are applied to AccountActions.
Is there any way I can apply query options in the URL to the returned lists of TransactionTypes? In other words, is there a way I can do a SelectMany from the URL to get the TransactionTypes related to the AccountActions to move on to apply the query options to the found TransactionTypes?
Below is an extract of the code that I am using.
[Route(FullControllerPath + "/TransactionTypes")]
public IHttpActionResult GetTransactionTypes(ODataQueryOptions<AccountAction> queryOptions, bool addCols, int? skip, int? take)
{
    using (AccountActionManagement _accountActionManage = new AccountActionManagement(this.GenerateInformation()))
    {
        _accountActionManage.SetTraslationList("DATASTRUCT-CONFIG-ACCOUNTACTIONTRANSACTIONTYPE", language);

        // Query composition
        IQueryable<TransactionType> query = queryOptions.ApplyTo(_accountActionManage.GetTypeAsQueryable<AccountAction>())
                                                        .OfType<AccountAction>()
                                                        .SelectMany(aa => aa.TransactionTypes)
                                                        .Include(tt => tt.AccountActionForDefaultTransactionType.DefaultTransactionType);

        var queryData = query.Select(tt => new
                        {
                            Id = tt.Id,
                            Name = tt.Name,
                            Operation = tt.Operation,
                            Type = tt.Type,
                            Default = tt.AccountActionForDefaultTransactionType != null &&
                                      tt.AccountActionForDefaultTransactionType.DefaultTransactionType.Id == tt.Id,
                            Version = tt.AccountActionForDefaultTransactionType.Version
                        });
        // Get count
        int totalRows = queryData.Count();

        // Get biggest version in query
        var maxVersion = queryData.Max(i => i.Version);

        // Get data from database
        var queryResult = queryOptions.OrderBy == null
                              ? queryData.OrderBy(i => i.Id)
                                         .Skip(skip ?? 0)
                                         .Take(take ?? totalRows)
                                         .ToList()
                              : queryData.Skip(skip ?? 0)
                                         .Take(take ?? totalRows)
                                         .ToList();
...}}

As seen in the diagram below, AccountAction has a many-to-many relationship to TransactionType. AccountAction has the first role and TransactionType has the second role.

A: I found a workaround for this issue. I realized that I was not passing the right type to the ApplyTo method. Now, I apply the query options to an IQueryable of TransactionTypes instead of applying the query options to an IQueryable of AccountActions.
Below is the code with the described modification. Also, a diffchecker of the change I made is here.
[Route(FullControllerPath + "/TransactionTypes")]
public IHttpActionResult GetTransactionTypes(ODataQueryOptions<AccountAction> queryOptions, bool addCols, int? skip, int? take)
{
    using (AccountActionManagement _accountActionManage = new AccountActionManagement(this.GenerateInformation()))
    {
        _accountActionManage.SetTraslationList("DATASTRUCT-CONFIG-ACCOUNTACTIONTRANSACTIONTYPE", language);

        // Query composition
        IQueryable<TransactionType> query = queryOptions.ApplyTo(_accountActionManage.GetTypeAsQueryable<AccountAction()
                               .SelectMany(aa => aa.TransactionTypes)
                               .Include(aa =>      aa.AccountActionForDefaultTransactionType.DefaultTransactionType))
                               .OfType<TransactionType>();

        var queryData = query.Select(tt => new
                        {
                            Id = tt.Id,
                            Name = tt.Name,
                            Operation = tt.Operation,
                            Type = tt.Type,
                            Default = tt.AccountActionForDefaultTransactionType != null &&
                                      tt.AccountActionForDefaultTransactionType.DefaultTransactionType.Id == tt.Id,
                            Version = tt.AccountActionForDefaultTransactionType.Version
                        });
        // Get count
        int totalRows = queryData.Count();

        // Get biggest version in query
        var maxVersion = queryData.Max(i => i.Version);

        // Get data from database
        var queryResult = queryOptions.OrderBy == null
                              ? queryData.OrderBy(i => i.Id)
                                         .Skip(skip ?? 0)
                                         .Take(take ?? totalRows)
                                         .ToList()
                              : queryData.Skip(skip ?? 0)
                                         .Take(take ?? totalRows)
                                         .ToList();
...}}


text:
Q: What is the maximum storage capacity for kubernetes PersistentVolumes Here is an example of .yml file to create an PersistentVolume on a kubernetes cluster:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: task-pv-volume
  namespace: prisma
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: xxGi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/data"

Can the storage capacity be more than the available storage capacity on the node with the smallest disk in the cluster? Or the maximum is the sum of available disk on the cluster nodes ?

A: generally you are binding the pv to an external storage volume your cloud provider offers (for example - aws EBS), abstracted as a StorageClass, in a size that matches your needs. cluster nodes come and go, you shouldn't rely on their storage.
quick guides: gcp aws azure

A: The hostPath mode is intended only for local testing so the requested size does absolutely nothing I'm pretty sure.


text:
Q: usar PHPMailer sin configurar SMTP Buenas, estoy tratando de configurar phpmailer por primera vez. Me ha funcionado a la perfección por las guías que he leído, pero no he conseguido una manera de enviar el correo sin usar SMTP.
Quisiera saber si existe una forma de usarlo de esta manera, ya que me gustaría que cuando lleguen los correos, donde dice "DE:" aparezca el correo de quien lo envió.
Aqui mi codigo:
<?php
require("class.phpmailer.php");
require("PHPMailerAutoload.php");
$mail = new PHPMailer();

// VARIABLES
$name = $_POST["name"];
$email = $_POST["mail"];
$message = $_POST["message"];
$emailTo = "correo@gmail.com";
$subject = $_POST["subject"];

//SMTP
//$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->Username = 'correo@gmail.com';
$mail->Password = 'xxxxxx*';
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;

// ENCABEZADO
$mail->setFrom($email, $name);
$mail->addAddress($emailTo, $name);
$mail->Subject = $subject;

// MENSAJE
$mail->Body = $message;

// ENVIAR MENSAJE
if ($mail->send()) {
    echo "<script type='text/javascript'>
            alert('Enviado Correctamente');
          </script>";
} else {
    echo "<script type='text/javascript'>
            alert('No enviado, intentar de nuevo');
          </script>";
}

?>

A: Puedes mandar correos usando la función mail de php.
En la propia página del PHPMailer hay un ejemplo:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('myfriend@example.net', 'My Friend');
$mail->Subject  = 'First PHPMailer Message';
$mail->Body     = 'Hi! This is my first e-mail sent through PHPMailer.';
if(!$mail->send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}


text:
Q: Particle in a box as easy model for molecules I am trying to use the particle in a box model as a simplified model to calculate the energy difference between HOMOs and LUMOs of a molecule.
The molecule I work with is made out of n phenyl-groups. Displayed in the picture below.

Now thinking of a particle in a 1-D box, the approx. energy difference between a HOMO and LUMO is described as
$$
\Delta E = \frac{h^2(N+1)}{8m_eL^2}
$$
where N is the amount of $\pi$-electrons in the molecule and L the length of the box. The length of the box as well as the number of $\pi$-electrons depends on the number of phenyl-groups (n). I know how I can get the length of such a molecule, but how can I get the amount of $\pi$-electrons?


text:
Q: iOS - Dismissing view controller itself through delegate work once I present customViewController and trying to dismiss itself through delegate. It works only for the first time. When I presentCustomViewController again, view controller appears but it cannot dismiss itself. But when I try to dismiss it via button it works every single time. Could you tell me what's the reason?
- (void)presentCustomViewController {
    CustomViewController *customViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"CustomViewController"];

    customViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    customViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    customViewController.delegate = self;

    [self.window.rootViewController presentViewController:customViewController animated:YES completion:nil];
}

#pragma mark - CustomViewController

@implementation CustomViewController {
    NSURLSession *backgroundSession;
    NSURLSessionDownloadTask *downloadTask;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    backgroundSession = nil;
    self.mailComposeViewController = nil;
    self.documentInteractionController = nil;

    [self startDownload];
}

- (void)startDownload {
    NSURLSessionConfiguration *backgroundConfigurationObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"myBackgroundSessionIdentifier"];
    backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfigurationObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    downloadTask = [backgroundSession downloadTaskWithURL:[NSURL URLWithString:_attachment.url]];
    [downloadTask resume];
}

- (IBAction)cancelButtonClicked:(id)sender {
    [downloadTask cancel];

    self.mailComposeViewController = nil;
    self.documentInteractionController = nil;

    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - CustomViewControllerDelegate

- (void)viewController:(CustomViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];

    NSLog(@"%@, %d", viewController, [viewController isBeingDismissed]);
 }

Logs:
<CustomViewController: 0x100691390>, 1
<CustomViewController: 0x100691390>, 0


text:
Q: How do I edit the legend title and labels? First post so hopefully I've included everything.
I'm trying to do two things on the below charts:

*

*Change the legend title from z,z1,z2 to POS, ROD, INS

*Change the legend labels all to AOK and TUR

I've been trying to find the answer all day and so far nothing has worked.

My data is:
Year Area   Percentage
  <dbl> <fct>       <dbl>
1  2008 AOKPOS      0.571
2  2008 AOKPOS      0.6
3  2008 AOKPOS      0.5
4  2008 AOKPOS      0.846
5  2008 AOKPOS      0.2
6  2008 AOKPOS      0.625

My code is:
plot1 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), size=1)

plot1

plot2 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1)

plot2

plot3 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1)

plot3

grid.arrange(plot1, plot2, plot3, nrow=3)

A: I don't know how you want to change it but
you can use labs() function to do that like so
#Default plot
print(p)

#Modify legend titles
p + labs(fill = "Dose (mg)")

after using the code the title is change like this

A: Ok, so shortly after posting I managed to figure it out:
    plot1<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), name = "Possum",size=1)

plot1<- plot1 + scale_color_discrete(name="Pos", label=c("Aok","Tur"))

plot1

plot2<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1)

plot2<- plot2 + scale_color_discrete(name="Rod", label=c("Aok","Tur"))

plot2

plot3<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1)

plot3<- plot3 + scale_color_discrete(name="Ins",label=c("Aok","Tur"))

plot3

grid.arrange(plot1,plot2,plot3, nrow=3)


text:
Q: Cost-benefit analysis
Let's say I have a set of data points which represents the cost and the benefit, for each data point. The entire curve is represented in the chart above by the solid blue line.
What I am trying to figure out is which point on that solid blue line is "optimal", in a sense that you get maximum benefit for the lowest cost. One would think that it would be the point where the benefit/cost ratio is maximized, but this would not make sense, as it would place you infinitely close to the point [0,0]. That's because the shape of the blue line is such that you get progressively less and less benefit for any additional units of costs.
Intuitively, it feels that the "optimal" point would be somewhere in the middle section of the blue curve. I've identified two such points:

*

*Point B (marked with the red cross): this one minimizes the distance between the "nirvana" point A, and the curve. That is, I want to be as close as possible to the "nirvana", which happens to be distance |AB|.

*Point D (marked with the green cross): this one maximizes the distance between the "indifference" line (solid black diagonal line), and the blue curve. That happens to be distance |CD|.
I've selected both points intuitively, as they both make sense to me. But which one makes more theoretical sense? If not points B and D, is there some well known, established methodology for finding the "optimal point" on a given curve where you want to accomplish a dual objective: minimize X and maximize Y?
Thanks.

A: Note that the cost and benefit axes have both been scaled from $0$ to $1$, so the upper right just represents maximum cost and maximum benefit.  It says nothing about whether the benefit exceeds the costs or not at that point.  This graph is not sufficient to determine whether any money should be spent at all.
On the silly assumption that the scales are the same and at the upper right the cost equals the benefit, the vertical segment CD represents the maximum profit that can be made.  By spending $0.46$ we get benefit of $0.70$ for a profit of $0.24$.  If the budget is not constrained this is an optimum point.  As you point out, the relative profit is highest at the low end.  We could spend $0.1$ and get $0.2$ benefit for a profit of $0.1$   If we have five projects like this one, we could spend our $0.46$ spread across them and get a profit of $0.46$ or so, which is preferable to spending all the $0.46$ on one alone.
There is nothing special about point B.


text:
Q: add_post_meta Multi value not working when i try to add them using loop At WordPress, I use a loop to add multiple meta values at a meta field. But every time it adds the lat value.
Here is my code:
$value = array("red", "green", "yellow")
foreach ( $value as $item ) {
    add_post_meta( $post_id, "_color", $item );
}

Every time after saving it save only yellow.
NOTE: This code works on my server but when I try to a client-server, it is behaving like this.
Wordpress Version: 4.7
Please help me.

A: Lets try by adding fourth parameter as "false".
add_post_meta( $post_id, "_color", $item, false );

I know, the fourth parameter is 'false' by default, but lets try it once, because your value is overwritten every time by the same key, therefore it is storing the last value i.e. "Yellow".

A: check this code:
$post_id = $post->ID;
add_post_meta($post_id, 'counter_meta', 'XYZ');
$return = get_post_meta($post_id, 'counter_meta', true );
echo '<pre>';
print_r($return);
exit();

A: Please try this
$post_id = 12;
$value = array("red", "green", "yellow")
foreach ( $value as $item ) {
    add_post_meta( $post_id, "_color", $item );
}


text:
Q: Can phpunit start with a certain test and then keep going? I use stopOnFailure in phpunit.  Just my preference.  I'm wondering if there is a way to isolate 1 test and run it, like --filter but then keep going.  So that if my test suite finds a failure half way thru all the tests ... I just want to pick up where I left off when I'm done isolating and fixing.
(Not looking for solutions like paratest)

A: No. But you can configure PHPUnit to start the execution with tests that failed the last time: --order-by=defects.


text:
Q: pretty faces configuration to remove folder from URL (JSF2.2 application deployed on Glassfish) I have JSF 2.2 application deployed on glassfish.
I wan't to beautify the URL

http://MyWebsite/test/SOMEFOLDER/login.xhtml

to be

http://MyWebsite/test/login.xhtml

I am using pretty faces using the follow configuration
<url-mapping id="login">
  <pattern value="/login.xhtml" />
  <view-id value="/SOMEFOLDER/login.xhtml" />
  <!-- Non JSF View Id -->
</url-mapping>

I am not adding anything in the web.xml


text:
Q: PyQt5 does not loop the video in RaspberryPi I'm developing a screen for an application that will loop a video until there is a touch event on the screen. The event to detect the touch is working, but the video only runs once and then goes to black screen.
I'm developing in python, on windows the application makes the video loop correctly but when I migrate to the raspberry pi 4 environment, the video is only played once.
I would like to understand if there is something I am missing, some library, some incorrectly applied function...
Here's code:
class Video_Screen(QWidget):

    def change_first_screen(self):
        thread.screen.emit(1)

    def __init__(self,parent=None):

        super(QWidget,self).__init__(parent)
        filename = ""
        if(os.environ['SYSTEM'] == "RASPBIAN"):
            filename = diretorio+'/RaspberryPi/'+os.environ['VIDEO_FILENAME']
        else:
            filename = diretorio+'\\RaspberryPi\\'+os.environ['VIDEO_FILENAME'].replace('/','\\')

        self.playlist = QMediaPlaylist()

        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(filename)))
        self.playlist.setPlaybackMode(QMediaPlaylist.PlaybackMode.Loop)

        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setPlaylist(self.playlist)

        videoWidget = QVideoWidget()

        self.mediaPlayer.setVideoOutput(videoWidget)

        self.mediaPlayer.play()

        main = QVBoxLayout()
        main.addStretch(1)
        main.addWidget(videoWidget)
        main.addStretch(1)
        self.setLayout(main)

    def mousePressEvent(self, event):
        self.change_first_screen()

The following libraries are installed on the raspberry pi:
sudo apt-get install libqt5multimedia5-plugins python3-pyqt5.qtmultimedia python3-pip python3-pyqt5 -y

I tried a few different approaches like detecting when the video ends and setting the position to 0, or signal detecting when the video ends to trigger play again, but nothing worked.
Expectation is to get the video running in loop, the video is in .avi format.


text:
Q: What char to escape for html input pattern???, I can't for the life of me find a list of chars to escape. So first question, where can I find a list of chars to escape for HTML5 input pattern.
Because, and this is my 2nd question, I cannot find a way for this pattern to work
pattern="[a-zA-Z0-9_\-!\?\#]{6,}"

What do I need to escape. Please full list if you can.


text:
Q: How do I go about debugging Varnish not starting correctly? I'm attempting to run Varnish, but it seems that a child process is dying on startup.  Can anyone suggest the best way for me to go about debugging what's going wrong?
Background
I have a raspberry pi on which I'd installed Debian, which was running varnish fine.
Recently, I decided to install Raspbian (An OS based on Debian, but optimised for the raspberry pi).  To do this, I did a fresh install and used puppet to make sure that I had all the same settings as I did previously.
The only substantial difference between the two setups I can think of is that Raspbian uses a later version of Debian (Wheezy) than I had been using previously (Squeeze), so came with Varnish 3, rather than 2.
Debugging attempts so far:
I looked in /var/logs/syslog and found the following:
Sep 21 22:26:28 interceptor varnishd[15056]: Platform: Linux,3.1.9+,armv6l,-smalloc,-smalloc,-hcritbit
Sep 21 22:26:28 interceptor varnishd[15056]: child (15064) Started
Sep 21 22:26:28 interceptor varnishd[15056]: Pushing vcls failed:#012CLI communication error (hdr)
Sep 21 22:26:28 interceptor varnishd[15056]: Stopping Child
Sep 21 22:26:28 interceptor varnishd[15056]: Child (15064) died signal=11
Sep 21 22:26:28 interceptor varnishd[15056]: Child (-1) said Child starts
Sep 21 22:26:28 interceptor varnishd[15056]: Child cleanup complete
Sep 21 22:26:28 interceptor varnishd[15056]: Manager got SIGINT

I tried googling for the error, but couldn't find anything useful.
I also ran strace -f whilst restarting varnish, but obviously that returned a lot of output and I wasn't sure what to look for.  I grepped for the pid of the child process (15064), but that didn't seem to match anything.
The strace did contain lots of lines like
[pid 15114] close(131072)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131071)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131070)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131069)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131068)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131067)               = -1 EBADF (Bad file descriptor)
[pid 15114] close(131066)               = -1 EBADF (Bad file descriptor)

but I'm not sure if this is normal or perhaps a result of my problem, rather that its cause.
Any advice on how I should proceed is much appreciated.

A: The best output on failures during start is to stdout/stderr - but the default init scripts stop this output from being displayed.
Try running just varnishd -f /etc/varnish/default.vcl - this should show you any errors in loading your VCL.

A: Try attaching running varnish with some very simple flags:
varnishd  -l 8m  -s file,/tmp,8m -b localhost:8080 -a 0.0.0.0:80 -w 2
and then attach the gdb debugger and see if you can find out why the child is segfaulting


text:
Q: Trig modeling - population A population drops from 200,000 in 1950 to 76,000 in 1996, and has risen since then. Taking into account that the population follows a sinusoidal cycle affected by environmental conditions and predation, and the population will reach its previous high again, what is a possible sinusoidal formula to describe the population as a function of time in years?
So far, I have
let t=0 in 1950
A(t)= 200,000(r)^t
I'm not sure how to factor in the sinusoidal cycle part.

A: Suppose that the maximum value is $200$ (in thousands), and the minimum is $76$ (in thousands). Then we want an amplitude of $\frac{200-76}{2}$. We really want a period of $2\cdot46$ (max/min occurs at half the period), and so the coefficient of $t$ set as $\frac{2 \pi}{2 \cdot 46}$ satisfies this. A cosine function will work well here. What we have so far is
$$\frac{(200 - 76)}{2}\cos\left(\frac{2\pi}{2\cdot46} t\right).$$
Now we need to add a constant, because this thing has a peak at $\frac{200-76}{2}=62$. We want it to peak at $200$, and so we add $138$, and end with
$$f(t)=\frac{(200 - 76)}{2}\cos\left(\frac{2\pi}{2\cdot46} t\right)+138.$$
Here is a plot of that effect:

A: Hint:

So if the period of the $y=cos({2x\pi\over t})$ is $t$, what do you need the period of your function to be? How far horizontally do you need to shift your function? How far vertically? How much do you need to scale it?


text:
Q: Link Lookup Table to Account Name Field In CRM Online I need to link the Account Name field in the Account entity to a lookup table of imported and approved company names.  The goal is to require users to pick from an approved list instead of letting them make up a company account name.   I know there is an Account Name lookup in Contacts which uses existing Account Name records, but I need the lookup in the Account entity.  Thanks for any tips.

A: CRM renders a Lookup control for a 1:N relationship. What you are trying achieve would fall more into a data validation scenario where users can enter account names from a pre-set list of names.
You can leverage a new event introduced in CRM 2016 - addOnKeyPress which can be easily used to build an autocomplete  feature which would be more inline with what you are trying to achieve. If a user doesn't "pick" a value instead types anything in disregarding the autocomplete use attribute control's setNotification to set an error message which would invalidate the save preventing the user from saving the record.

A: If you are referring to a different entity as LookupTable, then create a relationship between Account ans the Lookup Table entity. After that you can use that entity as Lookup attribute in Account entity


text:
Q: How do I make DbContext in using statement work with unit tests? The situation I have is this:

*

*I am working on an ASP.NET MVC project that does not implement the repository pattern

*All DbContext calls are made from the controller layer

*DbContext is wrapped in a using statement and instantiated as necessary for memory management purposes NOT connection pool purposes

*We need to unit test these controllers, which means injecting the DbContext into the controller.

*We are not using an IoC container. I would have to create a new instance in a parameter-less constructor and use that for the life of the call to the controller's action.

*I cannot change most of these conditions.

Conditions I can change:

*

*Get rid of the using statement, if a reliable option can take its place.

*Admit this code is just not testable as-is and move on to spending energy elsewhere.

So, my question is this: how do I pass in a DbContext to the constructor so I can mock the responses being returned, but maintain the reliability of the using statement, as these tend to contradict each other.
I'm ok if I need to stop using the using statement, as long as there is a way to ensure that the context is disposed every time when it is done performing the requested action.
Any thoughts on this one?

A: Constructing a DbContext inside a method you'd like to test is no different than instantiating any other concrete instance of a dependency within the code, it means you cannot test with a mocked dependency. So the immediate options that come to mind are (without code/structure changes):

*

*Implement an in-memory data provider to point EF at for the unit tests.

*Set up a known-state database that can be restored between test runs. (More of an integration test, not well suited to TDD where you want tests that can run very quickly, very often.)

*Put it in the "wasn't designed for unit testing" bucket due to lack of DI/IoC

Mocking a DbContext is messy, but do-able. Once you have one mock-able I would recommend adding an IoC container like Autofac into the project. I don't know the circumstances that would prevent you from introducing an IoC container, but if the team is worried about it being an all-or-nothing re-factor and too big of a job, then I'd reassure them that it can be added with minimal changes to the project and in a way that does not break existing code. Aside from the DbContext, if the code isn't using DI/IoC Container, how do you plan to handle other concrete dependencies? You don't have to switch out all dependencies/controllers in one go, but improve them incrementally.
Once a container is set up to resolve MVC Controllers, existing controllers with default constructors will not be affected. You can then register your DbContext with the container, and adjust your controller under test to accept the context in the constructor. The IoC Container would set up the DbContext lifetime scope to Instance per Request for example, so you don't need the using {} block. From there your tests can provide the mocked DbContext, while The container manages the Context lifespan.
Regarding making unit-test friendly controllers/code with an IoC container I'd recently posted an article on the use of Lazy dependencies /w Autofac to make writing tests for classes with multiple dependencies a snap. You can have a read at https://medium.com/@StevePy/writing-easily-testable-code-with-autofac-lazy-properties-f9c63457c8ce

A: Difficult but not impossible with those constraints.  You didn't mention Core which would make that a breeze.
Most likely, create a constructor that accepts a DbContext object.  In your Unit Test, create your "mocked" DbContext and pass it to the controller.  Controller does not create a DbContext if it received one.
Also, look into creating an in-memory EF DbContext for testing purposes before any of your tests and destroy it when tests are complete.
Insofar as no IOC, DI is amazing when developing TDD.  It is built-in for .Net Core so those constraints are a dead-end.


text:
Q: Omission of function declarations Are there any circumstances in which it is acceptable to omit function declarations from source files? I have a C project which will not compile, and I do not know why. As far as I can determine the compiler (GCC 4.4.1) cannot find the declaration of the 'sepData' typedef when it gets to the declaration of the function 'sysData' in 'system.h'.
From sepsis.h
typedef struct {
    int16 intensity;
    int16 offset;
} sepData;

From sepsis.c
sepData sepR, sepIR;

From system.h
void sysData(sepData *sepR, sepData *sepIR);

From system.c
#include "system.h"
#include "sepsis.h"

extern sepData sepR, sepIR;

void sysData(sepData *sepR, sepData *sepIR)
{
}

If I remove the declaration of 'sysData' from 'system.h', then the project compiles without error. Not knowing a great deal about C, I thought that including such declarations was compulsory. Is anyone able to explain what is going on here?

A: When you include system.h, you haven't yet declared the type sepData.
Switch around the order of includes and try again.
#include "sepsis.h"
#include "system.h"

extern sepData sepR, sepIR;

//you might also want to re-think your arguments' names
void sysData(sepData *_sepR, sepData *_sepIR)
{
}

A: #include "system.h"
#include "sepsis.h"

If system.h does not #include "sepsis.h" itself, then the type sepData will not be known when you prototype the sysData() function, and you get the error message. You can probably paper over this problem by swapping the order of the two headers:
#include "sepsis.h"
#include "system.h"

But that only fixes this specific compilation unit. If you have other compilation units in this application, you'll need to care about the order of #include lines, which gets tiresome. Perhaps system.h needs to #include "sepsis.h" itself -- and have sepsis.h guard against multiple inclusion via the usual incantation:
#ifndef _SEPSIS_H_
#define _SEPSIS_H_
...
#endif // _SEPSIS_H_

Your codebase was able to compile without the sysData() prototype because you hadn't used the function before the function's declaration. Had you used the function before declaration, I expect the compiler would have given you a warning message and assumed every single argument should be an int and the return type should also be an int. (The old K&R rules.) This would, of course, not work, but it might not be obvious why it doesn't work. (Yay C.)


text:
Q: Get dictionary (or keyvaluepair or whatever) of columns and tables used in a SQL Query I'm looking for a way to take an SQL query, pass it to a method, and retrieve a dictionary back of all of the columns and their associated table.  I was able to get a list of tables from a query based on this:
List of tables used in an SQL Query
For example, the following query:
SELECT P.FirstName, P.LastName, P.BirthDate, P.DeathDate, VP.FullName
FROM Presidents P
INNER JOIN VicePresidents VP ON P.VicePresidentID = VP.VicePresidentID

Ideally, it would return a dictionary (or keyvaluepair or whatever really) item with the following:
{FirstName, Presidents},
{LastName, Presidents},
{BirthDate, Presidents},
{DeathDate, Presidents},
{Fullname, VicePresidents}

Ideally, this should not touch SQL at all (if possible).  The identifiers (P,VP) may not always be there.  My method that returns tables does return Presidents and VicePresidents, but I really need the column/table relationship.  Any thoughts?
I'm creating an MVC control, that you pass an object from the model and it automatically creates the entire form based on the model.  The object from the model matches a sql query used to fill it.  I have parameters for lookups and many of the input types.  The one thing I can't do automatically though is the table name for the column.
I have this query:
SELECT
    AppSettingsTypeID,
    AppSettingsTypeName
FROM MasterImport.DBAppSettingsType
WHERE AppSettingsTypeID = 13

That creates an instance of this class
public class DBAppSettingFull
    {
        [FormField("App Setting Type", InputType.Dropdown, new int[] { 12, 12, 6, 6, 4 })]
        public int AppSettingsTypeID { get; set; }

        [FormField("App Setting Name", InputType.Textbox, new int[] { 12, 12, 6, 6, 4 })]
        public string AppSettingsTypeName { get; set; }
    }

With this line of code
model.Record = Interaction.Single<DBAppSettingFull>(sqlGeneric.GetFirstDBAppSetting.Resource());

Which is used in the cshtml with this line of code
@(Html.GenerateForm<Cold.Framework.Classes.DBAppSettingFull>(Model.Record))

and it creates the form on the cshtml page.  I'm in the process of writing my ProcessForm method.  My last version of this, I had to do manually give each property/column its table relationship.  I'd like to do that automatically.


text:
Q: Docker for Desktop is installed but doesn't lauch I have installed docker for desktop on my pc but it doesn't launch at all.
What all is done: Hyper-V is installed, is running a virtual machine
                  performed the following steps:-
                  Verifying that the Virtual Machine Management service on the computer is running:
Open "Window Security"
Open "App & Browser control"
Click "Exploit protection settings" at the bottom
Switch to "Program settings" tab
Locate "C:\WINDOWS\System32\vmcompute.exe" in the list and expand it
Click "Edit"
Scroll down to "Code flow guard (CFG)" and uncheck "Override system settings"
Start vmcompute from powershell
net start vmcompute   --> "already running"
rebooted my pc twice.
tried launching the app with run as administrator option
The above didn't work.
Please tell me how to launch it!

A: If you're using Windows and you have some apps like Virtualbox or VMWare you need to uninstall them I think and I'm not sure if you need to stop virtualization.


text:
Q: Angular Material mat-form-field input field icon In Angular project I have Angular Material mat-form-field my icon appears outside left from <input> field with placeholder on the right side:
<mat-form-field appearance="fill" class="fld">
  <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
  <input
    matInput
    placeholder="myPlaceholder"
    class="inp"
  />
</mat-form-field>

I'm trying to figure out how to put icon inside the <input> tag field on the same left side by matPrefix
I've tried:
<mat-form-field appearance="fill" class="fld">
  <input
    matInput
    placeholder="myPlaceholder"
    class="inp"
  >
    <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
  </input>
</mat-form-field>

error NG5002: Void elements do not have end tags "input"

Also maybe if I've to use <md-input-container> I've tried import { MdInputModule } from '@angular/material'; but app.module.ts does not load this way.

'MdInputModule' is declared but its value is never read

As I've a bit custom design, here is my my-comp.component.scss:
mat-form-field {
  width: 100%;
  background-color: #da2ba6;
}

::ng-deep .mat-form-field-infix {
  top: -3px;
  background-color: #da2ba6;
}

.inp {
  width: 90%;
  height: 34px;
  border-radius: 20px;
  background: #fff;
  text-align: right;
}

.my-icon {
  z-index: 1;
  position: relative;
}

.fld {
  width: 100%;
}

And here is actual result, appears outside:

and desired result in a right side inside the input field, in one line with placeholder, which is already exist on right side, also inside input field (just not included in image):

Any advice would be helpful

A: <input> is a void element : it's not meant to contains elements.
It means there is no existing closing tag </input> allowed.
You must remove this closing tag and place your <mat-icon> tags after (while still into the mat-form-field tags) :
<mat-form-field appearance="fill" class="fld">
  <input
    matInput
    placeholder="myPlaceholder"
    class="inp"
  >
  <mat-icon matPrefix class="my-icon">sentiment_very_satisfied</mat-icon>
</mat-form-field>

Here is the current official example with both prefix and suffix :
<form class="example-form">
  <mat-form-field class="example-full-width">
    <mat-label>Telephone</mat-label>
    <span matPrefix>+1  </span>
    <input type="tel" matInput placeholder="555-555-1234">
    <mat-icon matSuffix>mode_edit</mat-icon>
  </mat-form-field>
</form>

A: I created a small example to demonstrate the right use of matPrefix and matSuffix. You don't have to set any additional css, but: import the right Modules in your *module.ts and stylesheets in your angular.json!
https://stackblitz.com/edit/angular-ivy-12pssg

A: I like put the .css in styles.scss (to share inside all the aplication) If we can not affect to another component we add a "prefix", e.g. .special.
I imagine a .css (repeat, in styles.css)
.special.mat-form-field{
background-color:pink;
}
.special.mat-form-field-should-float .mat-form-field-label-wrapper
{
  top:-2.5rem;
  left:-1em;
}

.special.mat-form-field-appearance-fill .mat-form-field-underline::before, .special.mat-form-field-appearance-fill .mat-form-field-ripple {
    width: 80%;
    left: 10%;
    top:0.25em;
}
.special .mat-hint{
  margin-top:1rem
}
.special.mat-form-field-appearance-fill .mat-form-field-flex {
  margin-top:0;
    border-radius: 20px;
    padding: 0 .75em 0 .25em;
    background-color: white;
}
.special .mat-form-field-wrapper{
  padding: .5em .5em;
}
.special .mat-form-field-prefix, .special .mat-form-field-suffix {
    top: 0em;
}
.special.mat-form-field-appearance-fill .mat-form-field-infix {
    padding: 0.25em 0 0.25em .125em;
    margin-top:0em;
}
.special.mat-form-field-appearance-fill .mat-form-field-infix >input{
    padding: 0.125em 0 .625em .125em;
    margin-top:-2em;

}

See stackblitz
DISCLAMER: Really I'm a "poor designer", I don't know if there're a better way to do it