text:
Q: Shell Script to create a tar file whenever a particular folder gets modified New to shell scripting, just wanted to understand how to write a shell script to create a tar file whenever a particular directory gets modified.
When we say modification, its like new files got added/removed to/from that particular directory.
Tarfile should be something like nameofDir_timestamp.tar
find path/to/dir -mtime 10m exec tar -cvf {} ;

A: Assuming you have bash installed, you could do this
#!/usr/bin/env bash
dirname='folder'
dirlastmod='folder-last-modified'

[[ ${dirlastmod} -nt ${dirname} ]] && exit

timestamp=$(date '+%s')

tar -cvf "${dirname}_${timestamp}.tar" "${dirname}"
touch "${dirlastmod}"

and add it to a cronjob.
This will check if the directory folder is newer than the file folder-last-modified, and exit if it's not. If it is, it will create a tar file of the directory folder, and use touch to update/create the timestamp on the folder-last-modified file.


text:
Q: Jmockit @Mocked return empty object on lombok @builder I am using Jmockit for my Junit test.
When I'm testing a function which uses lombok's builder.build(), it returns an instance with empty values.
I've also tried to use @Injectable and @Capturing, both gave me the same result.
@Test
public void test_updateStatusFromResponse_success_payment_result(@Mocked MyObject myObject) {
    myClass.myFunction("paraA","paraB");
}

public class myClass{
    public void myFunction(String paraA, String paraB){
        MyObject myObject = MyObject.builder.
                                     StringA(paraA).
                                     StringB(paraB).
                                     build();
        //myObject's both StringA and StringB is null
    }
}

@Builder
@Getter
public class MyObject {
    private final String StringA;
    private final String StringB;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: $X$ is a vector field tangent to $S$ along $\alpha$, but always orthogonal to $\alpha$. Shouldn't $X \cdot \alpha = 0$? Part of the problem statement...

Let $\alpha: I \rightarrow S$ be a unit speed curve in an n-surface, $S$, and let $X$ be a smooth vector field, tangent to $S$ along $\alpha$, which is everywhere orthogonal to $\alpha~$ ($\color{red}{(X(t)) \cdot \dot{\alpha(t)} = 0}$ for all $t \in I$).

This isn't the whole problem statement—but the part highlighted in red is what I'm questioning. If $X$ is orthogonal to $\alpha$ at all points, then shouldn't $X \cdot \alpha = 0$, and not $X \cdot \dot{\alpha} = 0$?

A: You're forgetting that $\alpha$ is a curve, not a vector field. However, $\dot{\alpha}(t)$ is a vector field along $\alpha$ (i.e., $\dot{\alpha}(t) \in T_{\alpha(t)}S$ for all $t \in I$), so it makes sense to require $X(t) \cdot \dot{\alpha}(t) = 0$.


text:
Q: C# Win. Form - Data not reflecting when 2 datagridviews are set equal I have 2 forms (Form1, Form2) each having 1 datagridview with modifier Public and 1 button. The code written on the buttons are:-
Form2 f = new Form2();
f.Show();
f.datagridview1 = datagridview1;

Problem
Now when i press the button of Form1, Form2 appears but the values in datagridview1 of Form1 are not displayed in the datagridview1 of Form2 but when i programmatically check for the values in datagridview1 of Form2, the values are there.
Solutions tried

*

*datagridview1.Refresh(); - i tried to refresh the control of Form2 but no changes were seen.

*f.Refresh(); - i even tried to update the whole Form2 but still no changes were seen

Note:- I know i instead of writing f.datagridview1 = datagridview1; i can write a loop to populate the datagridview but i need to know what is the problem with the above code.
Thanks in advance

A: You shouldn't override the reference to the dataGridView (which means that you will access the dataGridView from Form1, even if you access f.dataGridView1 from Form2), but rather set the DataSource from both dataGridViews to the same object.
So the error in your code can be made visible if you add the following line in your code:
Form2 f = new Form2();
f.Show();
f.datagridview1 = datagridview1;
f.datagridview1.DataSource = null;

You will see that, all of a sudden, your datagridview in Form1 will be empty, because datagridview1 AND f.datagridview1 will point to the same datagridview in Form1. Also you can no longer access the datagridview from From2 (at least not that easy).
So maybe try this instead:
f.datagridview1.DataSource = datagridview1.DataSource

This code will just set both DataSources (which contain the actual data) to the same object in both datagridviews.
I hope this explanation is somewhat understandable : )

A: You could use ResetBindings on the BindingSource object. Like that:
//could be simpler assignment, but to give you a view on what is going on
BindingSource source = new BindingSource();
source.DataSource = f.datagridview1.DataSource;
source.ResetBindings(false);

Let me know if that works for you


text:
Q: Realm - module file was created by an older version of compiler I use latest version of xcode and swift 2.2. One of my projects, which I havent open for several month now not building, because of error
module file was created by an older version of compiler
I tried the following

*

*Removed realm frameworks from project, then download the latest version from realm.io and copy the new frameworks to project

*Building realm by build.sh build from github sources with REALM_SWIFT_VERSION=2.2 and adding to project

Neither of these helped, still got error.
Any advices ?

A: Can you try the following?

*

*Delete derived data

