text:
Q: Getting errors while casting into Date fields : org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar How do I need to send the value of the field so that it is casted properly. Currently, I am sending Date type field with value -> 2020-10-10
Here is the query :
                 query.append("SELECT * from STUDENT where")
                .append(" CAST(STUDENT.ADM_DTTM AS DATE) BETWEEN")
                .append(" CAST(")
                .append("?")
                .append(" AS DATE) AND")
                .append(" CURRENT_DATE-5 DAY");

             final Date[] args = new Date[]{getMyDate()};
             int[] types = new int[]{Types.DATE};
             result = jdbcTemplate.query(query, args, types, new Mapper());

Here is the detailed stacktrace :
nested exception is com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-313, SQLSTATE=07001, SQLERRMC=null, DRIVER=4.19.66
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1444) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:669) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:706) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]

Edit 1: Added the parameters passed to match the number of parameters markers in the query
 final Date[] args = new Date[]{
            getMyDate(),
            getMyDate(),
            getMyDate(),
            getMyDate()
    };
    int[] types = new int[]{Types.DATE, Types.DATE, Types.DATE, Types.DATE};

Error :
nested exception is com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-401, SQLSTATE=42818, SQLERRMC=null, DRIVER=4.19.66
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:93) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1444) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:669) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:706) ~[spring-jdbc-5.1.5.RELEASE.jar:5.1.5.RELEASE]

A: Actually, you shouldn't need any casting at all in your DB2 query:
SELECT *
FROM STUDENT
WHERE ADM_DTTM >= ? AND ADM_DTTM < CURRENT_DATE - 5 DAY;

The reasons for this is that first the lower bound of your range comparison is a valid DB2 date literal.  This should not require any casting to represent the date.  Second, since ADM_DTTM is a datetime (presumably) we don't need to cast it.  If it would pass as a datetime, it would also still pass when cast to a date.
I omitted the actual updated code for your JDBC template query.  Assuming the syntax there is already correct, the above query should not be giving you any errors.


text:
Q: Is It Possible To Set Transparency When Using LineCollection in Matplotlib? There are a number of helpful posts for using LineCollections in Matplotlib.
I have working code, but am having trouble figuring out how to set the transparency of the lines. For example, in Pandas it's as easy as doing:
df.plot(kind='line',alpha=.25)

However, I chose the LineCollection method because I want to plot a dataframe with >15k lines and the above example does not work.
I've tried adding ax.set_alpha(.25) in my code:
fig, ax = plt.subplots()

ax.set_xlim(np.min(may_days), np.max(may_days))
ax.set_ylim(np.min(may_segments.min()), np.max(may_segments.max()))

line_segments = LineCollection(may_segments,cmap='jet')

line_segments.set_array(may_days)
ax.add_collection(line_segments)

ax.set_alpha(.05)

ax.set_title('Daily May Data')

plt.show()

but there is no change.
Unfortunately I cannot provide a sample of the data with which I'm working; however, I've found the second example this Matplotlib gallery doc to be easy to copy.

A: You do it the same way you'd do it in pandas.
line_segments = LineCollection(may_segments, cmap='jet', alpha=0.05)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return an array from shell script to iterate/process in shell command line I have a script that makes a list of calls to APIs and collects the response Codes into an array called updateResponses. I looked many placed and declare -p was recommended, but it's not working the way it's described or maybe I am using it wrong.
What I need : return the Array from the script and verify the elements by iterating over them.
My script.sh contains the highlights for this action:
   updateResponses=()
   do
    ..get statusCodes from list of calls in a loop...
     updateResponses+=("$statusCode")
   done
declare -p updateResponses

in my terminal after I execute this script, I see the array printed out but it is not an array to iterate over although it looks as if it was re-initialized to be used. Running echo "${#updateResponses[@]}" returns 0 as the size.
Example of the output after script.sh is done running :
declare -a updateResponses='([0]="200" [1]="200" [2]="200" [3]="200" [4]="200" [5]="200" [6]="200" [7]="200" [8]="200" [9]="200" [10]="200" [11]="200" [12]="200" [13]="200" [14]="200" [15]="200" [16]="200" [17]="200" [18]="200" [19]="200" [20]="200" [21]="200" [22]="200" [23]="200" [24]="200" [25]="200" [26]="200" [27]="200" [28]="200" [29]="200" [30]="200" [31]="200" [32]="200" [33]="200")'

A: You need to run the output of the script in the context of the current shell, e.g.
$ . <(arr=('a b' 'c d' 'e;f') ; declare -p arr)
$ echo ${arr[1]}
c d


text:
Q: Can I choose which one to use if two files generated from two artifacts share name/pacakge but contain different content? As the title mentioned, is there a way in Maven to select which one to use if two files share the name/package but contain different content. I could not simply exclude one artifact because each of them carries some information used by other files. And it is also not feasible to refactor two artifact due to some restrictions and limitations of our project. I am just wondering if it is possible to prioritize one of them. Thanks.
P.S. I am using maven 3

A: it seems there is already some discussion about this existing on this forum
how to load same class from different jars


text:
Q: Why am I failing to mirror a web site (using wget)? I have tried using wget --mirror http://tshepang.net/, but it only retrieves one page, "tshepang.net/index.html". Is this a bug in wget?
Here's the output, from using the --debug option:
DEBUG output created by Wget 1.12 on linux-gnu.

