text:
Q: How to prove this supposedly simple inequality? The text book says that the following inequality "follows quite easily" but I don't see why.
Given $\alpha \lt 1 \lt \beta$ and $\psi : \mathbb{R}_{\ge 0} \rightarrow \mathbb{R}_{\ge 0}$ increasing, show that that:
$$\frac{1}{(1-\alpha)x}\int_{\alpha x}^x\psi(u)du \le \psi(x) \le \frac{1}{(\beta-1)x}\int_x^{\beta x} \psi(u)du$$
I think it may be assumed that $\alpha$ is non-negative.

A: You have $\psi(u) \leq \psi(x)$ for $u \in [\alpha x,x]$. Integrating with respect to $u$ gives $\int_{\alpha x}^x \psi(u) du \leq \psi(x)(x - \alpha x) = \psi(x) (1-\alpha) x$, or equivalently, $\frac{1}{1-\alpha} \int_{\alpha x}^x \psi(u) du \leq \psi(x)$. The other side of the inequality follows the same line of reasoning.

A: Hint: Sice it is assumed that $\psi$ is a continous function on $[\alpha,\beta]$, so using The First Mean Value Theorem is useful.

A: Let $\Phi$ be the primitive of $\phi$. We have $$\frac{\Phi(x)-\Phi(\alpha x)}{x-\alpha x}\le \phi(x)$$
Because this is the average of $\Phi' = \phi$ over $(\alpha x,x)$ which is less than $\phi (x)$ by monotonicity. The same thing applies for $\beta$ in the opposite direction.


text:
Q: Make height:auto in table with fixed column Is it possible to  set the height of rows in the table to be as the height of the first column in the row if it's position is absolute?
It of course works if I do not use 'position:absolute' (or 'position:fixed') but I need first and last columns to be fixed.
In the example you can see that first column's rows are overlapping. I would like the first and second rows to fit the text inside completely.
http://jsfiddle.net/ujwz4htg/27/

table {
  border-collapse: separate;
  border-top: 1px solid grey;
}

td {
  height: auto;
  margin: 0;
  border: 1px solid grey;
  border-top-width: 0px;
}

td:first-child {
  white-space: intial;
  position: absolute;
  width: 80px;
  left: 0;
  top: auto;
  border-top-width: 1px;
  margin-top: -1px;
  overflow: hidden;
}

td:last-child {
  white-space: initial;
  position: absolute;
  width: 80px;
  right: 160px;
  top: auto;
  overflow: hidden;
  background: grey;
}

div {
  width: 600px;
  overflow-x: scroll;
  padding-left: 5em;
  overflow-y: visible;
  padding-bottom: 1px;
}

.long {
  background: pink;
  letter-spacing: 1em;
}

      Row Row Row Row Row
      QWERTYUIOPASDsdasdFGHJKLZXCVBsdfsdfNM
      LAST

      1 222222 333333333
      QWERTYUIOPASDsdasdFGHJKLZXCVBsdfsdfNM
      LAST

      3
      QWERTYUIOPASDsdasdFGHJKLZXCVBsdfsdfNM
      LAST

      4
      QWERTYUIOPASDsdasdFGHJKLZXCVBsdfsdfNM
      LAST

      5
      QWERTYUIOPASDsdasdFGHJKLZXCVBsdfsdfNM
      LAST

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed optional dependency /chokidar/fsevents: I am installing "cordova-plugin-geolocation" via npm but "cordova-plugin-geolocation" is unable to install. I am seeing the following warnings:

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14

Is there any possible solution?

A: I used the following command to install NPM dependencies with the parameter NO-OPTIONAL
npm install --no-optional

source:
https://github.com/ariesjia/grunt-riot/issues/16

A: Make .npmignore with

node_modules
chokidar/fsevents
 inside

A: I was getting this error when I run gulp command
Error: watch node_modules/bootstrap/scss/bootstrap.scss ENOSPC
        at _errnoException (util.js:1022:11)
        at FSWatcher.start (fs.js:1382:19)
        at Object.fs.watch (fs.js:1408:11)
        at createFsWatchInstance

I ran this and it works for me
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p


text:
Q: Can we use Spock with plain Java I started on working with Spock from couple of days and in all the documentations I have seen the tests are written in Groovy. Is there any way to use Spock in plain Java class? Because we have a requirement to use only Java as programming language.

A: Spock makes extensive use of Groovy magic such as AST transforms, and you can only write Spock tests in Groovy. However, you can certainly use Spock to test Java-only code and not include Groovy or any Groovy-based code in your compile scope.

A: I'm using spock and groovy only for tests and must say it's awesome mix!
Check this project used for workshop during codepot.pl conference:
https://github.com/codepot-groovy-android/groovy_no_way_back
The app and tests both use groovy, with tests using spock as well.
But there is also a branch with with app written in Java and only tests in groovy with spock:
https://github.com/codepot-groovy-android/groovy_no_way_back/tree/codepot/livetesting

A: As others said if the requirement is for production code to be Java, yes you can use Spock to test Java code. In fact I wrote a book on this subject alone :-)
https://www.manning.com/books/java-testing-with-spock
If the requirement is that all code should be in java (including unit tests) then no, Spock cannot be used.


text:
Q: Apache Sling Resource Mapping in CQ 5.6.1 I've been taking several hours fiddling this Resource Mapping for no luck. I have put a new node in /etc/map/http named GoogleAnalyticsMap. It had the following properties:
Name: jcr:primaryType
Type: Name
Value: sling:Mapping

Name: sling:internalRedirect
Type: String
Value: /content/dam/website/Common/my_google_analytics_key.html

Name: sling:match
Type: String
Value: [^/]+/[^/]+/my_google_analytics_key.html

Funnily, when i checked to /system/console/jcrresolver or Adobe CQ Web Console Sling Resource Resolver. It resolves into the following
Pattern: ^http/[^/]+/[^/]+/my_google_analytics_key.html
Replacement: /content/dam/website/Common/my_google_analytics_key.html
Redirect: internal