*Clean the build folder (click on Xcode's Product menu while holding down the Option key, and choose the Clean Build Folder menu item)

Sometimes simply performing a clean build isn't sufficient to flush the invalid intermediate products or cached data.

A: I had this issue when upgrading from Swift 2.2 to Swift 3.0, specifically for Realm Swift cocoapod. I think this solution should work for this general issue. Here is what worked for me:
(1) Go to derived data folder /Users/(yourUserName)/Library/Developer/Xcode/DerivedData
(2) Select project with error
(3) Delete
(4) Clean project
(5) Run
Cleaning initially did not work for me. Hope this helps!

A: I faced the same issue when used Swift 3.2 in my project. After upgrading to Swift 4.0 issue disappeared. Cleaning project folder, derived data, restarting Mac - nothing helped.


text:
Q: Element X is undefined in cfloop over dynamically generated named radio buttons I'm coding this new feature for a client. I need to give a user rights to the following:

*

*A District

*An operation center

*Projects in that ops center

Here is a screenshot of my add_a_user page that shows the district > Ops Center > projects layout:

There are currently 8 districts in my district table, but only "1" and "4" have ops centers right now. That is why you only see those in this screenshot. So there can be more than 1 ops center, in each district, and many projects tied to an individual ops center.
So my table structure in MS SQL server is like this:

*

*Districts / Columns:

*

*[district_id]

*[district_name]

*Operation_centers  / Columns:

*

*operation_center_id

*operation_center_name

*oc_district_id (links this ops center to the district it belongs to)

*Projects  / Columns:

*

*project_name_id

*project_name

*project_oc_id (links the project to the ops center it belongs to)
I also have 3 other tables that store the rights for the users:

*

*district_access

*

*district_access_id (district access id)

*district_user_nm (user who has right to this district)

*district_role (holds the value for their role - Admin,manager,editor,user)

*ops_access / Columns:

*

*ops_access_id (ops center access id)

*ops_user_nm (user who has access to this ops center)

*Project_access / Columns:

*

*project_access_id (project access id)

*project_user_nm (user who has access to this project)
I named the radio buttons dynamically like this:
f_district_access_#district_id# (district access)
f_da_#district_id# (district role)
f_ops_#operation_center_id# (ops center access)
f_projects_#getdistricts.project_name_id# (project access)

On my action page I'm trying to use this cfloop (and I do a cfloop for the ops centers and project also):
<CFQUERY  datasource="#datasource#" name="get_district_count">
    SELECT MAX(district_id) AS DC
    FROM   districts
</CFQUERY>
<cfset DC = get_district_count.DC>
<!-- Insert district access-->
<CFLOOP from="1" to="#DC#" index="dis">
    <cfset districtname = "f_district_access_" & dis>
    <cfif structKeyExists(form,"#districtname#")>
        <cfquery datasource="#datasource#" name="submit_districts">
            INSERT into district_access
            (
                district_access_id,
                district_user_nm,
                district_role
            )
            Values(
                #form["f_district_access_" & dis]#,
                #NEWID#,
                #form["f_da_" & dis]#
            )
        </cfquery>
    </cfif>
</CFLOOP>

Now I'm getting this error:

Element F_DA_4 is undefined in a Java object of type class
  coldfusion.filter.FormScope.

So my questions are, am I over complicating this and how can I simplify this?


text:
Q: Allow customer to send me email I'm bulding website where I want to allow future customers to send me an email. I'm using Node.js to handle sending and thought SendGrid would be good solution. There's actually problem, because SendGrid requires me to define sender and that's impossible because I'd like to customer fill form with his email, etc so I would get this data on my inbox. Is it even possible with SendGrid or maybe there's other tool that would fit me better?
Thanks in advance

A: what I have implemented in the past was a solution where the application sends an email to it self, and the email address of the user was added to the email header reply-to, this way whenever somebody with the access to the email client would press the Reply button, the user's mail would be the destination.
Example:
admin@yoursystem.com ---> Sends an email to ---> admin@yoursystem.com (with the user's message and his email address in the mail header reply-to).


text:
Q: STAssertEquals for checking NSArray count - clean way What is the correct way to check the NSArray items count with STAssertEquals for NSArray.
Following was expected to work:
...
STAssertEquals(1, [myArray count], @"One item should be in array");

This code produces "Type mismatch" runtime error when running test.
Instead I have to do an explicit cast to NSUInteger:
STAssertEquals((NSUInteger)1, [myArray count], @"One item should be in array");

This works - but looks kind a ugly due to explicit cast.
I also want to avoid using STAssertTrue because STAssertEquals looks more appropriate (we compare two values) and shows the actual and expected values.
What is correct way to check it in Objective-C?
UPDATE 1
Thanks for the answers suggested to use 1u as unsigned int literal
STAssertEquals(1u, [myArray count], @"One item should be in array");

But as @Aaron mentioned it still ugly - I would like to use "1" directly - thinking on using myArray.count == 1 instead now. And the reason for it is that 1u doesn't look very clean. The 1 is 1 for me. You never write 1u in math :-) Any other suggestions?
UPDATE 2
As @H2CO3 mentioned 1u even could not always work and as suggested in some thread we could use more declarative definition for expected value which will solve the problem of casting:
NSUInteger expectedItemsCount = 1;
STAssertEquals(expectedItemsCount, [myArray count], @"One item should be in array");

I prefer it to 1u solution because it looks cleaner. But the cons of this approach is that we have extra line and code is not very compact. So it looks like we have to choose between two approaches: (NSUInteger)1 and NSUInteger expectedItemsCount = 1;

A: C's type system...
1 is int, so it's signed. NSArray.count is NSUInteger so it's unsigned. Make the integer literal unsigned:
STAssertEquals(myArray.count, 1u, @"+1 item needed");

Edit: Even better, the above will fail on 64-bit (it would work with 1ull there), so what if you just use something like
const NSUInteger expectedLength = 1;
STAssertEquals(myArray.count, expectedLength, @"+1 item needed");

(The thread from where I stole this...)

A: You can use STAssertEquals(1U, myArray.count, @"One item should be in array"); to make the 1 unsigned.  Maybe that's still ugly.  It's a little bit less typing.

A: 1U is correct. But if you want to avoid that ugliness (and step into a better world of assertions), use OCHamcrest:
assertThat(myArray, hasCountOf(1));

A: If your project is substantial, or you expect this code to have a long life, consider adding specific assertions for things like this.  Define a special-case macro
  STArrayCount(myArray,1)

which can expand to something like
  STAssertTrue(myArray.count==1u,@"Expected %u but array count is %u",myArray.count,1);

Writing custom assertions makes your unit test clearer when you revisit it in a few years, and also provides a hook for additional testing. Suppose today myArray is an NSArray, but sometime later it becomes an instance of BigFancyObject that does some other things.  BigFancyObjects make most of your code much cleaner and hide implementation details, so that's all great. But you'd like to be sure that the BigFancyObject is valid because something keeps invalidating them.  So, you can redefine STArrayCount to
  STAssertTrue(myArray.isValid && myArray.count==...)

and now your unit tests check the object's validity, too.

A: The way I do it is to compare them as objects, which will work on 32 & 64 bit, prevent the need for any casting or unnecessary variable declarations, and maintain a nice failure message that includes the failed values:
STAssertEqualObjects(@(5), @(datas.count), @"unexpected array count");


text:
Q: How to transpose (and reshaping) a long dataset in a more compact one? Using R I have this dataset with N.treated=171 and N.controls=164. Thus the dataset has 171*164=28044 rows. (DIM: 28044 * 3)
Treated  Control  RESULT
1A        99A     Lose
1A        99B     Win
1A        99C     Win
2C        99A     Tie
2C        99B     Lose
2C        99C     Tie

I would like to obtain a dataset like the following:
     99A   99B    99C
1A  Lose   Win    Win
2C  Tie    Lose   Tie
3B  Win    Tie    Win

So the dimension of the above dataset is (171*164). How can I do it in R?
In addition, I would like to create a 3d Histogram of this above dataset. With the frequency of the three categories (Lose-win-tie) for each comparison. One problem is that my results are not numeric but categorical. I would like to have the results in terms of frequency of each category.
Thank you very much


text:
Q: yarn start command failed with exit code 127 Every time I try to start my project as usual using "yarn start" I get the "Command failed with exit code 127" error. I've realised I started to get this error once I've updated my iOS to Monterey v12.6.1 . My node version is not compatible with the yarn it seems like.
What have I tried to fix this:

*

*I have tried to upgrade/update my node version.

*I have uninstalled manually node/npm and yarn and reinstall them back with node version 16.0.0

*I have deleted the node_modules and package_lock.json

*I have had run the command "yarn" and every other update/upgrade command

Everything that I have tried failed.
This is the yarn error log:
Yarn version:
  1.22.10

Node version:
  15.7.0

Platform:
  darwin x64

Trace:
  Error: getaddrinfo ENOTFOUND registry.yarnpkg.com
      at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26)

npm manifest:
  {
    "name": "web",
    "version": "0.1.0",
    "homepage": "https://danibis.github.io/",
    "private": true,
    "dependencies": {
      "@testing-library/jest-dom": "^5.11.4",
      "@testing-library/react": "^11.1.0",
      "@testing-library/user-event": "^12.1.10",
      "cors": "^2.8.5",
      "express": "^4.17.2",
      "focus-trap-react": "^8.9.1",
      "leaflet": "^1.8.0",
      "node-sass": "^6.0.1",
      "nodemailer": "^6.7.2",
      "react": "^18.1.0",
      "react-dom": "^18.1.0",
      "react-leaflet": "^4.0.0",
      "react-scripts": "4.0.3",
      "styled-components": "^5.3.3",
      "web-vitals": "^1.0.1",
      "webpack-hot-middleware": "^2.25.1"
    },
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject",
      "predeploy": "yarn run build",
      "deploy": "gh-pages -d build"
    },
    "eslintConfig": {
      "extends": [
        "react-app",
        "react-app/jest"
      ]
    },
    "browserslist": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }

yarn manifest:
  No manifest

Lockfile:
  No lockfile

Any other idea how to sort this out would be much appreciated.
Thank you for your time!


text:
Q: Obtaining year and month from date column in R I have a date column where dates look like this:
19940818
19941215
What is the proper command to extract the year and month from them?

A: If your data is e.g.
(df <- data.frame(date = c("19940818", "19941215")))
#      date
#1 19940818
#2 19941215

To add two columns, one for month and one for year, you can do
within(df, {
    year <- substr(date, 1, 4)
    month <- substr(date, 5, 6)
})
#       date month year
# 1 19940818    08 1994
# 2 19941215    12 1994

I don't see a need to convert to Date class here since all you want is a substring of the date column.

A: Another option is to use extract from tidyr.  Using df from @Richard Scriven's post
library(tidyr)
extract(df, date, c('year', 'month'), '(.{4})(.{2}).*', remove=FALSE)
#      date year month
#1 19940818 1994    08
#2 19941215 1994    12


text:
Q: Tally up results from a grep search? Say I have a list such as this:
8
382.34.6
sally
sally
8
923
183.3.3
183.3.3
183.3.3
8

And I want to tally up the number of times each unique value repeats and get output like this:
8 3
382.34.6 1
sally 2
923 1
183.3.3 3

What command would I need to run to do this?  If it makes a difference, the list is coming from a grep search.

A: Try this:
sort file | uniq -c | awk '{print $2,$1}'

Output:

183.3.3 3
382.34.6 1
8 3
923 1
sally 2

A: You could feed the list through | sort | uniq -c | sort -n, Like this:
echo -e "8\n382.34.6\nsally\nsally\n8\n923\n183.3.3\n183.3.3\n183.3.3\n8" | \
sort | uniq -c | sort -n
      1 382.34.6
      1 923
      2 sally
      3 183.3.3
      3 8

If you want the counts after the values, you could append | awk '{print $2,$1}'

A: One option is to use awk as follows: create an associative array, keyed by the item to be counted, and increment it each time the same item is read; at the end of input, iterate over the array and print the keys and counts:
your grep command | awk '{a[$0]++;next;}; END{for (i in a) print i,a[i];}'
A possible advantage is that you may be able to do the pattern matching directly in awk, doing away with grep altogether i.e.
awk '/your regex/{a[$0]++;next;}; END{for (i in a) print i,a[i];}'