Enqueuing http://tshepang.net/ at depth 0
Queue count 1, maxcount 1.
[IRI Enqueuing `http://tshepang.net/' with None
Dequeuing http://tshepang.net/ at depth 0
Queue count 0, maxcount 1.
--2011-01-15 12:32:51--  http://tshepang.net/
Resolving tshepang.net... 66.216.125.32
Caching tshepang.net => 66.216.125.32
Connecting to tshepang.net|66.216.125.32|:80... connected.
Created socket 4.
Releasing 0x089e2be0 (new refcount 1).

---request begin---
GET / HTTP/1.0

User-Agent: Wget/1.12 (linux-gnu)

Accept: */*

Host: tshepang.net

Connection: Keep-Alive

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 302 Found

Server: nginx/0.7.65

Date: Sat, 15 Jan 2011 10:33:45 GMT

Content-Type: text/html; charset=utf-8

Connection: keep-alive

Status: 302 Found

Location: http://posterous.com/sso/verify/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F

X-Runtime: 3

Set-Cookie: cookies_enabled=true; path=/

Cache-Control: no-cache

Content-Length: 141

X-Varnish: 419207385

Age: 0

Via: 1.1 varnish

X-Cache: MISS

---response end---
302 Found

Stored cookie tshepang.net -1 (ANY) / <session> <insecure> [expiry none] cookies_enabled true
Registered socket 4 for persistent reuse.
Location: http://posterous.com/sso/verify/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F [following]
Skipping 141 bytes of body: [You are being redirected.] done.
--2011-01-15 12:32:52--  http://posterous.com/sso/verify/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F
conaddr is: 66.216.125.32
Resolving posterous.com... 184.106.20.99
Caching posterous.com => 184.106.20.99
Releasing 0x089e3e20 (new refcount 1).
Found posterous.com in host_name_addresses_map (0x89e3e20)
Connecting to posterous.com|184.106.20.99|:80... connected.
Created socket 5.
Releasing 0x089e3e20 (new refcount 1).

---request begin---
GET /sso/verify/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F HTTP/1.0

User-Agent: Wget/1.12 (linux-gnu)

Accept: */*

Host: posterous.com

Connection: Keep-Alive

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 302 Found

Server: nginx/0.7.65

Date: Sat, 15 Jan 2011 10:33:46 GMT

Content-Type: text/html; charset=utf-8

Connection: close

Status: 302 Found

Location: http://tshepang.net/sso/recovery/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F

X-Runtime: 7

Set-Cookie: _sharebymail_session_id=296a636c8ed3cb6e4e7cabb10256008a; domain=.posterous.com; path=/; HttpOnly

Cache-Control: no-cache

Content-Length: 142

X-Varnish: 2019529137

Age: 0

Via: 1.1 varnish

X-Cache: MISS

---response end---
302 Found
cdm: 1 2
Stored cookie posterous.com -1 (ANY) / <session> <insecure> [expiry none] _sharebymail_session_id 296a636c8ed3cb6e4e7cabb10256008a
Location: http://tshepang.net/sso/recovery/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F [following]
Closed fd 5
--2011-01-15 12:32:53--  http://tshepang.net/sso/recovery/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F
Reusing existing connection to tshepang.net:80.
Reusing fd 4.

---request begin---
GET /sso/recovery/2d35d71b1e728dc99f3c153eaf6f8fa0?jumpto=%2F HTTP/1.0

User-Agent: Wget/1.12 (linux-gnu)

Accept: */*

Host: tshepang.net

Connection: Keep-Alive

Cookie: cookies_enabled=true

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 302 Found

Server: nginx/0.7.65

Date: Sat, 15 Jan 2011 10:33:46 GMT

Content-Type: text/html; charset=utf-8

Connection: keep-alive

Status: 302 Found

Location: http://tshepang.net/

X-Runtime: 5

Set-Cookie: _sharebymail_session_id=cab0227db8c38f17e572984ee188dc5e; domain=tshepang.net; path=/; HttpOnly

Cache-Control: no-cache

Content-Length: 86

X-Varnish: 419207606

Age: 0

Via: 1.1 varnish

X-Cache: MISS

---response end---
302 Found
cdm: 1 2
Stored cookie tshepang.net -1 (ANY) / <session> <insecure> [expiry none] _sharebymail_session_id cab0227db8c38f17e572984ee188dc5e
Location: http://tshepang.net/ [following]
Skipping 86 bytes of body: [You are being redirected.] done.
--2011-01-15 12:32:54--  http://tshepang.net/
Reusing existing connection to tshepang.net:80.
Reusing fd 4.

---request begin---
GET / HTTP/1.0

User-Agent: Wget/1.12 (linux-gnu)

Accept: */*

Host: tshepang.net

Connection: Keep-Alive

Cookie: _sharebymail_session_id=cab0227db8c38f17e572984ee188dc5e; cookies_enabled=true

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 200 OK

Server: nginx/0.7.65

Date: Sat, 15 Jan 2011 10:33:49 GMT

Content-Type: text/html; charset=utf-8

Connection: keep-alive

Status: 200 OK

ETag: "6ec7aeb4e15e3a80e733f7c2b5e00d6f"

X-Runtime: 1680

Cache-Control: private, max-age=0, must-revalidate

Content-Length: 66513

X-Varnish: 419207692

Age: 0

Via: 1.1 varnish

X-Cache: MISS

---response end---
200 OK
Length: 66513 (65K) [text/html]
Saving to: `tshepang.net/index.html'

     0K .......... .......... .......... .......... .......... 76% 25.7K 1s
    50K .......... ....                                       100% 39.3K=2.3s

2011-01-15 12:32:58 (27.9 KB/s) - `tshepang.net/index.html' saved [66513/66513]

Deciding whether to enqueue "http://tshepang.net/".
Already on the black list.
Decided NOT to load it.
Redirection "http://tshepang.net/" failed the test.
FINISHED --2011-01-15 12:32:58--
Downloaded: 1 files, 65K in 2.3s (27.9 KB/s)

A: The --no-cookies option helped (thanks to wag):

It seems like all the redirection caused wget to interrupt the request. Try with --no-cookies.

This was determined from reading the attached log.

A: Assuming wget is in your path (if not, you'll have to enter the full path) issue the following commands:
mkdir wget_files
cd wget_files
wget --mirror –-wait=2 --page-requisites --html-extension –-convert-links –-directory-prefix wget_files/example1 http://www.yourdomain.com

A: You also need to set -r for recursive and -l X for link depth, where X is an integer. It's also a good idea to set -A to set the list of acceptable file types to keep (otherwise you only get HTML files).


text:
Q: "Exceeded quota: too many free query bytes scanned for this project" in Google BigQuery I'm getting the above error since yesterday, after trying out Google BigQuery with JasperReports Server. I couldn't find any info on this, since the first 100GB should be free and the BigQuery Access Report is saying:
BigQuery Resource Usage for API Project
Data Analysis
Jan 31, 2013 – Feb 27, 2013
Data Processed Per Day
0 MB Peak 0.00 MB Average
I haven't reached the free query/user/day limit either:
API     Per-User Limit  Used    Billable Limit  Courtesy Limit
BigQuery API    5.0 requests/second/user
0%  200,000 requests/day    10,000 requests/day
and
Traffic Reports for API Project
Total requests
935
Requests/day
856 peak 33.39 average
Start Date
Jan 31, 2013
Sample Period
28 days
I'm trying to use the natality sample data in a project for my university and it's pretty urgent. It was working fine for a day or so. The queries are made by the JasperSoft BigQuery Connector (http://code.google.com/p/jaspersoft-bigquery-datasource/) using an Ad-hoc-View (based on a JasperReport as Topic).
I am using the following statement:
SELECT
    STRING($P!{dimension1}) as dimension_1,
    STRING($P!{dimension2}) as dimension_2,
    SUM(record_weight)  as count_group,
    AVG(weight_pounds)  as avg_weight_pounds,
    AVG(apgar_1min) as apgar_1min,
    AVG(apgar_5min) as apgar_5min
FROM publicdata:samples.natality
WHERE
    year >= $P!{year_first}
    AND year <= $P!{year_last}
GROUP BY dimension_1, dimension_2
ORDER BY dimension_1, dimension_2

Any help would be highly appreciated! Thanks in advance!

A: Summarising the comments above and below for anyone else's benefit:

*

*The quota for your usage doesn't show up in the developer console if you don't enable billing.

*Looking at the reports page will show 0GB used if you don't enable billing.

*Unless you enable billing, you have a limit of 100GB to query per month.

*Enabling billing will enable you to query more than 100GB of data.

*The BigQuery team are working on a fix for the reports page not including queries on data when you haven't enabled billing

A: Even in 2021 still a relevant question. Now with PowerBi connected to BigQuery (Direct Queries). It shows an error message, in my case with code 31780: quota exceeded free query bytes scanned.
Here's the problem

*

*When the data is connected BQ seems to not connect to the correct project.

Here's how to solve it:

*

*Click the table with the BQ connection

*Click on the transform data (it's on the home tab)

*Within transform data go to the view tab

*Click on advanced editor

*You'll see this line:

    Source = GoogleBigQuery.Database(null),

*

*Change it to:

    Source = GoogleBigQuery.Database([BillingProject="project-id"]),

Note: not the project name, the project ID
Do this for all tables that fetch data from BQ.
source: https://learn.microsoft.com/en-gb/power-bi/connect-data/desktop-connect-bigquery#considerations-and-limitations


text:
Q: How do I find out the tag of a view I am touching I am having trouble determining the tag of the view I am touching.
I have a scroll view and subclassed it in order to capture touch down events (I have pictures on the subview). However, I need to determine which picture I touched down.
I want to determine that tag of the subview, but I am getting random results (mostly tag 0). Whats the proper way of capturing this?

A: You can try using UIView hitTest. It will return you the subview the user is touching.


text:
Q: android keep the reference to old google api project I am working with YouTube google api and I have this error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err: {
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:   "code" : 403,
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:   "errors" : [ {
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:     "domain" : "usageLimits",
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:     "message" : "Access Not Configured. YouTube Data API has not been used in project XXXXXXXXXXXX before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube/overview?project=XXXXXXXXXXXX then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:     "reason" : "accessNotConfigured",
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:     "extendedHelp" : "https://console.developers.google.com/apis/api/youtube/overview?project=XXXXXXXXXXXX"
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:   } ],
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err:   "message" : "Access Not Configured. YouTube Data API has not been used in project XXXXXXXXXXXX before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube/overview?project=XXXXXXXXXXXX then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
04-15 13:25:42.951 22653-24865/com.player.jointv W/System.err: }

I thought that my problem was with an disable api or maybe using a wrong username but then I click on the project reference in the error and I saw that the project ID (XXXXXXXXXXXX) is wrong because it was an old project.
The problems are:

*

*I don't know how to update or what do I need to change in order to
get the new project ID??

*Do I need to remove any trash file??

*Where or how android project keep these references? I am worry about that because if I need to remove the current project maybe I will get the same error in the future.

Tools.
Using Android Studio 2.0 on Windows.
Get the Auth Token
I get the token using GoogleAuthUtils:
token = GoogleAuthUtil.getToken(context, account, Config.YOUTUBE_SCOPES);

Where:
context: AppCompatActivity
account: Account
Config.YOUTUBE_SCOPES:
final String YOUTUBE_SCOPES = "oauth2:https://www.googleapis.com/auth/yt-analytics.readonly" +
            " https://www.googleapis.com/auth/youtube.readonly";

Creating Credentials
I took this peace of code from Google Credential example:
GoogleCredential credential = new GoogleCredential()
                                  .setAccessToken(authToken);

Using credential to configure the api services.
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                    .setApplicationName("youtube-analytics-api-report-example")
                    .build();

//This object is used to make YouTube Analytics API requests.
analytics = new YouTubeAnalytics
                .Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

Using a web API KEY
I create a web api key and I got the error:
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err: {
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:   "code" : 401,
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:   "errors" : [ {
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:     "domain" : "global",
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:     "location" : "Authorization",
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:     "locationType" : "header",
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:     "message" : "Invalid Credentials",
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:     "reason" : "authError"
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:   } ],
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err:   "message" : "Invalid Credentials"
04-15 15:36:27.274 14733-16676/com.player.jointv W/System.err: }

What is happen? I feel bad?


text:
Q: Why do dpkg and aptitude want to remove MOST of my system? I was installing and uninstalling some packages on my home 11.10 system, when I suddenly noticed that dpkg and aptitude want to remove almost everything. Synaptic seems fine. At work, where I have an almost identical setup, I am NOT having this problem. From here, I thought it was a multiarch problem, but, again, the same setup at work is fine.
The only thing besides current updates that I've applied was a qdbus package, which I notice now was i386. I installed the "normal" version, which automatically uninstalled the 32-bit version, but my system is still insane.
I can't get aptitude to make sense out of the recommendations. If I use `e' to examine the solution, it starts a slow count to inifinity. If I disable multiarch, as in the other thread, then aptitude can make sense of it's own resolution, but that's still to remove thousands of packages, and free 4 GB of drive space (which is just about everything).
Is there any way to get this sorted, or am I looking at a reinstall?
UPDATE: I'm seeing various packages with status "pd". I can't find any reference that tells me what the "d" means. >-/
SECOND UPDATE: I disabled multiarch, and aptitude thought it could work things out. Despite telling me that it was going to KEEP 832 packages, it started deleting them all. SCREW IT. I'll just reinstall. I'm getting too old for this crap.

A: (OP solved issue)
I disabled multiarch, and aptitude thought it could work things out. Despite telling me that it was going to KEEP 832 packages, it started deleting them all. I'll just re-install.


text:
Q: creating maven project without IDE get build faliure I try to create maven project from command line, i am using apache maven 3.3.3 with jdk 7.
C:\MVN\CubeGenerator>mvn archetype:generate -DgroupId= com.mavapp -DartifactId=C
    ubeGenerator -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=
    false
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.169 s
[INFO] Finished at: 2015-08-07T00:13:23+05:30
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] The goal you specified requires a project to execute but there is no POM
 in this directory (C:\MVN\CubeGenerator). Please verify you invoked Maven from