I have no idea how they could register ^[^/]+/[^/]+/welcome$ as shown in the example and did not have the 'http' there. Nevertheless, whenever i try to hit the pattern locally (i.e. http://localhost:4502/my_google_analytics_key.html) it only shows resource not found. Also checked through the Configuration test section that available in Adobe CQ Web Console Sling Resource Resolver it says that it can't resolve. Did i miss something?
    , type=sling:nonexisting, path=/my_google_analytics_key.html, resource=[NonExistingResource, path=/my_google_analytics_key.html]

Thank you for the help.
p.s. i've checked the Sling documentation also, however, it baffles me that i can't add sling:alias, perhaps its also something to do with the sling version. Nevertheless, i should ask this as second question later, once the sling:match is working properly.
Edit: fiddling a bit, changing the sling:match to localhost.4502/google.html does let it to redirect localhost:4502/google.html to the desired DAM item. Well, i'm still asking for 'domain-free' matching though.. so i have no trouble when using the mapping for all environment i have..
Edit, Updates:

*

*Apparently due to me put the new sling:Mapping under http folder it will always prefix the path with http. Perhaps the example is meant to be put not under http folder.

*Next item is, it will always assume the matching item will be protocols, domain, and port separated by dots (yes, even \. is not a valid input and CQ or rather sling will sanitize it somehow). Something like *.(4502|4503|80|443)/my_google_analytics_key.html will accept any domains and those designated ports. I do wonder if it really the case, since they says regex but it does not feel so much regex.

*Some says that sling:internalRedirect should be a String[] - yes i know the docs says String. I have not test this further and take it as it is..


text:
Q: Auto update export I have a Google Spreadsheet with several events and two tables.

*

*Table A contains all data and a function, which checks based on the current time if an event is in the past or in the future. If it is in the future, the value based on current date/time is "show", if it is in past the value changes to "hide"

*Table B contains a filter function to get only the lines with "show" from Table A

The function is:
=FILTER(tablea!A:D;table!B:B="show")

Until here everything works perfectly. Values were updated automatically, even if I don't change anything manually.
Now I export Table B as JSON. My problem is, when in Table A the value in Column B changes to "show", it also updates in Table B - but the export does not update. Only when I change something manually, it gets a new update.
I already tried:
- include a column with "now()" in Table B to get changing values
- set settings to update every minute
But still, the export only changes, when I change something manually.


text:
Q: what are these OpenLDAP directories used for I have remove an openldap installation from my centos7 server and discovered that these directories are left /run/openldap
/usr/lib64/openldap
/usr/libexec/openldap
please what are these openldap directories used for  and are they created when openldap is installed


text:
Q: Proving an inequality by rearranging it I want to prove the statement:
$∃a∈ℕ,∀x∈ℕ,x>a⇒\frac{x^5}{50}≥-x^4+5$
I learned that you can't assume the conclusion in the beginning when proving but can I still rearrange the inequality to prove something else? For example:
$\frac{x^5}{50}≥-x^4+5$ can be rearranged to $x^5+50x^4≥250$
So instead, I will prove $∃a∈ℕ,∀x∈ℕ,x>a⇒x^5+50x^4≥250$
Let $a=10$
Let $x∈ℕ$
Assume $x>a$
$x^5+50x^4=x^4(x+50)>10^4(10+50)=600000≥250$
Is something like this allowed?

A: yes, that is allowed.
You have used the property that $x^5+5-x^4$ is an increasing function and also
$$\frac{x^5}{50} \ge -x^4+5$$ is equivalent to $$x^5+50x^4 \ge 250$$
Alternatively, notice that over the positive domain, $f(x)=\frac{x^5}{50}$ is an increasing function and $g(x)=-x^4+5$ is a decreasing function.
In particular $f(2) > 0 > g(2)$, hence for all $x > 2$, $f(x) \ge g(x)$.


text:
Q: Querying a pandas dataframe with an object I have a pandas and a Dataframe and a class with some of the same fields.
Example:
Dataframe:
customer_dict = {"name": ["matthew", "mark", "luke", "john" , "john"],
                "series_number": [2,2,5,8,8],
                "personality": ["intj", "entp", "intp", "enfj", "intj"] ,
                "classification" : ["good", "bad", "bad", "good", "bad"]}

customer_df = pandas.DataFrame(customer_dict)

 customer_df.head()
      name  series_number personality classification
0  matthew              2        intj           good
1     mark              2        entp            bad
2     luke              5        intp            bad
3     john              8        enfj           good
4     john              8        intj            bad

Class:
class Customer():
         def __init__(self, name, series_number, personality):
             self.name = name
             self.series_number = series_number
             self.personality = personality

Notice the Class does not have a classification attribute, but the other attributes are the same as the dataframe's column names.
If I have an object to that class, I want to be able to search the dataframe for the line that matches it so I can get it's classification:

customer = Customer("john", 8, "enfj")

customer_df[customer]

Expected result:
      name  series_number personality classification
3     john              8        enfj           good

Is there an easy way to do it?

A: You can select rows in a dataframe using multiple conditions. Each must be in parenthesis and & converts to AND.
condition = (customer_df['name']=='john') & (customer_df['series_number']==8) & (customer_df['personality']=='enfj')

customer_df = customer_df[condtion]

A: You can do a simple function to enable querying your class instances, instead of doing lengthy masks. This even works for optional attributes.
def clsQuery(cls):
    return ' & '.join(["{}=='{}'".format(key, value)
                       for key, value in cls.__dict__.items()
                      if not value is None])

customer = Customer("john", 8, "enfj", 'good')
customer_df.query(clsQuery(customer))

Output:
     name   series_number   personality classification
3   john        8                enfj           good

You can go beyond to define the function as a class method for ease of access:
class Customer():
    def __init__(self, name, series_number, personality, classification):
        self.name = name
        self.series_number = series_number
        self.personality = personality

    def query(self):
        return ' & '.join(["{}=='{}'".format(key, value)
                       for key, value in self.__dict__.items()
                      if not value is None])

customer = Customer("john", 8, "enfj", 'good')
customer_df.query(customer.query())

A: try this and kindly give default value to classification
class Customer():
         def __init__(self, name, series_number, personality, classification=None):
             self.name = name
             self.series_number = series_number
             self.personality = personality

#initialize the obj
cust = Customer("john", 8, "enfj")

customer_df[(customer_df['name']==cust.name)
            &(customer_df['series_number']==cust.series_number)
            &(customer_df['personality']==cust.personality)]

    name    series_number   personality classification
3   john    8                    enfj   good

A: You need to create Boolean mask:
mask_name = customer_df['name'] == customer.name
mask_series_number = customer_df['series_number'] == customer.series_number
mask_personality = customer_df['personality'] == customer.personality

And then query with masks
customer_df.loc[mask_name & mask_series_number & mask_personality]

Output:
    name    series_number   personality classification
3   john    8               enfj        good


text:
Q: Why does this code memory leak when adding `bracketOnError`? First, I appologize for not having a minimal example (I can attempt to construct one, but for now I have a "before and after" example):
First the "after" which has the memory leak:
protoReceiver :: RIO FdsEnv ()
protoReceiver = do
  logItS Info ["Entering FarmPCMessage protoReceiver"]
  tMap <- liftIO $ newThreadMap
  fdsEnv <- ask
  let lgr = fdsLogger fdsEnv
  loopBody <- pure $ bracketOnError
    (runResourceT $ protoServe fdsEnv tMap readFarmPCMessage)
    (\(_,w) -> do
      logLogItS Debug lgr ["Entering cleanup for protoReceiver"]
      )
    (\(server,_) -> do
      logLogItS Debug lgr ["Entering FarmPCMessage protoReceiver bracket"]
      server
        .| mapMC (liftIO . traverse_ (persistFarmEntry fdsEnv))
        .| mapMC ((logLogIt Info lgr) . pure)
        .| sinkUnits & runConduitRes
      )
  liftIO loopBody

Here's the "before" code, which does not memory leak:
protoReceiver :: RIO FdsEnv ()
protoReceiver = do
  logItS Info ["Entering FarmPCMessage protoReceiver"]
  tMap <- liftIO $ newThreadMap
  fdsEnv <- ask
  let lgr = fdsLogger fdsEnv

  (dmgrProtoServe, tcpWorker) <- liftIO $ runResourceT
    $ protoServe fdsEnv tMap readFarmPCMessage
  liftIO $ runResourceT $ dmgrProtoServe
    .| mapMC (liftIO . traverse_ (persistFarmEntry fdsEnv))
    .| mapMC ((logLogIt Info lgr) . pure)
    .| sinkUnits & runConduit

I did some profiling of the leak, though I'm not sure if it is particularly helpful (any suggestions on better profiling charts appreciated):

A: The problem is a variant of the classic leak scenario in which we retain a reference to the head of a lazy list while it's being consumed:
import Data.Foldable (traverse_)

main :: IO ()
main = do
    let xs = [1..]
    traverse_ print xs
    traverse_ print xs -- commenting this statement solves the leak

Here, the conduit Source is working as a "lazy list" of sorts. We need to retain a reference to the original source value (server) even as we consume it, because it must be passed to the exception handler in case of error. And yet the exception handler doesn't seem to make use of it.
The solution is to cut that reference as soon as the main computation we pass to bracketOnError gets hold of the value. We can use an MVar for that purpose. Not because of its synchronization abilities, but because it's a mutable reference that can be "left empty".
The allocation action, instead of returning a (Source m r, a) value, could return an (MVar (Source m r), a) value instead. Then, the main computation would perfrom a takeMVar to get hold of the conduit source. Once we start consuming the source, the original value will be garbage collected because there won't remain any more references to it.
Here is the working code the OP used after following these suggestions:
protoReceiver :: RIO FdsEnv ()
protoReceiver = retryForever $ do
  logItS Info ["Entering FarmPCMessage protoReceiver"]
  tMap <- liftIO $ newThreadMap
  fdsEnv <- ask
  let lgr = fdsLogger fdsEnv
  loopBody <- pure $ bracket
    (runResourceT $ do
      swTup <- protoServe fdsEnv tMap readFarmPCMessage
      serverMVar <- newMVar $ fst swTup
      pure (serverMVar, snd $! swTup)
      )
    (\(_, worker) -> do
      logLogItS Debug lgr ["Entering cleanup for protoReceiver"]
      killChildThreads tMap
      cancel worker
      )
    (\(serverMVar, _) -> do
      logLogItS Debug lgr ["Entering FarmPCMessage protoReceiver bracket"]
      server <- takeMVar serverMVar
      logLogItS Debug lgr ["FarmPCMessage protoReceiver bracket: got server"]
      server
        .| mapMC (liftIO . traverse_ (persistFarmEntry fdsEnv))
        .| mapMC ((logLogIt Info lgr) . pure)
        .| sinkUnits & runConduitRes
      )
  liftIO $ retryForever $ loopBody
  where
    killChildThreads = liftIO . killThreadHierarchy


text:
Q: How to get incremental serial number in Angular table pagination I am using Angular table pagination. I have a serial number that starts from 1 for each page, but I want continuous page numbers. How to get it?

            S.no
            Name
            Age

                {{$index+1}}
                {{data.name}}
                {{data.age}}

Full code: https://jsfiddle.net/mLvLzzg7/4/
If I try:
{{itemsPerPage * (currentPage - 1) + $index + 1}}

It is returning null. Any suggestions?

A: Formula for calculating the index is correct, but you didn't initialize your variables properly:
app.controller('myController', function($scope) {
    $scope.itemsPerPage = 3;
    $scope.currentPage  = 1;
    $scope.details = [{
        ...
    }];
}

    {{($index + 1) + (currentPage - 1) * itemsPerPage}}

Also, your fiddle didn't include dirPagination directive:
angular.module('myApp', ['angularUtils.directives.dirPagination']);

And I updated jQuery version to newer one in the jsfiddle - now the app works fine.


text:
Q: Creating a Document Database using Microsoft Access I am attempting to create a table within a database which store all of the documents related to the database "in it".  What I really want to do is have a file uploaded and have vba code which copies the file to a network location, renames the file by concatenating two fields from the document table form (eliminating the issue of duplicate file names in the external location), and then stores the file name and file path in a file path field in the table.  I am very new to access and vba so I am having difficulty getting everything to work.  The code I currently have is below:
Option Compare Database

Private Sub Command15_Click()
Dim f As Object

Set f = Application.FileDialog(3)

f.AllowMultiSelect = False

If f.Show Then
    For i = 1 To f.SelectedItems.Count
        sFile = Filename(f.SelectedItems(i), sPath)
        MsgBox sPath & "---" & sFile
    Next
End If

End Sub

Public Function Filename(ByVal strPath As String, sPath) As String
    sPath = Left(strPath, InStrRev(strPath, "\"))
    Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function

I can not seem to get a handle on how to move, rename by concatenating the two fields from the form, or store the path in the path field of the table.  I have been to the following locations to obtain what information I could
ms access browse for file and get file name and path
VBA to copy a file from one directory to another
I am currently using Microsoft Access 2010, and I do not wish to use the file attachment field type because of database size constraints.  Currently I press a button and a file explorer appears to navigate to the file being uploaded, and the path and file name are entered into strings.  After this point I am lost.  If any other information is needed please let me know.  Thanks in advance for the assistance.

A: I believe your approach to managing the documents is right. In most cases, it doesn't make much sense to store documents in the database itself when the filesystem is a more suited to this job.
What you are doing is fairly straightforward but the main complexity will come from the correct management of the various paths and filenames and extracting the right information from them.
It can become tricky if you're not using some helper functions to to dissect and recompose the various bits of the paths.
I have created a sample database that has a few functions. Might not be exactly in line with what you need but you can easily play around with it to suit your particular case.
The sample database includes a Tools VBA module that has a few useful functions to split a Path into its constituents.
Basically, the database has 2 forms.
The main form allows you to set the network path where the files are to be saved.
You can then select a pre-defined Account number (listed in the Account table) associated with a document, then click the upload button.

This creates a new record in the Document table and opens a form where you can edit the document title and click a button to upload a file to the server.

The file selected by the user is copied to the server after its path has been transformed.
I took the assumption that the file would keep its original extension, the filename would be renamed to the ID of the Document record where the file information is saved (like 5845.pdf) and that the folder where the file is saved on the server would be the account number, so that a source file selected by the user
C:\Users\user\Desktop\SuperSecretFile.pdf

would be saved as, for instance:
\\docserver\files\123-55547\5845.pdf

The Main form also allows you to update an existing record, open the file from the server, open the server's folder where the file is located or even copy the server file back to the user's computer with the original name of the file.
I'll let you play around with it. Let me know if you have any issues.


text:
Q: Connection pooling in spring jdbc I have implemented spring jdbc in my project. I am just curious to know how connection pooling in handled in spring jdbc? If spring is taking care of connections, then where can I specify the max number of connections allowed for my application?
Another question is how is connection pooling handled in simple jdbc.
Please clarify.

A: You can use own custom datasource, like this:
<bean id="springDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_TEST" />
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
   <property name="username" value="root" />
   <property name="password" value="root" />
   <property name="removeAbandoned" value="true"/>
   <property name="initialSize" value="20" />
   <property name="maxActive" value="30" />
</bean>

//Dao class configuration in spring
 <bean id="EmployeeDatabaseBean" class="com.test.EmployeeDAOImpl">
    <property name="dataSource" ref="springDataSource"/>
 </bean>

Official documentation
Here or here described pretty simple.


text: Q: Downloading a file async from s3 bucket to local machine using versionId and object key .net core I am trying to download a file from an Amazon S3 bucket asynchronously using an object key and version Id, but it is not downloading. I am not sure what I am doing wrong. Can anyone please help me on this?


text:
Q: Squareroot of a number I have a question regarding this video
https://www.khanacademy.org/math/algebra/exponent-equations/exponent-properties-algebra/v/adding-and-simplifying-radicals
He said that $\sqrt {x^2}=|x|$ has to be the absolute value of $x$ because $x$ can be positive or negative, which makes sense but why is $\sqrt 4= 2$? Shoudln't it be $|2|$ too? Because $-2 \cdot -2 = 4$ and $2 \cdot 2 = 4$.

A: I'd make this a comment if I had the reputation, but as it stands, just think about what $|2|$ is.

A: $\left | 2 \right |=2$. Indeed $\sqrt{x^2}=\left | x \right |$ since $\sqrt{x^2}=x$ only for non-negative values of $x$. Consider for example this case:
$\sqrt{9}=\sqrt{(-3)^2}\neq -3$. But $\left | -3 \right |=3$ which is the correct answer.

A: Remember the definition of $|x|$: $$
|x| = \left\{
        \begin{array}{ll}
            x & \quad x \geq 0 \\
            -x & \quad x < 0
        \end{array}
    \right.
$$  So what is $|-2|$ according to this definition? It is $|-2|=-(-2)=2$


text:
Q: spring data repository failed to save entity with idClass I have a simple project using spring data jpa with hibernate implementation. There is an entity with composite id, which I mapped it with id-class in xml.
I defined my entity like this:
public class MyEntity {
    private long idA;
    private String idB;
    private String idC;

    public MyEntity() {
        super();
    }

    public MyEntity(long anIdA, String anIdB, String anIdC) {
        super();
        this.idA = anIdA;
        this.idB = anIdB;
        this.idC = anIdC;
    }

    public long getIdA() {
        return idA;
    }

    public String getIdB() {
        return idB;
    }

    public String getIdC() {
        return idC;
    }

    @Override
    public String toString() {
        return "Entity [idA=" + idA + ", idB=" + idB
                + ", idC=" + idC + "]";
    }
}

I defined idClass like this:
public class MyEntityId implements Serializable {
    private static final long serialVersionUID = 9073138829628574603L;

    private long idA;
    private String idB;
    private String idC;

    public MyEntityId() {
    }

    public MyEntityId(long anIdA, String anIdB, String anIdC) {
        this.idA = anIdA;
        this.idB = anIdB;
        this.idC = anIdC;
    }

    public long getIdA() {
        return idA;
    }

    public String getIdB() {
        return idB;
    }

    public String getIdC() {
        return idC;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj != null && obj instanceof MyEntityId) {
            MyEntityId uk = (MyEntityId) obj;
            return this.idA == uk.getIdA()
                    && this.idB != null ?
                            this.idB.equals(uk.getIdB())
                            : uk.getIdB() == null
                    && this.idC != null ?
                            this.idC.equals(uk.getIdC())
                            : uk.getIdC() == null;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(idA, idB, idC);
    }

}

My repository is this:
public interface MyEntityJpaRepository extends
        JpaRepository<MyEntity, MyEntityId> {
}

And the orm.xml
<entity class="myProject.domain.MyEntity" name="MyEntity"
    metadata-complete="true" access="FIELD">
    <table name="tb_myentity" />
    <id-class class="myproject.persistance.MyEntityId" />
    <attributes>
        <id name="idA">
            <column name="id_a" />
        </id>
        <id name="idB">
            <column name="id_b" />
        </id>
        <id name="idC">
            <column name="id_c" />
        </id>
    </attributes>
</entity>

Now is the problem:
MyEntityJpaRepository.exists(aMyEntityIdInstance) is worked well, but
MyEntityJpaRepository.save(aMyEntityInstance) throws this exeption:
org.springframework.dao.InvalidDataAccessApiUsageException: Class must not be null; nested exception is java.lang.IllegalArgumentException: Class must not be null
by SimpleJpaRepository.save
I found spring Data seemed to fail to get an ID.
What have I done wrong or what did I missed?
Any body can help?
Edit:
This is the code in which the exception happenned.
    @Autowired
    private MyEntityJpaRepository myProxyRepository;
   ....
    public void append(long idA, String idB, String idC) {
        assertNotNull(idB);
        assertNotNull(idC);
        myProxyRepository.save(new MyEntity(idA, idB, idC)); //throw exception
    }

Here is the exception stack:
Caused by: java.lang.IllegalArgumentException: Class must not be null
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:97)
at org.springframework.beans.AbstractNestablePropertyAccessor.<init>(AbstractNestablePropertyAccessor.java:140)
at org.springframework.beans.BeanWrapperImpl.<init>(BeanWrapperImpl.java:109)
at org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper.<init>(DirectFieldAccessFallbackBeanWrapper.java:39)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation$IdentifierDerivingDirectFieldAccessFallbackBeanWrapper.<init>(JpaMetamodelEntityInformation.java:314)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.getId(JpaMetamodelEntityInformation.java:152)
at org.springframework.data.repository.core.support.AbstractEntityInformation.isNew(AbstractEntityInformation.java:51)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.isNew(JpaMetamodelEntityInformation.java:227)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:507)
at sun.reflect.GeneratedMethodAccessor26.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:520)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:505)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)