A: Try this
stuff=(apple,boat,chicken)
for (i=0; i<${#stuff}; i=i+1); do
echo INPUT | grep ${stuff[i]} | wc
done

INPUT meaning the text to search. Also fill in the array with your words.


text:
Q: finding location of HTML elements with javascript & offsettop I'm trying to find the location of an element on the screen using javascript. This is what I'm doing.
function locateTargets(){
    var targets = document.getElementsByTagName("span");
    for(var i = 0;i<targets.length;i++){
        if(targets[i].className == "target"){
            targetsY[targets[i].getAttribute("id")] = targets[i].offsetTop;
        }
    }
}

This works fine in Firefox, Chrome and IE, but Opera and Safari end up finding 0 for all but the last element.
Any ideas why this might be happening and how to fix it?

A: offsetTop finds the top location relative to the last absolutely-positioned parent/ancestor element (document.body is the first absolutely-positioned ancestor element for any other element).
It looks like Opera has a bit of trouble with document.body and even fixed elements.
If these are not your issues, posting a bit of code may help us help you troubleshoot.


text:
Q: Why is this dockerized Postgres not able to authenticate with a password? I am working on changes to an Alpine fork of the official Docker postgres image ( https://hub.docker.com/r/deinspanjer/docker-postgres95-alpine34/ ).  It has been working fine for a while, but I needed to do some fdw connections, and that required host authentication to be set up so the user mapping could have a password.
You can see the startup / initdb code in the docker-entrypoint.sh file, but the meat of the matter is this:

*

*Takes advantage of the POSTGRES_USER and POSTGRES_PASSWORD environment variables

*Before calling initdb, writes the plain password to /tmp/.pwfile and writes the line: *:*:*:$POSTGRES_USER:$POSTGRES_PASSWORD to ~/.pgpass (chmod 600).

*Calls initdb passing the --pwfile=/tmp/.pwfile argument to try to get it to initialize the superuser with the desired password.

*Alters the pg_hba.conf file to add an additional line for host all all 0.0.0.0/0 md5
The problem is, after initdb, it starts up the server listening only on localhost to continue with the rest of the bootstrapping, but when it tries to run psql --username $POSTGRES_USER, it gets an authentication failure.
The log indicates that it is using the .pgpass, so I'm wondering if the initdb isn't picking up the password right or something, but I've fought with it until late in the night tonight, and I haven't been able to crack it.
If anyone else might be able to help, I would greatly appreciate it.
If you want to try running the entrypoint script manually, here is how you can do it:
docker run -e POSTGRES_USER=testuser -e POSTGRES_PASSWORD=testpass -e POSTGRES_INITDB_ARGS="-A md5" -p 5432:5432 -it --rm --entrypoint bash deinspanjer/docker-postgres95-alpine34
# printenv | grep POSTGRES
# /docker-entrypoint.sh postgres


text:
Q: Scraping data from 'See all answers' button I am trying to scrape reviews from this website : https://www.productreview.com.au/listings/aami-car-insurance?page=1#reviews . Each review container has 5 ratings (value for money, customer service etc.). when we initially load the page most of the info is hidden under the 'See all Answers' button. Therefore i can only scrape two of the ratings that show up at the top.
from bs4 import BeautifulSoup as bsoup
import requests

url = 'https://www.productreview.com.au/listings/aami-car-insurance?page=1#reviews'

req = requests.get(url)
soup = bsoup(req.text, 'html.parser')

reviews = soup.find_all('div', attrs = {'class' , 'mb-0__MF overflow-hidden_Yg5 card_UzP card-full_soR card-full-md_tUp'})

ratings = reviews[0].find_all('div' , attrs = {'class' , 'flex-column__BR d-flex_RNf col-12_hGx col-md-6_qwV'})
ratings

I checked the network monitor and when the button is pressed a GET request is generated to fetch the data.
How do I scrape the data hidden under the button?
Thanks for the help.

A: Their API is exposed;
https://api.productreview.com.au/api/au/listings/aami-car-insurance/reviews?page=1&withAggregations=false&limit=25
Just loop through this and increment page, each loop page = page + 1 and so on; parse the JSON grab the items; simple :)


text:
Q: Path of the current, parents and root directory I need to print the path of the current, parent and root directory in UNIX. I can use commands, or a shell script. I managed to do that for the current and the parent directory, but I do not know how to print it for the root directory.
Here is what i have done:

*

*current: pwd

*parent: echo $(pwd) | sed -e s/\\/[^\\/]*$//

A: gnu sed
echo $(pwd) | sed -r -e 'p; :a; s#(.*)/.*#\1#; H; ta; x' | sed '/^$/d'

this will print all directories from current -> root
it uses greedy search for '/' keeping only left part, appending in hold space, ta is conditional branch for substutution, so if there is one it branches to :a, at the end x is swaping hold space to pattern space.
Last sed command is for clearing empty lines

A: I think it's easier to do this using awk:
echo $(pwd) | awk 'BEGIN {FS=OFS="/"} {l=NF; while (i++<l-1) {print; NF--}}'

Explanation
This will print all directories from current --> root. It does this by printing the line, then decrementing the NF, the number of fields. Notice that I have set both the input and output field separators to the /.

A: Same idea as @josifoski
pwd | sed ':a;\#/\(.*\)/[^/]*# {p;s##/\1#;ba}'

Print and cycle until only 1st folder name, removing every cycle the last folder of the path


text:
Q: Excel Pivot Table into Specific Format I have a bit of a weird situation and im currently using a pivot table to get my info in excel then manually format it to what it needs to look like for the end users.
This is my pivot table

Here is the hierarchy for how the data needs to be displayed

Example of an End Product

I am wondering if there could be an easier way to do it instead of manually feeding those cells.

A: This looks like what I would call an "unwrapping" of row data. Say you have column headers A B C D, with row data like this:
A B C D
w x y z
f g h i

And you want to unwrap it like this:
A w
B x
C y
D z

A f
B g
C h
D i

You can use this formula in a new sheet (assuming sheet1 contains the data, starting with headers in row 1 and data from row 2). In A1:A10000
=INDEX(SHEET1!$A$1:$D$1, MOD(ROW()-1, 4)+1)

And in B1:B10000
=INDEX(SHEET1!$A$2:$D$2501, INT((ROW()-1)/4)+1, MOD(ROW()-1, 4)+1)

With a bit of tweak, you could even include a blank "" row as a spacer.
Also, FYI, you might be able to do this unwrapping with power query (old excel) or "Get and Transform" (renamed in Excel 365). It sounds more daunting than it is, but have a youtube search for some guides.


text:
Q: Libreoffice 4.2.7.2 bug: will it be an upgrade to 4.3 soon? I got this bug in Libreoffice today, was advised to upgrade to LO 4.3, will an official upgrade for Ubuntu 14.04 be available soon?
http://ask.libreoffice.org/en/question/43767/calc-deleted-several-foreign-sheet-name-references/


text:
Q: How to correctly load .pcss - postcss files with webpack? I'm trying, without success so far, to load postcss , .pcss files with webpack
Packages installed :
"postcss": "^8.4.13",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.2.1",
"extract-text-webpack-plugin": "^3.0.2"

 "webpack": "^5.23.0",
 "webpack-bundle-analyzer": "^4.4.0",
 "webpack-cli": "^4.5.0"

In webpack.config.js file :
        {
          test: /\.pcss$/,
          use: [
              //{
                  //loader: 'style-loader',
              //},
              //{
                  //loader: 'css-loader',
                  //options: {
                      //sourceMap: true,
                  //},
              //},
              { // https://github.com/webpack-contrib/postcss-loader#getting-started
                  loader: 'postcss-loader',
                  options: {
                      //config: {
                        //path: `${__dirname}/postcss.config.js`,
                      //},
                      postcssOptions: {
                        plugins: [
                          "postcss-preset-env",
                        ],
                      },
                      //sourceMap: true,
                  },
              },
          ],
        },

But it still says:
ERROR in ./src/assets/css/rssfeeds/app.pcss 9:0
Module parse failed: Unexpected token (9:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| html,
| body,
> #app {
|     min-height: 100vh;
| }

I tried also in this way in webpack.config.js :
const extractPCSS = new ExtractTextPlugin('../css/[name].css');

    {
      test: /\.pcss$/,

      // https://stackoverflow.com/questions/46865384/postcss-with-webpack?rq=1
      use: extractPCSS.extract([ 'css-loader', 'postcss-loader' ])
    }

But I still get this error:
ERROR in ./src/assets/css/rssfeeds/app.pcss 9:0
Module parse failed: Unexpected token (9:0)
You may need an appropriate loader to handle this file type,
currently no loaders are configured to process this file

The postcss file is:
html,
body,
#app {
    min-height: 100vh;
}

div[role='menu'] {
    outline: none;
}

div[role='menuitem'] {
    outline: none;
}

input:focus {
    outline: none;
}

[role='button']:focus {
    outline: none;
}

[role='menuitemradio']:focus {
    outline: none;
}

.thin-scroll {
    @apply overflow-y-scroll;
}

.thin-scroll::-webkit-scrollbar {
    @apply bg-transparent w-2;
}

.thin-scroll::-webkit-scrollbar-thumb {
    @apply bg-gray-500 rounded-lg border-4 border-transparent bg-clip-content;
}

.rss-item {
    @apply leading-8 text-gray-300 flex items-center justify-between cursor-pointer px-3 py-2;
}

.rss-item.active {
    @apply bg-gray-600;
}

Other info:
node: v16.15.0
O.S.: Ubuntu 20.04 Desktop


text:
Q: Copying data to "cufftComplex" data struct? I have data stored as arrays of floats (single precision).  I have one array for my real data, and one array for my complex data, which I use as the input to FFTs.  I need to copy this data into the cufftComplex data type if I want to use the CUDA cufft library.  From nVidia: " cufftComplex is a single‐precision, floating‐point complex data type that consists of interleaved real and imaginary components."  Data to be operated on by cufft is stored in arrays of cufftComplex.
How do I quickly copy my data from a normal C array into an array of cufftComplex ?  I don't want to use a for loop because it's probably the slowest possible option.  I don't know how to use memcpy on arrays data of this type, because I do not know how it is stored in memory.  Thanks!

A: You could do this as part of a host-> device copy. Each copy would take one of the contiguous input arrays on the host and copy it in strided fashion to the device. The storage layout of complex data types in CUDA is compatible with the layout defined for complex types in Fortran and C++, i.e. as a structure with the real part followed by imaginary part.
float * real_vec;       // host vector, real part
float * imag_vec;       // host vector, imaginary part
float2 * complex_vec_d; // device vector, single-precision complex

float * tmp_d = (float *) complex_vec_d;

cudaStat = cudaMemcpy2D (tmp_d, 2 * sizeof(tmp_d[0]),
                         real_vec, 1 * sizeof(real_vec[0]),
                         sizeof(real_vec[0]), n, cudaMemcpyHostToDevice);
cudaStat = cudaMemcpy2D (tmp_d + 1, 2 * sizeof(tmp_d[0]),
                         imag_vec, 1 * sizeof(imag_vec[0]),
                         sizeof(imag_vec[0]), n, cudaMemcpyHostToDevice);


text:
Q: Matching unique Id's from two mysql tables, my query is only pulling a portion of them I'm not sure what I'm doing wrong but I have my tables. I know this question has been asked a million times but I can't seem to figure out why it's only pulling a portion of the transaction ID's from one of my tables.
I have two tables. author and tab2.
author looks like so and the unique id is COL9:
COL1  COL2  COL3  COL4  COL5  COL6  COL7  COL8  COL9
data  data  data  data  data  data  data  data  6314085733

My other table is tab2 and there is only one column in it:
COL1
6300798484
6300917409
6301563169

UPDATE: I just realized that there are two spaces in quiet a few of the COL1 fields. I changed the data type to varchar(10) to eliminate those extra spaces and reran the query.. still nothing.
My query is like so:
SELECT b.Col1, a.*
FROM author a
JOIN tab2 b
ON b.COL1 = a.COL9
ORDER BY a.COL9 DESC

I know there has to be more than 600 and the results I'm getting are:

Showing rows 0 - 24 (29 total, Query took 7.2141 sec) [COL9: 6319720972 - 6302432564]

A: If COL1 and COL9 holds numeric values use a cast to get the data.
SELECT b.Col1, a.*
FROM author a
JOIN tab2 b
ON CAST(b.COL1 AS BIGINT) = CAST(a.COL9 AS BIGINT)
ORDER BY CAST(a.COL9 AS BIGINT) DESC;

Or you can use a TRIM.
Trim is not by default available in mssql.
first create a Scalar valued function.
    CREATE FUNCTION [dbo].[Trim]
    (
        -- Add the parameters for the function here
        @pString VARCHAR(2000)
    )
    RETURNS VARCHAR(2000)
    AS
    BEGIN
        RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(@pString, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')));
    END

GO

Use the below query
SELECT b.Col1, a.*
FROM author a
JOIN tab2 b
ON dbo.Trim(b.COL1) = dbo.Trim(a.COL9)
ORDER BY dbo.Trim(a.COL9) DESC;

A: You need to use TRIM, like this:
SELECT b.Col1, a.*
FROM author a
JOIN tab2 b
ON TRIM(b.COL1) = TRIM(a.COL9)
ORDER BY a.COL9 DESC


text:
Q: What does \. mean in Swift For example in SwiftUI we can choose dark or light mode using environment(\.colorScheme, .dark), or get Identifiable key using \.id.
But what does this syntax mean: \.something

A: See Key-Path Expression in the Expressions section of the Language Reference in The Swift Programming Language.


text:
Q: How to disable remaining radio buttons if a specific radio button is checked? I have the following bit of code generated by WooCommerce to display available shipping options:

<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate5" value="flat_rate:5" class="shipping_method"  checked='checked' />
Call 386-410-4757 for Shipping Quote

<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_wf_shipping_uspsd_express_mail" value="wf_shipping_usps:D_EXPRESS_MAIL" class="shipping_method"  />
Priority Mail Express™ (USPS): $22.95

<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_wf_shipping_uspsd_priority_mail" value="wf_shipping_usps:D_PRIORITY_MAIL" class="shipping_method"  />
Priority Mail® (USPS): $6.45

What I need to be able to do is disable radio buttons 2 and 3 if the first radio button is selected.
I have tried this to no avail:
$('.shipping_method').click(function(){
   if(this.value == 'flat_rate:5' && this.checked){
       console.log($('input[value=wf_shipping_usps:D_EXPRESS_MAIL], input[value=wf_shipping_usps:D_PRIORITY_MAIL]'));
        $('input[value=wf_shipping_usps:D_EXPRESS_MAIL], input[value=wf_shipping_usps:D_PRIORITY_MAIL]').prop('disabled', true);
   }
   else{
      $('.shipping_method').not(this).prop('checked', false).prop('disabled', false);
   }
});

Any help would be much appreciated!
Thanks,
Cynthia

A: WooCommerce loads many things by AJAX, which means you need to use event delegation.
Further, you may misunderstand what this represents inside of a jQuery function, so I've reworked a few of your checks.
Lastly, you want ALL other inputs disabled, so rather then identifying them specifically, I've modified the code to disable ALL but the one that is required:
// WordPress loads jQuery in noConflict mode, so
// First be sure you can use the $ by wrapping inside of a
// noConflict-safe document ready
jQuery(function($) {
    // Event delegation
    $(document).on('click', '#shipping_method input', function() {
       // Use jQuery .val() and jQuery .is() to check if it's the correct item
       if( $(this).val() == 'flat_rate:5' && $(this).is(':checked') ) {
           $('input.shipping_method').not('[value="flat_rate:5"]').prop('disabled', true);
       } else {
           $('input.shipping_method').not('[value="flat_rate:5"]').prop('checked', false).prop('disabled', false);
       }
    });
});

If you have problems, be sure to check your browser's developer console, and to report as much detail about the problem back, otherwise it's impossible to help.


text:
Q: While loading subview from xib to UIScrollView getting error 'EXC_BAD_ACCESS' in swift I am trying to load a custom UIView from xib
customView.swift
import UIKit
@IBDesignable class customView: UIView {

var view: UIView!

override init(frame: CGRect) {
    super.init(frame: frame)

    xibSetup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    xibSetup()
}

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let nibName:String = "customView"
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: nibName, bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView // **Getting error at this line**
    return view
}
}

customView.xib
File's Owner is the CustomView class.
In StoryBoard
I have a UIViewController (Scroll View Controller) with a UIView with the custom class: CustomView. The xib @IBDesignable propagates through and all is well.
Now the problem starts. I am trying to use the customView multiple times (just like cells in a tableView) in the ScrollViewController, just as I do with viewOne
MyUIViewController.swift
import UIKit

class MyUIViewController: UIViewController,UIScrollViewDelegate {

let scrollView = UIScrollView()
let height = CGFloat(234.0)

override func viewDidLoad() {
    super.viewDidLoad()

    self.scrollView.frame = CGRectMake(0, 150, self.view.bounds.size.width, height)
    self.scrollView.contentSize = CGSizeMake(height*3,self.view.bounds.size.width)
    self.scrollView.backgroundColor = UIColor.redColor()
    self.view.addSubview(self.scrollView)

    var y = CGFloat(0.0)

    for i in 0..<2 {

        //Adding viewOne
        let viewOne = self.createViewOne(i)
        viewOne.frame = CGRectMake(0, y, 320, 200)
        self.scrollView.addSubview(viewOne)

        //Adding CustomView
        let customView = self.createCustomView(i)
        customView.frame = CGRectMake(0, y, 320, 200)
        self.scrollView.addSubview(customView)

        y += height
    }

}

func createViewOne(index: Int) -> UIView {
    let viewOne = UIView()

    if index == 0{
        viewOne.backgroundColor = UIColor.greenColor()
    }

    if index == 1{
        viewOne.backgroundColor = UIColor.redColor()
    }

    return viewOne
}

func createCustomView(index: Int) -> UIView {

    let customViewDummy: customView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0] as! customView

    if index == 0{
        customViewDummy.backgroundColor = UIColor.greenColor()
    }

    if index == 1{
        customViewDummy.backgroundColor = UIColor.redColor()
    }

    return customViewDummy
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

I am trying to load a custom UIView from nib multiple times in ViewController.
I referred following link - How to use custom nib view in ViewController multiple times
I am using Xcode 7.3.1
Any suggestion is appreciated. Thank you In advance.

A: You are creating one more view within your customView and adding it as subView. Hence some mismatches. Try below code and make sure your filesOnwer is set to customView:
@IBDesignable class customView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        loadViewFromNib()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        loadViewFromNib()
    }

    func loadViewFromNib() -> UIView {
        let myView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil).first as! UIView
    return myView
    }
}