the correct directory. -> [Help 1]
[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MissingProject
Exception

A: You have some extra spaces after the "=" for two properties.
I think you want:
mvn archetype:generate -DgroupId=com.mavapp -DartifactId=CubeGenerator -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


text:
Q: Accessing Vuex action in Javascript ES6 module I am using NuxtJS framework to build a Vue application. I writing a custom plugin for TinyMCE editor to upload images to server. This plugin is an ES6 module with a single export(I have taken out code for brevity). So here, image is selected -> compressed -> upload to server.
  import { actions } from '@/store/common/post_editor.js'

  const imageUpload = function (editor) {

    function _onAction() {
      let imageBlob = null
       onChange: function (api, details) {
          //get the image selected
          compressImage(image).then((output) => {
          imageBlob = output
        })
      }
    },
    onSubmit: function (api) {
        actions
          .uploadToServer(imageBlob)
          .then((url) => {
            editor.insertContent('

')
          })
          .catch((error) => {
          })
      },
    })
  }
}

export { imageUpload }

I am importing Vuex action in the module that uploads the image to server. And following is the code for it.
uploadToServer(vuexContext, blob) {
return new Promise((resolve, reject) => {
  let formData = new FormData()
  formData.append('file', blob)
  console.log(this.$axios) // this is undefined
  this.$axios
    .$post('/server/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    .then((res) => {
      resolve(res.location)
    })
    .catch((error) => {
      reject(error)
    })
  })
}

But when using this plugin, axios is not triggered. And apparently the reason is this.$axios is undefined. So, it seems this is not the correct way to import Vuex action into an ES6 module.
Any help is appreciated, thanks.
EDIT
For now, I am using
window.$nuxt.context.store .dispatch('common/post_editor/uploadToServer', imageBlob)
But not sure if this is a good practice.

A: Vue and Nuxt plugins define properties on component instances. this inside an action is not component instance and so isn't supposed to have this.$axios. It's an outdated and questionable practice to use loosely defined this dynamic context anywhere besides strict OOP code.
It's incorrect way yo use an action. A store should be imported instead of an action:
import store from '.../store`.

It's incorrect way to import Axios. It should be explicitly imported in non-component modules. In case there's Axios instance with interceptors, etc, it can be maintained within a module:
import axios from '.../common/axios`.


text:
Q: Windows 10 slowly increases RAM usage on 2 different PCs I have 2 computers with Windows 10:
PC:

*

*Windows 10 Education 1803 (April Update)

*Intel Core i5 8400

*Crucial Ballistix Sport LT 16GB (2x8GB) DDR4 2400

*MSI GeForce GTX 1060 3GT OC, 3GB GDDR5

*MSI Z370 SLI PLUS - Intel Z370

*Samsung SSD 850 EVO - 250GB, Basic

*Seagate BarraCuda - 2TB

Notebook:

*

*Windows 10 Home 1803 (April Update)

*Specification: https://msi.com/Laptop/GS70-2PE-Stealth-Pro/Specification
The problem is that the longer the computers are running the more RAM they use. And the more RAM they use the more laggy they behave, especially in games (some games becomes even unplayable because of "micro lags" every few seconds so I need to restart the computers to clear the RAM) and even video starts to be desynchronized with audio after some time.
Moreover, after the April Update, the System process started to consume a lot of CPU, probably because of increasing RAM usage as the xperf program probably said. Maybe the CPU usage is higher when the computers are running longer but it is not as straightforward as in RAM case.
I tried to use poolmon and found out that the pool tags "Proc" and "Toke" are increasing its memory usages. But I was unable to find which driver or another software uses these tags and leaks memory.
The problems on both PCs started probably in January when I bought the PC.
Here are some screenshots after about 5 hours:

*

*RAM usage in Processes tab in Task Manager

*RAM usage in Performance tab in Task Manager

*RAM usage in Users tab in Task Manager

*Poolmon output

*CPU usage by System process

*Xperf output for CPU usage by System process
Some non standard software I use:

*

*Google Drive Sync

*ManicTime

*MEGAsync

*MSI Afterburner

*OpenVPN

*VirtualBox

*WireShark

I tried with no success:

*

*Set ClearPageFileOnShutdown

*Disable Prefetch

*Disable Superfetch

*Disable NDU

*Update all drivers

*Uninstall some drivers

*Run sfc /scannow

Could anyone tell me what could be the problem or what should I try next?

EDIT:
Many thanks to @magicandre1981. The problem was with zombie processes generated by Win10 Widgets skin for Rainmeter.
I used the utility "FindZombieHandles" from the article about zombie processes and it showed me about 20000 zombie processes in my system after 2 hours of runtime and the count of it was still increasing at rate about 5 new zombie processes per second. It did not show me which process cause this leak but it gave me at least an idea what is wrong.
Then I debugged the utility to see if there is more information. I found out that there were a lot of zombie CMD processes. So I used Process Explorer to see what process creates those CMDs and it was the already mentioned Rainmeter.

A: The cpu usage of the system process is about that Windows thinks you run out of memory and trims working set.

Next use xperf/WPA to see which processes use "Proc" and "Toke" tag. (Proc means a lot of processes are running).
In Final step look in CPU entry under Taskmgr->Perf if you have a high number of Handles (over 100k).

This could indicate zombie processes. Run FindZombieHandles to find zombie processes and close them to free memory.


text:
Q: Is it possible to sync a folder from NAS drive to Ubuntu One Cloud? I am running Ubuntu One on Windows 7. I have a Synology DS212+ NAS drive that I would ideally like to back up to my cloud. However, Ubuntu One only allows me to backup from the user documents folder on the computer I am running from. Is there a way to back up a folder from my NAS directly?
At the moment, I run a scheduled sync toy task to copy the folder from the NAS to the user documents folder, which then gets picked up in my nightly Ubuntu sync. This seems a bit of a hack.
Is there any way of mounting the nas folder inside the user directory?

A: Currently Ubuntu One doesn't support syncing from a NAS. Also, keep in mind that it's not a backup tool, because it preserves no history, and accidental deletion on your device will cause deletion on our servers!
The suggested mechanism is doing a backup, and then syncing the backup, just like you are doing.


text:
Q: Xcode>Instruments>Automation>Mac: is there a way to use regular expression within Automation in Instruments I am totally new to Instruments>Automation. Trying to test the internal app using Automation in Instruments.
Here is my problem:
Our app has the UI cells generated on the fly. There is no way to predict how many cells will be created and what name they will have. But, all of them will contain a certain string (like "Courses"). The question is - How, using Automation, find out if particular cell contain that string in its name?

A: You are able to get total cells count simply using "length" property.
var cellsCount = <YourUIATableViewObject>.cells().length;
UIALogger.logMessage("total cells count = " + cellCount);

After that you will be able to get cell properties and operate with them:
for (var i = 0; i < cellsCount; i ++)
{
     var cellValue = <YourUIATableViewObject>.cells()[i].value();
     var cellName = <YourUIATableViewObject>.cells()[i].name();
     UIALogger.logMessage("Cell #"+i+" properties: cellValue ="+cellValue+"; cellName ="+cellName);

     //Try to use match() or search() functions to find what you need.
     if ( cellName.search("Courses") != -1 )
     //if (cellValue.search("Courses") != -1 )
     {
          UIAlogger.logMessage("Cell #"+i+" contains 'Courses'");
     }
     else
     {
          UIAlogger.logMessage("Cell #"+i+" does not contain 'Courses'");
     }
}

This JavaScript tutorial will help you:


text:
Q: How do retain debug symbols when profiling C++ code on Windows? I'm trying to profile a C++ shared library on Windows 10, in order to find which lines the program is spending most time on.  (The code happens to form part of an R package.)
I've previously used
AMD µprof and
Very Sleepy.  However, I'm now having trouble compiling the code: all these profilers show is which DLL is being used, rather than which function / line.
I suspect that the problem relates to debugging symbol tables being missing.  Per
Enabling debug symbols in shared library using GCC, I've ensured that a -g flag is applied when compiling each file, and that there is no -s flag at the linker stage.  What else do I need to do to allow  µprof / Very Sleepy to tell me which lines of the code are proving a bottleneck?
Detailed compilation notes
I'm using RBuildTools MinGW-w64 v3 g++ 8.3.0 to compile the code on 64-bit Windows 10.
Here are some sample compile commands, which are being generated by R, using Makevars / Makeconf templates.
g++  -std=gnu++14 -I"<<include paths>>" -DNDEBUG -g -O2 -Wall
     -mfpmath=sse -msse2 -mstackrealign
     -c source_file.cpp -o source_file.o

g++ -shared -static-libgcc -g -Og
    -o PackageName.dll tmp.def source_file.o <<Other files>>
    -L<<Library paths>>

I've also tried replacing -g with -gdwarf-2 -g3, and adding -fno-omit-frame-pointer, per Very Sleepy doesn't see function names when capturing MinGW compiled file.
Running without shared library
ssbssa suggested running against a simple executable.
I tried:
#include <chrono>
#include <thread>
#include <iostream>

long sumto(long n) {
  if(n > 0)   {
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    return n + sumto(n - 1);
  }
  return 1;
}

int main() {
  std::cout << sumto(1000) << std::endl;
  return 0;
}

>"C:/RBuildTools/4.0/mingw64/bin/"g++ -std=gnu++14 -gdwarf-2 -g3 -Og -c test.cpp

>"C:/RBuildTools/4.0/mingw64/bin/"g++ -std=gnu++14 -gdwarf-2 -g3 -Og -o test test.o

test.exe runs as expected.  When I profile test.exe, AMD µprof states "The raw file has no data!", whereas VerySleepy does detect activity in sumto and displays the associated source code.