A: Well, it's a defect of spring-data-jpa, which was fixed in 1.11.11.snapshot. Before the release version was distributed, I have to add an @IdClass annotation on the entity class.


text:
Q: Why is there a discrepancy between python sockets and tcp ping for the same IP:port destination? My setup:

*

*I am using an IP and port provided by portmap.io to allow me to perform port forwarding.

*I have OpenVPN installed (as required by portmap.io), and I run a ready-made config file when I want to operate my project.

*My main effort involves sending messages between a client and a server using sockets in Python.

*I have installed a software called tcping, which basically allows me to ping an IP:port over a tcp connection.

This figure basically sums it up:

Results I'm getting:

*

*When I try to "ping" said IP, the average RTT ends up being around 30ms consistently.

*I try to use the same IP to program sockets in Python, where I have a server script on my machine running, and a client script on any other machine but binding to this IP. I try sending a small message like "Hello" over the socket, and I am finding that the message is taking a significantly greater amount of time to travel across, and an inconsistent one for that matter. Sometimes it ends up taking 1 second, sometimes 400ms...

What is the reason for this discrepancy?

A:
What is the reason for this discrepancy?

tcpping just measures the time needed to establish the TCP connection. The connection establishment is usually completely done in the OS kernel, so there is not even a switch to user space involved.
Even some small data exchange at the application is significantly more expensive. First, the initial TCP handshake must be done. Usually only once the TCP handshake is done the client starts sending the payload, which then needs to be delivered to the other side, put into the sockets read buffer, schedule the user space application to run, read the data from the buffer in the application and process, create and deliver the response to the peers OS kernel, let the kernel deliver the response to the local system and lots of stuff here too until the local app finally gets the response and ends the timing of how long this takes.
Given that the time for the last one is that much off from the pure RTT I would assume though that the server system has either low performance or high load or that the application is written badly.


text:
Q: Expected '(' or '[' when creating ArrayList I am making a program that uses GridWorld for Java.  I want to use an ArrayList in my code but JGrasp is giving me a very strange error that is very infuriating.  This is my code:
public ArrayList<Actor> getActors()
{
     ArrayList <Location> occLocs = getGrid().getOccupiedLocations();
     ArrayList <Actor> a = new ArrayList <Actor>;

     for(Location test: occLocs)
     {
        a.add(getGrid().get(test));
     }

     return a;
}

And this is the error that I got:
AttractiveCritter.java:12: error: '(' or '[' expected
     ArrayList <Actor> a = new ArrayList <Actor>;

A: You are missing open and closed parentheses needed when creating an object. Change,
ArrayList <Actor> a = new ArrayList <Actor>;

to
ArrayList <Actor> a = new ArrayList <Actor>();

and your error should be resolved.


text:
Q: Google maps infowindow error f = undefined infowindow.js I've got a weird problem. It says f = undefined in infowindow.js. But I don't even have a file infowindow.js... This happens when I click on it. It has to show infowindow, but it doesn't.
Got the code from documentation here: LINK
Here's my code (address array is now adjusted, in my code there are normal addresses in it):
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: { lat: 52.3, lng: 5.7 }
    });
    var geocoder = new google.maps.Geocoder();

    var addresses = [
        {
            'adres': 'teststraat 21',
            'plaats': 'Apeldoorn',
            'postcode': '1234AB',
            'telefoon': '0123456789',
            'openingstijden': 'test'
        },
        {
            'adres': 'teststraat 21',
            'plaats': 'Apeldoorn',
            'postcode': '1234AB',
            'telefoon': '0123456789',
            'openingstijden': 'test'
        },
        {
            'adres': 'teststraat 21',
            'plaats': 'Apeldoorn',
            'postcode': '1234AB',
            'telefoon': '0123456789',
            'openingstijden': 'test'
        },
    ];

    geocodeAddress(geocoder, map, addresses);
}

function geocodeAddress(geocoder, resultsMap, addresses) {
    for(var i = 0; i < addresses.length; i++) {
        geocoder.geocode({'address': addresses[i]['adres'] + addresses[i]['plaats']}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                var counter = i - addresses.length;
                var infowindow = new google.maps.InfoWindow({
                    content: 'test',
                    maxWidth: 200
                });
                var marker = new google.maps.Marker({
                    map: resultsMap,
                    position: results[0].geometry.location,
                    title: 'testadres ' + addresses[counter]['plaats'],
                });
                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                });
                i++;
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
}