text:
Q: CLI calli on x64 calling convention Calli opcode requires a calling convention. By default it is stdcall, while extern "C" in native libraries uses cdecl.
JIT recently allowed to inline methods with calli, but only with default calling convention. When I call a method with calli without unmanaged cdecl it works on x64 and performance is 58% faster than DllImport and 2.2x faster than unmanaged function pointer. (on netcoreapp2.1, on net471 the difference is bigger: 82% and 5.5x ) When I run a method with calli unmanaged cdecl, performance is on par with DllImport (around 1% slower).
I have read that on x64 there is no longer a mess with stdcall vs cdecl and all methods use cdecl (or fastcall, seen that in another place, cannot find a link). The difference only applies to x86, where my call without unmanaged cdecl does indeed crash the app with segfault.
The method in question is the following. For tests I use noop native method only to measure native call overhead.
  .method public hidebysig static int32 CalliCompress(uint8* source, native int sourceLength, uint8* destination, native int destinationLength, int32 clevel, native int functionPtr) cil managed aggressiveinlining
  {
    .custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor()
             = {}
    //
    .maxstack  6
    ldarg.0
    ldarg.1
    ldarg.2
    ldarg.3
    ldarg 4
    ldarg 5
    calli unmanaged cdecl int32 (uint8* source, native int sourceLength, uint8* destination, native int destinationLength, int32 clevel)
    ret
  }