text:
Q: How can I use Kotlin to handle asynchronous speech recognition? The Code A is from the artical https://cloud.google.com/speech-to-text/docs/async-recognize
It write with Java, I don't think the following code is a good code, it make the app interrupt.
while (!response.isDone()) {
     System.out.println("Waiting for response...");
     Thread.sleep(10000);
}
...

I'm a beginner of Kotlin. How can I use Kotlin to write the better code? maybe using coroutines ?
Code A
public static void asyncRecognizeGcs(String gcsUri) throws Exception {
  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  try (SpeechClient speech = SpeechClient.create()) {

    // Configure remote file request for FLAC
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speech.longRunningRecognizeAsync(config, audio);
    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    for (SpeechRecognitionResult result : results) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
      System.out.printf("Transcription: %s\n", alternative.getTranscript());
    }
  }
}

A: You will have to provide some context to understand what you are trying to achieve, but it looks like coroutine is not really necessary here, as longRunningRecognizeAsync is already non-blocking and returns OperationFuture response object. You just need to decide what to do with that response, or just store Future and check it later. There is nothing implicitly wrong with while (!response.isDone()) {}, that's how Java Futures are supposed to work. Also check OperationFuture, if its normal Java Future, it should implement get() method, that will let you wait for result if necessary, without having to do explicit Thread.sleep().


text:
Q: Regex expression for odd # of a's and odd # of b's I need to create a regex in the language {a,b} that accepts all string with an odd number of a's and an odd number of b's.
Here is my latest and closest try:
(((aa+bb)*(ab+ba))*+((ab+ba)(aa+bb)*)*)

The grader says that it failed on "", which I assume means it accepts lambda but I do not see how. This does not mean that this is the only thing wrong.
Help please!

A: Your attempt has several issues:

*

*Indeed "" is matched (and shouldn't): all parts of your regular expression are optional

*abab, abba, ... etc would be matched as well because ((aa+bb)*(ab+ba))* could be matching an even number of times.

*The same goes for the second half of the regular expression

Here is one that would do the trick:
(aa+bb)*(ab+ba)((aa+bb)*(ab+ba)(aa+bb)*(ab+ba))*(aa+bb)*

Here the first (ab+ba) part is not optional, so "" would not match.
There are four states to consider:

*

*even number of a's, even number of b's (initial state)

*even number of a's, odd number of b's

*odd number of a's, even number of b's

*odd number of a's, odd number of b's (target state)

(aa+bb)* is state invariant: the state before the match is the same as the state after the match.
(ab+ba) swaps state 1 with state 4 and vice versa (and state 2 with state 3 and vice versa, but we're not interested in that)
((aa+bb)*(ab+ba)(aa+bb)*(ab+ba))* is state invariant, but it allows the state to go to any other state and come eventually back to the original, ... in all possible ways. When this pattern is executed, the starting state is 4, and so it also exits at that state.
If we take out all the state invariant parts, only (ab+ba) is left over, which transitions the initial state to the target state.
All allowed atomic state changes are covered in this expression.


text:
Q: Why creating a float32 array from a list raises value error? I'm trying to create a float32 array as follows,
np.float32([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist])
However, I'm getting the following error,

ValueError: setting an array element with a sequence.

I tried to cast it to numpy array explicitly as follows and retry but still, I'm getting the same error
np.array([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist]).astype(float)
what am I missing?

A: Specify the datatype with the dtype argument to np.array().
np.array([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist], dtype=float)

A: Here's an example that produces your error:
In [910]: np.array([1,[1,2,3],4])
Out[910]: array([1, list([1, 2, 3]), 4], dtype=object)

fine without the float conversion - but then the error:
In [911]: np.array([1,[1,2,3],4]).astype(float)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'list'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-911-9c007059d6ad> in <module>
----> 1 np.array([1,[1,2,3],4]).astype(float)

ValueError: setting an array element with a sequence.

I suspect [kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist] contains a mix of numbers, arrays, lists that produces an object dtype array.
If the list does contain a mix of numbers and lists of numbers (or arrays), hstack might be what you want:
In [922]: np.hstack([1,[1,2,3],4])
Out[922]: array([1, 1, 2, 3, 4])


text:
Q: How to download OS X El Capitan from the App Store even if never downloaded before macOS Sierra was released or purchased is grayed out I know that in the past if I've previously downloaded OS X El Capitan from the App Store I could download it again from the Purchased tab in the App Store, however now that macOS Sierra is out I'm not able to download it as it says INSTALLED (and grayed out) even on a system running OS X Mountain Lion 10.8.5. Pressing any key combination, e.g control, option, etc. doesn't change the button to DOWNLOAD. All other previous versions of OS X can still be downloaded from my Purchased tab in App Store as they still say DOWNLOAD and are not grayed out, thus active.
The image below is from a system running OS X Mountain Lion 10.8.5, does not have OS X El Capitan installed on it or even the Install OS X El Capitan.app on its filesystem, yet it says it's installed and grayed out.

A: Whether or not you've downloaded it in the past, you can now download OS X El Capitan 10.11.6 (6.21 GB) via this link which will open first in the Browser, then in the App Store.

OS X El Capitan
This version of OS X El Capitan is for users running OS X Snow Leopard
  who would like to upgrade to macOS Sierra. If you are running Snow
  Leopard and would like to upgrade to Sierra, you need to install El
  Capitan first. This version of El Capitan can also be installed on Mac
  computers that are not comparable with Sierra.

Note: If doing this to downgrade from macOS Sierra.
In order to use the Install OS X El Capitan.app from macOS Sierra you need to create a USB Installer and boot the Mac with it.  You'll also need to erase the Macintosh HD and perform a clean install.  Make sure you have proper User Data Backups from which to restore your Data before erasing the Macintosh HD.
Have a look at Create a bootable installer for OS X. Excerpt show below:

Use the 'createinstallmedia' command in Terminal

*

*Download the OS X installer from the Mac App Store. Quit the installer if it opens automatically after downloading. The installer
  will be in your Applications folder.

*Mount your USB flash drive or other volume. You could also use a secondary internal partition.

*Open the Terminal app, which is in the Utilities folder of your Applications folder.

*Use the createinstallmedia command in Terminal to create the bootable installer. Examples of this command are in the next section.
  For detailed usage instructions, make sure that the appropriate
  Install OS X app is in your Applications folder, then enter one of the
  following paths in Terminal:

  Path for El Capitan:
/Applications/Install\ OS\ X\ El\ Capitan.app/Contents/Resources/createinstallmedia

Examples
This is the basic syntax of the command. Replace volumepath with
  the path to your USB flash drive or other volume, and replace
  installerpath with the path to the Install OS X app.
createinstallmedia --volume volumepath --applicationpath installerpath

The following examples assume that the OS X installer is in your
  Applications folder and the name of your USB flash drive or other
  volume is MyVolume:
Example for El Capitan:
sudo /Applications/Install\ OS\ X\ El\ Capitan.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume --applicationpath /Applications/Install\ OS\ X\ El\ Capitan.app


text:
Q: Angular httpclient 4.3 rewrite response status from 200 to 500 I have a server that responds with 200 status always but responds with errorCode in the body. I want to intercept that response and rewrite the status to 403 or 500. How do i do this with the new http interceptors? here is code thus far
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {

    return next.handle(req)
      .map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse  && (event.body.errorCode)) {
          return event.clone({status: 500})
        }
      });
   }
}


text:
Q: Rails rake db:migrate has no effect I made a new Rails 3 app today, added a simple migration, and for some reason, nothing happens when I do rake db:migrate. It simply pauses a few seconds, then returns to the command prompt, with no errors or anything. Schema.rb and the database stay empty.
Any ideas what could be going on? I've made many apps and never had this problem. Everything is a totally standard setup too.

A: There's a few reasons why your migrations won't run, but the most common is that the system is already under the impression that all the migrations you've defined have already run.
Each migration creates an entry in the schema_migrations table with the version column corresponding to the identifier number. If you want to force a migration to re-run you can usually back it out and retry it. For example, if you had 20100421175455_create_things.rb then you would re-run it using:
rake db:migrate:redo VERSION=20100421175455

A common situation is that your migration has failed to run in the first place, that it generated an exception for instance, and yet Rails still considers it complete. To forcibly re-run a migration, delete the corresponding record from the schema_migrations table and run rake db:migrate again.
One way to avoid this kind of problem in the future is to define your migrations with an automatic back-out procedure:
class CreateThings < ActiveRecord::Migration
  def self.up
    # ... (migration) ...

  rescue
    # If an exception occurs, back out of this migration, but ignore any
    # exceptions generated there. Do the best you can.
    self.down rescue nil

    # Re-raise this exception for diagnostic purposes.
    raise
  end
end

If you have a mistake in your migration you will see the exception listed on the console. Since the migration has automatically been rolled back you should be able to run it again and again until you get it right.

A: I faced the same problem. I did a kind of a short hack that helped me. I am posting it just in case anyone wants  a short and sweet solution. I agree with what Tadman is saying

"the system is already under the impression that all the migrations
  you've defined have already run"

What I did was to change the name of the migrate file in the /app_folder/db/migrate folder. I think the numeric part in the name of the ruby migrate file is the time at which the file was created.
You can add say 1 , to the filename, every time you want to re-run the migrate. After changing the name drop/delete the table (I used mysql command line tool for deleting) and then run rake db:migrate and the migrations should be done.

A: Calling spring stop might solve your problems.

A: Well, I found out what was causing my problem. I'm using the slim_scrooge gem and commenting it out makes everything proceed normally. Don't know why though...

A: I faced similar problem today while migrating plugin for Redmine using
rake redmine:plugins:migrate RAILS_ENV=production NAME=plugin_name

where plugin_name is actually plugin name defined in init.rb of the plugin.
I struggled for 4 hours and finally figured out that my plugin directory name was not the same as the plugin name (note redmine_ prefix):
~/redmine/plugins/redmine_plugin_name