A: You use map instead of resultsMap in this piece of code:
The map object doesn't exist in this context. Should be:
infowindow.open(resultsMap, marker);

To close the staying infowindow before opening a new one, add only one infowindow instance and change it's content and position on marker click:

var infowindow = null;
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: { lat: 52.3, lng: 5.7 }
    });
    var geocoder = new google.maps.Geocoder();

    var addresses = [];

    geocodeAddress(geocoder, map, addresses);
}

function geocodeAddress(geocoder, resultsMap, addresses) {
    var infowindow = new google.maps.InfoWindow();
    for(var i = 0; i < addresses.length; i++) {
        geocoder.geocode({'address': addresses[i]['adres'] + " " + addresses[i]['plaats']}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                var counter = i - addresses.length;
                var marker = new google.maps.Marker({
                    map: resultsMap,
                    position: results[0].geometry.location,
                    title: 'testadres ' + addresses[counter]['plaats'],
                });
                marker.addListener('click', function() {
                    infowindow.setContent('test content');
                    infowindow.open(resultsMap, marker);
                });
                i++;
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
}


text:
Q: Wordpress filters and excerpts I am trying to pull content from one page into another.  I could be going about this the wrong way, but I am just trying to get the general method of how it is done.  This is what I have so far trying to get the data I need.  I am not getting the permalink or the image.  The other issue is when applying the substr method to the $content variable it actually cuts the html tags off to making it to where anything after it gets nested into whatever html happens to be in the content.  I appreciate any tips you may have.  Here is the function I created to try and pull the content in it's initial stage.
function show_post($path) {
  $post = get_page_by_path($path);
  $title = apply_filters('the_title', $post->post_title);
  $image = apply_filters('featured_image', $post->the_post_thumbnail);
  $content = apply_filters('the_content', $post->post_content);
  $link = apply_filters('the_permalink', $post->get_permalink);
  echo '<h3>'.$title.'</h3>';
  echo substr($content, 0, 300) . '...';
}

$path is the relative url of the website to where I am pulling content so lets say my url i want to grab data is www.test.com/about/bio I would make the path be about/bio.
I appreciate your help in this.


text:
Q: compress and decode picture for max quality having trouble keeping an images quality while compressing > sending to sever (in BLOB format) > retrieving image > decoding BLOB > then setting bitmap.
When i take the picture on the device or choose to upload one it looks alright on the camera but once I send it to the server and get it back later the quality is garbage.
here is the code I am using while compressing the image:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byte_arr = stream.toByteArray();
                String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);

and decoding:
    String pict = getIntent().getExtras().getString("pic");
    byte[] encodeByte = Base64.decode(pict, Base64.DEFAULT);

thanks in advanced!


text:
Q: There are eight coins in a row, all showing heads. There are eight coins in a row, all showing heads. In each move, we can flip over two adjacent coins provided that they are both showing heads or both showing tails. How many different patterns of heads and tails can we obtain after a number of moves?
My solution: We can replace each head with the number '1', and each tail with the number '0', we will then end up with a binary sequence with a starting decimal value of 255. Each move will add or subtract $3*2^n$, $(6 \geq n \geq 0)$, thus there will be $255 / 3 + 1 = 86 $ solutions.
There is already a solution on StackExchange here: How many different patterns of heads and tails can we obtain after a number of moves?
Although I understand the accepted solution for the above link, I still don't understand why my solution is wrong, can anyone help continue my solution or give me a hint?

A: You are suggesting that you can reach any multiple of 3. But you can't reach, for instance, $21$, that is $00010101$.

A: I wrote a python script to count them by brute force.  It turns out that there are $70$ strings, and they are exactly the nonnegative multiples of $3$ less than $256$ with an even number of $1$ bits in their binary representation.
Before trying to prove this, I tested the hypothesis, that if their are $n$ coins, and $n$ is even, then the reachable positions are the nonnegative multiples of $3$ less than $2^n$ with an even number of $1$ bits, and if $n$ is odd, the then the reachable positions are the nonnegative numbers less than $2^n$ and $\equiv1\text{mod } 3$ with an odd number of $1$ bits.
This turned out to be true for $n=2,3,...,10$ but false for $n=11,12,13,14,15,16$. It appears likely then, that some ad hoc argument is required for the $n=8$ case, which will essentially come down to brute force.


text:
Q: Codeigniter validation Based on the backend data i may have n number of items displayed along with the check box and textarea for selecting and give commnet on the page and there is also a option given to the user to remove the items based on the requirements. I need to set a validation like atlease one item is required.
Since its number is based on the query dont know how to set the validation.

A: It's hard to say without a bit more detail, but in general if you have a set of checkboxes and you want to make sure at least one is checked you could do this in your HTML:

<input type="checbox" name="my_field_name[]" value="item1" />Item 1

<input type="checbox" name="my_field_name[]" value="item2" />Item 2

<input type="checbox" name="my_field_name[]" value="item3" />Item 3

and just set a rule that "my_field_name" is a required field. That's assuming it works for you to have the values returned in one array like that.


text:
Q: How to go about solving pairwise disjoint proof with collections of sets? Let A, B be two pairwise disjoint families of sets. let D=AUB.
Prove if Union over A and Union over B are disjoint, the D is pairwise disjoint.
I started the proof and split it into three cases. Well I'm having issues picking a third case.
I have
Let X,Y be in D=AUB
Need to show: X=Y or X interest Y= empty set
Case 1: X,Y in A
Case 2: X,Y in B
Case 3: I'm confused as how to set up. I want to do it with cases as I understand it better this way. Any help as to how to continue is appreciated! I have X in A and Y in B but then I realized I'm just going a step back.

A: $\displaystyle (u \in X) \wedge (X \in A) \implies u \in \bigcup_{S \in A}S$. Similarly
$\displaystyle (u \in Y) \wedge (Y \in B) \implies u \in \bigcup_{S \in B}S$.
 Since we assumed these unions were disjoint, we have a contradiction. Hence  $X, Y \in D$ must also be disjoint.


text:
Q: How to undo dist-upgrade? I was trying to find a way to resize correctly my window for virtual box(to get it full screen) , however at one point I executed the command get-apt dist-upgrade and I think this command break my computer running on Ubuntu 16.04
The computer boots but I can't use my keyboard(can't open a terminal) or my mouse on my desktop. So I taught about rebooting in secure mode but I don't know how to do it. My computer is a dell so I did F12 to enter Bios and then I hold esc so I enter the grub. Instead of having an option to boot in secure mode I just have a command line. I used the command "reboot" and now I'm in the Bios.
How can I do to boot in secure mode?
I have a save of many of my files in a USB drive, how to get back to that save or undo that apt-get dist-upgrade?
Thanks. !


text:
Q: How to set category in logger in flutter using logger.dart I'm using the package:logger/logger.dart to log messages to the console area of the Run tab which appears as:
20:45:48.622 info flutter.tools    MapsDemo - _pushPage<…>

This is the code
class MyLogger extends PrettyPrinter {
    final String className;
    MyLogger(this.className);
    @override
    void log(Level level, message, error, StackTrace stackTrace) {
        var color = PrettyPrinter.levelColors[level];
        var emoji = PrettyPrinter.levelEmojis[level];
        println(color('$emoji $className - $message'));
    }
}

Logger getLogger(Object className) {
    return Logger(printer:  MyLogger(className.runtimeType.toString()));
}

And how it's invoked:
Logger log = getLogger(this);
log.i("_pushPage", );

So I want to change the category which I believe is the flutter.tools portion of the console listing to something of my own choosing.


text:
Q: How to get return from event handler Here is a draft code:
<form action="test.php" method="post">
    <input type="text" id="content">
    <input type="button" name="validate_button" id="validate_button" value="Validate" />
    <input type="submit" name="submit_button" id="submit_button" value="Send" />
</form>

<script>
$('#submit_button').click(function(e) {
    if (!($('#validate_button').click()))
        e.preventDefault();
});

$('#validate_button').click(function() {
    if ($('#content').val() === '')
        return false;
    return true;
});
</script>

I want when clicking submit_button to run the event handler of validate_button and decide for submitting or not the form. Obviously, my condition !($('#validate_button').click()) is not correct since it returns a jQuery object. How may I get return results of the event handler itself?
P.S. Do not suggest to put the condition $('#content').val()==='' inside the first event handler...

A: Why not create a function and call that in both click handlers:
$('#submit_button').click(function(e){
    if (!validate())
      e.preventDefault();
});

$('#validate_button').click(function(){
    return validate();
});

function validate() {
    if ($('#content').val()==='')
      return false;
    return true;
}

A: You can create a function and use it as handler to the #validate_button click and it can be called from #submit_button click handler too.
// Function to validate the value of `#content`
// Return false when value is empty, true o.w.
function validate() {
    // Trim the leading and trailing spaces
    // Note: Empty string in JS is falsy
    return $.trim($('#content').val());
}

$('#submit_button').click(function (e) {
    // Other code

    return validate();
});

// Pass the function reference to the click()
$('#validate_button').click(validate);

A: Why not not use JavaScript at all?
<input type="text" id="content" required />


text:
Q: How to use CheckBox for set string in Android In my application i want use 3 CheckBox and i want when check of each this CheckBoxs add one world into my String.
For example : I want 3 CheckBox (chBoxFree, chBoxDownload, chBoxBuy) and when check each of this CheckBoxs add Free, Download, Buy into one String and when uncheck CheckBox remove from this String.
If checked the chBoxFree, chBoxBuy add "free-buy" in this string value and when uncheck chBoxBuy, remove buy from this string
How can i it?

A: You can observe the checked/unchecked inside onCheckedChanged and do your operation accordingly.
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    private TextView textView;
    private List<String> list = new ArrayList<>();

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

        textView = findViewById(R.id.textview1);

        CheckBox checkBox1 = findViewById(R.id.checkbox1);
        CheckBox checkBox2 = findViewById(R.id.checkbox2);
        CheckBox checkBox3 = findViewById(R.id.checkbox3);

        checkBox1.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox3.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked) {
            switch (buttonView.getId()) {
                case R.id.checkbox1:
                    list.add("Free");
                    break;
                case R.id.checkbox2:
                    list.add("Download");
                    break;
                case R.id.checkbox3:
                    list.add("Buy");
            }
        } else {
            switch (buttonView.getId()) {
                case R.id.checkbox1:
                    list.remove("Free");
                    break;
                case R.id.checkbox2:
                    list.remove("Download");
                    break;
                case R.id.checkbox3:
                    list.remove("Buy");
            }
        }

        textView.setText(TextUtils.join("-", list));
    }
}


