text:
Q: sqlcipher SQLiteException: not an error on api 11 I'm using sqlcipher for encoding my database . I've added the libraries and jar files and it works fine on api 18 and 16 but It gives me this error on api 11 :
 java.lang.RuntimeException: Unable to start activity ComponentInfo{}: net.sqlcipher.database.SQLiteException: not an error
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)

 Caused by: net.sqlcipher.database.SQLiteException: not an error
    at net.sqlcipher.database.SQLiteDatabase.dbopen(Native Method)
    at net.sqlcipher.database.SQLiteDatabase.<init>(SQLiteDatabase.java:1942)
    at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:875)
    at net.sqlcipher.database.SQLiteDatabase.openDatabase(SQLiteDatabase.java:868)
    at net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:903)
    at net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:914)
    at com.example.com.DBAdapter.open(DBAdapter.java:106)
    at com.example.com.Spots.onCreate(Spots.java:81)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
    ... 11 more

this is how I open database from sd card :
SQLiteDatabase.loadLibs(context);
String outFileName = Environment.getExternalStorageDirectory() +"/Android/data/"+ context.getPackageName()
                + "/files/files.dll";
        File databaseFile = new File(outFileName);
        db = SQLiteDatabase.openOrCreateDatabase(databaseFile,"mypass", null);

this is the image of my asset folder and lib folder :

Could you help me to solve this ?
thanks


text:
Q: Mousemove events not registering after window.resize event For whatever reason, natively in Chrome, mousemove events that immediately follow a mousedown event are not firing or are simply ignored altogether for a small period of time (500-1000ms?) following the mousedown event.
Strange thing is that this issue is nonexistent on codepen (on Chrome too) and the code is the exact same... There's also no issues with Firefox, Edge, etc, only natively on Chrome.
Here is a codepen nonetheless. Test it for yourself.
Copy and paste this code into actual .html, .css, and .js files, and then run it in the browser directly, you'll notice that paper.onmousemove does not fire or register immediately after a window.resize event for a very small period of time.
None of this makes any sense!
Anybody have any idea what's going on? Why would it work fine in codepen (and every other browser), yet not directly in the browser?!
I have found one issue with the codepen version, which produces a very similar bug (but involves a couple extra steps in the beginning).

*

*Create an element by dragging your mouse on the white area

*Select that element by clicking it

*Drag that element anywhere on the page

*Resize the browser and immediately try to create another element by dragging

However, on codepen mousedown isn't firing in this case, whereas mousemove is not firing if viewed directly in the browser. Again, there is a discrepancy, which incredibly bizarre.
Update
It turns out it only happens when the developer console is open, which is why it was not happening in codepen.

A: This seems to be some weirdness with Chrome DevTools. The bug you describe seems to only occur when DevTools is open. It goes away when you close DevTools. It may just be a weird coincidence, but it starts logging out mousemove events immediately when the resolution label in the top right goes away.
That being said, you have a combination of onmousemove and addEventListener going on. For instance you have both
paper.addEventListener('mouseup', checkMouseUp)
and
paper.onmouseup = function(event) {}
I'm not sure if it's the cause of the DevTools issue, but this can lead to unintended consequences since paper now has two separately assigned mouseup functions. In your case, I'd just stick with addEventListener.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update the quantity of a field in a column automatically based on data from another table in MySQL It's quite simple really. Here's my database schema:
Table 1: posts
Columns: ID, contents, likes, dislikes
Table 2: posts_likes_dislikes
Columns: ID, user_id, post_id, like_or_dislike (1 or 0)
I want to update likes and dislikes in the table 1 depending on the information on table 2. I want a way to match the post_id (table 2) with the id (posts) and then count the amount of 1's and 0's. Based on that amount, I want to update likes and dislikes in table 1. I'm not entirely sure if this is possible. As much as possible, I don't want to use a cron job.

A: I would use a query like this:
UPDATE
  posts INNER JOIN (SELECT   post_id,
                             SUM(like_or_dislike=1) likes,
                             SUM(like_or_dislike=0) dislikes
                    FROM     posts_likes_dislikes
                    GROUP BY post_id) l
  ON posts.ID = l.post_id
SET
 posts.likes = l.likes,
 posts.dislikes = l.dislikes

Please see fiddle here.
Edit: if you need to update your posts table dinamically with a trigger, you could use a solution like this:
CREATE TRIGGER after_insert
BEFORE INSERT ON posts_likes_dislikes
FOR EACH ROW
  UPDATE posts
  SET
    posts.likes = posts.likes + (new.like_or_dislike=1),
    posts.dislikes = posts.dislikes + (new.like_or_dislike=0)
  WHERE
    posts.ID = new.post_id;

(please notice that, depending on how your database is structured, you might also want to consider an update and a delete trigger).
Fiddle is here.


text:
Q: Can I pass a TABLELIKE parameter to a PostgreSQL FUNCTION/PROCEDURE? I have a function which returns:
TABLE (id TEXT, collected TIMESTAMPTZ)

In another function, I would like to be able to pass the result of that first function as a parameter. For example:
CREATE FUNCTION my_func(devices TABLE(id TEXT, collected TIMESTAMPTZ)) ....

That syntax gives me an error:
ERROR: syntax error at or near "TABLE"

Is there some way to accomplish this in PostgreSQL?

A: OK, based on feedback from Erwin Brandstetter above, I came up with a VERY nice solution detailed below:
CREATE TABLE device_data (
  collected TIMESTAMPTZ,
  id VARCHAR(100),
  data JSON,
  PRIMARY KEY(id,collected)
);

COPY device_data (collected, id, data) FROM stdin;
2016-01-02 00:02:12+00  switch1.mycompany.com   {}
2016-01-02 00:02:12+00  switch2.mycompany.com   {}
2016-01-02 00:02:12+00  switch3.mycompany.com   {}
2016-01-02 00:02:12+00  switch4.mycompany.com   {}
2016-01-02 00:02:12+00  switch5.mycompany.com   {}
2016-01-02 00:02:12+00  switch6.mycompany.com   {}
2016-01-03 00:02:12+00  switch1.mycompany.com   {}
2016-01-03 00:02:12+00  switch3.mycompany.com   {}
2016-01-03 00:02:12+00  switch4.mycompany.com   {}
2016-01-03 00:02:12+00  switch5.mycompany.com   {}
2016-01-03 00:02:12+00  switch6.mycompany.com   {}
\.

CREATE OR REPLACE FUNCTION get_most_recent()
RETURNS TABLE(id TEXT, collected TIMESTAMPTZ) AS $$
SELECT
    id,
    MAX(collected) AS collected
FROM device_data GROUP BY id
$$ LANGUAGE SQL;

CREATE OR REPLACE FUNCTION get_data()
RETURNS TABLE(id TEXT, data JSON) AS $$
SELECT
  d.id,
  d.data
FROM device_data d
INNER JOIN get_most_recent() r ON r.id=d.id AND r.collected=d.collected
$$ LANGUAGE SQL;

SELECT * FROM get_data();


text:
Q: Add one more element to the object array inside for each loop in mule 3 I have Input as below
[{Name=ABC, ID=123},{Name=XYZ, ID=345}]

I would iterate over this collection in a for-each loop and add one more element Age to each object.
My expected output would be like
[{Name=ABC, ID=123, Age=23},{Name=XYZ, ID=345, Age=24}]

Any help would be highly appreciated. Thanks in advance.

A: HTH..
%dw 2.0
output application/json
var inp = [
     {
         "Name":"ABC",
         "ID":"123"
     },
     {
         "Name":"XYZ",
         "ID":"345"
     }
    ]
---
inp map {
  ($),
  age:  (23 + ($$)) // or your logic to derive age

}

A: It was not possible with DW as because payload inside for-each was modified. So I tried using Expression component. Below is my configuration XML.
<flow name="add-one-more-element-to-the-original-payload">
    <poll doc:name="Poll">
        <fixed-frequency-scheduler frequency="30" timeUnit="SECONDS"/>
        <logger message="Pooling Started" level="INFO" doc:name="Log"/>
    </poll>
    <dw:transform-message doc:name="Transform Payload">
        <dw:set-payload><![CDATA[%dw 1.0
%output application/java
%var collection = [{"Name":"ABC","ID":123},{"Name":"XYZ","ID":345}]
---
collection]]></dw:set-payload>
    </dw:transform-message>
    <set-variable variableName="outputList" value="#[new java.util.ArrayList()]"
doc:name="Set Variable"/>
            <foreach doc:name="For Each" collection="#[payload]">
        <dw:transform-message doc:name="CurrentPayload">
            <dw:set-variable variableName="currentPayload"><![CDATA[%dw 1.0
%output application/java
---
payload]]></dw:set-variable>
        </dw:transform-message>
        <flow-ref name="get-age-subflow" doc:name="Get Age"/>
        <expression-component doc:name="Expression"><!
[CDATA[flowVars.currentPayload.Age=payload.Age;]]></expression-component>
        <expression-transformer expression="#
[flowVars.outputList.add(flowVars.currentPayload)]" doc:name="Expression"/>
    </foreach>
    <logger message="#[flowVars.outputList]" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="get-age-subflow">
    <dw:transform-message doc:name="Transform Age">
        <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
{
Age:24
}]]></dw:set-payload>
    </dw:transform-message>
</sub-flow>


text:
Q: Add length prefix to DNS request using TCP and Scapy In the RFC 1035 about DNS, it's written :

4.2.2. TCP usage
Messages sent over TCP connections use server port 53 (decimal).  The
  message is prefixed with a two byte length field which gives the
  message length, excluding the two byte length field.  This length
  field allows the low-level processing to assemble a complete message
  before beginning to parse it.

I want to send a DNS request with TCP but I don't know how to add these two bytes before the DNS request. I try with that code :
from scapy.all import *

ip=IP(dst="216.239.32.10")

request = DNS(rd=1, qd=DNSQR(qname = "google.be", qtype="A")) #size = 27(dec) = 1b (hex)
twoBytesRequestSize = "\x1b\x00"
completeRequest = str(request) + twoBytesRequestSize

SYN=ip/TCP(sport=RandNum(1024,65535), dport=53, flags="S", seq=42)
SYNACK=sr1(SYN)

ACK=ip/TCP(sport=SYNACK.dport, dport=53, flags="A", seq=SYNACK.ack, ack=SYNACK.seq + 1)
send(ACK)

DNSRequest = ip/TCP(sport=SYNACK.dport, dport=53, flags="PA", seq=SYNACK.ack, ack=SYNACK.seq + 1) / completeRequest
DNSReply = sr1(DNSRequest, timeout = 1)

But my paquet is interpreted like a simple TCP packet without DNS layer.
Have you an idea to add these two bytes prefix before the DNS request?
Thank you !