So, make sure your plugin is placed in folder named after plugin name. I believe it applies to other rails apps as well.


text:
Q: Post predefined data to twitter I am trying to get the text from value="" in my form into the php variable $_POST['twitter'] but I keep getting a blank and if I remove isset, I get an undefined error.
<?php
//$twitter=(isset($_POST['twitter']));
var_dump($_POST);
?>

<form method="post" action="">
        <input type="checkbox" name="twitter" value="My Posting Text">Would you like to send to Twitter?

</form>

    <a href="https://twitter.com/share?" id="my_twitter_id" data-show-screen-name="false" data-url="https://nyctelecomm.com" data-text="<?php echo $_POST['twitter']; ?>" data-counturl="null" class="twitter-share-button" target="_blank" data-count="horizontal" data-lang="en" data-via="NYCTelecomm.com">Tweet

A: You need to make sure your form is submitting.
Give this a try:
<?php
    if(isset($_POST['submit_twitter'])) {
        // should set here
        $twitter=(isset($_POST['twitter']));

        var_dump($_POST);
    }
?>

<form method="post" action="">
        <input type="checkbox" name="twitter" value="My Posting Text">Would you like to send to Twitter?

        <input type="submit" name="submit_twitter" value="Submit">
</form>

<?php
    // This will only show if $twitter has been set with the post data
    if(isset($twitter)) :
?>

    <a href="https://twitter.com/share?" id="my_twitter_id" data-show-screen-name="false" data-url="https://nyctelecomm.com" data-text="<?php echo $_POST['twitter']; ?>" data-counturl="null" class="twitter-share-button" target="_blank" data-count="horizontal" data-lang="en" data-via="NYCTelecomm.com">Tweet

<?php
    endif;
?>


text:
Q: Apache .htaccess rewrite rule tow conditions? I have a slight problem figuring out what I am doing wrong. I have a site where I only have https for two different urls - www.example.de and example.de. I also however have subdomains specified - x.example.de and y.example.de (that are being used from a different domain name altogether, in case that's relevant).
So I tried following code:
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond %{HTTPS} !=on [NC]
# RewriteCond %{HTTP_HOST} =^(example.de|www.example.de)  [NC]
RewriteCond %{HTTP_HOST} !^(x|y)\.example\.de$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST} [R=301,L]

</IfModule>

I was unsuccessful with everything I tried, in particular both RewriteConds above; in the code above for instance it changes http to https even if it is x or y subdomain. Can someone PLEASE HELP? Thank you!


text:
Q: What is the probability that the product of two randomly selected distinct positive integers less than $100$ is a multiple of $3$? Two different positive integers less than $100$ are randomly chosen and multiplied together. What is the probability that the resulting product is a multiple of $3$?
Sorry about that. I used a different approach and got the answer. The answer is down Below.

A: We can choose two numbers in $\binom{99}{2}=4851$ ways. Two numbers will have a product which is a multiple of 3 if at least one of them is a multiple of 3. We can more easily count the number of ways for the product to not be a multiple of 3: this happens when neither of the numbers is a multiple of 3. There are $\frac{99}{3}=33$ multiples of 3 less than 100, and $99-33=66$ numbers which aren't multiples of 3. The number of ways to choose two of these numbers is $\binom{66}{2}=2145$, so the number of way to choose two numbers where at least one is a multiple of 3 is $4851-2145=2706$. The final probability is $\frac{2706}{4851}=\boxed{\frac{82}{147}}$.


text:
Q: Notifee native module not found I have a mobile app with React Native and works without any problem. I wanted to add notification functionality to that app.
I installed firebase/app, firebase/messaging and @notifiee for being able to send notifications. After installed these packages, I am able to build my app on android emulator but i'm getting error on the console like this:
ERROR    Error: Notifee native module not found.
LOG      Running "myMobileApp" with {"rootTag":1}
ERROR    Invariant Violation: "myMobileApp" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.

I'm using Visual Studio Code, Android Studio Emulator and JDK 11 on an Ubuntu 20.04.4 LTS.
Relevant packages in my package.json:
"dependencies": {
     ...
    "@notifee/react-native": "^5.3.0",
    "@react-native-firebase/app": "^14.11.0",
    "@react-native-firebase/messaging": "^14.11.0",
    "react": "16.13.1",
    "react-native": "0.63.4",
     ...
  },

A: stop your project, close the running terminal window and on your android studio press on the "sync project with gradle files" icon, you can find it on the top bar behind the device manager
re-run your project

A: work for me
if you are using ZEGOCLOUD videocalling  .
compileSdkVersion = 33   // <----- change this in android/build.gradle