text:
Q: Temporarily suspend user from making another request I'm building a swift iOS-based app that limits users to submit only one request per 10 minutes.I'm suck now translating these three points to code
1- user clicks a button
2- button is disabled for 10 minute
3- button is enabled
I'm not expecting the full code :) just a method or advice.
Thank you

A: Note the following: timeInterval is in seconds so 60*10 is 10 minutes.  UI Updates need to happen on the main thread which is why the time block gets dispatched back to main.
    @IBAction func touchButton(_ sender: AnyObject) {
        button.isEnabled = false
        Timer.scheduledTimer(withTimeInterval: 60*10, repeats: false) { _ in
            DispatchQueue.main.async {
                self.button.isEnabled = true
            }
        }
    }

A: First you need to keep the state in persistent data, incase user go to another controller and go back, the button should still disabled.
class PersistentData {
    static let sharedInstance = PersistentData();
    var disableSubmitButton = false
}

Then in your controller
override func viewDidLoad() {
    // each load need to check
    if PersistentData.sharedInstance.disableSubmitButton == true {
        submitButton.isEnabled = false
    }
}

func onButtonClicked() {

    // change button to disable
    submitButton.isEnabled = false

    // set state in persistent data so it can be the same wherever controller you go
    PersistentData.sharedInstance.disableSubmitButton = true

    // now set the timer to enable back
    Timer.scheduledTimer(timeInterval: 10.0 * 60, target: self, selector: #selector(self.updateButtonState), userInfo: nil, repeats: false);
}

func updateButtonState() {

    // update value in persitence data
    PersistentData.sharedInstance.disableSubmitButton = false

    // change button to enable back
    submitButton.isEnabled = true
}


text:
Q: Drools is very slow when we integrate with Talend ETL and process millions of records we have used around 30 rules with multiple conditions in it. we are under the assumption that Drools takes one record and compares it against the records then will give the output for each one.So the time taken for processing 1 million record is around 4 hours. Cant we not process the records in batches. I mean to say in big numbers and reducing time for processing. Pls help me this issue. Thanks for the response.

A: Inserting 1M facts in one batch is a very bad strategy (unless you need to find combinations out of the lot). The documentation makes it clear that all work (at least in 5.x) is done during inserts and modifications. (6.x is reportedly different, but it's still bad practice to needlessly fill your memory up with objects galore.)
Simply insert, and after some suitable number, call fireAllRules() and process (transmit,...) the results. Make sure that no "dead stock" remains in Working Memory from such a batch - this would also slow you down.


text:
Q: How to continuously improve accuracy of tensorflow object detection model in production flow? I have already trained an object detection model and got a good prediction accuracy on real images. My question is how to continuously improve the accuracy of the model while using it in production flow.
I can manually check the prediction result, found the wrong predictions, manually label these images, then blend these images with the original training data, continue to train the model. I haven't tried it. But I guess this approach can probably improve the accuracy of the model in the long run. Are there other approaches?
And, if I find several wrong predictions and want to guarantee correct prediction on the same images in a short cycle, what can I do?
Thanks for any suggestions.

A: You answered it already and that's the way. You would have to retrain the model with more unseen/difficult images that you come across and were not predicted correctly and deploy it in production. To achieve this, save all the input image and predictions so that you can filter them offline and use for retraining


text:
Q: What is the difference between dma_mmap_coherent and remap_pfn_range? Currently, I am using an example driver to learn from, and from which I have based my own custom driver around. The mmap code is very nearly identical, save for the fact that I allow the user to manage their own requested size and base my memory allocation around that and the fact that I automatically create the char device within /dev.
To explain the context, for my use case, I'd like to narrow out an issue that I'm having. dma_mmap_coherent testably works when using kmalloc'd memory, but when I have a reserved physical address region that I want to use remap_pfn_range with it quietly appears to work, and dmesg doesn't report any errors, but when I go to read, no matter what I've written there it always returns 0xff bytes. This is true whether I use the iowrite & ioread in kernel land after ioremap'ing the memory or trying to write in userland using a small mmap'ing userland test.
I've done as much research on the topic as I can I think. All I can find for documentation of remap_pfn_range is the kernel.org page, and some kernel gmain mailing list archives on remap_pfn_range replacing remap_page_range. As for dma_mmap_coherent, I was able to find a little bit more, including a presentation from the linux archives.
Ultimately there has to be a difference; there seems to be so many different ways to map kernel memory into user land. The particular question I have is: what is the difference between dma_mmap_coherent and remap_pfn_range?
Edit it might be nice to provide a general overview of the ways to map kernel memory into userland in general, covering how different apis would be used in a kernel driver mmap callback.

A: dma_mmap_coherent() is defined in dma-mapping.h as a wrapper around dma_mmap_attrs(). dma_mmap_attrs() tries to see if a set of dma_mmap_ops is
associated with the device (struct device *dev) you are operating with, if not it calls dma_common_mmap() which eventually leads to a call to remap_pfn_range(), after setting the page protection as non-cacheable (see dma_common_mmap() in dma-mapping.c).
As to a general overview of mmap'ing kernel memory to user space works, the following is my quick and simple way of mmap'ing DMA buffers from user space :

*

*Allocate a Buffer via an IOCTL and designate a buffer ID for each buffer with some flags:
/* A copy-from-user call needs to be done before in the IOCTL */
static int my_ioctl_alloc(struct my_struct *info, struct alloc_info *alloc)
{

        ...
        info->buf->kvaddr = dma_alloc_coherent(dev, alloc->size, info->buf->phyaddr, GFP_KERNEL);
        info->buf->buf_id = alloc->buf_id;
        ...
}

*Define an mmap file ops :
static const struct file_operations my_fops = {
        .open = my_open,
        .close = my_close,
        .mmap = my_mmap,
        .unlocked_ioctl = my_ioctl,
};

Do not forget to register the my_fops struct somewhere in your driver's probe function.

*Implement mmap file ops :
 static int my_mmap(struct file *fptr, struct vm_area_struct *vma)
 {
         ...
         desc_id = vma->vm_pgoff;
         buf = find_buf_by_id(alloc, desc_id);
         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
         ret = remap_pfn_range(vma, vma->vm_start, buf->phyaddr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot);
         if (ret) {
              /* Error Handle */
         }
         return 0;
 }

With this your kernel driver should have the minimum to allocate and mmap buffers. Freeing the buffers is an exercise for the bonus points!
In the application, you would open() the file and get a valid file descriptor fd, call the allocate IOCTL and set the buffer ID before performing a copy-to-kernel. In the mmap, you would give the buffer ID via the offset parameter :
      mmap(NULL, buf_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buffer_id << PAGE_SHIFT);

PAGE_SHIFT is an architecture dependent compile time MACRO fixed in the kernel.
Hope this helps.
This is not checkpatch.pl compliant code, nor is this the best practice, but it's one way I know how to do this. Comments/improvements/suggestions welcome!
See Linux Device Drivers - Chapter 15: Memory Mapping and DMA for the textbook examples and good background information for the interested reader.


text:
Q: Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom' I recently started to use react native, but according to Iranians Sanctions, gradle cannot build my first projects, so I used VPN and also shecan service but I get the following error:

I read React native instructions and followed them, set up an emulator, react native cli, and chocolaty service. In environments, it was written that I should define my platform-tools folder of my SDK in a variable named PATH. But in variables, I have already had path in username and in system variables. In edit, I have added my platform-tools to them. But unfortunately it didn't work yet.

The PowerShell error messages in the image are:
PS C:\Others\RN_projects\React_native_shop\shop_project> react-native run-android

Starting JS server...
Building and installing the app on the device (cd android &&
  gradlew.bat installDebug)... FAILURE: Build failed with an exception.

*

*What went wrong: A problem occurred configuring root project 'shop_project'. Could not resolve all artifacts for configuration
  ':classpath'. Could not resolve com.android.tools.build:gradle:3.2.1.

  Required by:
project : Could not resolve com.android.tools.build:gradle:3.2.1.
  Could not get resource
  'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom'.
  Could not GET
  'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom'.
  Connect to 127.0.0.1:8580 [/127.0.0.1] failed: Connection refused:
  connect
Could not resolve com.android.tools.build:gradle:3.2.1.
Could not get resource
  'https://jcenter.bintray.com/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom'.
  Could not GET
  'https://jcenter.bintray.com/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.pom'.
Connect to 127.0.0.1:8580 [/127.0.0.1] failed: Connection refused:
  connect

*

*Try:

  Run with --stacktrace option to get the stack trace. Run with --info
  or --debug option to get more log output. Run with --scan to get full
  insights.

*

*Get more help at https://help.gradle.org
BUILD FAILED in 3s Could not install the app on the device, read the
  error above for details. Make sure you have an Android emulator
  running or a device connected and have set up your Android development
  environment:
  https://facebook.github.io/react-native/docs/getting-started.html
events.js:173
throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT
at Process.ChildProcess._handle.onexit
  (internal/child_process.js:246:19) at onErrorNT
  (internal/child_process.js:421:16) at processTicksAndRejections
  (internal/process/next_tick.js:76:17)
Emitted 'error' event at: at Process.ChildProcess._handle.onexit
  (internal/child_process.js:252:12) at onErrorNT
  (internal/child_process.js:421:16) at processTicksAndRejections
  (internal/process/next_tick.js:76:17)

A: Add this proxy information to your gradle.properties file:
systemProp.https.proxyPort=9595
systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=9595

and set above proxy port (ex. 9595) in your vpn like psiphon.
Then sync project.
see this post

A: I ran into the same issue.
What I tried:

*

*changed the gradle version, changed the gradle plugin version

*changed repositories where packages are searched

*set proxy settings in gradle.properties file

*set proxy settings in Windows 10 network settings

None of this helped me, and I installed a proxy program that can wrap the traffic of individual applications on the computer, and it worked!
It was a Proxyfire program - it has a 30-day free version.
The problem of accessing Google services in my case is related to local restrictions.


text:
Q: How do i find the limit of this sequence? $$\sum_{n=1}^\infty \frac{5(-2)^n-3^{(n+1)}}{5^n}$$
tried using geometric series, but unable to factor out the constant due to the minus sign.
Also tried using ratio test but I got stuck halfway.

A: It's
$$5\sum_{n=1}^\infty\left(-{2\over5}\right)^n-3\sum_{n=1}^\infty\left({3\over5}\right)^n=5{-{2\over5}\over1-\bigl(-{2\over5}\bigr)}-3{{3\over5}\over1-{3\over5}}=\ldots$$


text:
Q: цепочка сертификатов выпущена центром сертификации не имеющим доверия Всем добрый день!
При попытке подключения источника данных в Excel(SQL-сервер) выпадает следующая ошибка
Учетка пользователя на сервере и учетка база данных активна.
Подскажите в чем может быть проблема и куда копать.


text:
Q: How to speed up code in ParallelDo loops? I have a piece of code that I'm trying to run in a ParallelDo over 32 kernels. Using a normal Do loop in a kernel Mathematica takes about 6 minutes to do the calculation, however, in the ParallelDo loop across 32 kernels it takes just over a minute. Surely it should be much quicker than this (about 11 seconds)?! Here is the code:
LaunchKernels[2*$ProcessorCount - $KernelCount];
dk = 1;

ParallelEvaluate[
  g = 2*10^-1;
  ϕ = 1;
  m = 1;
  f = 7;
  lattsize = 50;
  p[P_, α_, β_] := {P*Sin[α]*Cos[β], P*Sin[α]*Sin[β], P*Cos[α]};
  q[Q_, a_] := {Q*Sin[a], 0, Q*Cos[a]};
  k[X_] := {0, 0, X};
  X = Interpolation[Table[{i, i}, {i, 0, lattsize, 10^-3}]];
  ω[x_] := Sqrt[x.x + m^2];
  (*x:=p,y:=q,z:=k,s:=k+(-)p+(-)q*)
  A1[x_, y_, z_, s_] := (1 + (g*ϕ^2)/(8*ω[x]^2))*ω[x] +
      (1 + (g*ϕ^2)/(8*ω[y]^2))*ω[y] + (1 + (g*ϕ^2)/(8*ω[z]^2))*ω[z] +
         (1 + (g*ϕ^2)/(8*ω[s]^2))*ω[s];

   minA1={};

   maxA1={};

 ];

ParallelDo[
 solA1 = NSolve[A1[p[P, α, β], q[Q, a], k[X[i]], k[X[i]] - p[P, α, β] - q[Q, a]] == f, Q, Method -> {Automatic, "SymbolicProcessing" -> 0}];
 If[solA1 != {},

  solA1 = Select[Q /. solA1, Positive];
  AppendTo[minA1, {{P, i, α, β, a}, Min[solA1] /. Infinity -> Null}];
  AppendTo[maxA1, {{P, i, α, β, a}, Max[solA1] /. -Infinity -> Null}];,

  AppendTo[minA1, {{P, i, α, β, a}, Null}];
  AppendTo[maxA1, {{P, i, α, β, a}, Null}]
  ],
 {P, 0, 5, dk}, {i, 0, 10, dk}, {α, 0, 3, dk}, {β, 0, 6, dk}, {a, 0, 3, dk},
 Method -> "CoarsestGrained"(*Automatic*)
]

I can't see anything I've done wrong, but I am fairly new to Mathematica, so any help would be much appreciated.


text:
Q: What Would Happen When NAT Mapping is Dropped As far as I Know, NAT will set a timeout value for every tcp or udp mapping entry, suppose here is a NAT and it has two mapping entries: one as udp pair, and the other as tcp pair. My questions are:
When the tcp/udp pair mapping is dropped because of timeout, what would happen to the endpoints? Will the endpoints get notified by NAT? What would happen if the endpoints still try to send packets to their communication peers?

A: TCP connections have a 'keep communication alive' mechanism, which will keep the mapping alive too. So you are unlikely to face a timeout. But, let's imagine you reach a timeout (with UDP or not), your code will throw an error, at most when you try to write a packet. This is handled by the TCP layer.


text:
Q: Can't get paramaters from url page of content I'm build two plugins, each install on a different site. Plugin Site "A" for encryption all link on content of post, If I have some links look like :
Go to facebook now

It will be encrypt to like this
Got to facebook now

So on site "B" I want to get link paramter, I have finished that and on local works perfectly, link paramater can get from url, and decrypt it. My problem is on production (nginx), I can't get link parameter.
 // wp-content/plugins/my-plugins/class.safelink.php
<?php
Class Safelink {
    public static function init(){
        add_filter('the_content', Array('Safelink','insert_content_here'));
    }

    public static function insert_content_here ($content) {
        if ( is_single()  && filter_input(INPUT_GET, 'link') ) {
            $params_code = absint(filter_input(INPUT_GET, link''));
            $dnc_url = self::decrypt($params_code);
            $custom_content = '
Download Here
';
            $custom_content .= $content;
            return $custom_content;
        } else {
            return $content;
        }
    }

    public static function decrypt($params_code){
        $key = 'mykey';
        $encrypted = strtr($params_code, '-_,', '+/=');
        $data = base64_decode($encrypted);
        $vi = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
        return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_ECB, $vi));
    }
}
?>