My questions:
1) Is it safe to omit unmanaged cdecl after calli on x64 "by design" or I am just lucky with this example? If on x64 all calls are cdecl then I could use JIT treating static readonly fields as constants dispatch to appropriate methods for free just using if(IntPtr.Size == 8) {..call fast method..}else{..use unmanaged cdecl..}
2) What does caller or callee cleans the stack mean? My native function returns an int that is on the stack after the call. Is this the issue about who removes this int from the stack? Or there is some other work needs to be done with stack inside native function? I am in control of native function and could return the value via a ref parameter - will this make the issue with the stack cleaning irrelevant since no stack changes are made during the call?

A: The answer is, it is not safe. See this discussion at dotnet/coreclr: https://github.com/dotnet/coreclr/issues/19997


text:
Q: Convert a postgres GENERATED column to a regular non-generated column (in place without DROP) I'm using postgres 13.3, and I already have an existing table with a GENERATED column such as:
CREATE TABLE test_table (
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    the_column_to_alter bool NOT NULL GENERATED ALWAYS AS (2 > 1) STORED,
    CONSTRAINT test_table2_pkey PRIMARY KEY (id)
);

But I've now changed my mind, and I want this to instead just be a regular non-generated column that I can edit manually...

*

*But I want to avoid having to DROP and re-create the column

*And I want to retain the existing values that are already in the column at the moment

Is this possible?  What would the ALTER query be to do this for the the_column_to_alter column?

A: Here's the command for the example table in the original post:
ALTER TABLE test_table ALTER COLUMN the_column_to_alter DROP EXPRESSION;

The postgres manual page is here: https://www.postgresql.org/docs/current/sql-altertable.html


text:
Q: Stream API получить сумму всех ключей Map Почему-то не получается посчитать сумму всех ключей
 Man vasia = new Man("vasia", "Pupkin", 2, 24, odessa);
 Man olaf = new Man("olaf", "olaf", 2, 24, moskov);
...

надо посчитать сумму всех детей у пользователей
Я написал так, но x.get(x) нет возможности выбрать,не пойму почему.
 final Map<Integer, List<Man>> coll = manLinkedList.stream()
                .collect(Collectors.groupingBy(Man::getCountOfChildren));

        int sum = coll.keySet().stream().mapToInt(x -> почему тут не могу испольховать x.get(x) + x ).sum();

        System.out.println(sum);

A: Вам не нужен Map, все на много проще:
int sum = manLinkedList.stream().mapToInt(Man::getCountOfChildren).sum();

И еще... Если у вас нет весомых аргументов для использования LinkedList откажитесь от него в пользу ArrayList. Не забывайте, что LinkedList является двусвязным списком, соответственно, каждый его элемент - полноценная нода со всеми вытекающими. Посему при использовании ArrayList вы в подавляющем большинстве случаев выиграете.


text:
Q: Java Annotations Processor to analyze expressions? I've been playing around with Java Annotation Processors, with great results.
Now I would like to do the following, which as far as I can see is not possible.
I have several Classes that implement the Builder Pattern. Say for instance
new FooBuilder().doSomething("A").doSomethingElse("B").execute();

It is vital that the "chain" of method calls is terminated using an execute() method. Otherwise, the builder will basically do nothing.
So I wanted to use JAP to verify the presence of an execute() method on certain expression types at compile time. Unfortunately it appears that the finest-grained information I can retrieve is on method declaration level, not expressions.
Is what I want at all possible?

A: Java's standard annotation processors provide a callback only at declarations, such as method and field declarations.
It's possible to use an annotation processor to analyze expressions, but it's a bit more work.  You will have to write an annotation processor that, at each method, obtains the AST (abstract syntax tree or parse tree) for the method and then visits each expression in the method.  The AST is compiler-specific.
The two best-known projects that do this are the Checker Framework and Project Lombok.  Maybe you could take inspiration from their implementations, or even write your annotation processor on top of one of them.


text:
Q: How to calculate the average score in a SharePoint list Perhaps someone can assist me with the following how to get the average score in this taxonomy list.
I have a SharePoint list as follows:
Taxonomy Name     Score     Average Score

Taxonomy1           4             3.67
Taxonomy1           4             3.67
Taxonomy1           3             3.67
Taxonomy2           9              5
Taxonomy2           1              5

Hope someone can help me out.

A: You can modify view, group by "Taxonomy Name", in Total section, set "Average" for score:

Then the list looks like the following:


text:
Q: .net maui CarouselView is not quite compatible with Slider control: CarouselView swipe operation takes over Slider's drag action .net maui app.
Dragging value element along the slider bar does not work if the the slider put into CarouselView's template like this:
 <CarouselView ItemsSource="{Binding Items}">
      <CarouselView.ItemTemplate>
            <DataTemplate>
                        <Slider Minimum="0" Maximum="30" WidthRequest="200" />
            </DataTemplate>
      </CarouselView.ItemTemplate>
 </CarouselView>

CarouselView takes over the swipe event for scrolling through the items, and Slider does not get the event (DragStarted is not even called). You can actually click along the slider bar to change its value, so it's not completely frozen, but not how it's supposed to work. Drag & drop is main way user deal with slider control.
Could anyone advise any workaround? I want users to be able scroll through carousel view items also. It's just if they swipe inside the control, event should not handed over to its parent container, if it's possible to do so.
If I add it outside of the corouselview, combine both in Grid and use padding to align slider inside the corouselview, it works as expected, but I need to add lots of additional code, calculate the desirable location and redirect all bindings, which ends up to be an awkward workaround.

A: At first, I don't suggest you use the slider in the CarouselView. Becasue you want the same behavior has two effects. There is a conflict between them.
But for the android, you can use the custom handler to deal with the swipe event.
Put the Handler class in the /Platform/Android:
    public class MySliderHander : SliderHandler
    {
        protected override void ConnectHandler(SeekBar platformView)
        {
            base.ConnectHandler(platformView);
            platformView.SetOnTouchListener(new SliderListener());
            // the listener will make the slider deal with the swip event not the CarouselView.
        }
    }

Put the SliderListener class in the /Platform/Android
    public class SliderListener : Java.Lang.Object, IOnTouchListener
    {
        public bool OnTouch(global::Android.Views.View v, MotionEvent e)
        {
            if (e.Action == MotionEventActions.Down || e.Action == MotionEventActions.Move)
            {
                v.Parent.RequestDisallowInterceptTouchEvent(true);
            }
            else
            {
                v.Parent.RequestDisallowInterceptTouchEvent(false);
            }
            return false;
        }
    }

And in the MauiProgram.cs:

builder
                  .UseMauiApp<App>()
                  .ConfigureMauiHandlers(handlers => {
             #if ANDROID
                        handlers.AddHandler(typeof(Slider), typeof(YourProjectName.Platforms.Android.MySliderHander));
                  #endif
                  })

In addition, the Slider's height is same as the CarouselView. So you can use a frame to contain the Slider and swipe the CarouselView by swiping the frame.


text:
Q: PHP setting up a function I need to set up a function which will convert random number between 1 and 7 into days of a week for example if the random numbers appears to be "1" it should display "Monday" and same goes for "2" which will display "Tuesday" etc. Does anyone here know the simple way of doing it ? Also later on in the second task i'll have to make all the days of the week display from Monday until a random day of the week(1-7) for example "Friday". Im pretty new to PHP and this got me so confused.

A: Custom function could be like:
function convertWeekday($num) {
   switch ($num) {
      case 1: $result = 'Monday'; break;
      case 2: $result = 'Tuesday'; break;
      case 3: $result = 'Wednesday'; break;
      case 4: $result = 'Thursday'; break;
      case 5: $result = 'Friday'; break;
      case 6: $result = 'Saturday'; break;
      case 7: $result = 'Sunday'; break;
   }
   return $result;
}

But you should better make use of the PHP date() function.

http://php.net/manual/en/function.date.php

A: You could try this and go from there
    $day_of_week = date('N', strtotime('Monday')); {
    echo $day_of_week ;
}


text:
Q: PSQLException: Syntax Error near at or "Entity" - Spring Boot I have a Spring-boot project with maven and I connect the code with the database through annotations, so I don't manipulate the data manually. I'm using Posgresql.
When I'm trying to access to an Url in my Server, the  eclipse console show me this error:
org.postgresql.util.PSQLException: ERROR: error de sintaxis en o cerca de «order»
  Position: 145
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2310) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2023) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:166) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:118) ~[postgresql-9.4.1209.jre7.jar:9.4.1209.jre7]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2117) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1900) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.doQuery(Loader.java:919) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2617) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2600) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483) ~[hibernate-entitymanager-5.0.9.Final.jar:5.0.9.Final]
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:50) ~[hibernate-entitymanager-5.0.9.Final.jar:5.0.9.Final]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:114) ~[spring-data-jpa-1.10.2.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78) ~[spring-data-jpa-1.10.2.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:102) ~[spring-data-jpa-1.10.2.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:92) ~[spring-data-jpa-1.10.2.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.12.2.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.10.2.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at com.sun.proxy.$Proxy114.findByClient(Unknown Source) ~[na:na]
    at es.tfg.restfood.model.service.OrderServiceImpl.getOrdersByClient(OrderServiceImpl.java:42) ~[classes/:na]
    at es.tfg.restfood.model.service.OrderServiceImpl$$FastClassBySpringCGLIB$$a48360e8.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at es.tfg.restfood.model.service.OrderServiceImpl$$EnhancerBySpringCGLIB$$939eee47.getOrdersByClient(<generated>) ~[classes/:na]
    at es.tfg.restfood.controllers.rest.OrderController.getOrdersByClient(OrderController.java:41) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105) ~[spring-boot-actuator-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107) ~[spring-boot-actuator-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]