text:
Q: Issues with the following json data I'm trying to figure out whats wrong with the following json data, i'm currently using http://jsonlint.com/ to validate it which keeps failing with;
Parse error on line 9:
...                    "Question 2" : [
-----------------------^
Expecting 'EOF', '}', ',', ']'

My code;
{ "questions" : {
        "Question 1" : [
        { "Q" :"Question" },
        { "A" : "Answer A"  },
        { "B" : "Answer B" },
        { "C" : "Answer C" },
        { "D" : "Answer D" },
        { "Answer" : "C" }
        ]
        "Question 2" : [
        { "Q" :"Question" },
        { "A" : "Answer A"  },
        { "B" : "Answer B" },
        { "C" : "Answer C" },
        { "D" : "Answer D" },
        { "Answer" : "C" }
        ]
    }
}";

A: You've forgot a comma!
{ "questions" : {
                "Question 1" : [
                { "Q" :"Question" },
                { "A" : "Answer A"  },
                { "B" : "Answer B" },
                { "C" : "Answer C" },
                { "D" : "Answer D" },
                { "Answer" : "C" }
                ],
                "Question 2" : [
                { "Q" :"Question" },
                { "A" : "Answer A"  },
                { "B" : "Answer B" },
                { "C" : "Answer C" },
                { "D" : "Answer D" },
                { "Answer" : "C" }
                ]
}}

A: Missing the comma between your Question keys.
{ "questions" : {
                    "Question 1" : [
                    { "Q" :"Question" },
                    { "A" : "Answer A"  },
                    { "B" : "Answer B" },
                    { "C" : "Answer C" },
                    { "D" : "Answer D" },
                    { "Answer" : "C" }
                    ],
                    "Question 2" : [
                    { "Q" :"Question" },
                    { "A" : "Answer A"  },
                    { "B" : "Answer B" },
                    { "C" : "Answer C" },
                    { "D" : "Answer D" },
                    { "Answer" : "C" }
                    ]
}
                    }

A: you're missing a comma after the array closes.
JSON = {
  "questions" : {
      "Question 1" : [
          { "Q" :"Question" },
          { "A" : "Answer A"  },
          { "B" : "Answer B" },
          { "C" : "Answer C" },
          { "D" : "Answer D" },
          { "Answer" : "C" }
      ],// end of Question 1 "this is where you'r missing the comma"
      "Question 2" : [
          { "Q" :"Question" },
          { "A" : "Answer A"  },
          { "B" : "Answer B" },
          { "C" : "Answer C" },
          { "D" : "Answer D" },
          { "Answer" : "C" }
      ] // end of Question 2
  }//end of questions object
}";

A: Expecting 'EOF', '}', ',', ']'
Between array of Questions, You missed COMMA after "Question 1" as answered by others. Let Plain Object to JSON string mapping be done by REST providers like JAKSON if you're using JERSEY. Otherwise, use other APIs for mapping.
The validation answers it clearly, however where exactly the comma is missing. The very common mistakes experienced are either missing { brace for object, [ bracket for representing arrays or ,(comma) for delimiting array of elements.


text:
Q: Playing audio files with HTML5 i have this code where i have three audios...i want to play them one after another after the page has loaded completely...this is happening with the following code but i can't seem to work on the delay between two audios...how do i accomplish it?
<audio id="my_audio">
  <source src="bark.mp3" type="audio/mpeg">
</audio>
<audio id="my_audio2">
  <source src="roar.mp3" type="audio/mpeg">
</audio>

<audio id="my_audio3">
  <source src="hoot.mp3" type="audio/mpeg">
</audio>


text:
Q: Why can't my dynamically allocated array be accessed outside of it's function? [C] I'm trying to access an array that was created in function fooA() in the main function. I'm dynamically allocating the array using malloc and pointing a passed pointer at it, but in main the pointer no longer points to the same value.
int main() {
    int *test;
    fooA(test);
    printf("%d\n", test[0]);
    free(test);
}

void fooA(int *pass){
    int pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

A: First, the problems in code....

void fooA(int *pass)  /*<<<<  pass is declared here */
{
    /*
       however you have redefined pass as a different type here.
       This variable hides the previous definition of pass.
       I'd suggest turning up the warning level on your compiler
       to catch errors like this. (-Wall on gcc/clang, or warning
       level 4 on Visual C)
     */
    int pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

Later when you call the method, you are passing a copy of test into fooA, rather than a reference to the original variable. i.e. Any changes you make to 'pass' within fooA will be working on the copy, and not the original variable.
    int *test;
    fooA(test);

The easiest option here would be to simply return the pointer.
/* change the prototype to return the pointer instead of passing in as arg! */
int* fooA(void);

int main() {

    /* this should now be good */
    int *test = fooA();
    printf("%d\n", test[0]);
    free(test);
}

int* fooA(void){
    int* pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
    return pass;
}

If you wanted to do it with a function argument, it's possible, but only if you use a pointer to a pointer, i.e.
void fooA(int** pass);

int main() {
    int *test;
    fooA(&test); /*< passing address of test variable */
    printf("%d\n", test[0]);
    free(test);
}

void fooA(int** pass) {
    /* need to dereference pass here to modify the original pointer value */
    *pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        (*pass)[i] = i;
    }
}

Although this question is tagged as C, for completeness, in C++ you can pass the variable by reference (i.e. add the & symbol to the end of the type)
void fooA(int*& pass) {
    // working on the original variable, rather than a copy.
    pass = (int*)malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

And now this code would work just fine:
    int *test;
    fooA(test);


text:
Q: Two equal functions on a topological space Can anybody help please help me, I have to answer this problem in topology:
"Let $f$ and $g$ be continuous functions from the topological space $T$ into $\mathbb{R}$, with the usual topology. Show that $\{ x \in T \:| \:f(x) = g(x) \}$ is closed.
Also show that if $f(x)=g(x)$ for all x in some dense subset of $T$, then $f=g$ for all $x$ in $T$."
I hope someone can help me with this! Thank you.

A: Let $h:T\to\Bbb R$ be defined by $h(x)=f(x)-g(x)$. You should be able to show that $h$ is continuous. Your set is precisely the preimage under $h$ of the closed set $\{0\}$, so is closed by continuity of $h$.
If $S$ is a dense subset of $T$, then the closure of $S$ is $T$. But the closure of $S$ is the smallest closed subset of $T$ that contains $S$, and so if $S$ is a subset of the closed set in the first part (that is, if $f,g$ agree on $S$), then $T$ is the set from the first part, meaning $f=g$.

A: A nicer result can be seen as following:

Theorem: For any pair $f,g$ of continuous mappings of a space $X$ into a Hausdorff space $Y$, the set $\{x\in X: f(x)=g(x)\}$ is closed in $X$.

Proof: We shall show that the set $A=\{x \in X: f(x)\not=g(x)\}$ is open. For every $x \in A$ we have $f(x)\not=g(x)$; hence there exist in $Y$ open sets $U_1, U_2$ such that $f(x)\in U_1$, $g(x)\in U_2$ and $U_1\cap U_2=\emptyset$. The set $f^{-1}(U_1) \cap g^{-1}(U_2)$ is a neighbourhood of $x$ contained in $A$.
And hence,

Corollary: For any pair $f,g$ of continuous mappings of a space $X$ into a Hausdorff space $Y$ with $f(x)=g(x)$ for any $x\in S$, where $S$ a dense subset  of $X$, then for any $x\in X$, $f(x)=g(x)$.

Proof: It is clearly to see that $S \subset \{x\in X: f(x)=g(x)\}$. By the above theorem, we can conclude that $\overline{S} \subset \{x\in X: f(x)=g(x)\}$, and hence $X = \{x\in X: f(x)=g(x)\}$.


text:
Q: Automatically copying a file to a network drive when it is saved I was wondering if there is any way through applescript or automator in Mac OSX Mountain Lion to automatically copy a file or folder to a network drive after the file is saved/the folder is modified. I am trying to do this for a user who designs in Photoshop and has 2GB+ size files that take a long time to save to the network drive directly so I am trying to create a way where he can save locally and automatically have it copied over to the networked drive.

A: Using launchd, you could save a plist like this as ~/Library/LaunchAgents/rsync_folder.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>rsync_folder</string>
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-c</string>
    <string>[[ -e /Volumes/WD ]] && rsync -a ~/Notes /Volumes/WD</string>
  </array>
  <key>WatchPaths</key>
  <array>
    <string>~/Notes/</string>
  </array>
</dict>
</plist>

Then load it with launchctl load ~/Library/LaunchAgents/rsync_folder.plist or by logging out and back in.
Or create a rule like this in Hazel:

Neither watches for changes to files in subfolders (like ~/Notes/subfolder/file.txt) though.


text:
Q: VirtualBox - Automatic screen resolution stopped working I'm running VirtualBox 5.0.18 with Ubuntu 16.04.
I've installed VirtualBox Guest Additions and DKMS, which enabled the automatic screen resolution in my VB.
This worked fine for several months until today. I accidentally changed the screen resolution and the automatic screen resolution stopped working.
Installing Guest Additions and DKMS again didn't work. They are still installed and are up to date with the latest versions.
I've tried this command but it didn't work:
sudo dpkg-reconfigure virtualbox-guest-dkms

Is there a way to activate the automatic screen resolution again?
Thanks.


text:
Q: After packaging for ad-hoc distribution, iOS app data persistence doesn't work I just finished an app that allowed users to store lists of serial numbers in a tableview. The way the app stores the numbers is by storing in an NSMutableDictionary then writing to a persistence plist file. The app ran perfectly fine during testing.
However, I just built and packaged the app for ad-hoc distribution, and now when I test the app from an end-user perspective, the data is not being saved, i.e. when I add a new row to my tableview and typing in a new number, the new row is not being created and nothing is being written to the dictionary. I use the following code to write to the plist (assuming dict is already populated):
[dict writeToFile:[appDelegate dataFilePath] atomically:YES];

where in my App Delegate:
- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

And I read the plist from disk using this:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:[appDelegate dataFilePath]];

What's wrong here?

A: If you say you're having trouble persisting data, you really should show the code where you write this plist file to disk, and also show the code where you load it from disk. Otherwise you're asking us to speculatively debug your code.
If you're doing it inside the application bundle, that is an example of an operation that will work in the Simulator, but not when run on a device.

A: Oh I realize something. I did all my development using the 4.2 beta SDK and now running the app compiled using 4.1 as the base, the data doesn't seem to persist! Is there something new in 4.2 that does this?


text:
Q: Detecting dependency collisions Short version of the question:
Is there a good way to detect at build time if I have any cases where 2 or more projects reference different versions of the same assembly?  (really, I would like to teach our CI server to do this)
Long Version:
So here's an interesting problem (simplified a bit for easy digestion):
Recently encountered a situation where we had 2 projects in a solution, A and B.  Both A and B depend upon a 3rd party nuget package C.
A always loads C, B only needs C in rare circumstances.
So, during this sprint, a developer updated Project A to use the latest version of the C package (not realizing that B also depended upon C)
Everything built and the tests that we had passed (we have insufficient test coverage), but when we released to production, we had failures occuring when B attempted to use the dependency (loader issues, because we wanted a different version of the strongly named assembly).
We found the problem, and corrected it, but.  I would really love to be able to catch this during development.  It would be even cooler if our build server could detect this (TFS 2012) when it does a CI build.
How might I go about detecting this situation?

A: VS can't do this for you because of the dynamic loading (unless I'm missing something): it just has no way of knowing which assemblies wil be loaded at runtime.
We had the same problem once (using Prism - all our assemblies are loaded at application startup normally, and the order is described in a config file though most are optional). I First thought of making a small tool that basically scans all packages.config or csproj files to see what assemblies are used in what version, and make it complain when two packages of different versions are found. But I ended up with dealing with it at a higher level, more direct and foolproof: we now have a simple class, sort of a stub of the actual application, that just loads all the application's components and modules as described in the config file. This results in all assemblies that can ever get loaded to be loaded so if something goes wrong it will be found. This functionality is simply placed in a unit test.


text:
Q: ChartJS unable to register global plugin After a ChartJS migration from v2 to v3 i'm unable to registed a global plugin, by following the migration guide i changed Chart.plugins.register in Chart.register but i get this:

class does not have id: function (chart)

The issue i think is in afterDraw function but how should it be fixed after a migration?
The code
Chart.register({
    afterDraw: function (chart) {
        var data = chart.data.datasets[0].data;
        if (data.length === 0) {
            // No data is present
            var ctx = chart.chart.ctx;
            var width = chart.chart.width;
            var height = chart.chart.height
            chart.clear();

            ctx.save();
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.font = "16px normal 'Helvetica Nueue'";
            ctx.fillText('Nessun dato disponibile', width / 2, height / 2);
            ctx.fontColor = "#828282";
            ctx.restore();
        }
    }
});

A: By reading the documentation better a unique id must be configured for each registered plugin.

Plugins must define a unique id in order to be configurable.

So i just added the id in my code
Chart.register({
    id: 'no_data_label',
    afterDraw: (chart, args, options) => {
        const data = chart.data.datasets[0].data;
        if (data.length === 0) {
            // No data is present
            console.log(chart)
            const current = chart.ctx;
            const width = chart.width;
            const height = chart.height
            chart.clear();

            current.save();
            current.textAlign = 'center';
            current.textBaseline = 'middle';
            current.font = "16px normal 'Helvetica Nueue'";
            current.fillText('Nessun dato disponibile', width / 2, height / 2);
            current.fontColor = "#828282";
            current.restore();
        }
    }
});


text:
Q: Can I append a header row of data with a different number of columns in R? EmployerID | 1.0    | 20220801
Dairy      | Milk   |   1.99   | Mary    | 2x
Produce    | Tomato |   1.49   | John    | 1x
Produce    | Orange |   0.99   | Nilofar | 3x

I'm working with a pipe-delimited text file that has a header row with a different number of columns. For example, the header in the data above has 3 columns while the rest of the data has 5 columns. My goal is to read the file into RStudio, cleanse the data, and upload the data to a folder in the same format.
I was able to read the data into R using 2 dataframes by separating the header from the rest of the data. Then, I used rbind.fill() of the "plyr" package to attach the header to the dataframe. However, the header defaults to the same number of columns as the rest of the data like this:
EmployerID | 1.0    | 20220801 ||
Dairy      | Milk   |   1.99   | Mary    | 2x
Produce    | Tomato |   1.49   | John    | 1x
Produce    | Orange |   0.99   | Nilofar | 3x

How can I append the header row of data while maintaining only 3 columns (or only 2 pipes)?
Here is what I have so far
dataframe <- read.csv(
                  "file_name.txt",
                  sep = "|",
                  skip = 1,
                  header = FALSE)

header <- read.csv(
               "file_name.txt",
               sep = "|",
               nrows = 1,
               header = FALSE)

newfile <- rbind.fill(header, dataframe)

write.table(newfile, file = "new_file_name.txt",
              sep = "|",
              col.names = FALSE,
              row.names = FALSE)

A: In the moment you row-bind, the extra columns will be created.  You could keep your data separate and use append in write.table. If you need to keep track of header and data, you could put the data frames into a list.
write.table(header, file = "new_file_name.txt",
            sep = "|",
            col.names = FALSE,
            row.names = FALSE)

write.table(dataframe, file = "new_file_name.txt",
            append = TRUE,
            sep = "|",
            col.names = FALSE,
            row.names = FALSE)

Output:
EmployerID | 1.0    | 20220801
Dairy      | Milk   |   1.99   | Mary    | 2x
Produce    | Tomato |   1.49   | John    | 1x
Produce    | Orange |   0.99   | Nilofar | 3x


text:
Q: Can Seagate Expansion external HDD be connected to desktop SATA bus? Please help, help is needed.
I am terribly sorry if my wording is unprofessional, I am a Chinese and I don't even know how to express them in Chinese!
Long story short, recently I have run some tests on my Seagate Expansion 2TB (1863 GiB ish) external HDD, and the results show some random bad sectors with cylinder numbers changing each time, I have preliminarily excluded the possiblity of physical bad sectors, and when I open Seatools, it displays only two devices: the internal HDD and external HDD, while it normally will display the external hard disk enclosure as a third device.
I think the USB chip is faulty, so I opened the case of my external HDD, and opened my computer's case, and found out I am unable to connect the HDD to the computer...
So this is my external HDD itself:

As you can see, the socket of my HDD has two "plates" covered with metal bars extruding from the "main disk", the socket has two parts, one is much larger than the other, I had found a spare SATA bus in my computer, the port is roughly the same size as the big "plate", but I can't quite plug the port into the socket, the shape of the thing holds the HDD in place on the port doesn't match the corresponding part in the socket, and the numbers of metal bars don't match, and I can't found a piece that matches the other part...
So do I have to buy an external HDD enclosure or I can plug the HDD into my computer?
The front cover of my HDD:

A: That's a standard SATA connector. It should work with any computer.
The smaller, 7-pin part is a SATA connector. It connects to the motherboard using a SATA cable.
The larger, 15-pin one is SATA power. Your power supply should have a plug that matches it.
Make sure you're not plugging cables in upside down. The angled protrusions on HDD side should fit into matching holes in respective cables.


text:
Q: JsTree Custom Icons with Json_data plugin I am using a JsTree on an MVC website. I am using the json_data plugin to populate the tree. My Controller action returns a JsonResult using a class I made to represent the nodes. I have been reading the documentation on how to specify a custom icon for a specific node, but I can't seem to get it right. It seems to suggest that data should be an object that contains title and icon strings, but this stopped the tree from loading when I tried it. The class structure I am using at the moment is as follows.
public class NodeModel
{
    public string data;
    public NodeAttribute attr;
    public string state = "closed";
    public string icon = "default/file.png";
}

public class ParentNodeModel : NodeModel
{
    public List<NodeModel> children;
}

public class NodeAttribute
{
    public string id;
    public string type;
}

Does anyone know what format the json data should look like to give each node an individual icon? I would like to avoid using the types plugin if possible.
Resolved
Changing my class structure to make the data string into a new object was actually the correct format. But with the new structure another part of my code was crashing (fixed now). So the classes will now look like this
public class NodeModel
{
    public NodeData data;
    public NodeAttribute attr;
    public string state = "closed";
}

public class NodeData
{
    public string title;
    public string icon = "path/file.png";
}

A: Seems that your objects defined correctly. From jsTree documentation:

if icon contains a slash / it is treated as a file, used for
  background. otherwise - it is added as a class to the "ins" node

I assume that "default/file.png" has been added as the CSS class to the "ins" node, so maybe slash '/' should be the first symbol, try to set the icon value as "/default/file.png".
Also you can check how we're using jsTree in our project:

*

*controller(method LoadCategoryTree)

*view


text:
Q: CruiseControl email error I m getting following error when trying to send a email to a gmail account from CruiseControl.
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first.
Appreciate any idea to resolve this.

A: See if this patch helps you.
http://jira.public.thoughtworks.org/browse/CC-277


text:
Q: When starting the program, getting Error creating bean with name 'entityManagerFactory' defined in class path resource This error appears, I read on the sites to fix it I need to add various dependencies. I have already added everything I could, it has not disappeared. Tell me what is wrong please.
my implementation
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
// postgresql
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.19'

implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'
implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
implementation group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.4.30.Final'

//lombok
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'

testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'

// spring-security-taglibs
implementation group: 'org.springframework.security', name: 'spring-security-taglibs', version: '5.4.2'

// javax.servlet
compileOnly group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'

Class User
import lombok.Data;
import org.springframework.data.annotation.Id;

import javax.persistence.*;
import java.util.Set;

@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String username;

@Column
private String password;

@Transient
@Column
private String passwordConfirm;

@Column
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles;
}

Class Role
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.*;
import java.util.Set;

@Data
@Entity
@Table(name = "t_role")
public class Role implements GrantedAuthority {

@Id
@Column
private Long id;
@Column
private String name;
@Transient
@ManyToMany(mappedBy = "roles")
private Set<User> users;

public Role(Long id) {
    this.id = id;
}

public Role(Long id, String name) {
    this.id = id;
    this.name = name;
}

@Override
public String getAuthority() {
    return getName();

}

Class WebSecurityConfig
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf()
            .disable()
            .authorizeRequests()
            //Доступ только для не зарегистрированных пользователей
            .antMatchers("/registration").not().fullyAuthenticated()
            //Доступ только для пользователей с ролью Администратор
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/news").hasRole("USER")
            //Доступ разрешен всем пользователей
            .antMatchers("/", "/resources/**").permitAll()
            //Все остальные страницы требуют аутентификации
            .anyRequest().authenticated()
            .and()
            //Настройка для входа в систему
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .logoutSuccessUrl("/");
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
 }
}

Logs
Error starting ApplicationContext. To display the conditions report re-run
your application with 'debug' enabled.
2021-05-05 12:32:55.159 ERROR 11924 --- [           main]
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean
 with name 'entityManagerFactory' defined in class path resource

Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: No identifier specified for entity:
com.project.project.model.Role
at
at

... 17 common frames omitted
Process finished with exit code 1

Application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/main_bd
spring.datasource.username=mysql
spring.datasource.password=mysql

spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

Class UserService
@Service
public class UserService implements UserDetailsService {

@PersistenceContext
private EntityManager em;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;

@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("Пользователь не найден");
    }
    return (UserDetails) user; // ПРОВЕРИТЬ!
}