I try with $_GET['link'] but output is null, just only appear like this :

Download Here

And also, I tried with
add_filter('query_vars', Array('Safelink', 'parameter_queryvars'));

public static function parameter_queryvars( $qvars )
{
        $qvars[] = 'link';
        return $qvars;
}

But still null when I print $wp_query->query_vars['link'];
FYI, I'm use nginx and subdirectory (subdomain). On apache server I can get link parameter.


text:
Q: How to hide footnote separator in beamer animated slides? I have a slide that have two images that are uncovered in parts. One of the figure has a caption and a footnote associated with the caption. I am able to uncover the footnote at the right instant but the footnote separator appears on all the slides as shown below. A MWE is given below:
\documentclass[beamer]{standalone}
\usepackage{tikz}
\begin{document}
    \begin{frame}
        \frametitle{Title}
        \begin{columns}
            \begin{column}{0.5\textwidth}
                \begin{figure}
                    \begin{tikzpicture}
                        \only<1>
                            {
                            \node [inner sep=0pt,opacity=0.2]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-a}
                                };
                            }
                        \only<2->
                            {
                            \node [inner sep=0pt]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-a}
                                };
                            }
                    \end{tikzpicture}
                    \onslide<2->
                        {
                        \caption{Caption 1\footnotemark}
                        }
                \end{figure}
            \end{column}
            \begin{column}{0.5\textwidth}
                \begin{figure}
                    \begin{tikzpicture}
                        \only<1-2>
                            {
                            \node [inner sep=0pt,opacity=0.2]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-b}
                                };
                            }
                        \only<3->
                            {
                            \node [inner sep=0pt]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-b}
                                };
                            }
                    \end{tikzpicture}
                    \onslide<3->
                        {
                        \caption{Caption 2}
                        }
                \end{figure}
            \end{column}
        \end{columns}
            \footnotetext<2->{Lorem ipsum}
    \end{frame}
\end{document}

How to hide the footnote separator for the first part of the slide?
Update
I do not want to use \only as it causes the position of the images to shift based on the size of the footnote text.
Slides

A: Just use \only.
\documentclass[beamer]{standalone}
\usepackage{tikz}
\begin{document}
    \begin{frame}
        \frametitle{Title}
        \begin{columns}
            \begin{column}{0.5\textwidth}
                \begin{figure}
                    \begin{tikzpicture}
                        \only<1>
                            {
                            \node [inner sep=0pt,opacity=0.2]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-a}
                                };
                            }
                        \only<2->
                            {
                            \node [inner sep=0pt]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-a}
                                };
                            }
                    \end{tikzpicture}
                    \onslide<2->
                        {
                        \caption{Caption 1\footnotemark}
                        }
                \end{figure}
            \end{column}
            \begin{column}{0.5\textwidth}
                \begin{figure}
                    \begin{tikzpicture}
                        \only<1-2>
                            {
                            \node [inner sep=0pt,opacity=0.2]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-b}
                                };
                            }
                        \only<3->
                            {
                            \node [inner sep=0pt]
                                {
                                \includegraphics[height=4cm,keepaspectratio,trim={0 0 0 0},clip]{example-image-b}
                                };
                            }
                    \end{tikzpicture}
                    \onslide<3->
                        {
                        \caption{Caption 2}
                        }
                \end{figure}
            \end{column}
        \end{columns}
            \only<2->{
            \footnotetext{Lorem ipsum}}
    \end{frame}
\end{document}


text:
Q: PHP number_format not working I'm making a website and I've got the following problem.
I'm importing query's from MySql, but to make it easier to understand I'm using local arrays now.
<?php
            $productnames = array("Raspatat oorlog", "Raspatat mayo", "Raspatat pizza", "Raspatat ui", "Raspatat curry");
            $productprices = array(1.7, 2.3, 2.45, 3.45, 34.669);

            echo "

                        Product
                        Prijs

";
            for($i =0; $i < sizeof($productnames); $i++) {
                $iprice = number_format((float)$pruductprices[$i], 2, ',', '');
                echo "
$productnames[$i]
                $iprice
";
            }

            echo "
";
            echo $iprice;
        ?>

The code is running, but in my table i get a price of 0,00 everywhere.
Does anyone know why?
Thanks!
(this is the table
Product         Prijs
Raspatat oorlog |0,00
Raspatat mayo   |0,00
Raspatat pizza  |0,00
Raspatat ui     |0,00
Raspatat curry  |0,00

}

A: You have a typo in your code (around your variable pruductprices name):
<?php
    $productnames = array("Raspatat oorlog", "Raspatat mayo", "Raspatat pizza", "Raspatat ui", "Raspatat curry");
    $productprices = array(1.7, 2.3, 2.45, 3.45, 34.669);

    echo "

    Product
    Prijs

";
    for($i =0; $i < sizeof($productnames); $i++)
    {
        $iprice = number_format((float)$productprices[$i], 2, ',', '');
        echo "
$productnames[$i]
        $iprice
";
    }

    echo "
";
    echo $iprice;
?>

Output:
 Product    Prijs
Raspatat oorlog     1,70
Raspatat mayo   2,30
Raspatat pizza  2,45
Raspatat ui     3,45
Raspatat curry  34,67
34,67

If you want to easily debug a script, add this to the top:
error_reporting(E_ALL);
ini_set('display_errors', 1);

It will show you all the whoopsie-daisies and makes for debugging bliss.