A: The solution uses Big endian notation. \x00\x1b instead of \x1b\x00. But the rest of the code above is correct. Thank you Armin.


text:
Q: APEX 5 interactive report column order I have an issue with changing interactive report column order.
My APEX version 5.0.3.00.03.
If i change order in Columns nothing change.
If i change order in SqlQuery nothing change.
If i change type of report (eg select classic report) and come back to interactive order finally change.
I'm doing wrong or there is a bug?

A: SQL statement order is merely defines the default order upon creation, and has no impact afterwards.
Classic reports get their order from the column sequence at design time.
Column order for interactive reports is defined at runtime, where the developer uses action toolbar to select columns, order, sort etc.
Design time capability for IR may be present in APEX 5.2

A: Don't forget to save the report as default report afterwards or else it will reset on refresh (actions -> save report then choose default from select list).

A: To change the order of columns displayed go on IR bar "actions" and select "Columns". Here you can choose what display and in which order. Then save the report as default.

A: So what we can do here is, once you run your report and see the output.
Click on "Action" button on your report output, near the Search bar. Then choose "columns". Now in the next pop up window, you can reorder the columns and even opt to not show some of the column. Once you are done with the changes, click on "Apply".
Now you need to follow these steps to make these changes default for all.
Actions --> Reports --> Save Report --> Choose "As Default Report Settings" in save drop down menu --> Apply.
Now your changes will be done and saved as default for all.


text:
Q: Remote loaded successfully but  could not be found! Verify that the name is correct in the Webpack configuration While using Module Federation plugin from webpack, I've connected two react applications and using dynamic url based import by using below
import { importRemote } from 'module-federation-import-remote';

remote url gets loaded in network tab but I see this error being shown by React Dom

I am using below to import remote app:
return importRemote({
    module: 'main',
    scope: 'campaign',
    bustRemoteEntryCache: true,
    remoteEntryFileName: 'campaign.js',
    version: 'some-version',
    url: 'https://localhost.corp.xyz.com:12398',
    remoteEntryFileName: 'campaign',
});

I expected remote application to be imported and running by module federation

A: Issue was due to webpacks splitChunks. changing optimization to below code resolved the issue
  optimization: {
    splitChunks: false,
  },


text:
Q: Scrape images from 9gag, unable to read correct HTML-page Im trying to write a script thats gonna scrape 9gag for images and images only. But i have faced a problem which is that my requests or the Beautifulsoup is getting the wrong HTML page.
Beautifulsoup is currently getting the source-page and not the page that is containing the images.
Why is Beautifulsoup excluding the classes that contain the actual images? Or is it diffrent HTML-pages?
I have tried diffrent formats for the Beautiful soup "parser" but still getting the wrong page.
If you go to 9gag and right-click and the "inspect" you can get to the images, and the page to extract the images with script.
My script:
import requests
from bs4 import BeautifulSoup
import os

def download_image(url, fileName):          #save image function
    path = os.path.join("imgs", fileName)
    f = open(path, 'wb')
    f.write(requests.get(url).content)
    f.close()

def fetch_url(url):                        # fetching url
    page = requests.get(url)
    return page

def parse_html(htmlPage):                  #parsing the url
    soup = BeautifulSoup(htmlPage, "html.parser")
    return soup

def retrieve_jpg_urls(soup):

    list_of_urls = soup.find_all('list')       #classes wanted
    parsed_urls = []
    for index in range(len(list_of_urls)):
        try:
            parsed_urls.append(soup.find_all('img')[index].attrs['src']) #img wanted inside class
        except:
            next
    return parsed_urls

def main():
    htmlPage = fetch_url("https://9gag.com/")
    soup = parse_html(htmlPage.content)
    jpgUrls = retrieve_jpg_urls(soup)
    for index in range(len(jpgUrls)):
        try:
            download_image(jpgUrls[index], "savedpic{}.jpg".format(index))
        except:
            print("failed to parse image with url {}".format(jpgUrls[index]))
    print("")

if __name__ == "__main__":
    main()

What Beautifulsoup is getting:
<!DOCTYPE html>

<html lang="en">
<head>
<title>9GAG: Go Fun The World</title>
<link href="https://assets-9gag-fun.9cache.com" rel="preconnect"/>
<link href="https://img-9gag-fun.9cache.com" rel="preconnect"/>
<link href="https://miscmedia-9gag-fun.9cache.com" rel="preconnect"/>
<link href="https://images-cdn.9gag.com/img/9gag-og.png" rel="image_src"/>
<link href="https://9gag.com/" rel="canonical"/>
<link href="android-app://com.ninegag.android.app/http/9gag.com/" rel="alternate"/>
<link href="https://assets-9gag-fun.9cache.com/s/fab0aa49/5aa8c9f45ee3dd77f0fdbe4812f1afcf5913a34e/static/dist/core/img/favicon.ico" rel="shortcut icon"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<meta content="9GAG has the best funny pics, gifs, videos, gaming, anime, manga, movie, tv, cosplay, sport, food, memes, cute, fail, wtf photos on the internet!" name="description"/>

I want the following:
<img src="https://img-9gag-fun.9cache.com/photo/aLgyG2V_460s.jpg" alt="There&#039;s genuine friend love there" style="min-height: 566.304px;">

A: Try extracting the JSON on the page:
import re
import json

# ...
res = requests.get(...)
html = res.content

m = re.search('JSON\.parse\((.*)\);</script>', html)
double_encoded = m.group(1)
encoded = json.loads(double_encoded)
parsed = json.loads(encoded)

images = [p['images']['image700']['url'] for p in parsed['data']['posts']]
print(images)

output:
['https://img-9gag-fun.9cache.com/photo/abY9Wg8_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/aLgy4o5_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/aE2LVeM_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/amBEGb4_700b.jpg', 'https://img-9gag-fun.9cache.com/photo/aKxrv56_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/a5M8wXN_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/aNY6QEv_700b.jpg', 'https://img-9gag-fun.9cache.com/photo/aYY2Deq_700b.jpg', 'https://img-9gag-fun.9cache.com/photo/aQR0AEw_460s.jpg', 'https://img-9gag-fun.9cache.com/photo/aLgy19P_700b.jpg']


text:
Q: method(E[]) is not applicable to the arguments(int[]) I'm trying to implement my sort method, which takes a generic E[] as an argument, upon my int[]. I receive the error:

The method sort(E[]) in the type HeapSort is not applicable for the arguments (int[]).

My code is as follows:
public <E extends Comparable<E>> void sort(E[] array){

//my code

}

public static void main(String[] args){
    int[] arr = new int[30];
    for(int rep = 0; rep < arr.length; rep++){
        arr[rep] =(int )(Math.random() * 100 + 0);
    }

    System.out.println("The unsorted Array: ");
    System.out.println(sort(arr).toString());
}

Any ideas as to why I get this error? All help appreciated! Thank you!

A: A primitive type can't replace a generic type parameter (and even if it could, it couldn't satisfy your extends Comparable<E> type bound, since primitive types don't extend any class and don't implement any interface).
You can replace your int[] with an Integer[] and it will work.
Beside that error, sort(arr) doesn't return anything, so you can't execute toString on it.
You can replace it with :
new HeapSort ().sort(arr); // you must create an instance of the class that contains
                           // the sort method in order to call it
System.out.println(Arrays.toString(arr));

A: lets look at what you wrote there.
public <E extends Comparable<E>> void sort(E[] array)

this is a method called sort. it has generic parameter with a constraint. The constraint is that whatever the generic parameter you have put in, it must implement Comparable.
int doesn't implement Comparable, in fact int doesn't implement anything.
Java generics don't work with primitive types at all. Generic constraints only limit you farther.


text:
Q: Record Consecutive Days by Group in R I have a dataframe as follows:
DATE <- as.Date(c('2016-12-01', '2016-12-02', '2016-12-03', '2016-12-04', '2016-12-01', '2016-12-03', '2016-12-04', '2016-12-04' ))
Parent <- c('A','A','A','A','A','A','A','B')
Child <- c('ab', 'ab', 'ab', 'ab', 'ac','ac', 'ac','bd')
salary <- c(1000, 100, 4000, 2000,1000,3455,1234,600)
avg_child_salary <- c(500, 500, 500, 500, 300, 300, 300, 9000)
Callout <- c('HIGH', 'LOW', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'HIGH', 'LOW')
employ.data <- data.frame(DATE, Parent, Child, avg_child_salary, salary, Callout)

employ.data

        DATE Parent Child avg_child_salary salary Callout
1 2016-12-01      A    ab              500   1000    HIGH
2 2016-12-02      A    ab              500    100     LOW
3 2016-12-03      A    ab              500   4000    HIGH
4 2016-12-04      A    ab              500   2000    HIGH
5 2016-12-01      A    ac              300   1000    HIGH
6 2016-12-03      A    ac              300   3455    HIGH
7 2016-12-04      A    ac              300   1234    HIGH
8 2016-12-04      B    bd             9000    600     LOW

I have filtered out just yesterday's data being 2016-12-04 as follows:
yesterday <- as.Date(Sys.Date()-1)
df2<-filter(employ.data, DATE == yesterday)
df2

            DATE Parent Child avg_child_salary salary Callout
    4 2016-12-04      A    ab              500   2000    HIGH
    7 2016-12-04      A    ac              300   1234    HIGH
    8 2016-12-04      B    bd             9000    600     LOW

My goal is to include a column next to Callout showing the amount of consecutive days from 2016-12-04 the callout has been HIGH or LOW by Child based on the employ.data dataframe. This is what I need as the final output:
            DATE Parent Child avg_child_salary salary Callout   Consec. Days with Callout
    4 2016-12-04      A    ab              500   2000    HIGH                           2
    7 2016-12-04      A    ac              300   1234    HIGH                           2
    8 2016-12-04      B    bd             9000    600     LOW                           1

Thanks!

A: try this my man
library(lubridate)

df3 <- df2 %>%
       group_by(child, callout) %>%
       mutate(DATE = ymd(DATE),
              consecutive_day_flag = if_else(DATE == (lag(DATE) + days(1)), 1, 0),
              how_many = sum(consecutive_day_flag))

A: Here is another approach that is quite messy but I think does what you want:
library(dplyr)
yesterday <- as.Date(Sys.Date()-1)
df2 <- employ.data %>% group_by(Child) %>%
  mutate(`Consec. Days with Callout`=cumsum(rev(cumprod(rev((yesterday-DATE)==(which(DATE == yesterday)-row_number()) & Callout==Callout[DATE == yesterday]))))) %>%
  filter(DATE == yesterday)