public User findUserById(Long userId) {
    Optional<User> userFromDb = userRepository.findById(userId);
    return userFromDb.orElse(new User());
}

public List<User> allUsers() {
    return userRepository.findAll();
}

public boolean saveUser(User user) {
    User userFromDB = userRepository.findByUsername(user.getUsername());

    if (userFromDB != null) {
        return false;
    }

    user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    return true;
}

public boolean deleteUser(Long userId) {
    if (userRepository.findById(userId).isPresent()) {
        userRepository.deleteById(userId);
        return true;
    }
    return false;
}

}

I tried all the tips I found and nothing helped. Can you please tell me what is my mistake here?

A: the error is org.hibernate.AnnotationException: No identifier specified for entity:  com.project.project.model.Role.
Hibernate is telling you that your entity Role has not an id associated. This is because you @Id annotation in your entity is from org.springframework.data.annotation package, and not from javax.persistence.
Try changing the import for @Id to javax.persistence.Id


text:
Q: Writing test cases for RxJava doOnSubscribe and doOnFinally situations Let's say I've this particular piece of code in Kotlin. My question is how do I test during subscribing I have set the visibility of button to VISIBLE and set the text to "". And once subscription is completed I've made the visibility to GONE and test to "DONE".
fun getInfo() {
    getInfoFromApi()
        .doOnSubscribe {
            buttonVisibility.set(View.VISIBLE)
            buttonText.set("")
         }
        .onFinally {
            buttonVisibility(View.GONE)
            buttonText.set("DONE")
        }
        .subscribe {
            // Some other random stuff
        }
    }
}

As of now my test cases look like this.
@Test
fun getInfo() {
    viewModel.getInfo()
    Assert.assertEquals(View.GONE, viewModel.buttonVisibility.get())
    Assert.assertEquals("DONE", viewModel.buttonText.get())
}

Which obviously is correct when you look at what the final state should be, but how do I test the intermediate stages of doOnSubscribe?
Is there a way to Assert, if the button text was set to DONE from "", and visibility went from VISIBLE to GONE?

A: doOnSubscribe and onFinally are just states of your View/ViewModel, so you can extract these states and check state changes:
fun getInfo() {
    getInfoFromApi()
        .doOnSubscribe {
            view.setButtonVisible()
         }
        .onFinally {
            view.setButtonGone()
        }
        .subscribe {
            // Some other random stuff
        }
    }
}

And then verify calls:
@Test
fun getInfo() {
    val view = mock(View::class)
    viewModel.getInfo()
    verify(view, times(1)).setButtonVisible())
    verify(view, times(1)).setButtonGone())
}

By the way, if your example supposed to be used with MVVM then your ViewModel should not have reference to View. ViewModel should provide bindings for view. And then code could look like this:
fun getInfo():Observable<State> {
    return concat(
       just(State.Progress),
       getInfoFromApi().map(State.Result)
    ).onErrorResumeNext(just(State.Error))
}

And then tests became even more abstract and clear
@Test
fun getInfoSuccess() {
    //config api success behaviour
    TestObserver<State> observer = TestObserver.create();
    viewModel.getInfo().subscribe(observer)
    observer.assertResult(State.Progress, State.Result);
}