Finally there is the code:
- Controller:
@RestController
@RequestMapping(value="/orders")
public class OrderController {

@Autowired
OrderService orderService;

@RequestMapping(value="/add", method= RequestMethod.POST)
@CrossOrigin(origins = "http://localhost:8100")
public Order addOrder(@RequestBody OrderDTO orderDTO){
    return orderService.addOrUpdateOrder(orderDTO);
}

@RequestMapping(value="/update", method= RequestMethod.PUT)
@CrossOrigin(origins = "http://localhost:8100")
public Order updateOrder(@RequestBody OrderDTO orderDTO){
    //TODO contemplar como va a ser la actualizacion de un pedido
    return orderService.addOrUpdateOrder(orderDTO);
}

@RequestMapping(value="/{idClient}", method= RequestMethod.GET)
@CrossOrigin(origins = "http://localhost:8100")
public List<Order> getOrdersByClient(@PathVariable(value="idClient") Long idClient){
    return orderService.getOrdersByClient(idClient);
}

}

-Service
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

@Autowired
OrderRepository orderRepository;

@Autowired
ClientRepository clientRepository;

@Autowired
TableRestaurantRepository tableRepository;

@Override
public List<Order> getAllOrders() {
    // TODO añadir variables page y size para navegar entre paginas
    return orderRepository.findAll();
}

@Override
public List<Order> getOrdersByClient(Long idClient) {
    // TODO añadir variables page y size para navegar entre paginas
    Client client = clientRepository.findOne(idClient);
    return orderRepository.findByClient(client);
}

@Override
public Order addOrUpdateOrder(OrderDTO orderDTO) {
    // TODO Auto-generated method stub
    Client client = clientRepository.findOne(orderDTO.getIdClient());
    TableRestaurant table = tableRepository.findOne(orderDTO.getIdTable());
    // TODO
    Calendar dateOrder = Calendar.getInstance();
    Order order = new Order(1L, OrderState.SENT, dateOrder, dateOrder, client, table);
    orderRepository.save(order);
    return order;
}

}

-Repository:
public interface OrderRepository extends PagingAndSortingRepository<Order,Long>{

List<Order> findAll();

List<Order> findByClient(Client client);

}