##Source: local data frame [3 x 7]
##Groups: Child [3]
##
##        DATE Parent  Child avg_child_salary salary Callout Consec. Days with Callout
##      <date> <fctr> <fctr>            <dbl>  <dbl>  <fctr>                     <dbl>
##1 2016-12-04      A     ab              500   2000    HIGH                         2
##2 2016-12-04      A     ac              300   1234    HIGH                         2
##3 2016-12-04      B     bd             9000    600     LOW                         1

Notes:

*

*(yesterday-DATE)==(which(DATE == yesterday)-row_number()) & Callout==Callout[DATE == yesterday] computes a condition that will be TRUE for the row if the Callout is the same as the Callout for yesterday and if the distance in rows from the row that is yesterday is the same as the distance in days for the date. This gives the Cond column as shown below:
Source: local data frame [8 x 7]
Groups: Child [3]

        DATE Parent  Child avg_child_salary salary Callout  Cond
      <date> <fctr> <fctr>            <dbl>  <dbl>  <fctr> <lgl>
1 2016-12-01      A     ab              500   1000    HIGH  TRUE
2 2016-12-02      A     ab              500    100     LOW FALSE
3 2016-12-03      A     ab              500   4000    HIGH  TRUE
4 2016-12-04      A     ab              500   2000    HIGH  TRUE
5 2016-12-01      A     ac              300   1000    HIGH FALSE
6 2016-12-03      A     ac              300   3455    HIGH  TRUE
7 2016-12-04      A     ac              300   1234    HIGH  TRUE
8 2016-12-04      B     bd             9000    600     LOW  TRUE

*Given this we want to count backwards the number of consecutive TRUE from the row that is yesterday (grouped by Child). To do this, we can reverse the vector using rev, do a cumprod, which will switch from 1 to 0 as soon as it encounters a FALSE, reverse the vector back again using rev, and finally do the cumsum to accumulate the consecutive days. Doing this gives the following where the Consec. Days with Callout column is interpreted as the number of previous consecutive days with the same Callout as yesterday:
Source: local data frame [8 x 7]
Groups: Child [3]

        DATE Parent  Child avg_child_salary salary Callout Consec. Days with Callout
      <date> <fctr> <fctr>            <dbl>  <dbl>  <fctr>                     <dbl>
1 2016-12-01      A     ab              500   1000    HIGH                         0
2 2016-12-02      A     ab              500    100     LOW                         0
3 2016-12-03      A     ab              500   4000    HIGH                         1
4 2016-12-04      A     ab              500   2000    HIGH                         2
5 2016-12-01      A     ac              300   1000    HIGH                         0
6 2016-12-03      A     ac              300   3455    HIGH                         1
7 2016-12-04      A     ac              300   1234    HIGH                         2
8 2016-12-04      B     bd             9000    600     LOW                         1

*Finally, do the filter as you did to generate the final result.


text:
Q: Loading from text file into list I have been trying to read from an external .txt file into a list of "Tasks" to form a ToDo list, but trying to read in more than a single line into the list gives  the following error, which tells me that the array isn't properly expanding to fit the extra lines.

java.lang.ArrayIndexOutOfBoundsException: 1

But what I'm asking help for is getting the array to properly fill, when as far as I know, it should be from this function call.
public void loadList(boolean showStatus) {
myList.clear();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
            String line = br.readLine();
            while (line != null) {
                String[] tokens = line.split(",");
                Task item = new Task();
                item.setDescription(tokens[0]);
                item.setPriority(Integer.parseInt(tokens[1]));
                item.setDueDate(tokens[2]);
                item.setStatus(Boolean.parseBoolean(tokens[3]));
                myList.add(item);
                line = br.readLine();
            }
    } catch (FileNotFoundException ex) {
            Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }

(For reference, here's the format of the .txt file)

Assassinate Santa,4,12-25-19,false
Shave Bear,3,03-09-19,false
Level Canada,4,09-09-19,true

Additionally, apparently the parseBoolean attempt doesn't actually read whether the .txt file Tasks are true/false, and is defaulting everything to false.

A: String[] tokens = line.split(",");
if(token.length != 4)
{
 // Then you may skip this line and proceed to next line
 continue;
}
// Or do the reading tokens array

You can do this to solve the issue mentioned in the comment.


text:
Q: InputStream.read sometimes stops reading My App should be able to receive messages from a server using Stream-class.
My code is:
var inputStream  : InputStream? = nil
var outputStream : OutputStream? = nil

...

func establishConnection() {
    ...
    Stream.getStreamsToHost(withName: "app.mybusiness.com", port: port, inputStream: &self.inputStream, outputStream: &self.outputStream)
    ...
}

func stream(_ someStream: Stream, handle eventCode: Stream.Event) {

    switch eventCode {
        case Stream.Event.hasBytesAvailable:
        var output = ""

        var buffer = [UInt8](repeating: 0, count: 1024)

        while (self.inputStream!.hasBytesAvailable){

            let bytesRead:Int=inputStream!.read(&buffer, maxLength: buffer.count)

            if (bytesRead > 0) { // had here (bytesRead >= 0) too
                output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding:String.Encoding.utf8.rawValue)! as String
            } else {
                print("# error")
            }
            print("> \(output)")
        }

        // Now do something with the data we got
        HelpMethods.pushServerIncoming(inString: output)

       default:
           ...
    }

}

So this works quite nice, but sometimes it seems to stop receiving data.
It reads the first 1024 bytes, then the second 1024 and instead of continuing (about 3 or 4 more iterations are necessary to get the whole message) it reads only a few more bytes and then inputStream.hasBytesAvailable returns false.
It would be easy to say: Ahh thats the fault of the server, but this problem does not occur within the android-version of the app.
I tried to change buffer-size (from 1 to 4096) but it doesn't change anything. With 4096 bytes I had a case where the stream reads only a few hundred bytes in the first run and then said: all done buddy! nothing more to read ...
The behavior is not predictable. Tested it with the same message a lot of times and it worked, worked, worked, did not work, ...
Any suggestions?

A: To avoid hanging or crashing of Inputstream reader You can first read the InputStream to a String...
String myString = "Hello there how are you";
InputStream inputStream = new ByteArrayInputStream(myString .getBytes(StandardCharsets.UTF_8));

If reading from a socket...
String myString = socket.getInputStream().toString();  //if reading socket

Then you can assign the Inputstream variable...
InputStream inputStream = new ByteArrayInputStream(myString .getBytes(StandardCharsets.UTF_8));


text:
Q: Is it possible to run OSGi components within Weblogic 10.3? Is it possible to run OSGi components within Weblogic 10.3? From what i have read it is not possible but im asking just to be 100% sure. There is no option to swap out WL 10.3 so there is no need to list any other application servers or OSGi containers.
Thanx

A: You can embed an osgi container inside of WLS 10.3, then deploy your bundles inside it.
Equinox in a Servlet Container
It's pretty rough, but might be worth a look.
WLS 10.3 supports j2ee deployable libraries which can be used to modularize a large application.

A: What do you mean by OSGi components ? If you mean a bundle, then you can certainly load it, since a bundle is just a .jar file with additional metadata. However you're not going to get the lifecycle events, and if the bundle depends on these to bind to additional services then you will have a problem.


text:
Q: Problems with regex A while ago, i've built the following regular expression:
~(?:<a.*?|\[url.*?\[/url]|\[/?[^]]++]|</?[^>]++>)(*SKIP)(*FAIL)|\bcdkey\s*-\s*.*\b~is

This matches every kind of cdkey-xxx that's NOT inside of a bbcode or a html tag. That works fine so far.
However, i can't make it work properly when including bbcodes and html tags. I thought, removing the front part is enough, but i seem to be wrong:
~\bcdkey\s*-\s*.*\b~is

With this regex,
https://www.google.de/#q=cdkey-0192xdasas

becomes

and
[url]https://www.google.de/#q=cdkey-0192xdasas[/url]

becomes
[url]https://www.google.de/#q=***]

while the expected results are
https://www.google.de/#q=***

and
[url]https://www.google.de/#q=***[/url]

I have no idea, how to fix that.