A: You wrote 'pruductprices' - change it to $productprices and it works.
Seems you need some more error reporting for your development.


text:
Q: Real-time multiplayer game using Cordova, Javascript, PHP, MySQL - Help & Tips I'm trying to create a simple game (like Agar.io) in real time using Cordova: Javascript, AJAX, PHP & MySQL.
The code works great:
1) JS Send X and Y to PHP server
2) PHP saves X and Y to MySQL Database
3) PHP retrieves X and Y from MySQL Database
4) PHP posts X and Y
5) JS retrieves PHP post of X and Y
6) Display circle at retrieved X and Y coordinates
Now for the problem..
It's very slow! This whole process takes about 1 second to complete (giving it 1 second delay). Also, some times it even lags from 2-10 seconds!
I understand this method isn't the quickest, but I still feel like I may be doing something wrong or inefficient.
HELP
It may be that this is the most efficient way possible, but I feel I am doing something wrong. Or maybe there is a better method of doing this?
Also, I am currently using HostMonster, Shared account (Maybe that's the issue?), which I'm waiting for them to open so I can upgrade to a Dedicated server and try it on there.
Note: In the mean time, I'm really trying to avoid using Node.js / Websockets because servers are just very pricey. And the free ones are very limited =/
Worse comes to worse, I will learn more JS PHP MySQL :)
JAVASCRIPT
function update
{
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.drawImage(test, positionX - c.width/40, positionY - c.width/40, c.width/20, c.width/20);

    if((directionX != positionX || directionY != positionY) &&
        dataServerSendOn && dataServerGetOn)
    {
        dataServerSendOn = false;
        dataServerGetOn = false;

        setTimeout(function(){requestAnimationFrame(sendData);}, FPS);
    }

    requestAnimationFrame(update);
}

function sendData()
{
    var params = "uuid=" + uuid + "&directionX=" + directionX + "&directionY=" + directionY;

    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange =
    function()//Call a function when the state changes.
    {
        if(http.readyState == 4 && http.status == 200)
        {
            dataServerSendOn = true;
            requestAnimationFrame(getData);
        }
    }
    http.send(params);
}

function getData()
{
    xmlhttp.onreadystatechange =
    function()
    {
        /*
         * 0: Hasn't Started
         * 1: Connected to the Server
         * 2: Server has received our request
         * 3: Server Processing
         * 4: Request is finished and data is ready
         */
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            httpTransferString = xmlhttp.responseText;
            requestAnimationFrame(sortData);
        }
    }

    xmlhttp.open("GET", "http://www.example.com/game", true);
    xmlhttp.send();
}

function sortData()
{
    positionX = "";
    positionY = "";

    for(var i = 0; httpTransferString[i] != '&'; i++)
    {
        positionX += httpTransferString[i];
    }
    for(var i = positionX.length + 1; httpTransferString[i] != '#'; i++)
    {
        positionY += httpTransferString[i];
    }
    dataServerGetOn = true;
}

PHP
<?php
require 'core.php';
require 'connect.php';

if(loggedin())
{
    if(isset($_POST['uuid']) &&
       isset($_POST['directionX']) &&
       isset($_POST['directionY']))
    {
        $uuid       = $_POST["uuid"];
        $directionX = $_POST["directionX"];
        $directionY = $_POST["directionY"];

        $query = "SELECT `UUID` FROM `users` WHERE `UUID`='$uuid'";
        if($query_run = mysql_query($query))
        {
            $queryX = "UPDATE `users` SET `x` = '$directionX'  WHERE `uuid`='$uuid'";
            $query_runX = mysql_query($queryX);
            $queryY = "UPDATE `users` SET `y` = '$directionY'  WHERE `uuid`='$uuid'";
            $query_runY = mysql_query($queryY);
        }
    }
}
else
{
    echo "You're not logged in";
}

?>
<form name="tcpForm" action="<?php echo $current_file; ?>" method="POST">
UUID       <input type="text" name="uuid">

directionX <input type="text" name="directionX">

directionY <input type="text" name="directionY">

<input type="submit" value="Send">
</form>

Please any advice I will greatly appreciate, I am still a noob =]

A: HTTP is not considered to be the best choice when it comes to real-time applications as it does not provide a full two-way communication. This means that whenever something changes on the server-side there will be no way to notify the client. The client would need to either to send a lot of requests, which puts a lot of load on the server or use long-polling. Long-polling is a way, actually more of a hack, to partially circumvent the lack of two-way communication in HTTP. It consists of the client sending a request to the server and the server keeping the connection open until there is something to respond back to the client. This is also not optimal as the server might run out of sockets.
Now for a good real-time service (or a game) you could use some of the protocols that are specifically targeted towards real-time. Enter WebSockets and WebRTC.

*

*WebSockets are persistent duplex (two-way) connections between a server and a client which allow the client to send and receive much smaller "requests", basically only the app-specific data, to the server. Unlike HTTP this a persistent connection, which means that you don't need to send additional data with each request (headers for ex.). Another great thing is that WebSockets are supported in all major browsers and are currently becoming a de-facto standard for real-time comms.

*WebRTC - this is a peer-to-peer connection protocol where you connect to other clients for communication and not directly to the server. This pretty much means that your players would connect directly to each other and this would be even faster as they would not be connecting to a centralized location, which could suffer from performance issues or network degradation. It is supported by most modern browser, with IE trailing behind.
So these are the best available options for creating real-time services/applications. I'd recommend using WebSockets as it is more mature and has a bigger adoption at the moment. If you have your mind set on using PHP you can checkout some of the ready-made libraries for working with websockets such as http://socketo.me/


text:
Q: Design for amplifier make/model settings database? As a personal project, I essentially want to create a web application that allows users to submit amplifier settings for specific tones, which will render images and create an archive of guitar tones for specific amps.
I know that I first should design a database to support this web application.  After reading about relational databases and normalization, I have started to draft a database, but I've confused myself in the process.
So far, I've created the following tables:
tbl_Makes (list of amplifier brands):

tbl_Models (list of amplifier models, linked to their brand by the MakeID field):

But I am at a bit of a loss on how to design the remaining table(s).  I assume I will need a tbl_Settings table which contains both MakeID, and ModelID as foreign keys, but also some sort of column(s) to hold the amplifier settings.  The issue I'm currently facing is that most amplifiers have different settings, so I'm not sure how I'd handle that.  Would I need an additional table for each amplifier model to hold its specific settings?
Any suggestions?  Is my current database design ok, or does it need to be modified?

A: You may be breaking it down too far.  A table with Make and Model may be good enough.  However with your current design, you would make the MakeID a Foreign Key to the Make table's Primary Key (ID).
Then you'd have an "settings" table which has a ModelID, attribute, and value - since each AMP may have different attributes.  You may want to have an attribute table and use attributeID if you want to control the attribute types (with a PK and FK relationship).
Oh, and for the love of God, please don't prefix tables with tbl_


text:
Q: How to use "move2kube collect" command? I am new to movetokube tool. I am struggling to understand how the move2kube collect command works. The web site doesn't have any documentation on this command which is very surprising. I want to get all the applications installed in the Cloud Foundary cluster and I hope move2kube does this through move2kube collect command (or not?). I am not sure sure whether I have to execute the move2kube command on the Cloud Foundary cluster or K8 cluster. Please help!
I am executing the following move2kube command on a CF cluster

move2kube collect

I see the following error
INFO[0000] Begin collection
INFO[0000] [*collector.ClusterCollector] Begin collection
WARN[0001] Error while fetching storage classes using command [/usr/local/bin/kubectl get sc -o yaml]
ERRO[0001] API request for server-group list failed
WARN[0001] Failed to retrieve preferred group information from cluster
WARN[0001] Failed to collect using the API. Error: "Get \"https://cluster02.someserver.com:8443/api?timeout=32s\": failed to refresh token: oauth2: cannot fetch token: 401 \nResponse: {\"error\":\"unauthorized\",\"error_description\":\"Bad credentials\"}" . Falling back to using the CLI.
ERRO[0001] Error while running kubectl api-resources: exit status 1
WARN[0001] Failed to collect using the CLI. Error: "exit status 1"
WARN[0001] [*collector.ClusterCollector] failed. Error: "exit status 1"
INFO[0001] [*collector.ImagesCollector] Begin collection
INFO[0001] [*collector.ImagesCollector] Done
INFO[0001] [*collector.CFContainerTypesCollector] Begin collection
WARN[0002] Error while getting buildpacks : exit status 1
WARN[0002] Unable to collect buildpacks from cf instance : exit status 1
ERRO[0002] exit status 1
WARN[0002] Unable to find used buildpacks : exit status 1
INFO[0004] [*collector.CFContainerTypesCollector] Done
INFO[0004] [*collector.CfAppsCollector] Begin collection
ERRO[0004] exit status 1
WARN[0004] [*collector.CfAppsCollector] failed. Error: "exit status 1"
INFO[0004] Collection done
INFO[0004] Collect Output in [/home/mytest/move2kube/samples/m2k_collect]. Copy this directory into the source directory to be used for planning.

A: From the move2kube GitHub page:

Usage
One step Simple approach
move2kube transform -s src
Two step involved approach

*

*Plan : Place source code in a directory say
src and generate a plan. For example, you can use the samples
directory. move2kube plan -s src

*Transform : In the same directory,
invoke the below command. move2kube transform
Note: If information about any runtime instance say cloud foundry or kubernetes cluster
needs to be collected use move2kube collect. You can place the
collected data in the src directory used in the plan.

And from the article Introducing Konveyor Move2Kube on Medium:

Move2Kube Usage
Move2Kube takes as input the source artifacts and
outputs the target deployment artifacts.
Move2Kube accomplishes the
above activities using a 3 step approach of

*

*Collect : If runtime
inspection is required, move2kube collect will analyse your runtime
environment such as cloud foundry or kubernetes, extract the required
metadata and output them as yaml files in m2k_collect folder.

...


text:
Q: Column size in Android GridView How to do diferent size columns in Android GridView.
I need one long fild for name and nine short for numbers.
 GridView XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="700dp"
        android:numColumns="10" >
    </GridView>
</RelativeLayout>

Item XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="match_parent"
 android:layout_height="match_parent"

 android:orientation="vertical">

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
   />

</LinearLayout>

A: do onething, take one xml having parent linear layout, with in the linear layout take sub linear layouts, with in the each linear layout we can design what you require,
hope this will help to u.