@Test
fun getInfoError() {
    //config api error behaviour
    TestObserver<State> observer = TestObserver.create();
    viewModel.getInfo().subscribe(observer)
    observer.assertResult(State.Progress, State.Error);
}


text:
Q: what's difference , to launch from 'Notifications' and launcher icon? My MainActivity is overriding onNewIntent.
And myService is foreground service with Notification.
After myprogram is killed,
If i launch my program from launcher icon, onNewIntent is called finally.
But if i launch from Notification, onNewIntent is never called.
I think stack is different.
What do you think?
My Notification from myService class is like this
Intent i = new Intent(this,InputMainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

Notification n = new Notification(R.drawable.notiicon,"comment",System.currentTimeMillis());
                    n.setLatestEventInfo(myService.this,"comment","comment",pi);
startForeground(1,n);

How should i do to call onNewIntent when this program is called from Notification?

A: Does it work with this code?
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);


text:
Q: Can't find ruby element with selenium I've been trying since yesterday to find a nested_form link_to_add button using selenium. When I copy its XPATH from chrome and paste it into the script:
element = browser.find_element(:xpath => "//*[@id='tabpage_1']/a")

I get the following error when running selenium:
': undefined method `*' for //:Regexp (NoMethodError)

If you know of any other way detect such a element it would be very appreciated. This is the elements HTML:
Add Level

A: try it this way
element = browser.find_element(:xpath => "//*[@id=\"tabpage_1\"]/a")

Note: Escape the double quotes.
Tip - If you use a nice text editor (example - Sublime), the colour of the text will change and will help uou detect errors like these


text:
Q: Update values corresponding to different existing keys in unordred_map from multiple threads I have an unordered map looks like this:
unordered_map<string, MyClass*> idToMyClassMap;

Now I understand that I cannot do insert/delete and etc to this map from multiple threads without synchronization. But can I pre-populate this map with the largest possible entries that I will use with an list of pre-known string key and all nullptr for MyClass. When I actually want to "insert" to this map, I will just iterate through the map, find which key is nullptr and use that. When I am deleting, I will set the value to nullptr again.
Would this work?

A: Yes, this would work in the sense that you will not be subjecting yourself to race conditions - assuming you do not modify the same element from more than one thread.
find is a rare example of the container member function which is not marked const (because it returns modifiable iterator) but still is safe to be called from multiple threads simultaneously.
To get more information on container thread-safety, I strongly recommend memorizing this page: http://en.cppreference.com/w/cpp/container


text:
Q: Populate form selections lists depending on previous answers drop down I really don't know where to begin with this and can't seem to find the right terms to find the answer on the net to help me achieve this.
I want to create a form with drop down selection lists that will then display a set of drop down answers based on the previous drop down selection.
For example your first drop down would be: Fruit or vegetable, fruit selected so next option would apples or oranges, apples selected so your next option would be granny smith or cox.
How do I go about doing this jQuery? any help much appreciated?

A: You can use onchange function to trigger this:
For example:
<select id="selectBox1">
<option value="fruit">Fruit</option>
<option value="Vegetable">Vegetable</option>
</select>

<select id="resultBox1"></select>

in jquery:
$("#selectBox1").change(function(){
var value = $(this).val();
if(value == 'fruit'){
// append or display your fruit list
}else{
//vegetable list
}

});

Hope this will help you out..


text:
Q: The Tutorials in Qiskit: Option Pricing with qGANs # Set upper and lower data values
bounds = np.array([0.,7.])
# Set number of qubits used in the uncertainty model
num_qubits = [3]

# Set entangler map
entangler_map = []
for i in range(sum(num_qubits)):
    entangler_map.append([i, int(np.mod(i+1, sum(num_qubits)))])

# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]

# Set an initial state for the generator circuit
init_dist = NormalDistribution(sum(num_qubits), mu=1., sigma=1., low=bounds[0], high=bounds[1])
init_distribution = np.sqrt(init_dist.probabilities)
init_distribution = Custom(num_qubits=sum(num_qubits), state_vector=init_distribution)

I want to know how to obtain the trained circuit parameters, which Attribute or Method should be used?


text:
Q: fopen trying to access a different folder I'm learning how to do file operations and whilst using fopen I seem to have encountered a problem. My project is in 'C:\Users\Bob\Documents', however, when I use fopen, it saves or tries to access files from  C:\Users\Bob\Documents\Debug. Debug is a folder in my Documents.

*

*How can I have my program access files from C:\Users\Bob\Documents only and not from the Debug folder.

*Is there a way to specify different locations to save or access files from, instead of the current directory where my project is.
int main(){

FILE *fpointer;
char ch;
fpointer = fopen("test.txt", "r");

while(1){
    ch = fgetc(fpointer);
    if( ch == EOF){
        break;
    }
    printf("%c", ch);
}

return 0;
}

A: Since you don't pass a path to fopen it will open files in the current working directory, which happens to be the Debug directory in your case.
Pass a full path instead, e.g.
fpointer = fopen("C:\\Users\\Bob\\Documents\\test.txt", "r");`

or change the working directory (either programatically, or in your IDE settings).

A: A lot of what you are asking depends on your development environment.
Your development environment should be offering you some means to somehow configure how your program is launched, by modifying something called "debug configuration" or "launch configuration" or something along these lines.  Note that these options are different from the general options of the development environment, because they differ from project to project.
Right now it appears that nothing is configured, so the current directory of your application is the same directory as the directory where the .exe file is.  Since you are running your debug build, the .exe file is generated under Documents\Debug, and that's its working directory.  So, in the launch configuration specify that you want its working directory to be in C:\Users\Bob\Documents.
Alternatively, you can of course try opening "..\test.txt", but this will fail if you ever try to run your .exe under deployment conditions, where both the .exe and "test.txt" are probably going to be in the same directory.


text:
Q: Segmentation fault using MeasureTextEx() I ran into a problem while using Measuretext().
My goal is to ru
#include <raylib.h>

int main()
{
    Font font=GetFontDefault();
    const char *text="Hello world!";
    float fontSize=10.f;
    float spacing=10.f;

    Vector2 textSize;

    textSize=MeasureTextEx(font, text, fontSize, spacing);

    return 0;
}

I tried modifying the sourcecode of MeasureText() but upon removing part of the code, it also returned segmentation fault
#include <raylib.h>

int main()
{
    Font font=GetFontDefault();
    const char *text="Hello world!";
    float fontSize=10.f;
    float spacing=10.f;

    Vector2 vec;

    // Check if default font has been loaded
    if (GetFontDefault().texture.id != 0) //<- Upon removing this, it also returns segmentation fauls
    {
        vec = MeasureTextEx(font, text, (float)fontSize, (float)spacing);
    }

    return 0;
}


text:
Q: SAPUI5: WizardControl - Change Text on Button and add buttons I am using the wizard control and i was trying to modify the text in the button for the next step also add some buttons inline with it. I have a screenshot here of what it currently by default looks like and what i wanted to achieve.
Current:

Target:

Can you guys please help me how to achieve this?

A: I asked a friend who did something like that. Ha just deactivated the button (using showNextButton="false") and made one himself.
Making a customized Button will solve your problem for sure.
Your custom buttons should have a controller function that changes the steps of the wizard. this.getView().byId("wizID").nextStep()


text:
Q: Mapping Likert Scale Options to Numbers I have a data set which is based on 5-point Likert scale. The options are in either [Strongly disagree, ..., Strongly agree] or [Never, ..., Very frequently]. Now I want to map the responses to numbers like [Strongly disagree -> 1, Disagree -> 2, Neutral -> 5, Agree -> 10, Strongly agree -> 17] for running some machine learning algorithms. Is it ok? Am I doing it right?

A: A likert scale is not the 5-point answering format. A scale is a sum of such "assigned" numbers and usual practice is to do some thourough investigation (including but not limited to factor analysis) whether the added items belong together in the sense of forming more or less a single factor.
Such sums of multiple items have been used by Rensis Likert in Likert, R. "A technique for the measurement of attitudes".Archives of Psychology, 1932;Vol 22, No. 140, p 55 https://legacy.voteview.com/pdf/Likert_1932.pdf
Whilst attaching numbers to ordinal data still results in ordinal data that you are not allowed to sum, simply doing so worked well for Likert, as he writes

Although the sigma technique seemed to be quite satisfactory for the
  intended use, it was decided to try a simpler technique to see if it
  gave results comparable with the sigma technique. If it did, the
  simpler method would save considerable work in a general survey type
  of study of this kind. The simpler technique involved the assigning of
  values of from 1 to 5 to each of the five different positions on the
  five-point statements. The ONE end was always assigned to the negative
  end of the sigma scale, and the FIVE end to the positive end of the
  sigma scale. After assigning in this manner the numerical values to
  the possible responses, the score for each individual was determined
  by finding the average of the numerical values of the positions that
  he checked. Actually, since the number of statements was the same for
  all individuals, the sum of the numerical scores rather then the mean
  was used. The reliability of odds vs. evens for this method yielded
  essentially the same values as those obtained with the sigma method of
  scoring. The scores obtained by this method and the sigma method
  correlated almost perfectly as will be seen in Table IV.

So you are doing something that is not following strict mathematical rules but has worked anyways for some time now in a framework called "Classical Test Theory". Taking the habit of summing ordinal data out of that framework (i. e. scale building etc.) might impose serious problems, so there is no simple saying "Its ok, you're doing it right." Depending on the circumstances it may be the most suitable thing for you to do, but be aware of breaking the rules of mathematics here. The mean of "disagree" and "neutral" is not "disagree and a half"!

Strongly disagree -> 1, Disagree -> 2, Neutral -> 5, Agree -> 10, Strongly agree -> 17

Assigning number 1 to 5 is common practice, using values of 5, 10 and 17 will need some serious justification.