So, what i try to achieve is to replace
[url]https://www.google.de/#q=cdkey-0192xdasas[/url]
[url=https://www.google.de/#q=cdkey-0192xdasas]Test[/url]
[img]https://www.google.de/#q=cdkey-0192xdasas[/img]
[url="https://www.google.de/#q=cdkey-0192xdasas"]Test 3[/url]
https://www.google.de/#q=cdkey-0192xdasas
    Another plaintext cdkey   -   bla
https://www.google.de/#q=cdkey-0192xdasas
Le Google

with
[url]https://www.google.de/#q=***[/url]
[url=https://www.google.de/#q=***]Test[/url]
[img]https://www.google.de/#q=***[/img]
[url="https://www.google.de/#q=***"]Test 3[/url]
Plaintext https://www.google.de/#q=***
    Another plaintext ***
https://www.google.de/#q=***
Le Google

A: The problem I see with your regular expression is the .* part.
You're matching the most amount possible across your matches, and no need to use the s modifier.
If you know your cdkey will always be numbers and letters, you could do something like this.
$text = preg_replace('/cdkey\s*-\s*[a-z0-9]+/i', '***', $text);

See working demo

A: I think the word boundaries \b are not compatible with the syntax you have inside them. Specifically  the hyphen  and dot-star sequence  is not  going to match the same way It normally does.

A: If you know what might terminate the cdkey, something like this
 # \bcdkey\s*-\s*[^<>\[\]"'\s]*

 \b cdkey \s* - \s* [^<>\[\]"'\s]*


text:
Q: help in forming mysql query to find free(available) venues/resources for a give date range I have tables & data like this:

venues table contains : id
+----+---------+
| id | name    |
+----+---------+
|  1 | venue 1 |
|  2 | venue 2 |
---------------

event_dates : id, event_id, event_from_datetime, event_to_datetime, venue_id
+----+----------+---------------------+---------------------+----------+
| id | event_id | event_from_datetime | event_to_datetime   | venue_id |
+----+----------+---------------------+---------------------+----------+
|  1 |        1 | 2009-12-05 00:00:00 | 2009-12-07 00:00:00 |        1 |
|  2 |        1 | 2009-12-09 00:00:00 | 2009-12-12 00:00:00 |        1 |
|  3 |        1 | 2009-12-15 00:00:00 | 2009-12-20 00:00:00 |        2 |
+----+----------+---------------------+---------------------+----------+

This is my requirement: I want venues that will be free on 2009-12-06 00:00:00
i.e.
I should get
|venue_id|
|2       |

Currently I'm having the following query,

select ven.id , evtdt.event_from_datetime, evtdt.event_to_datetime
from venues ven
left join event_dates evtdt
on (ven.id=evtdt.venue_id)
where evtdt.venue_id is null
or not ('2009-12-06 00:00:00' between evtdt.event_from_datetime
                                  and evtdt.event_to_datetime);
+----+---------------------+---------------------+
| id | event_from_datetime | event_to_datetime   |
+----+---------------------+---------------------+
|  1 | 2009-12-09 00:00:00 | 2009-12-12 00:00:00 |
|  2 | 2009-12-15 00:00:00 | 2009-12-20 00:00:00 |
|  3 | NULL                | NULL                |
|  5 | NULL                | NULL                |
+----+---------------------+---------------------+

If you note the results, its not including venue id 1 where date is in between 2009-12-06 00:00:00 but showing other bookings.
Please help me correct this query.
Thanks in advance.

A: SELECT  *
FROM    venue v
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    event_dates ed
        WHERE   ed.venue_id = v.id
                AND '2009-12-06 00:00:00' BETWEEN ed.event_from_datetime AND ed.event_to_datetime
        )

A: or not ('2009-12-06 00:00:00' between evtdt.event_from_datetime
                              and evtdt.event_to_datetime);

12/6/2009 is between 12/5/09 and 12/7/09... that's why venue_id 1 is being excluded... what is it you're trying to extract from the data exactly?
The join query you've constructed says, take the venues table and for each row of it that has a matching venue_id make a copy of the venue table row and append the matching row. So if you just did:
select *
  from venues ven
  left join event_dates evtdt
  on (ven.id=evtdt.venue_id);

It would yield:
+----+---------+------+----------+---------------------+---------------------+----------+
| id | name    | id   | event_id | event_from_datetime | event_to_datetime   | venue_id |
+----+---------+------+----------+---------------------+---------------------+----------+
|  1 | venue 1 |    1 |        1 | 2009-12-05 00:00:00 | 2009-12-07 00:00:00 |        1 |
|  1 | venue 1 |    2 |        1 | 2009-12-09 00:00:00 | 2009-12-12 00:00:00 |        1 |
|  2 | venue 2 |    3 |        1 | 2009-12-15 00:00:00 | 2009-12-20 00:00:00 |        2 |
+----+---------+------+----------+---------------------+---------------------+----------+

If you then added your condition, which states the date of interest is not between the from and to date of the event, the query looks like:
select *
  from venues ven
  left join event_dates evtdt
  on (ven.id=evtdt.venue_id)
  where not ('2009-12-06' between evtdt.event_from_datetime and evtdt.event_to_datetime)

Which yields a result of:
+----+---------+------+----------+---------------------+---------------------+----------+
| id | name    | id   | event_id | event_from_datetime | event_to_datetime   | venue_id |
+----+---------+------+----------+---------------------+---------------------+----------+
|  1 | venue 1 |    2 |        1 | 2009-12-09 00:00:00 | 2009-12-12 00:00:00 |        1 |
|  2 | venue 2 |    3 |        1 | 2009-12-15 00:00:00 | 2009-12-20 00:00:00 |        2 |
+----+---------+------+----------+---------------------+---------------------+----------+

These are my actual experimental results with your data in MySQL.
If you want to get the venue_ids that are free on the proposed date then you would write something like:
  select ven.id, SUM('2009-12-06' between evtdt.event_from_datetime and evtdt.event_to_datetime) as num_intersects
    from venues ven left join event_dates evtdt on (ven.id=evtdt.venue_id)
    group by ven.id
    having num_intersects = 0;

which yields:
+----+----------------+
| id | num_intersects |
+----+----------------+
|  2 |              0 |
+----+----------------+

this also comes up with the right answer (without modification) in the case where you have a venue with no events in the event_date table.

A: At a guess, if you remove not from
or not ('2009-12-06 00:00:00' between evtdt.event_from_datetime
                                  and evtdt.event_to_datetime)

this will then return row 1 from event dates but not the other event date rows.
I say "at a guess" because your where clause is a bit hard to understand. Maybe you mean
select ven.id , evtdt.event_from_datetime, evtdt.event_to_datetime
from venues ven
left join event_dates evtdt
on (ven.id=evtdt.venue_id)
where '2009-12-06 00:00:00' between evtdt.event_from_datetime
                                  and evtdt.event_to_datetime;


text:
Q: Class method not recognised in php in Yii I have a simple model which adds 2 numbers which are gives as argument however it looks as if the build-in function add() is not getting recognised.
Here is the model
    <?php

class SimpleMaths extends CModel{

    private $numberone;
    private $numbertwo;

    public function SimpleMaths($numberones,$numbertwos){
        $numberone = $numberones;
        $numbertwo = $numbertwos;

    }

    public function add()
    {
        return $numbertwo + $numberone;
    }

    public function attributeNames(){
        return array('number 1' => $numberone, 'number 2'=> $numbertwo);
    }
}

?>

Here is the controller:
    <?php

class BlogController extends Controller{

    public function actionIndex(){
        $none = $_GET['n1'];
        $ntwo = $_GET['n2'];
        $model = new SimpleMaths($ntwo,$none);
        // $sum = $model.add();
        $array = get_class_methods('SimpleMaths');

        $this->render("index",array("interesting"=>$array,"model"=>$model));
    }

}

?>

Here is the view
    <?php

echo "Hello World";
foreach($interesting as $one)
{
    echo $one."
";
    echo "
";
    echo $model.add();
}

?>

The add function gets displayed as one of the functions however when called it simply hides itself?
Here is the error:
Fatal error: Call to undefined function add() in C:\wamp\www\testdrive\protected\views\blog\index.php on line 8

A: in the code that you are showing, it's like you want to echo $model which is an Object, then append whatever function add() returns to it,
you need to change that to
echo $model->add();


text:
Q: AXIOS Post not working with REACT application in Internet Explorer Note: I do have a solution for this already, I wanted to provide it here as a Question/Answer so if others run into this issue they can see if what works for me will also work for them.
What I'm trying to do:
I've been working on a REACT application that needs to send data to a Java Servlet.
Looking online I saw AXIOS being recommended to make Post commands to do just that.
The Issue:
I have the following code that works fine in Edge, Chrome and Firefox, but fails in Internet Explorer (with the error being URLSearchParams not being found in IE's browser console)
        let axiosConfig = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
        // Putting together the data to be passed to the java servlet.
        const params = new URLSearchParams();
        params.append('var1', this.state.data1);
        params.append('var2', this.state.data2);

        var urlToPost = 'https://localhost:8080/someServlet/someMethod';

        axios.post(urlToPost, params, axiosConfig)
            .then((res) => {
                // Handling Response from Servlet.
                console.log("AXIOS POST RESPONSE RECEIVED: ", res);
            })
            .catch((err) => {
                // Handler exception error thrown by Servlet.
                alert('Error during submission');
            })

A: There was several suggestions I saw online on how to resolve it, and there was some that "worked" in IE, meaning I got no error on the IE Browser console, but when the data reached the Java Servlet the extracted data fields were null.
So to the point the solution for me was to use jQuery to do the post when using Internet Explorer, as such:
       // This if statement checks to see if the user's browser is Internet Explorer
       // if its true then use jQuery to do the POST
       if((navigator.userAgent.indexOf("MSIE") !== -1 ) || (!!document.documentMode === true )) //IF IE > 10
       {
           var myObject = {
              var1: this.state.data1,
              var2: this.state.data2
            };
            var urlToPost = 'https://localhost:8080/someServlet/someMethod';
            $.post(urlToPost, myObject,
                function(result) {
                   // handle response
               })
              .done(function(result) {
                   // handle response
              })
              .fail(function(result) {
                  // handle response
              })
              .always(function(result) {
                 // handle response
              });

       } else {
        // use the AXIOS POST command code from my initial question above
       }

Before doing that I had to install jquery and promise by using the following commands:

npm install jquery
npm install es6-promise

Then at the top of my react file I had to include the following imports:
import $ from 'jquery';
import { polyfill } from 'es6-promise'; polyfill();

With those changes Internet Explorer did not give me any more console errors, and the Java Servlet I have was able to extract non-null data from the HTTP Response object.

A: You are going to need a polyfill for URLSearchParams in IE
https://www.npmjs.com/package/url-search-params-polyfill


text:
Q: Tensor product and conjugate space Let $H$ and $K$ be Hilbert spaces and $\overline{K}$ be the conjugate space of $K$, i.e., the elements of $\overline{K}$ are the same of $K$, the sum and norm are the same, and the product rule is given by $\lambda . x$ = $\overline{\lambda}x$, $\lambda \in \mathbb{C}$, $x \in K$.
Can we identify the Hilbert spaces $H \otimes \overline{K}$ and $\overline{H \otimes K}$?
What about the spaces $B(H \otimes K)$ and $B(H \otimes \overline{K})$. More specifically, if $a_j \in B(H)$, $b_j \in B(K)$, $1 \leq j \leq n$, is it true that
\begin{equation}
\|\sum a_j \otimes b_j\|_{B(H \otimes K)} = \|\sum a_j \otimes \overline{b_j}\|_{B(H \otimes \overline{K})}
\end{equation}
Thank you.


text:
Q: Округление числа Builder C++ Всем доброго времени суток, столкнулся с следующей проблемой:
Есть некая написанная программа на C++ Builder 6 выполняющая серверную роль, опрашивает pci модули и производит нужный расчет, затем записывает данные в бин. файл и бд, далее клиент может просмотреть нужную информацию, но дело в том что при опросе модуля гуляет тысячная которая участвует в расчете, и я хочу эту тысячную округлять, диапазон разброса не большой +-1 тыс. Решил использовать фун-цию RoundTo но она мне не помогла тысячная как гуляла так и гуляет. Тогда решил посмотреть что происходит, создал тестовый пример:
float t,a = 1.001,Hl,Hh;
 t=a;
 t=RoundTo(t, -2);
 Hl=t-(t*.15); Hh=t+(t*.15);
Chart1->LeftAxis->SetMinMax(Hl,Hh);
Label1->Caption = Hl;

При значении 1.001 не особо заметно, но если например попадают сл. данные 1,151 и тогда можно заметить 1,977499961853027 - меня этот ответ не устраивает и если пересчитать на калькуляторе то мы получим число 0,97835 что также меня не устраивает, потому как я уже говорил выше тысячная гуляет на +-1 и должно быть вместо 1,151 - 1,150 а при 1,150 значения равны 0,9775 что мне и нужно. Перечитав много информации я понял что проблема с типами а именно когда я заменил тип с float на double мои данные стали отображаться так как мне нужно, но я не хочу менять тип, как реализовать тот же результат но с типом float ?


text:
Q: How to provide Store in component which doesn't has a default AppState from forRoot() jnitalization I have question about NGRX store, and providing it to components.
Currently my app architecture is like this:
app.module -> StoreModule.forRoot(reducers, {metaReducers})
export interface AppState {
  user: User.State;
}

export const reducers: ActionReducerMap<AppState> = {
  user: userReducer,
};

other feature module -> StoreModule.forFeature('feature', featureReducers),
In this approach everything is working fine and I can provide store to components like this:
constructor(
  private store: Store<AppState>,
) {}

Now I want to stop using default AppState. I want to remove forRoot in app.module and using only the features modules with forFeature.
In this situation how can I provide Store to components? What should I pass into Store<???>?

A: The store always contains the whole state object. When you inject the store, the generic is purely for type checking/safety. In other words, you can do:
constructor(
  private store: Store<FeatureState>,
) {}

Also, make sure you leave the forRoot import in your AppModule, you need this once in your application to wire up NgRx internally. While doing this you can pass an empty reducer object.
StoreModule.forRoot({}, [])


text:
Q: Did the Elder Wand's power in Draco's wand go back to the original Elder Wand once Harry owned both of them? I'll try to explain the question as best as I can, for those who are still confused about what really happened with the Elder Wand:
When Draco disarms Dumbledore on the Astronomy Tower, the actual Elder Wand doesn't go to Draco (it stays with Dumbledore in his tomb), but the power does go to Draco's wand.

"The Elder Wand recognized a new master before Dumbledore died, someone who never even laid a hand on it. The new master removed the wand from Dumbledore against his will, never realizing exactly what he had done, or that the world's most dangerous wand had given him its allegiance..."

When Harry gets the Elder Wand from Malfoy, he gets the wand with the Elder Wand's power.
Voldemort takes the original wand from Dumbledore's grave- but that doesn't give him the actual power of it.

"I stole the wand from its last master's tomb! I removed it against the last master's wishes! Its power is mine!"
"You still don't get it, Riddle, do you? Possessing the wand isn't enough! Holding it, using it, doesn't make it really yours."

So Harry disarms Voldemort, and gets the original Elder Wand- as the ex-Voldemort wand, and the Elder Wand's power as the ex-Draco's wand.
Now that Harry has both wands, would the "power" recognize the "original" wand and reunite with it, leaving Draco's wand powerless?
I would think that the wand wouldn't reunite with the power, because the wand's owner didn't defeat the owner of the Elder Wand's power.
But then Harry mends his wand with the Elder Wand, and it seems as if the Elder Wand got it's power back.

He laid the broken wand upon the headmaster's desk, touched it with the very tip of the Elder Wand, and said, "Reparo."

So what's happening? Why would the Elder Wand's power go back to the Elder Wand itself?

A: The physical wand and its 'power's never separate.
If you believe Ollivander's view of wandlore, only the master of a wand can use it to its full extent.
When Voldemort takes the Elder Wand from Dumbledore's grave, he has the wand with power intact, but cannot access its full power as Draco is its master.
When Harry defeats Draco, he gains mastery of the Elder Wand, but doesn't physically possess it.
Once Voldemort is defeated and Harry has hold of the Elder Wand, it 'recognises' him and he can use it's full power to repair his Phoenix-feather wand.


text:
Q: High accuracy in mode.fit but low precision and recall I've been training a CNN with keras. A binary classificator where it says if a depth image has a manhole or not. I've manually labeled the datasets with 0 (no manhole) and 1 (it has a manhole). I have 2 datasets 1 with 45k images to train the CNN and one with 26k images to test the CNN.
Both datasets are unbalanced double of negatives images than positives.
This is the code:
# dimensions of our images.
img_width, img_height = 80, 60
n_positives_img, n_negatives_img = 17874, 26308
n_total_img = 44182

#Labeled arrays for datasets
arrayceros = np.zeros(n_negatives_img)
arrayunos = np.ones(n_positives_img)

#Reshaping of datasets to convert separate them
arraynegativos= ds_negatives.reshape(( n_negatives_img, img_height, img_width,1))
arraypositivos= ds_positives.reshape((n_positives_img, img_height, img_width,1))

#Labeling datasets with the arrays
ds_negatives_target = tf.data.Dataset.from_tensor_slices((arraynegativos, arrayceros))
ds_positives_target = tf.data.Dataset.from_tensor_slices((arraypositivos, arrayunos))

#Concatenate 2 datasets and shuffle them
ds_concatenate = ds_negatives_target.concatenate(ds_positives_target)
datasetfinal = ds_concatenate.shuffle(n_total_img)

Then I have the same for the second dataset for testing.
#Adding batch dimension to datasets 4dim
valid_ds = datasetfinal2.batch(12)
train_ds = datasetfinal.batch(12)

#Defining model
model = Sequential()
model.add(Conv2D(5, kernel_size=(5, 5),activation='relu',input_shape=(60,80,1),padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling2D((5, 5),padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(5, (5, 5), activation='relu',padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(5, (5, 5), activation='relu',padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
model.add(Dropout(0.3))
model.add(Conv2D(5, (5, 5), activation='relu',padding='same'))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(50, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))

#Compiling model
model.summary()

initial_learning_rate = 0.001
lr_schedule = keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True
)
model.compile(
    loss="binary_crossentropy",
    optimizer=keras.optimizers.Adam(learning_rate=lr_schedule),
    metrics=["acc"],
)

# Define callbacks.
checkpoint_cb = keras.callbacks.ModelCheckpoint(
    "2d_image_classification.h5", save_best_only=True
)
early_stopping_cb = keras.callbacks.EarlyStopping(monitor="val_acc", patience=15)

#Fitting the model
history= model.fit(train_ds, validation_data=valid_ds, batch_size=100, epochs=5,callbacks=[checkpoint_cb, early_stopping_cb])

This gives me 99% of acc in train dataset and 95% in test dataset.
But when i do this it gives me 60% precision for negatives images and 45% for positives:
#Get the real labels of valid dataset
valid_labels = list(valid_ds.flat_map(lambda x, y: tf.data.Dataset.from_tensor_slices((x, y))).as_numpy_iterator())
valid_labels = [y for x, y in valid_labels]

y_pred = model.predict(valid_ds)
y_pred = (y_pred > 0.5).astype(float)

from sklearn.metrics import classification_report
print(classification_report(valid_labels, y_pred))

Why this? I have printed both predicted labels and true labels and it look likes its random. It has no sense.
https://colab.research.google.com/drive/1bhrntDItqoeT0KLb-aKp0W8cV6LOQOtP?usp=sharing
If u need more information, just ask me.
Thanks!!!!


text:
Q: Why doesn't specifying the full path of an mp4 in video file work when relative path does using PHP on apache/Ubuntu 20.04 I've got a number of mp4 video files in a folder.  When I use scandir with a relative path, the files display correctly in the webpage and can be played.
Browser html looks like this.

<video src="./mp4Files/video1.mp4" type="video/mp4" loop class="clip" controls
</video>

When I specify the full path of the file, scandir finds the files, the browser constructs the videos in a  but the error appears - no video with supported format and MIME type found.
Browser html looks like

    <video src="/var/www/html/VideoRecTest/mp4Files/video1.mp4" type="video/mp4" loop
    class="clip" controls></video>

btw, open_base_dir has no value when I do a phpinfo().

A: These are not webservers

*

*html

*php

*javascript
These are webservers

*

*nginx

*apache2
Your webserver's vhost configuration will contain a path that is served as the root directory.
/var/www/html/ becomes 0.0.0.0/ or example.com/.
When you then want to visit, for example index.php the URI would be 0.0.0.0/index.php which uses /var/www/html/index.php.
Your use-case here is configured at /var/www/html and thus giving a path of /var/www/html/VideoRecTest/mp4Files/video1.mp4 would merely give an absolute path of
/var/www/html/var/www/html/VideoRecTest/mp4Files/video1.mp4

Your video would, however, be accessible perfectly fine just at
/VideoRecTest/mp4Files/video1.mp4

Since your webserver is already configured to serve directories and files from the root directory /var/www/html.
You also cannot traverse below the specified root directory. 0.0.0.0/../ will translate to /var/www/html/ and thus redirect back to 0.0.0.0/.
Note, the root directory can be changed in your vhost configuration. I use /var/www/html as an example due to it being the default.


text:
Q: Read data in a url in R I want to read the data in the following url into R but I couldn't do it.
Does anyone have any idea about it?? Thanks!
http://web.stanford.edu/~hastie/ElemStatLearn/
I need the data Ozone

A: The data is hosted at http://web.stanford.edu/~hastie/ElemStatLearn/datasets/ozone.data
The values are tab-separated, so you can read it using read_tsv from the readr package:
library(readr)
read_tsv("http://web.stanford.edu/~hastie/ElemStatLearn/datasets/ozone.data")

This will read the data directly from the website, so you won't need to download it manually yourself.


text:
Q: adding customed javascript analytics code to magento site i have created customized analytic code for my clients. It tracks visits and conversions. One is to be placed on the "thank you" page and one on all other pages. What is the quickest way to get my magento guys to paste the codes? Is there a header file and "thank you" page in magento for the codes. Do I write an extension for that? Any help will do. Thanks

A: You can add a global code to
/app/design/frontend/[your-interface]/[your-theme]/template/page/html/header.phtml

or
/app/design/frontend/[your-interface]/[your-theme]/template/page/html/footer.phtml

and the thank you page code can be placed at
/app/design/frontend/[your-interface]/[your-theme]/template/checkout/success.phtml


text:
Q: Download multiple MP3 files in the background in Android LEVEL: Beginner
Language: Java
IDE: Android Studio
CASE: Downloading multiple MP3 files from multiple URL's in a row in the background.
ISSUE: download task in the loop to download all the urls.
the songs did download in the following path but aren't fully downloaded (every song is downloaded for 3 seconds/4 seconds basically very less).
don't know what's the problem, It'll be great if i can get any help

*

*receive mp3 url's from API

*download them using the following code. (ISSUE)

*get the path of all and store them in the Database

*fetch the path and play one by one continuously.
private class DownloadTask extends AsyncTask<SongDetails, Integer, String> {
Context context;

public DownloadTask(Context context) {
    this.context = context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    Utilities.showProgressDialog(getActivity(), getFragmentManager());
}

@Override
protected String doInBackground(SongDetails... songDetails) {
    for (SongDetails songs : songDetails
    ) {
        donwloadsong(songs);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Utilities.dismissProgressDialog();
}
}

 for (SongDetails songs : songDetails
    ) {
        downloadTask(songs);
    }

 public void downloadTask(SongDetails songs){
   HttpURLConnection httpURLConnection = null;
   try {
     URL url = new URL(songs.getUrl());
     httpURLConnection = (HttpURLConnection) url.openConnection();
     httpURLConnection.setRequestMethod("GET");
     httpURLConnection.connect();

    int fileLength = httpURLConnection.getContentLength();
         InputStream inputStream = new
    BufferedInputStream(url.openStream(), 8192);
    OutputStream outputStream1;
    outputStream1 = new
    FileOutputStream(Environment.getExternalStorageDirectory() + "/gbeduwarssongs/" + songDetails.getTitle().trim() + ".mp3");
    int count = 0;
         byte data[] = new byte[1024];
    int buffer_length;

    while ((buffer_length = inputStream.read(data)) != -1) {
        outputStream1.write(data, 0, count);
          count += buffer_length;
    }
    outputStream1.flush();
    outputStream1.close();
    inputStream.close();

} catch (Exception e) {
    e.printStackTrace();
    Log.e("Error", "Download Error Exception " + e.getMessage());
} finally {
    if (httpURLConnection != null)
        httpURLConnection.disconnect();
  }
}

A: Rather calling iteration inside a new thread, use iteration first and then start new thread in every iteration. I hope it will help you. I am posting code for your help.
for (SongDetails songs : songDetails) {
        new DownloadTask(pass your song object in constructor).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

and in doInBackground call your downloading method stuff.

A: I offer to use DownloadManager or workmanager for it. AsyncTask has used a bad idea. It has a problem with a memory leak.
The asyncTask use only one thread
The same question


text:
Q: wp_insert_post not returning post ID? I've had a read of the existing posts on here and still can't see why my instance is doing this, but I'm using wp_insert_post to add a post with some data it's given, and it's inserting the post just fine but the function is returning 0 in place of the post ID - does it have to be triggered to use this?
    $ember_prepare_post = array(
    'post_author' => $ember_current_user_id,
    'post_category' => $ember_post_category,
    'post_content' => $ember_post_content,
    'post_title' => $ember_post_title,
    'post_status' => 'publish',
    'post_excerpt' => $ember_post_excerpt,
    'tags_input' => $ember_post_tags
    );

// now we've prepared an array with the data, we're going to save it into the WP database and obtain the resulting post ID.

$ember_newpost_id = wp_insert_post($ember_prepare_post, true);

I'm not seeing any errors, and have had a read of the wp_insert_post function itself and cannot see why it wouldn't work. The ID's of the posts it creates definitely aren't zero, either.
Thanks!


text:
Q: Change tabitem style when selected item changes I have a TabControl and a style for each of my TabItem (with a StyleSelector).
I want each TabItem to change its style when the selected item changes.
So I create a TabItemCustom with a property IsItemAfterSelected:
public class TabItemCustom: TabItem
{
    public static readonly DependencyProperty IsItemAfterSelectedProperty =
    DependencyProperty.Register("IsItemAfterSelected",
        typeof(bool),
        typeof(TabItemCustom),
        new PropertyMetadata(false));
    public bool IsItemAfterSelected
    {
        get { return (bool)GetValue(IsItemAfterSelectedProperty ); }
        set { SetValue(IsItemAfterSelectedProperty , value); }
    }
}

This property has to contain True if one of the next items is selected.
I can know when the SelectedIndex changes with this DataTrigger:
<sys:Boolean x:Key="StyleValueTrue">True</sys:Boolean>
<DataTrigger Binding="{Binding Path=SelectedIndex, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabControl}}, Mode=TwoWay, Converter={StaticResource ConverterTabItemAriane}}" Value="{StaticResource StyleValueTrue}">
    <Setter Property="IsItemAfterSelected" Value="{Binding Converter={StaticResource ConverterTabItemAriane}, RelativeSource={RelativeSource Self}}"/>
 </DataTrigger>

I use the same converter to detect if is the SelectedIndex (if integer always return True) and to set my value:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value is DependencyObject)
    {
        DependencyObject container = (DependencyObject)value;
        var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
        var itemIndex = itemsControl.ItemContainerGenerator.IndexFromContainer(container);
        if (itemsControl is TabControl)
        {
            TabControl tabcontrol = (TabControl)itemsControl;
            if (tabcontrol.SelectedIndex >= itemIndex) return true;
            else return false;
        }
    }
    else if (value is int) return true;// selected index has changed
        return false;
    }

I've checked with breakpoints: when I change the selected item it goes in the converter and returns True.
But my Property is set only once on the loading of the TabControl. The Trigger always return the same value why the property is set once?
When I'll be able to set this property my goal is to add a DataTrigger like this:
<DataTrigger Property="IsItemAfterSelected" Value="True">
    <Setter Property="Background" Value="Red" />
</DataTrigger>

I don't know if my approach is the easiest but I didn't found a better solution (I've tried removing StyleValueTrue and put True instead but same result).
Any thoughts to solve this?

A: If you want to do it with Bindings:
XAML:
<Style TargetType="{x:Type local:TabItemCustom}">
    <Setter Property="IsItemAfterSelected">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource ConverterTabItemAriane}">
                <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type TabControl}}"/>
                <Binding RelativeSource="{RelativeSource Self}"/>
                <Binding Path="SelectedIndex" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type TabControl}}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsItemAfterSelected" Value="True">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

Converter:
public class ConverterTabItemAriane : IMultiValueConverter
{

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        TabControl tabControl = values[0] as TabControl;
        TabItem tabItem = values[1] as TabItem;
        if (tabControl != null && tabItem != null && values[2] is int)
        {
            var selectedIndex = (int)values[2];
            var itemIndex = tabControl.ItemContainerGenerator.IndexFromContainer(tabItem);
            return selectedIndex >= itemIndex;
        }
        return false;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

If you want to do it inside your TabControl:
XAML:
<Style TargetType="{x:Type local:TabItemCustom}">
    <Style.Triggers>
        <Trigger Property="IsItemAfterSelected" Value="True">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

TabControl:
public class TabControlCustom : TabControl
{
    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
        return new TabItemCustom();
    }

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);

        int i = 0;
        foreach (var item in Items)
        {
            var tabItem = ItemContainerGenerator.ContainerFromItem(item) as TabItemCustom;
            if (tabItem != null)
            {
                tabItem.IsItemAfterSelected = SelectedIndex >= i;
            }
            i++;
        }
    }
}