text:
Q: Normalize a list with jsons to a dataframe in steps I have a problem. I have a list with JSONs. I want to create a complete dataframe in steps. My idea is, for example: My list contains 100 elements. I want to say the size of the steps should be 25. So I say len(list) / size = 4 = 100 / 25. I have 4 runs of the for loop and 4 times of concat the small dataframe to the complete. For the MVP I have build a list, with 4 elements and with a step of 2. So every loops it should contactened two elements.
At the end my dataframe_complete contains only two rows. What is the problem for that?
The first loop should contain my_Dict and my_Dict2 the second my_Dict2 and my_Dict2. So the list should go from 0-1 and from 2-3. So every loop run should contain two elements.
import pandas as pd

my_Dict = {
'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }
 }

my_Dict2 = {
'_key': '2',
 'group': 'test',
 'data2': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail2': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }
 }

list_dictionaries = [my_Dict, my_Dict2, my_Dict2, my_Dict2]

df_complete = pd.DataFrame()

size= 1
for i in range((len(list_dictionaries) // size)):
    print(i)
    df = pd.json_normalize(list_dictionaries[i], sep='_')
    df_complete= pd.concat([df_complete, df])

print(df_complete)

[OUT]

    _key    group   type    code    conType flag    createdAt   currency    detail_selector_number  detail_selector_isTrue  detail_selector_requirements    detail2_selector_number detail2_selector_isTrue detail2_selector_requirements
0   1   test        007 1   None    2021    EUR 12312   True    [{'type': 'customer', 'requirement': '1'}]  NaN NaN NaN
0   2   test        007 1   None    2021    EUR NaN NaN NaN 12312   True    [{'type': 'customer', 'requirement': '1'}]

Expected output
    _key    group   type    code    conType flag    createdAt   currency    detail_selector_number  detail_selector_isTrue  detail_selector_requirements    detail2_selector_number detail2_selector_isTrue detail2_selector_requirements
0   1   test        007 1   None    2021    EUR 12312   True    [{'type': 'customer', 'requirement': '1'}]  NaN NaN NaN
1   2   test        007 1   None    2021    EUR NaN NaN NaN 12312   True    [{'type': 'customer', 'requirement': '1'}]
2   2   test        007 1   None    2021    EUR NaN NaN NaN 12312   True    [{'type': 'customer', 'requirement': '1'}]
3   2   test        007 1   None    2021    EUR NaN NaN NaN 12312   True    [{'type': 'customer', 'requirement': '1'}]

A: The problem most likely arose that at the first iteration an empty dataframe was obtained.Since the list_dictionaries[:0] slice was used. Try the code below.
list_dictionaries = [my_Dict, my_Dict2, my_Dict2, my_Dict2]
df_complete = pd.DataFrame()

for i in range(0, len(list_dictionaries)):
    df = pd.json_normalize(list_dictionaries[i], sep='_')
    df_complete = pd.concat([df_complete, df])

print(df_complete.reset_index())

Is that what you need?
If you need two dictionaries at each iteration:
for i in range(0, len(list_dictionaries), 2):
    print(list_dictionaries[i:i+2])

If you want to connect all normalized frames in two iterations.
for i in range(0, len(list_dictionaries), 2):
    df1 = pd.json_normalize(list_dictionaries[i], sep='_')
    df2 = pd.json_normalize(list_dictionaries[i+1], sep='_')
    df_complete = pd.concat([df_complete, df1, df2])

df_complete = df_complete.reset_index()
print(df_complete)

Or in general, so as not to create unnecessary four dictionaries in 'list_dictionaries'.
It is necessary to pass in a loop a list of the necessary elements at each iteration and take indexes from them.The first iteration is the first and second[0, 1] dictionary, the second is both second[1, 1] dictionaries.
list_dictionaries = [my_Dict, my_Dict2]
df_complete = pd.DataFrame()
for i in [[0, 1], [1, 1]]:
    df1 = pd.json_normalize(list_dictionaries[i[0]], sep='_')
    df2 = pd.json_normalize(list_dictionaries[i[1]], sep='_')
    df_complete = pd.concat([df_complete, df1, df2])

df_complete = df_complete.reset_index()


text:
Q: Elastic search preference set to custom value, document still returned from different shards I'm having issue with scoring: when I run the same query multiple times, each documents are not scored the same way. I found out that the problem is well known, it's the bouncing result issue.
A bit of context: I have multiple shards across multiple nodes (60 shards, 10 data nodes), all the nodes are using ES 2.3 and we're heavily using nested document - the example query doesn't use them, for simplicity.
I tried to resolve it by using the preference search parameter, with a custom value. The documentation states:

A custom value will be used to guarantee that the same shards will be used for the same custom value. This can help with "jumping values" when hitting different shards in different refresh states. A sample value can be something like the web session id, or the user name.

However, when I run this query multiple times:
GET myindex/_search?preference=asfd
{
  "query": {
    "term": {
      "has_account": {
        "value": "twitter"
      }
    }
  }
}

I end up having the same documents, but with different scoring/sorting. If I enable explain, I can see that those documents are coming from different shards.
If I use preference=_primary or preference=_replica, we have the expected behavior (always the same shard, always the same scoring/sorting) but I can't query only one or the other...
I also experimented with search_type=dfs_search_then_fetch, which should generate the scoring based on the whole index, across all shards, but I still get different scoring for each run of the query.
So in short, how do I ensure the score and the sorting of the results of a query stay the same during a user's session?

A: Looks like my replicas went out of sync with the primaries.
No idea why, but deleting the replicas and recreating them have "fixed" the problem... I'll need some investigations on why it went out of sync
Edit 21/10/2016
Regarding the "preference" option not being taken into account, it's linked to the AWS zone awareness: if the preferred replica is in another zone than the client node, then the preference will be ignored.
The differences between the replicas are "normal" if you delete (or update) documents, from my understanding the deleted document count will vary between the replicas, since they're not necessarily merging segments at the same time.


text:
Q: See .sql file in Tableau Public I am new to Tableau and I cannot figure out how to get the application to open a .SQL file. It is a query that I have to explain but I don't know how to display the tables in it.

A: Tableau public cannot connect to sql databases. See the docs here for more information. https://community.tableau.com/docs/DOC-9135#subhead20


text:
Q: how to get no data message in sql query I am using some condition in where clause. for some condition some o/p data will come and for some there will not b any o/p data. so when there will b no o/p data I want to print a msg like "No data Available" ..... how can do that?
here is my query ......
SELECT
     "CUSTOMERS"."CUSTOMERNAME",
     "PRODUCTS"."PRODUCTNAME",
     "ORDERDETAILS"."QUANTITYORDERED",
     "ORDERS"."STATUS"
FROM "ORDERS"
INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus}

A: You may use the below Query if You want to do it in Databse side only otherwise you may do it in your Front end tool
Declare @count INT

SELECT
     @count=Count("CUSTOMERS"."CUSTOMERNAME")
FROM "ORDERS"
INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus}

IF @count>0
Begin
   SELECT
    "CUSTOMERS"."CUSTOMERNAME",
    "PRODUCTS"."PRODUCTNAME",
    "ORDERDETAILS"."QUANTITYORDERED",
    "ORDERS"."STATUS"
   FROM "ORDERS"
   INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
   INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
   INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
   WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus}
END
ELSE
BEGIN
  PRINT 'NO DATA AVAILABLE...'
END

Edit: Otherwise you may use the query like
Declare @Temptbl Table
(
CUSTOMERNAME Varchar(250),
PRODUCTNAME Varchar(250),
QUANTITYORDERED Int,
STATUS Varchar(50)
)

Insert into @Temptbl(CUSTOMERNAME,PRODUCTNAME,QUANTITYORDERED,STATUS)
SELECT
    "CUSTOMERS"."CUSTOMERNAME",
    "PRODUCTS"."PRODUCTNAME",
    "ORDERDETAILS"."QUANTITYORDERED",
    "ORDERS"."STATUS"
   FROM "ORDERS"
   INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
   INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
   INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
   WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus}
IF (Select Count(*) from @Temptbl)>0
Begin
   Select * from @Temptbl
END
ELSE
BEGIN
    PRINT 'NO DATA AVAILABLE...'
END

A: use Exists to Check The data is avail or not
if exists (SELECT
    1
   FROM "ORDERS"
   INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
   INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
   INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
   WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus})
begin
 SELECT
    "CUSTOMERS"."CUSTOMERNAME",
    "PRODUCTS"."PRODUCTNAME",
    "ORDERDETAILS"."QUANTITYORDERED",
    "ORDERS"."STATUS"
   FROM "ORDERS"
   INNER JOIN "CUSTOMERS" ON "ORDERS"."CUSTOMERNUMBER" = "CUSTOMERS"."CUSTOMERNUMBER"
   INNER JOIN "ORDERDETAILS" ON "ORDERS"."ORDERNUMBER" = "ORDERDETAILS"."ORDERNUMBER"
   INNER JOIN "PRODUCTS" ON "ORDERDETAILS"."PRODUCTCODE" = "PRODUCTS"."PRODUCTCODE"
   WHERE "CUSTOMERS"."CITY" = ${LoadCity} AND "ORDERS"."STATUS" = ${LoadStatus}
end
else
 begin
 PRINT 'NO DATA AVAILABLE...'
end


text:
Q: Why is the string output using echo PHP missing the space after the first word when opened in MS Edge? When I run the php script the space is removed automatically from the string printed using echo.
I tried to use echo somewhere else and the space is there. Only in this case the space is removed.
Why does PHP remove the space after the first word when returning a string in a function
someone said that the problem is with the MS edge browser. It is true, the code works in IE. but still why does it not work in MS edge but sometimes does?
<?php
    if (date("D") == "Fri"){
        echo "Have a nice weekend!";
    }
    else {
        echo "Have a nice day!";
    }
?>

I expected Have a nice day! , but the output is Havea nice day!
why is the first space not showing?!

A: You need to execute your Code within the HTML Tags to make it work.
Otherwise the Browser tries to "wrap" some kind of HTML around it automatically - which is some kind of buggy.
The following would work just fine:
<html>
<head>
   <title>test</title>
</head>
<body>
   <?php
       if (date("D") == "Fri"){
           echo "Have a nice weekend!";
       }
       else {
           echo "Have a nice day!";
       }
   ?>
</body>
</html>