-The entity class:
@Entity
@Table
public class Order {

private Long codOrder;
private OrderState state;
private Calendar date;
private Calendar lastUpdate;
private Client client;
private TableRestaurant table;

public Order() {
}

public Order(Long codOrder, OrderState state, Calendar date, Calendar lastUpdate, Client client,
        TableRestaurant table) {

    this.codOrder = codOrder;
    this.state = state;
    this.date = date;
    this.lastUpdate = lastUpdate;
    this.client = client;
    this.table = table;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getCodOrder() {
    return codOrder;
}

public void setCodOrder(Long codOrder) {
    this.codOrder = codOrder;
}

@Enumerated(EnumType.STRING)
public OrderState getState() {
    return state;
}

public void setState(OrderState state) {
    this.state = state;
}

@Temporal(TemporalType.TIMESTAMP)
public Calendar getDate() {
    return date;
}

public void setDate(Calendar date) {
    this.date = date;
}

@Temporal(TemporalType.TIMESTAMP)
public Calendar getLastUpdate() {
    return lastUpdate;
}

public void setLastUpdate(Calendar lastUpdate) {
    this.lastUpdate = lastUpdate;
}

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_client")
public Client getClient() {
    return client;
}

public void setClient(Client client) {
    this.client = client;
}

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cod_table")
public TableRestaurant getTable() {
    return table;
}

public void setTable(TableRestaurant table) {
    this.table = table;
}

}

And finally the application.properties:
spring.datasource.url=jdbc\:postgresql\://localhost/restfood
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.max-wait=10000
spring.datasource.max-active=50
spring.jackson.serialization.indent_output=true

I hope anyone could help with this.

A: I fixed the problem changing the name of order. In a similar post, Marc B says:

order is undoubtedly a reserved word. I'll bet you a shiny penny that
if you rename the table to something else, it'll start working.


text:
Q: Obj-c How to inherit a method has array of arguments? I understand the usage of key words "va_list" "va_start" "va_arg" "va_end".
And my supper class has a init method looks like this:
Super Class:
- (id) initWithChildren:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION{
    if(self = [super init]){
        va_list children;
        va_start(children, firstChild);

        self.children = [[NSMutableArray alloc] initWithObjects:firstChild, nil];
        firstChild.father = self;

        NSObject* child;
        while ((child = va_arg(children, NSObject*)) != nil){
            [_children addObject:child];
        }
        va_end(children);
    }
    return self;
}

It works well.But I have trouble to inherit it.
Sub Class
- (id) initWithName:(NSString*)name children:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION{
    self = [super initWithChildren:"what should I write here?"];
    if (self){
        self.name = name;
        //other subclass work
    }
    return self;
}

Any ideas?Thanks.

A: In order to do this, your superclass needs to expose a designated initializer that takes va_list as a parameter. See vprintf for an example of how it is done in the standard library.
- (id) initWithChildren:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION {
    va_list args;
    va_start(args, firstChild);
    id res = [self initWithChildren:firstChild varArg:args];
    va_end (args);
    return res;
}

- (id) initWithChildren:(NSObject*)firstChild, varArg:va_list args {
    // Do the actual initialization here
    ...
}


text:
Q: How do I write the equals (==) function? class Character {

    construct new(name,life){
        _name = name
        _life = life
    }

    name  { _name }
    life  { _life }
}

If the name and life are the same, it should return true otherwise false.

A: class Character {

    construct new(name,life){
        _name = name
        _life = life
    }

    name  { _name }
    life  { _life }

    ==(other){
        return _name == other.name &&
               _life == other.life
    }
}

var player_one = Character.new("Nova",100)
var player_two = Character.new("Mint Hot Chocolate",50)
var player_three = Character.new("Nova",100)

System.print(player_one == player_three) // Output: true
System.print(player_one == player_two) // Output: false


text:
Q: What is the origin of the colloquial term "bum" meaning a homeless person? Just out of curiosity, I was wondering about the history of the term "bum" meaning a homeless person, not the UK version referring to someone's posterior.
Bonus: If you know the background on "Hobo" that would be interesting too, and does it have any relation to the town Hoboken, New Jersey?

A: Wikipedia offers some speculation on the origin of Hobo. It would seem the etymology revolves around railroads or migrant workers, and that it originated in California.

Author Todd DePastino has suggested that it may come from the term hoe-boy meaning "farmhand," or a greeting such as Ho, boy!. Bill Bryson suggests in Made in America that it could either come from the railroad greeting, "Ho, beau!"

As to the origin of Bum, it seems to come from the German word for loafer (bummler), which comes from loaf (bummeln), presumably from the unemployed trying to obtain bread. Wiktionary

1864, Back-formation from bummer., from German Bummler ("loafer"), from bummeln ("loaf")

A: The New Oxford American Dictionary reports that bum is synonym of vagrant ("a person without a settled home, or regular work, who wanders from place to place and lives by begging"), and that to bum means, "to travel, with no particular purpose or destination." On the list of the phrases, it lists also on the bum to mean, "traveling with rough provisions and with no fixed home."
The dictionary reports that the origin of the word is probably from bummer, and that bummer derives perhaps from German Bummler, from bummeln ("stroll, loaf around").
For hobo, the same dictionary reports that its origin is late 19th century, but the word from which it derives is unknown.

A: The Facts on File Encyclopedia of Word and Phrase Origins (1997) has interesting entries for both bum and hobo. With regard to bum, it observes:

No self-respecting hobo, or tramp, would allow himself to be called a bum, for the word has degenerated from its original meaning of "a vagabond" over a century ago, and today usually stands for a "moneyless, prideless, filthy, hopeless derelict and habitual drunkard." One working definition to distinguish between the three classes of vagabonds is that "a hobo will work, a tramp won't, a bum can't." Bum was first recorded in 1855, and during the Civil War was used to describe a foraging soldier. It appears to derive from two words: the German bummer, "a high-spirited, irresponsible person," and the old English word bum, which has for four centuries been slang for both "a drunk" and "buttocks."

And as for hobo:

The word hobo is of uncertain origin. Perhaps it derives from a once common greeting of vagabonds to each other: "Ho! Bo" (Ho! a form of "Hi!" and Bo meaning "guy or brother"). This seems to be the most popular explanation, but wandering *ho*meward *bo*und Civil War veterans have also been suggested, as have hoe boys who left the farm and were on the road. The word is first recorded in the American Pacific Northwest, about 1889.

All I can say about the homeward bound Civil War soldiers is that they either were taking their time or got terribly lost if they started for home in 1865 (at the end of the war), and didn't get noticed as "hobos" until 1889 in the Pacific Northwest.
The Dictionary of American Slang, Third Edition (1995) adds this gloss:

hobo n by 1889 A person who wanders from place to place, typically by riding on freight trains and who may occasionally work but more often cadges sustenance...[origin unknown; perhaps fr the call "Ho, boy," used on late-1800s Western railroads by mail carriers, then altered and transferred to vagrants; perhaps putative hoe-boy, a migrant farm worker in the West, who became a hobo after the harvest season]

Followup (9/15/14): Early Occurrences and Meanings of Bum and Hobo
The term bum used in the sense of "buttocks" goes at least as far back as Shakespeare; in A Midsummer Night's Dream (by 1596), Robin Goodfellow brags to Titania's fairies:

The wisest Aunt telling the saddest tale,
Sometime for three-foote stoole, mistaketh me,
Then slip I from her bum, downe topples she,
And tailour cries, and fals into a coffe.

As for bum in the sense of "layabout," John S. Hittel, The Resources of California: Comprising Agriculture, Mining, Geography, Climate, Commerce, etc. etc. and the Past and Future Development of the State (1863) provides closely related definitions for both bummer and bumming:

§ 267. Californianisms.—The Californians have introduced certain words into the English language, or at least have adopted them in common use in the state, and a list of them, with their pronunciation and definition may not be out of place here.
...
Bummer.—An idle, worthless fellow, who does no work and has no visible means of support. The word "loafer," like "lounger," does not designate the general conduct or permanent character of a man, but only a temporary idleness. A respectable, industrious man may become a "loafer" by making idle, impertinent visits in business places during business hours ; but the word "bummer" implies a low, lazy character. It is probably derived from the vulgar German words Bummeln and Bummeler, which are about equivalent to "loafer" and "loaf." Its origin has been attributed to Boehmen, the German name of Bohemia, a nation celebrated for the number of its sharpers and adventurers. The Gipsies are alled Bohemiens in France, because of their roving lives and worthless character. "Bummer" is generally supposed here to be a Californianism.
Bumming, acting the bummer, used in such phrases as "he is bumming around."

Fourteen years later John Bartlett, Dictionary of Americanisms, fourth edition (1877) offers a more extensive definition, whose initial wording appears to have been cribbed from Hittell:

Bummer. An idle, worthless fellow without any visible means of support. A word much used by our soldiers during the late civil war. The "New York Herald," May 2, 1876, thus describes the individual: The army bummer is usually a "General" who has been in the Quartermaster's or Commissary Department, and whose rank represents influence about the War Office, and days and nights of hard duty about Willard's and the Arlington. Since the war, he has been very "loyal." He has "sustained" the Union, and "supported the government.  Unable to earn an honest living, without brains for any position higher than that of a car conductor, he lives by lobbying.He knows the inside of every office, the favorite wine of a secretary, and the kind of dinner fancied by this statesman or the other. So, in time, he finds himself in the enjoyment of a good income, for which he does nothing but eat and drink and talk. He is a disgrace to the army, whose uniform he wears for his own gain.

Notwithstanding the opening words appropriated from Hittel's definition, Bartlett's definition clearly identifies a bummer as a sycophant in search of a sinecure. But this meaning has largely died out, while Hittel's "Californianism" notions of bummer and bumming remain largely current in the words bum and bumming.
The word bummer appears on two occasions in Harper's New Monthly Magazine during the year 1864. First, in "Editor's Drawer" in the August 1864 issue, this vignette involving Bill, "a returned Californian, who pretended to have made his pile in the land of the gold":

Just then the boys, who were lying in wait to see the fun, exploded, and the shout which accompanied their yells of laughter—"Old Mose has sheared the wrong hoss!"—was a sufficient explanation of the matter. Bill had hired old Mose, a regular old bummer, to shear the parson's horse ; and being both in the same barn, and both harnessed, he very naturally made a mistake, of which Bill has not heard the last to this day.

And from "How We Fight at Atlanta" in the October 1864 issue:

Besides the fighting population of our camps there is a population constitutionally opposed to warfare—cooks, ambulance nurses, stretcher-bearers, shirks, and sometimes surgeons, who all come under the class technically called bummers. These are treated by the fighting men with a sort of cool contempt, no matter whether necessity or inclination keeps them to the rear, and they have a hard time. Frequently the rear of the army is a much more dangerous location than the front line, for the missiles passing over the front line must fall somewhere, and often demoralize whole hosts of "bummers," who build up miniature fortifications to live in and collect together in crowds ; for misery loves company. Any favorable ravine thus peopled immediately becomes denominated "Bummer's Roost." Here they spend their days in cooking for their nurses, if they are cooks, or attending to their own business, if their object be to escape duty and danger.
...
To watch these cooks, freighted with the precious coffee for the men in the trenches, as they go out to the front three times a day, is amusing. From continually dodging the passing shells or stray bullets their forms become bent and stooping. As they approach the line, the men in the trenches commence shouting. "Hey, bummer! Run quick, bummer! "A man was killed just there, bummer!" With such encouragements the coffee at last reaches its destination, and being distributed among the eager men the bummer is soon at liberty to hurry back to the "Roost."

One possible source of bum in the "hanger-on" or "follower" sense is English north country speech. From John T. Brockett, A Glossary of North Country Words, in Use (1829):

BUM, s. the assistant or follower of a bailiff. Dr. Johnson has bum-bailiff, a well-known name for an unpopular officer of the law ; but the north country bum, is a distinct personage, following and assisting the bailiff. It may be, as has been conjectured, from bound ; though more likely, I think, from bum, the buttocks ; a word which "the poet of all nature" disdained not to use   when he thought it most expressive to designate this very delicate part of the human body by one of its right English names.

One early discussion of the phrase "on the bum" suggests how the phrase can mean either "living a drifter's life" (when spoken of people) or "cheap and likely to break" (when spoken of machinery). From "Correspondence" in Stove Mounters' Journal (March 1903):

I have heard members say when they see a brother with cheap clothes on, "he looks on the bum." and when they get a cheap stove to mount they say "its on the bum." and so on. Why don't some one say a cheap organization is on the "bum." We are handicapped on account of a small fund, and if we could have a larger fund we certainly could better our condition; and if we can pay higher dues and don't pay them, thereby preventing the growth and prosperity of our international. I say our organization is on the "bum." And if we don't pay our executive officers more money than they can make in a shop why these positions will be on the "bum," and before long nobody will accept these positions unless he is on the "bum."

As for the earliest meaning and possible origin of hobo, Nathan K Griggs, Lyrics of the Lariat: Poem With Notes (1893) provides the following note to accompany his poem "Hobo's Lament":

The origin of Hobo, the term now so generally applied to the railroad grader, is unknown, but i generally supposed to have come from the salutation of "Ho, boy!" which was shouted by one workman to another, and finally shortened into the name now in common use. The Hobos are enlisted, so to speak, by labor agents, in the larger of the western cities and shipped, in car-loads, to the points where wanted. Naturally, as may well be imagined, the Hobo-car, long ere it reaches its destination, is redolent of odors not of those which are said to be clinging to the garments of the fair daughters of Farina. The Hobo is, or soon becomes, a queer type of humanity. Earning good wages, he toils contentedly on, despite rain and mud, till the monthly pay-day comes. Then he takes a lay-off for the purpose of spending his wealth, at which he is a phenomenal success. Indeed, as illustrative of this assertion, mention is here made of the fact that, upon one occasion, where a large number of such laborers were given their pay-checks, ninety per cent. of their entire earnings was held and owned by the adjacent saloons, dens of infamy and gambling hells, before the next sunrise. After a reasonable time spent in such debauchery, they are willing again to return to work, seemingly only hoping for another pay-day to arrive, to bring with it a repetition of its insane orgies and fancied delights.

In Griggs's poem, the hobo of the title is on foot, "hitting the trail, with usual zeal, To get to the East, to rustle a meal." The author describes him in consecutive stanzas as "this sorry Hobo," "this silly Hobo," "this luny Hobo," "this crazy Hobo," "this bummy Hobo," and "this busted hobo." So even though Griggs explicitly identifies hobos as working men (albeit as itinerant workers), he also associate them with impoverishment and irrational behavior and with adjectives from "sorry" to "bummy" to "busted."
Owen Wister, "The Evolution of the Cow-Puncher," in Harper's New Monthly Magazine (September 1895) identifies the hobo as being out of work more often (and more characteristically) than in work:

No one has accounted to me for hobo. A hobo is a wandering unemployed person, a stealer of rides on freight- trains, a diner at the back door, eternally seeking honest work, and when brought face to face with it eternally retreating. The hobo is he against whom we have all sinned by earning our living. Perhaps some cowboy saw an Italian playing a pipe to the accompaniment of a harp, and made the generalization: oboe may have given us hobo. Hobo-ken has been suggested by an ingenious friend; but the word seems of purely Western origin, and I heard it in the West several years before it became used in the East.

On the whole, Griggs's derivation of hobo from "Ho, boy" seems somewhat more plausible to me than Wister's derivations of the word from oboe and Hoboken.

A: I was told by a very old railroad worker that "HoBo" is actually an abbreviated term from the end of World War I as follows:
Most returning American soldiers came home from Europe in 1918 and 1919 over the Atlantic Ocean by ship. They were released from military service on the East Coast and then told they would need to make their way home on their own as best they were able. The military apparently had not developed any "wind down" plans for dealing with millions of soldiers needing transportation at the end of the war.
Having no significant funds and there being no significant travel infrastructure at the time (our national highway system didn't even start serious construction until after 1921) these soldiers (some in uniform and some in their "civvies") grabbed their duffel bags and jumped on board freight trains to cover the largest leg of their trip to their respective home states.
For a while the railroad companies supported this "patriotic" means of assisting our returning boys in uniform, referring to them as "Homeward Bounds" or "HoBos" but after 1919 many non-military people continued to capitalize on the free train trips and the term evolved into a derogatory name for freeloading rail riders.

A: My grandmother is a WWII survivor whose house was "bombed out" during the war. In such a war-torn situation, those that were "bombed out" of their homes were left with nothing. Already desperate for food, with no economy except war, these people were forced to beg for everything. They were bummed out by bummers, and they became bums, bumming for food. My grandmother's accent makes "bomb" sound like "bum." The term "bum" is a derogatory word, created by ignorant bullies, and used for victims of a greedy society.


text:
Q: Why to use @Autowired to run Kafka Streams topology in a Spring Boot Application? I am trying to run Kafka Streams Topology inside a spring boot application.
In the example on confluent website they did the following:
@Component
class Processor {
    @Autowired
    public void process(final StreamsBuilder builder) {
        // the logic to run the topology which is a blocking call
    }
}

I think the @Autowired annotation means that the method process will be invoked by the Spring framework.
My question is: Given that the call to the method process is blocking call
is this the best practice to run the topology inside a spring boot application?
Why not run it in a separate thread?

A: @Autowired instructs Spring to inject an existing StreamsBuilder bean as a parameter to the process(...) function. This is done while bootstrapping the application context, so it will not block the running topology itself which is started as a seperate thread via some kind of new KafkaStreams(builder.build(), props);
Therefore this is absolutely okay to do.


text:
Q: SyntaxError: EOL while scanning string literal with ast.parse The following the valid python code
In [49]: print('hello\n')
hello

but when I use ast module's parse method it returns, the Syntax error
In [47]: code = "print('hello\n')"

In [48]: ast.parse(code)
  File "<unknown>", line 1
    print('hello
           ^
SyntaxError: EOL while scanning string literal

In [51]: eval(code)
  File "<string>", line 1
    print('hello
        ^
SyntaxError: invalid syntax

why is ast module not able to parse the valid python code in this case?

A: You have to escape the \ in code
code = "print('hello\\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48cc0>

Or you can add r prefix to indicate everything in the string needs to be escaped
code = r"print('hello\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48ef0>

A: You should write:
code = "print('hello\\n')"

A: You need to use multiline comment '''YourCode''' or """YourCode"""
Ex:
import ast
code = "print('''hello\n''')"
print(ast.parse(code))


text:
Q: Correcting a Tic Tac Toe-Draw function I am making a multiplayer tic tac toe game with a semi-graphical interface. I have made the code and most of it works.The only part of it that doesn't work is the draw function.
I do understand that I am using TurboC++,which is a highly out of date compiler,but the Indian education system follows only TurboC++,so I have to make my project in it.(The syllabus was changed to have Python instead of C++ recently but I happened to be in the last batch of students that will not be taught Python)
The problem is in the last part of the result() function. I was unable to find what was wrong with it.I have not used graphics.h because it is not in my syllabus.
result function alone:
struct mat  //To store the positions and what is present in the 9 boxes
{
 int x,y;char ch;
};

struct xo  //To keep track of the match
{
 int actp,actx,acty;
 mat pos[3][3];
 char flag;

void setup() //To create the boxes/bars
 {
  actp=1,actx=1,acty=1;
  flag=0;
  for(int i=0;i<3;i++)
  {
   for(int j=0;j<3;j++)
   pos[i][j].ch=0;
  }
 }

void result()  //To find the result
 {
  char flage;
  for(int i=0;i<3;i++) //Column win
  {
   if(pos[i][0].ch==pos[i][1].ch&&pos[i][1].ch==pos[i][2].ch)
   flage=pos[i][0].ch;
  }
  for(i=0;i<3;i++) //Row win
  {
   if(pos[0][i].ch==pos[1][i].ch&&pos[1][i].ch==pos[2][i].ch)
   flage=pos[0][i].ch;
  }

  if(pos[0][0].ch==pos[1][1].ch&&pos[1][1].ch==pos[2][2].ch) //Diagonal win
  flage=pos[0][0].ch;

  if(pos[0][2].ch==pos[1][1].ch&&pos[1][1].ch==pos[2][0].ch) //Other diagonal win
  flage=pos[0][2].ch;

  if(flage=='X')flag='1';
  else if(flage=='O')flag='2';
  else flag='0';

  int chk=1;
  for(i=0;i<3;i++)
  {
   for(int j=0;j<3;j++)
   {if(pos[i][j].ch=='0'){chk=0;gotoxy(3,15);cout<<chk;} }//Added cout statement for debugging
  }
  if(flag=='0'&&chk==0)flag='D';//I understand that the condition is supposed to be chk==1,but it works only if I have this condition
 }
}a;

Here is the whole code,if necessary:
https://drive.google.com/open?id=19WMexp3Hw_p9hO3qiYm0HRj-GGAJeaTr
A screenshot:
https://i.stack.imgur.com/wGh7a.jpg
If I use the correct condition, the program says that the match is drawn just after 1 move.
With this wrong condition, the program works to a certain extent and is able to find winners but never declares a match drawn even if it happens.
Thanks for the help!!

A: I have corrected the errors, will elaborate soon. Thanks for the help.


text:
Q: More actions in Zend Rest Controller apart from the default actions I know that REST API can be implemented using Zend_Rest_Controller and it has 5 abstract methods indexAction, getAction, postAction,putAction,deleteAction to perform return, create, update , etc...
My question is, can I have more API fictions with in a controller apart from these default functions to perform various type of operations?.
Eg:
indexAction - returns a list of available books,
searchAction - returns a list of books based on search criterion.
(I know it can be done in the indexAction with some parameters but then the code will look more complicated, I need to avoid that)

A: Yes, you can create custom action methods in your controller. Although you're extending the abstract class Zend_Rest_Controller, as long as you define those 5 abstract methods (the ones you've already mentioned), you're free to customise the rest of your class.
The only similar method you might look into is the getAction(). This expects a parameter with the name of ID and will retrieve a record based on the primary key.

You'd probably have to define your routing in a configuration file:
routes.archive.route = "search/:keyword"
routes.archive.defaults.controller = books
routes.archive.defaults.action = search
routes.archive.defaults.year = "Hamlet"
routes.archive.reqs.year = "\s+"

And then you need to feed these configuration options into your Router:
$config = new Zend_Config_Ini('/path/to/config.ini', 'production');
$router = new Zend_Controller_Router_Rewrite();
$router->addConfig($config, 'routes');

Read Zend's documentation for a more in-depth tutorial.


text:
Q: c# psexec response get params im trying to execute remote process using psexec in c# application.
this is my code :
          System.Diagnostics.Process process = new System.Diagnostics.Process();
           System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

           startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
           startInfo.FileName = "cmd.exe";
           startInfo.Arguments = "/C psexec \\\\"+hostname +" "+command;
           startInfo.RedirectStandardOutput = true;
           startInfo.RedirectStandardError = true;
           startInfo.UseShellExecute = false;
           process.StartInfo = startInfo;
           process.Start();
           response = process.StandardOutput.ReadToEnd();
           process.WaitForExit();

the problem is im not getting response only if command="", i get the definition of the psexec command in response but if command="dir" for exemple i get nothing in response . any help.

A: You forgot to read standard error as well. Maybe, psexec writes to that.
I suggest you use one of the top voted snippets of stack overflow, to be found by: site:stackoverflow.com process RedirectStandardOutput. There are hundreds of such questions. Most solutions are subtly wrong but certainly better than this one which is clearly incorrect.
This is a good checklist.


text:
Q: PHP Regex String Exctraction I have a PHP array with 1000s of values, but I want to loop through it and identify the ones with the following pattern.
1234567-xxxx
That is 7 digits and a dash at 8th.
Sample array as below.
$a = array(1,1234567-xxx,'Hello','World',2223339-445566,'2)

A: Probably no need to loop. You can use

preg_grep — Return array entries that match the pattern

$res = preg_grep('/^\d{7}-/', $a);

See demo at eval.in and regex explained at regex101


text:
Q: How to convert Java Regex to JS regex? Java Regex:
String regex = "(?i)^[\\w.-][\\+\\w.-]*+@[\\w.-]+\\.[a-z]{2,4}$";
  Pattern  pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher("santo+abc@gmail.com");
 System.out.println(matcher.matches());

JS Regex:
 var regex = /^[\w.-][\w\+.-]*+@[\w.-]+\.[a-z]{2,4}$/i;

But JS regex is not a valid expression. Not sure what I am missing here. Please guide

A: *+ is a possessive quantifier. It's like *, but fails the match if it has to match less than what's available to it. Since @ doesn't match [\w\+.-] anyway, though, you can just replace it with *.
var regex = /^[\w.-][\w\+.-]*@[\w.-]+\.[a-z]{2,4}$/i;

Also, don't use this regex to validate e-mail addresses; it's incorrect. See Regex validation of email addresses according to RFC5321/RFC5322 for a correct one.

A: Try:
/^[\w.-][\w\+.-]*@[\w.-]+\.[a-z]{2,4}$/i

I removed the + after the *, because JavaScript doesn't support possessive quantifier.
You can try this regex here: https://regex101.com/r/FmUF5M/1