text:
Q: How to use Mockito to check number of calls to a function without making Mockito make an extra call We have made our own framework that makes it easy to setup an analysis pipeline.
Every time an analysis ends, finish() is called.
finish() uploads files that were generated during the analysis.
To ensure that the framework was used correctly, we have made a check that finish() is not called twice.
Now, I want to test that finish() is called for a specific step in the pipeline.
I do this by calling the following in my test:
verify(consumer).finish();

But apparently, verify() also calls finish() so an exception is thrown and the test fails.
Now, my question is:

*

*How do I avoid that finish() is called twice?

EDIT
A quick setup of the problem:
Analysis
package mockitoTwice;

public class Analysis extends Finishable {
    @Override
    public void finishHelper() {
        System.out.println("Calling finishHelper()");
    }
}

Finishable
package mockitoTwice;

public abstract class Finishable {
    protected boolean finished = false;

    public final void finish() {
        System.out.println("Calling finish()");
        if (finished) {
            throw new IllegalStateException();
        }
        finished = true;
        finishHelper();
    }

    public abstract void finishHelper();
}

Pipeline
package mockitoTwice;

public class Pipeline {
    private Analysis analysis;

    public Pipeline(Analysis analysis) {
        this.analysis = analysis;
    }

    public void runAnalyses() {
        analysis.finish();
    }
}

PipelineTest
package mockitoTwice;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Test;

public class PipelineTest {
    @Test
    public void test() {
        Analysis analysis = mock(Analysis.class);
        Pipeline pipeline = new Pipeline(analysis);
        pipeline.runAnalyses();
        verify(analysis).finish();
    }
}

A: Testing frameworks all have their quirks, but when you encounter problems like this then the first step is to assess your class and test design.
First, I notice that AnalysisTest isn't really testing the Analysis class. It's mocking Analysis and actually testing the Pipeline class. A proper test for Analysis would look something like this:
@Test
public void testFinishTwice() {

    Analysis analysis = new Analysis();

    try {
        analysis.finish();
        analysis.finish();
        Assert.fail();
    } catch (IllegalStateException ex) {
       // Optionally assert something about ex
    }
}

This will verify the implied contract that Analysis throws IllegalStateException when finish() is called more than once. There are a variety of solutions to your problem and most of them depend on validating this.
Next, the abstract Finishable class with a final finish() method is not quite as foolproof as it looks. Since the finishHelper method has protected access, then it is still accessible directly to any class in the package. So in your example, if Pipeline and Analysis are in the same package, then Pipeline could call finishHelper directly. I would guess that's the single biggest risk of the actual finish code getting called twice. How easy would it be to accidentally let your IDE autocomplete to finishHelper? Even if your unit test worked as you wanted, it could not catch this.
Now that I've addressed that, we can get to the root of the problem. The finish method is marked as final, so Mockito can't override it. Normally, Mockito would create a stub method for it but here it has to use the original code from Finishable. A true mock wouldn't even print "Calling finish()" when finish is called. Since it's stuck with original implementation, the real finish method gets called both by pipeline and then again by verify(analysis).finish();
So what do we do about it? There's no perfect answer and it really depends on details of the situation.
The simplest approach would be to drop the final keyword on the finish method. Then you just have to make sure that Analysis and Pipeline are not in the same package. The test you wrote ensures and the Pipeline only calls finish once. The test I suggested guarantees an exception the second time finish is called on Analysis. This happens even if it would override finish. You could still abuse it, but you'd have to deliberately go out of your way to do it.
You could also switch Finishable to an interface and rename your current class AbstractFinishable as a base implementation. Then switch Analysis to an interface that extends Finishable and create an ExampleAnalysis class that extends AbstractFinishable and implements Analysis. Then Pipeline references the Analysis interface. We have to do it that way because otherwise it could get access to finishHelper and we are back where we started. Here's a sketch of the code:
public interface Finishable {
    public void finish();
}

public abstract class AbstractFinishable implements Finishable {
    // your current Finishable class with final finish method goes here
}

public interface Analysis extends Finishable {
    // Other analysis methods that Pipeline needs go here
}

public ExampleAnalysis extends AbstractFinishable implements Analysis {
    // Implementations of Analysis methods go here
}

So that's one way to do it. It's essentially switching the classes to be coded to interfaces of their dependencies rather than specific class implementations. That's generally easier to mock and test. You could also use the delegate pattern and just put a Finishable on ExampleAnalysis rather than extending AbstractFinishable. There are other ways, too, and these are just ideas. You should know the specifics of your project well enough to decide the best route.

A: I verify it like this : verify(object, times(1)).doStuff();

A: The problem can be solved by catching the exception of the framework as follows:
@Rule
public ExpectedException exception;

@Test
public void test() {
    Analysis analysis = mock(Analysis.class);
    Pipeline pipeline = new Pipeline(analysis);
    pipeline.runAnalyses();
    exception.expect(IllegalStateException.class);
    verify(analysis).finish();
}

If finish() is called too few times, the verify handles the problem as one would expect.
If finish() is called too many times, the exception is called on pipeline.runAnalyses().
Otherwise, the test is successful.


text:
Q: How to extract part of string an array of strings in Node.js? I am trying to extract a part of a string for each element in the array.
I have managed to get all files ending with .pdf, but I don't know how to do the extraction part.
I would assume that I need to use a regular expression to do this job, however, I am not sure where to start with that.
Given the first element ./pdf/main/test1.pdf, I want to return /test1.pdf.
Follow my code below:
    glob('./pdf/main/*.pdf', {}, (err, files) => {
      console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
      files.map(f => {
        // Here I want to extract and return the following output:
        // /test1.pdf
        // /test2.pdf
      })
    })

A: Simple using split and retrieving the last value should do it
glob('./pdf/main/*.pdf', {}, (err, files) => {
  console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
  files.map(f => {
    let split = f.split('/'); // ['.', 'pdf', 'main', 'test1.pdf']
    return `/${split[split.length - 1]}`; // /test1.pdf
  })
})

Also since you've tagged node.js, and assuming this relates to file paths, you can use the basename function of the path module to do this, see here
nodejs get file name from absolute path?
glob('./pdf/main/*.pdf', {}, (err, files) => {
  console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
  files.map(f => `/${path.basename(f)}`); // ['/test1.pdf',  '/test2.pdf']
})

A: String split and using the path.basename may be easy to understand.
In case you'd like to know how to use regex to extract the filename, you could try the following code
glob('./pdf/main/*.pdf', {}, (err, files) => {
   files.map(f => f.match(/.*(?<filename>\/.+?\.pdf)/).groups.filename)
}


text:
Q: How to get bundle price from the steam web API I was looking to get some current price info for bundles from steam's json web api. Currently, I can retrieve price information for individual apps but I haven't worked it out for bundles yet.
Any clues?
Thanks


text:
Q: How to transform the data using $if $else condition mongodb How to transform the data using $if $else condition MongoDB
mongoPlayground
When no data we get I want to setup have an object
record: [
    {
      "text": "No Found",
    }
  ]

A: It looks like your query is attempting to match documents where the embedded History.user_id array contains a specific value, and the date field is greater than the History.date field.  You don't need $cond'/$iffor that, you can use$and`
db.main.aggregate([
  {$lookup: {
      from: "history",
      localField: "history_id",
      foreignField: "_id",
      as: "History"
  }},
  {$unwind: "$History"},
  {"$match": {
      $expr: {
        $and: [
          {$in: [
              "5e4a8d2d3952132a08ae5763",
              "$History.user_id"
          ]},
          {$gt: [
              "$date",
              "$History.date"
          ]}
        ]
      }
    }
  }
])

A: You Can Follow The Code
db.project.aggregate([

    {
        $project:{
            title:1,

            "author.middle":{
            $cond:{

                if:{$eq:["","$author.middle"]},
                then:"$$REMOVE",
                else:"$author.middle"
            }

            }
        }
    }

])


text:
Q: Unique polynomial in $C[x,y]$ I am working on the below problem:
Let $I$ be the ideal generated by $x$ and $y$ in $\mathbb{C}[x,y]$. Prove that there is a unique (up to scalar) polynomial $f(x,y)$ of degree $2$ in $I^2$ which satisfies $f(2,3) = f(-1,5) = 0$.
Here are my thoughts so far:
If $I = \langle{x,y}\rangle$ in $\mathbb{C}[x,y]$, from what I understand, $I^2 = \langle{x^2,y^2,xy}\rangle$ in $\mathbb{C}[x,y]$. Thus, if we have a polynomial of degree $2$ in $I^2$, $f(x,y) = ax^2 + by^2 + cxy$ for some complex scalars $a,b,c$.
Thus, if $f(2,3) = f(-1,5) = 0$, we have $0 = 4a + 9b + 6c$ and $0 = a + 25b -5c$. It remains to show that we can solve this system of $2$ equations in $3$ unknowns uniquely for $a,b,c$.
But, this seems impossible to me. A system of $n$ equations with $n + 1$ unknowns can't be solved uniquely. Where did my thinking go wrong? If I instead take $I^2 = \langle{x^2,y^2}\rangle$, the problem will work out -- we will arrive at a system of $2$ equations in $2$ unknowns, and the corresponding matrix will have full rank (determinant nonzero), so there will be a unique solution. But, this contradicts the notion of a square of an ideal.
With the right notion of the square of an ideal, is there a third equation I can arrive at from the given information?
Thanks!

A: I note that "up to scalar" allows a third degree of freedom.  Are you sure that your parametrized set of solutions are not all the same up to scalar multiple?
(When I solve it, this turns out to be the case.)


text:
Q: npm debug module: how to display object in fine prints? I'm using this nice node debug module,
https://www.npmjs.com/package/debug
All good except debug(req.body)
gives me [object Object]
was hoping to see a beautifully printed json object.

A: It seems that the npm module you are using is using console.error behind the scenes to log the messages.
If you pass an object, it will be stringified (using the toString method). As you can see in the previous link, by default an object is stringified as [object type] which in your case results in [object Object].
You can print the whole object by stringifying it. One simple way of doing that is using the JSON.stringify method:
debug(JSON.stringify(req.body))

Take into account that this strategy will fail if your JSON object has circular references!


text:
Q: Create AccountHistory record in test class Can we create the AccountHistory Reocrd in test class if it is possible plz post how ?

A: You can not create History records of any object.
Basically for creating them you have to make changes in that particular object record and then query the history records.

A: AccountHistory Represents the history of changes to the values in the fields of an account. You can not create AccountHistory Reocrd .
You can query AccountHistory record. In test class you have to set seeAllData=true
SELECT CreatedDate,Field,Id,IsDeleted,NewValue,OldValue FROM AccountHistory

A: It is suggested that it is possible to create AccountHistory Record in test here. However, you can't specify NewValue or OldValue fields values.
Still, it doesn't seem to be working for me: when I run code
@isTest class TestClass {
    static testMethod void testMetod() {
        Account a = new Account(Name = 'a');
        insert a;
        insert new AccountHistory(AccountId=a.Id, Field = 'Name');
    }
}

I see internal error
Maybe it is only error in my environment and it may work fine in your environment or in the future release.


text:
Q: How do I use remote machine's SSH keys in ansible git module I've been trying to get Ansible to provision a remote machine, and I want the remote machine to be set up with its own keys, and have the ability to clone git repositories from Bitbucket.
The user is set up, has its own id_rsa.pub, and the key has been registered with bitbucket.
But, when I use the Ansible Git module, it looks like the module always tries to use the keys from the machine running the playbook.
How do I get the git module to use the id_rsa.pub from the remote machine?
The relevant task is this:
- name: be sure prom-king has an up-to-date clone of its own repository
  git:
    repo: "ssh://ddcrnd@bitbucket.org/prom-king.git"
    dest: /home/promking/prom-king
    accept_hostkey: yes
    clone: yes
    key_file: /home/promking/.ssh/id_rsa.pub
    update: yes

The relevant inventory is this
# inventory file for use with the vagrant box in the testing directory.
[prom-king]
192.168.168.192 ansible_ssh_host=127.0.0.1 ansible_sudo=true ansible_connection=ssh  ansible_ssh_port=2222 ansible_ssh_user=vagrant ansible_ssh_private_key_file=testing/.vagrant/machines/default/virtualbox/private_key

A: This is how I deploy from Github using a key file set on the remote server. If the keyfile parameter for git doesn't work then something is wrong with your playbook:
- name: Creates .ssh directory for root
  sudo: yes
  file: path=/root/.ssh state=directory

# This public key is set on Github repo Settings under "Deploy keys"
- name: Upload the private key used for Github cloning
  sudo: yes
  copy: src=keys/github dest=/root/.ssh/github

- name: Correct SSH deploy key permissions
  sudo: yes
  file: dest=/root/.ssh/github mode=0600

- name: Deploy site files from Github repository
  sudo: yes
  git:
    repo: git@github.com:miohtama/foobar.git
    dest: /srv/django/foobar
    key_file: /root/.ssh/github
    accept_hostkey: yes
    force: yes

A: If I understand this correctly, you do - or want to - deploy your private key to the remote machine so you can clone the repo. I believe instead you should use key forwarding. In your .ssh/config set this:
ForwardAgent yes

Or if you want to limit this to Ansible you can define it in your ansible.cfg:
[ssh_connection]
ssh_args= -A

A: A note in case useful: for anyone using github (and I assume also applies to gitlab, etc.) - ensure that you provide the URL, correctly, in SSH form. If the key file is provided but you give ansible the HTTPS URL, it'll just quietly ignore the key and (potentially) hang waiting for input with a username and password.


text:
Q: Code like Bookworm Adventures in Unity How do you animate if the button is correct and the other buttons are not correct
if(btnA.isCorrect){
            //btnA Animation
         } else if(btnB.isCorrect){
             //btnB Animation
         } else if (btnC.isCorrect){
             //btnC Animation
         } else {
             //btnD Animation
         }

I have that code inside the method  UserSelect(int n) wherein n determines the btnNumber in my buttons,
and I do think that this is the logic of what I wanted to do if the user selected the buttons
PS: if the user selected a button and it is correct, the player will attack an enemy, otherwise, the enemy will attack the player


text:
Q: How I can get all activated pixels when in a touch event? I don't know if it is possible using Objective-C, but I would like to find all the pixels/points that have been sensibilized in a touch event.
For example, if I use my thumb to touch the screen, then I will 'activate' certain pixels. If I use a pen to do the same thing, then I should get fewer pixels activated.
Is there a way to retrieve the coordinates of these pixels?

A: This is currently not supported in the SDK (I actually submitted a request for the very same feature).
Ten One Design created a framework and demo'd it: http://www.macrumors.com/2010/07/01/pressure-sensitive-sketching-on-ipad-demoed/
Unfortunately, they used private APIs, and have yet to release it to the public (although it would still not be very valuable for a distribution build).

We plan to release this capability as
  a free software library so it can be
  included in any application.  However,
  this may not be possible for a while
  as the library now uses a private
  function call to access the required
  information.

A: its important to remember how touch detection works in iOS, the hardware and abstraction layer must detect the exact size of the touch in order to work out what the touch actually touches, iOS internally just checks to see which of the responders highest up the stack has the touch within its bounds. if it handles the touch, it goes from there and uses the first one as the responder.
this is total speculation but maybe you could set up a pseudo grid view in iOS that is transparent and detect which of your grid cells are within the touch ??? just an idea, and maybe fraught with performance issues but maybe a start ..?


text:
Q: Calculating some kind of confidence or error rate for a set of binary data Newbie question here. I'm calculating error rates from software test results. Basically for any particular test run it's going to pass or fail, in this case, because of inherent race conditions in the software in question. We're running about ~50k overall tests a week (some particular tests might be run 4000 times a week, some 200, with all sorts of numbers in between), so I'm starting to quantify the results of these into failure rates.
However, clearly the answer from failing 3 out of 200 tests is a less certain value that failing 30 out of 2000. So given a series of binary data, with no known baseline, is there a standard method using the sample size to provide some error rate?
The other challenge that this data has is we are doing rolling binning. So calculating the failure rates every day. Which means that at some point early in the day there are only a few events. It would be good to be able to quantify the difference in confidence between 4/4 success results vs. 100/100 success results.
Part of my thinking was that you could quantify this as 1/n (n being population size) as you could never know the answer better than the "resolution" you have. However, that's just instincts kicking in, with no statistical backing in there.

A: Constant failure rate within a given proportion, independent failure events
If the failure rate is constant under a given set of conditions and the tests are independent, then the occurrence of failures follows a Bernoulli process.
In that case, you can generate intervals for the proportion of failures assuming a binomial proportion.
The standard error of the proportion is $\sqrt{ p (1- p)/n}$, which is usually estimated as $\sqrt{\hat p (1-\hat p)/n}$, where $\hat p$ is the sample proportion.
With large sample size (as long as the proportion isn't too small), you might as well use the normal approximation; for an interval of coverage $1-\alpha$, the interval for $p$, the population proportion is
$$\hat p\pm z_{1-\frac{\alpha}{2}}\sqrt{\hat p (1-\hat p)/n}$$
if $p$ is small (so small that $np$ is less than 20 say), you might be better to choose one of the other intervals, such as the Wilson interval or the Clopper-Pearson interval.
In the situation where you have all-0, clearly $np$ is likely to be much less than 20 -- or even 5. Normal approximations cannot be used! A few of the other intervals do okay in this case (though some still need to be truncated to 0 on the left side), but a common approach* is the rule of three. Similar comments apply for all-1 by interchanging success and failure.
*(assuming a 95% interval, though the approach adapts to other coverage probabilities)

If the underlying rate is not constant within a calculated proportion, or there is dependence, then the nature of the variation in rate or the dependence structure (respectively) would usually need to be characterized in some way.
If we can assume independence between trials, we can quantify whether there's over-or-under dispersion relative to the constant-p assumption, and we can look for trends (changing average over time) in binomial proportions, via (say) smoothing splines in logistic regression. If there are, you need to be careful about what your hypotheses might be (you're not generally testing just a difference then).
If you're prepared to assume a mixture distribution with constant combination of binomial proportions within each group being compared (which may be untenable), it might be reasonable to consider some kind of permutation (when testing) or bootstrapping (when constructing intervals) approach.
On the other hand, if we can assume constant $p$, we can check for serial dependence fairly readily.


text:
Q: Execute SQL in File Geodatabase Is there a way to execute SQL queries on file geodatabase from Python? I'm looking for the same functionality provided by arcpy.ArcSDESQLExecute for SDE databases.

A: Most Python queries are limited to a Where clause, however, you can execute a subquery in the Select_By_attribute tool. Please see the ArcGIS SQL Reference for more details. Also, the arcpy.da UpdateCursor and SearchCursor let you issue groupby, distinct, top, order by in a sql_clause along with the where_clause.
From the SQL reference for query expressions used in ArcGIS:

Coverages, shapefiles, and other nongeodatabase file-based data
  sources do not support subqueries. Subqueries that are performed on
  versioned ArcSDE feature classes and tables will not return features
  that are stored in the delta tables. File geodatabases provide the
  limited support for subqueries explained in this section, while
  personal and ArcSDE geodatabases provide full support. For information
  on the full set of subquery capabilities of personal and ArcSDE
  geodatabases, refer to your DBMS documentation.

A: It is possible to use arbitrary SQL (though likely with some limitations) with the file geodatabase API driver of GDAL/OGR. See my answer this related question: ogr2ogr / GDAL remove features in FileGDB while in use by ArcGIS Server map service
Also, if you are looking to do this with Python and on Windows take a look at this question: Gdal Python Bindings and File Geodatabase API


text:
Q: How to send an array from React Application to Flask Application I've been trying to send a simple array from my React app to my Flask app but I'm pretty new to application networks.
Flask (entire application):
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data = request.data

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

Going to localhost:5000 when both apps are running I get:
 Internal Server Error
 The server encountered an internal error and was unable to
 complete
 your request. Either the server is overloaded or there is an error
 in the application.

React:
sendTopArtists() {
  fetch("http://localhost:5000", {
    method: "POST",
    headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json',
    },
    body:  JSON.stringify(artistList)
  })
  .then(function(response){
   return response.json();
   })
   .then(function(artistList){
   console.log(artistList)
   });
}

How do I send an array from my React app running on localhost:3000 to my Flask app running on localhost:5000?
Thanks!


text:
Q: Astyle does not work in Windows I just download Astyle from SourceForge. When I execute Astyle.exe in /bin, it said
Cannot convert to multi-byte string, reverting to English.
I don't know what happened.
I find there is a similar question, but that is about Astyle in OS X.
Here are the source code related to the error. I don't know the meaning of the second line.
// Not all compilers support the C++ function locale::global(locale(""));
// For testing on Windows change the "Region and Language" settings or use AppLocale.
// For testing on Linux change the LANG environment variable: LANG=fr_FR.UTF-8.
// setlocale() will use the LANG environment variable on Linux.

char* localeName = setlocale(LC_ALL, "");
if (localeName == NULL)     // use the english (ascii) defaults
{
    fprintf(stderr, "\n%s\n\n", "Cannot set native locale, reverting to English");
    setTranslationClass();
    return;
}

Finally, please feel free to correct my English.

A: Add following include to both ASLocalizer.cpp and style_main.cpp:
<#include "locale.h">


text:
Q: Easier way to rename all the TextViews in a fragment? I currently have a fragment with a bunch of card things I made. I'm trying to find an easier way to rename each of the textview's inside each card with data from an ArrayList containing "ScheduleEntry" instances. Any advice is appreciated!
XML Layout
http://pastebin.com/B8Nn9ZV0
Java Fragment
http://pastebin.com/a9LiSuDw
ScheduleEntry.java
    package club.spiralsolutions.witsmobile;

    public class ScheduleEntry {
    public int getPeriod() {
        return period;
    }

    public void setPeriod(int period) {
        this.period = period;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public int getAverage() {
        return average;
    }

    public void setAverage(int average) {
        this.average = average;
    }

    private int period;
    private String name;
    private int ID;
    private String teacher;
    private String room;
    private int average;

    public ScheduleEntry()
    {

    }

    public ScheduleEntry(int period, String name, int ID, String teacher, String room, int average)
    {
        this.period = period;
        this.name = name;
        this.ID = ID;
        this.teacher = teacher;
        this.room = room;
        this.average = average;
    }
    public ScheduleEntry(int period, String name, int ID, String teacher, String room)
    {
        this.period = period;
        this.name = name;
        this.ID = ID;
        this.teacher = teacher;
        this.room = room;

    }

}

A: You should create a list of card views , you could use RecyclerView which is availble in the v7 support library , here's a great training tutorial from the android developer website :
https://developer.android.com/training/material/lists-cards.html


text:
Q: line 26, in __init__ tk.Tk().__init__(self, *args, **kwargs). TypeError: create() argument 1 must be str or None, not App The problem here is that I get an error saying:
line 26, in init     tk.Tk().init(self, *args, **kwargs).
TypeError: create() argument 1 must be str or None, not App.
I have never dealt with this kind of error before does anyone know how to solve this?
import tkinter as tk
import tkinter.ttk as ttk

class App(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Tk().__init__(self, *args, **kwargs)
        container = tk.Frame(self)

        container.pack(side='top',fill="both",expand = True)

        container.grid_rowconfigure(0, weight =1)
        container.grid_columnconfigure(0, weight = 1)

        tk.Frame.title('Simulator')
        self.geometry("800x800")
        self.resizable(False, False)

        self.label = ttk.Label(self, text='Sim',font=("Calibri",28,"bold"))

        self.label0 = ttk.Label(self,font=("Calibri",24,"bold"), text='Monkey')
        self.label1 = ttk.Label(self,font=("Calibri",24,"bold"), text='Giraffe')
        self.label2 = ttk.Label(self, text="Flat border", font=("Calibri",24,"bold"), relief="flat")

# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    App = App()
    App.mainloop()
    time_hours(5)

A: There are few issues in your code:

*

*App should be inherited from tk.Tk instead of tk.Frame

*tk.Tk().__init__(self, *args, **kwargs) should be tk.Tk.__init__(self, *args, **kwargs), or super().__init__(*args, **kwargs)

*tk.Frame.title('Simulator') should be self.title('Simulator')

*self.simulation += [Monkey(), Giraffe, Elephant()] should be self.simulation += [Monkey(), Giraffe(), Elephant()], I think

*need to add from tkinter.messagebox import showinfo


text:
Q: mysql - retrieve specific column name from table I'm begginer in MYSQL.
I need to retrieve the COLUMN NAMES of columns which have value "TRUE"?
I found this code but I don't understand how to user it:
 SELECT `COLUMN_NAME`
 FROM `INFORMATION_SCHEMA`.`COLUMNS`
 WHERE `TABLE_NAME`='tablename'

Thanks in advance

A: I think this will help you MySQL query to get column names?
With the following you will get all information about the specific column
SELECT *
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
    AND `TABLE_NAME`='yourtablename';
    AND `COLUMN_NAME` = 'namecolumn'

If you want the names of all columns which have the value true in a row you could use foreach if you use php and write all keys in an array for example where the value is true
$list = array();
foreach($rows as $key => $value)
{
   if($value === true) $list[] = $key;
}

A: This code shows all column names from a specific table, the schema INFORMATION_SCHEMA stores information about the items created on your database server(schemas, tables, columns etc.)
The statement above will show you alle columns from tablename, theres also a more simple syntax to do this SHOW COLUMNS FROM tablename (MySQL Manual)
How do you want to determine that the value of a column is true? Maybe there a two rows in your table with the values TRUE and FALSE for one column (TRUE in one row and FALSE in the other row)
With one Row in PHP
If there is only one row in your table execute the SHOW COLUMNS FROM tablename do a fetch_array on the result and then foreach and save only the keys where the value is TRUE.
If you try to store something like a configuration use a key value table and query it using where clause, this will be more effective.