Admin links issue

Question: So if I am in my admin section
http://example.com/admin/content
and I try and click on
http://example.com/admin/structure
The url is
http://example.com/admin/admin/structure
I set the base_url but it keeps happening, is there a setting somewhere (in the table or in the admin) where I can edit it?
The base url is
<code>$base_url = 'http://example.com';</code>
Comment: I guess you've got something in .htaccess/vhost config doing the redirect, or a dodgy contrib module/configuration to do with the same. Drupal doesn't have that behaviour out of the box so you need to hunt down what's different about your site
Comment: The base url is fine, updated the post.
Answer: And at the front of this problem is not present? If this problem only in the admin area, then you may have incorrectly configured htaccess or problem in a certain module. Because server settings I think this should not be, but it can be. Therefore, try to deploy the site on another server environments.
Comment: It has been deployed on a digital ocean droplet and locally with the same issue.
Comment: Start disabling modules one-by-one until you find the culprit @LeBlaireau, it's very unlikely anyone will be able to guess what the issue is from here
Comment: Cheers Clive, you are right it is going to be a process of elimination!
Comment: Well, to solve the problem, you can then disconnect modules. But the fact that they have a problem. htaccess tried to rule?

Admin links issue


Harmonic Resonance and The Human Body

Question: I realize that this is going to be looked at as an odd question but I was wondering if there is a certain Tone or Harmonic that causes a human being discomfort? Im not interested in volume per se but more in the frequency in Hertz (Urrgyh! No pun intended...) Ideally it would be a very low frequency beyond the ability of the human ear to hear it that would travel unimpeded through most solid objects and not deteriorate. Think along the Lines of Eric Cartmans "Brown Note" in South Park..
Comment: I reckon every body (and maybe everybody) has a natural sympathetic vibration frequency, just as the apocryphal glass shattering opera singer story. So, yes, but maybe not discomfort or pain- too subjective- but an awareness at least.
Comment: There are various parts of the body that can resonate, and do, at different frequencies, but certainly no single note that "the body" will resonate to.

For example I often find my lungs resonate along with certain bass frequencies, and often find my trousers or jacket sleeves vibrate along with strong bass..
Comment: Cue the ever-resurgent "brown note" theorists :-)
Answer: I've been subjected to many different high-volume low-frequency sounds. In my personal experience, it's the volume that makes it uncomfortable, and there never seemed to be any particular frequency that was more uncomfortable than any other.
The most obvious areas of discomfort were my teeth and my eyes, not any part of my digestion. Yes, I have been in the presence of bass sounds so loud that my vision blurred and my teeth rattled if I didn't open my jaw slightly. Some venues go way overboard with the subwoofers. One time an engineer with lots of live sound experience told me that we tend to involuntarily clench muscles in the presence of very loud bass sounds, so the sound literally makes us tired. I'm not sure if that's true or not.
I've never felt digestive discomfort or anything like that from high volume, low frequency sounds. I recall reading that scientifically, the existence of a "brown note" in terms of the South Park sense has been disproved. At the same time, there has been military research on incapacitating sounds, and while I don't think there are any resonant frequencies of the human body related to that, it's possible that sound at high enough intensity could cause medical issues for a human, including voiding of oneself. Again, not because of resonance.
See this Wikipedia article.
Comment: *...told me that we tend to involuntarily clench muscles in the presence of very loud bass sounds, so the sound literally makes us tired.* New weight loss method? Burn 400 calories in just 15 minutes on the amazing new Bass Reflex!

Harmonic Resonance and The Human Body


Jenkins : Sending success email only once a day (though the job is running @hourly)

Question: I have a jenkins job configured to run hourly. I want the success build mail to be sent as email only once a day. Email-Ext gives me the option to send emails for all success , failures etc. But what i wanted is the ability to send success email only once.
Comment: http://jenkins-ci.361315.n4.nabble.com/generating-a-daily-weekly-report-on-job-status-by-mail-td3766477.html This looks like a solution to me(i haven't tried it though)
Comment: Do you want an email to be sent at a specific time every day? And should that mail be sent only if the job is successful or you want the status of the job?
Comment: I wanted a email to be sent at specific time every day and only if its successful.
Comment: @Rajesh just curious -- how did you configure it to run hourly? Was it using @hourly?
Comment: Would it be acceptable to only send the email on failure? No email, assume all is good.
Answer: This is an old question and you have probably found your own workaround already, but I had a similar need and I thought I'd share my solution anyway.  What I was trying to do was generate a once-daily summary email of jobs in a failed state.   This is fundamentally very similar to sending a once-daily success report for a single job.
My solution uses a Groovy build step coupled with the Email-Ext plugin's pre-send script feature.  I got the idea from the Nabble thread referenced in the comments above.  See also Email-Ext Recipes on the Jenkins site.
Here's the initial groovy script that determines which builds are failed, configured under Execute System Groovy Script. You could do something similar to determine whether your build succeeded or failed:
// List the names of jobs you want to ignore for this check
ignore = [ ]

// Find all failed and unstable jobs
failed = hudson.model.Hudson.instance.getView("All").items.findAll{ job ->
  job.getDisplayName() != "Daily Jenkins Job Nag" &&
  !ignore.contains(job.getDisplayName()) &&
  job.isBuildable() &&
  job.lastCompletedBuild &&
  (job.lastCompletedBuild.result == hudson.model.Result.FAILURE ||
   job.lastCompletedBuild.result == hudson.model.Result.UNSTABLE)
}

// Log the job names so the build results are legible
failed.each { job ->
  println(job.getDisplayName() +
          " " + job.lastCompletedBuild.result +
          " at build " + job.lastCompletedBuild.number +
          " (" + job.lastCompletedBuild.timestamp.format("yyyy-MM-dd'T'HH:mm ZZZZ") + ")");
}

// Return failure if there are any failed jobs
return failed.size

Then, down in the Editable Email Notification section, I set the Email-Ext plugin to notify on failure.  I set Content Type to Plain Text (text/plain), left Default Content empty, and set the following as the Pre-send Script:
failed = hudson.model.Hudson.instance.getView("All").items.findAll{ job ->
  job.getDisplayName() != "Daily Jenkins Job Nag" &&
  job.isBuildable() &&
  job.lastCompletedBuild &&
  (job.lastCompletedBuild.result == hudson.model.Result.FAILURE ||
   job.lastCompletedBuild.result == hudson.model.Result.UNSTABLE)
}

def output = StringBuilder.newInstance()

output << "\n"
output << " \n"
output << "
Jenkins reports the following failed jobs:
"
output << "
\n"

failed.each { job ->
  url = hudson.model.Hudson.instance.rootUrl + job.url + "/" + job.lastCompletedBuild.number + "/"
  output << "
"
  output << "" + job.displayName + ""
  output << " " + job.lastCompletedBuild.result
  output << " at build " + job.lastCompletedBuild.number
  output << " (" + job.lastCompletedBuild.timestamp.format("yyyy-MM-dd'T'HH:mm ZZZZ") + ")"
  output << "
\n"
}

output << "
\n"
output << " \n"
output << ""

msg.setContent(output.toString(), "text/html")

The key is that you have access to the msg object, which is a MimeMessage. You can set the content of the MIME message to whatever you want.
In this case, I'm generating a list of failed jobs, but in your case it would be whatever message you want to receive for your once-daily success report.  Depending on what you need, you could have Email-Ext send a result for every build rather than just for failed builds.
Answer: How about suppressing e-mails if insufficient time has lapsed since the previous e-mail?  Although not precisely what was requested, a pre-send script like this might be worth considering for its simplicity?
if (build.result != hudson.model.Result.SUCCESS) {
    cancel = true;
}
else {
  try {
    long minEmailGap = 1000 * 60 * 60 * 16; // 16 hours in milliseconds

    File file = new File("/TimestampForMyJob.txt");

    if (file.exists() == false) {
      file.createNewFile();
    }
    else {
      long currentTime = (new Date()).getTime();

      if (file.lastModified() + minEmailGap > currentTime) {
        cancel = true;
      }
      else {
        file.setLastModified(currentTime);
      }
    }
  }
  catch(IOException e) {
    // We can't tell whether the e-mail should be sent out or not, so we do nothing
    // and it just gets sent anyway - probably the best we can do with this exception.
  }
}

Answer: Well, there is no plugin that can do that for you. The default email feature in Jenkins is very simple and it works fine. There is Email-ext plugin though, and this one can do lot more for you.
First of all, with Email-ext, you can configure a specific trigger to send the email notification - it can be on success or failure, which is similar to the default behaviour of Jenkins. But then you have the more refined one, like First failure and Still failing. This will give you a great deal of control on when and to whom (Recipients list, Commiter or Requester) your Jenkins will send an email. In my case a good configuration here will help a lot with email traffic generated by Jenkins. And you can send specific emails in specific situation to specific list of people - great!
The other option, if you really do not need that level of control and want to just to limit the email traffic to one summary per day is to set up a mailing list. Most mailing list engines will let you send a daily digest of all email traffic to the list. It should be enough, although I really do not feel like it is actually a good option on the long term. I would definitely give a try to Email-ext plugin.
Comment: digest email is a good idea but it looks like a workaround to me . Currently i have configured 2 jobs in my jenkins - one that runs every hour and the other one that runs only at a specific time so that it sends only one success email
Comment: It always will be a workaround. Let's face it - there is no feature like that. BUT you can write your on plugin to do whatever you want it to do. Still, besides the regular features and the extended email plugin features there is not much you can do *out-of-the-box*


How to run CREATE TABLE migrations ignoring foreign keys that do not exist yet on Rails?

Question: I have a table that has 3 foreign keys to other table using the references statement. But rails won't let me run the migration due that this is the first table I'm creating and those 3 foreign keys don't exist yet. Is there any way to make this easy?. Thanks!
Answer: Remove the foreign key from your table. You can do this completely by by remove the statement for the referenced table from you migration. Or you can change the your t.references other_table or t.belongs_to other_table to t.integer other_table_id. I would suggest just completely removing that column. Once you have the other tables you can add a reference in another migration.
add foreign key
add_foreign_key :table, :other_table

Comment: You can just create it how ever you want an replace it with the line above on the inside. `rails g migration AddUsersBooks`
Comment: Thanks! which is the command to generate migration to add foreign key by console??
Comment: Thanks, perfect answer xD


Two overlapping ListBoxes. Selection problem

Question: I'm trying to display shapes in two separate Listboxes occupying the same space. I've set the Background to both Transparent and {x:Null} but the mouseclick is still getting captured by the topmost Listbox so I can't select any shapes from the underlying ListBox.
Here is some sample code reproducing the problem.
<Grid>

    <ListBox Background="{x:Null}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Background="{x:Null}"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="Transparent">
                    <Ellipse Width="100" Height="100" Stroke="Blue" StrokeThickness="10"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        1
    </ListBox>

    <ListBox Background="{x:Null}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Background="{x:Null}"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemContainerStyle>

        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Ellipse Width="100" Height="100" Stroke="Blue" StrokeThickness="10"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        1
    </ListBox>
</Grid>

This is how I solved this problem for now but I'm more than open for other suggestions :) I enabled hittesting on the Grid and disabled it for both ListBoxes. Then I did the hittesting in the event handler instead
<Grid MouseDown="Grid_MouseDown"
      IsHitTestVisible="True"
      Background="Transparent">

    <ListBox Background="Transparent"
             IsHitTestVisible="True"
             ..>
    </ListBox>

    <ListBox Background="Transparent"
             IsHitTestVisible="True"
             ..>
    </ListBox>
</Grid>

Event handler and hittesting
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
    Grid grid = sender as Grid;
    Point ptCurrent = e.GetPosition(grid);
    VisualTreeHelper.HitTest(grid, null, new HitTestResultCallback(HitTestCallback), new PointHitTestParameters(ptCurrent));
}
public HitTestResultBehavior HitTestCallback(HitTestResult htrResult)
{
    ListBoxItem listBoxItem = GetVisualParent<ListBoxItem>(htrResult.VisualHit);
    if (listBoxItem != null)
    {
        listBoxItem.IsSelected = true;
        return HitTestResultBehavior.Stop;
    }
    return HitTestResultBehavior.Continue;
}
public T GetVisualParent<T>(object child) where T : Visual
{
    DependencyObject c = child as DependencyObject;
    while ((c != null) && !(c is T))
    {
        c = VisualTreeHelper.GetParent(c);
    }
    return c as T;
}

Comment: Why don't you have all the shapes in a single listbox?  It seems really unlikely that the two-listbox approach will ever get you what you want.
Comment: That's my last out.. I'm dispalying items on top of a map and they don't share the same data at all so that's why I'm using two ListBoxes. The ItemsSource is DataTables
Answer: You can bind multiple sets of data to a single ListBox by using a CompositeCollection as the items source:
<ListBox ...>
  <ListBox.ItemsSource>
    <CompositeCollection>
      <CollectionContainer Collection={Binding ...}" />
      <CollectionContainer Collection={Binding ...}" />
    </CompositeCollection>
  </ListBox.ItemsSource>
</ListBox>

You can then use data templates to control the appearance of different data types. You can either use implicit data templates or you can use an ItemTemplateSelector.
For more information about using and binding to a CompositeCollection, see this resource: How do you bind a CollectionContainer to a collection in a view model?
Answer: You could bind your ListBoxes to a Visibility variable.  This way you can make the bottom box visible when you are in a situation where the bottom one would be selected and the top on collapsed and visa verse when you need the top one to be selected.
Comment: The problem is that both of my ListBoxes are visible all the time, thanks anyway


Variable size encrypted container

Question: Is there an application similar to TrueCrypt, but the one that can make variable size containers opposed to fixed-size or only-growing-to-certain-amount containers which can be made by TrueCrypt?
I want this container to be able to be mounted to a drive/folder, and the size of the outer container not be much different from the total size of all the files that I put into the mounted folder, while still providing strong encryption.
If to put it in other words, I want a program like truecrypt, which not only automatically grows the container if I put in new files, but also decreases it's size if some files are deleted.
I know there are some issues of course, and it would not work 100% as truecrypt, because it basically works on the sector level of the disk, giving all the filesystem-control to the OS, and so when I remove a file, it might as well be left there, or there might be some fragmentation issues that would stop just truncating the volume from working, but perhaps a program can be built in some other way? Instead of providing sector-level interface, it would provide filesystem-level interface? A filesystem inside a file which would support shrinking when files are deleted?
Comment: _"A filesystem inside a file which would support shrinking when files are deleted?"_ -- Zip/Rar/etc archive with encryption?
Comment: You understand that you would lose some of the security right?  The size alone may indicate to an evil person something about the contained files.
Comment: LazyOne, I didn't know archives could work in this way, I am going to study this.
Zoredache, yes, of course. As a small compensation for this, I would assume that any sane developer making such a solution would always use some kind of padding, making the outer size of the container grow/shrink in discrete steps, like a couple of megabytes perhaps.
Answer: On the Linux side, the encfs project seems to fit the bill.  The project page is here.  Basically, it's file-based (rather than volume-based) encryption, so that the encrypted files are stored individually.  There's a hidden directory with nonsense directory and file names.  Encfs loop mounts a decrypted view of that directory.  When you delete a file in the encfs mount, it will delete the file in the hidden directory, etc.
It's primarily Linux, but there are some instructions on how to build it for Mac OS X (I don't know how well it works), and there's an experimental Windows project called encfs4win that's trying to get its functionality over to there.  There's also a commercial product called Boxcryptor that purports encfs support in Windows.  I can't vouch for anything other than the Linux implementation, though.
Answer:
"A filesystem inside a file which would support shrinking when files
  are deleted?"

You might look into Virtual Machine Disk (VMDK)
(http://en.wikipedia.org/wiki/VMDK) which grows on demand (at least
when I use VirtualBox), and I think they can shrink too.
VMDK's can be encrypted, and/or you can put them inside another
encrypted container.
If you just need to grow a truecrypt image, you can try appending
random data to the end of the truecrypt file (after dismounting), then
remount to see if truecrypt now has a larger image. I haven't tested
this method, and from what I've read, it may not work on newer
versions of truecrypt.

Variable size encrypted container


How to get a list of G Suite users which are using Google Apps Script?


How to configure Spring Boot with common Entity class and multiple projects

Question: i have multiple project with common entity classes. So i created jar file of that common entity class and added this jar as library for multiple projects (right click on project -> property->libraries->Add external jars).
common entity folder under package
com.company.apmg.entity;
And the multiple project have the folder structure like
`com.company.apmg.usermanagement.v1`;
`com.company.apmg.shippingmanagement.v1`;
`com.company.apmg.billingmanagement.v1`;

here have the controller,service and repository files.
On compiling projects no issues found.
But running application it shows Entity class is Not a managed type.
How i can solve this issue...
I referred the google but no one could not solve my issue.
Answer: It is that you are creating different persistence units, which in turn creates different entity managers. So, try to scan the entity classes inside your project.
For instance, you can add a class PersistenceConfig like below.
@Configuration
@EnableJpaRepositories(basePackages = { "your.package.repositories" })
public class PersistenceConfig {
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("your.package.entities");

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }
@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver"); //com.mysql..cj.* is added on version 8 of the driver
    dataSource.setUrl("jdbc:mysql://localhost:3306/db");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    return properties;
}
}


Proving that in an infinite cyclic group order of every element is infinite

Question:
Prove that in an infinite cyclic group order of every element ($\ne e$) is infinite.

I have tried proving this way : If there exists an element of finite order, then it must generate a finite subgroup of $G.$ But this is not possible as by Lagrange's theorem, order of a subgroup must divide order of a group, which is not true here as order of $G$ is infinity.
Is this correct and complete ?
Comment: Try proving the contrapositive instead. Should be easier, now that I think about it. Then you may argue using Lagrange :)
Answer: It doesn't quite work, as there are infinite groups with elements of (any possible) finite order.
Instead, think that every element of your infinite cyclic group $\langle g \rangle$ is of the form $x = g^k$ for some $k$. What happens if $1 = x^ n = (g^k)^n$ for some $n > 0$?
Answer: This proof is invalid, since some infinite groups have finite subgroups.  E.g. $\mathbb{Z}_2 \times \mathbb{Z}$ has the subgroup $\mathbb{Z}_2 \times \{0\}$.
In an infinite cyclic group the elements are $$\{\ldots,g^{-3},g^{-2},g^{-1},1,g,g^2,g^3,\ldots,\}$$ for some generator $g$.
If $h \neq 1$ is in this group, then $h=g^k$ for some $k \in \mathbb{Z} \setminus \{0\}$.  So, the subgroup generated by $h$ has the underlying set $$\{\ldots,g^{-3k},g^{-2k},g^{-k},1,g,g^{2k},g^{3k},\ldots,\}.$$
Comment: ok, so as the set is infinite, order of $h$ must also be infinite. is that the logic behind ?
Comment: A subgroup $H$ of $G$ is proper if $H \neq G$ and $H$ is not the trivial group.  So, if $G$ is an infinite group, then $G$ is a subgroup of $G$ that is not proper; all other infinite subgroups would be proper.
Comment: That's right; the order of an element is the size of the group it generates.
Comment: ok, one side question, if a group is of infinite order, and it has a subgroup of infinite order. we call that subgroup proper or improper ?
Comment: Thanks Rebecca !! That was very helpful
Answer: That is not correct because Lagrange's theorem presumes the group to be finite, and you can't use it that way, specifically because you're not using the fact that is cyclic.
For example $$G=\mathbb{R}-\lbrace 0 \rbrace$$
$G$ is a group under multiplication and $H=\lbrace 1,-1\rbrace$ is a finite subgroup.
You're correct trying to use negation: if a element generates a finite subgroup, the it means that $g^k=1$ for some $k$. Is that possible if the group is cyclic?
Comment: I am still not able to think in the right direction
Answer: If you mean the infinite cyclic group $G := \{x^n | n\in \mathbb{Z}\}$. Then the proof would be by contradiction. Suppose there exists an element $y(\neq 1)\in G$ such that $y^n = 1$. But $y = x^m$ for some $m\in \mathbb{Z}$. Hence $1= y^n = (x^m)^n = x^{mn}$. But this implies G is finite, as then $G = \{x^{-mn+1},\ldots, x^{mn-1}\}$. Contradiction!


inferno-hyperscript hyperscript-helpers declaration error

Question: I'm using:

Inferno
webpack
typescript
hyperscript-helpers
hyperscript
inferno-hyperscript

I have this 3 code line:
import h from 'inferno-hyperscript';
import hh from 'hyperscript-helpers';
const html = hh(h);

this code give me this error:
TypeError: hyperscript_helpers_1.default is not a function
My package.json is:
{
  "name": "frontend",
  "version": "0.0.1",
  "private": true,
  "description": "Typescript inferno prove",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack-dev-server --inline"
  },
  "author": "Leonardo Saracini",
  "license": "MIT",
  "engines": {
    "node": "7.7.4"
  },
  "dependencies": {
    "@types/ramda": "^0.24.4",
    "classnames": "^2.2.5",
    "hyperscript": "^2.0.2",
    "inferno": "^3.6.4",
    "inferno-hyperscript": "^3.6.4",
    "hyperscript-helpers": "^3.0.3",
    "inferno-redux": "^3.6.4",
    "ramda": "^0.24.1",
    "redux": "^3.7.2"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.0",
    "awesome-typescript-loader": "^3.2.1",
    "css-loader": "^0.28.4",
    "ejs-loader": "^0.3.0",
    "file-loader": "^0.11.2",
    "html-webpack-plugin": "^2.29.0",
    "source-map-loader": "^0.2.1",
    "style-loader": "^0.18.2",
    "typescript": "^2.4.2",
    "webpack": "^3.3.0",
    "webpack-bundle-analyzer": "^2.8.3",
    "webpack-dev-server": "2.5.1"
  }
}

My webpack.config.js is:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
//var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// definePlugin takes raw strings and inserts them, so you can put strings of JS if you want.
var definePlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')),
  __PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false'))
});

module.exports = {
  entry: path.resolve(__dirname, 'src/index.ts'), //entrata da compilare. Se ne possono aggiungere molte creando vari profili
  output: {
    filename: 'bundle.js', //file di output dove mettere il compilato
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devServer: {
    hot: true, // Tell the dev-server we're using HMR
    contentBase: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
    devtool: "inline-source-map",
  plugins: [
        definePlugin,
    new webpack.LoaderOptionsPlugin({
      debug: true
    }),
    new HtmlWebpackPlugin({
      title: 'Prima prova',
      template: 'src/index.ejs'
    }),
    new webpack.HotModuleReplacementPlugin() // Enable HMR
    //, new BundleAnalyzerPlugin()
    ],
  module: {
    rules: [// rules was named loaders in webpack 1 or 2; but is be renamed "rules" in now
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
      {
        test: /\.ejs$/,
        loader: 'ejs-loader'
      },
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        options: {
          transpileOnly: true
        }
      },
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      {
        test: /\.js$/,
                enforce: 'pre',
        loader: 'source-map-loader'
      },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }, // inline base64 URLs for <=8k images, direct URLs for the rest
            { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      },
      { test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: [
          'file-loader'
        ]
      }

    ]
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json'] // note if using webpack 1 you'd also need a '' in the array as well
  }
};

My tsconfig.json is:
{
"compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": ["es6", "es7", "dom"],
    "types": [ "inferno" ],
    "noImplicitAny": true,
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "preserveConstEnums": true,
    "outDir": "./dist/",
    "listFiles": true,
    "sourceMap": true,
    "jsx": "preserve",
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": true,
    "experimentalDecorators": false,
    "noUnusedLocals": true,
    "strictNullChecks": true,
    "removeComments": false
},
"exclude": [ "node_modules" ],
"include": [
    "./typing.d.ts",
    "./src/**/*.ts",
    "./src/**/*.tsx"
],
"compileOnSave": false,
"formatCodeOptions": {
    "indentSize": 2,
    "tabSize": 2,
    "newLineCharacter": "\n",
    "convertTabsToSpaces": true,
    "insertSpaceAfterCommaDelimiter": true,
    "insertSpaceAfterSemicolonInForStatements": true,
    "insertSpaceBeforeAndAfterBinaryOperators": true,
    "insertSpaceAfterKeywordsInControlFlowStatements": true,
    "insertSpaceAfterFunctionKeywordForAnonymousFunctions": false,
    "insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false,
    "placeOpenBraceOnNewLineForFunctions": false,
    "placeOpenBraceOnNewLineForControlBlocks": false
},
"atom": {
    "rewriteTsconfig": true
}
}

My typings.json is:
{
  "dependencies": {
  "debug": "registry:npm/debug#2.0.0+20160723033700",
  "ramda": "registry:dt/ramda#0.0.0+20170322181526"
  },
  "globalDependencies": {
  "classnames": "registry:dt/classnames#0.0.0+20161113184211",
  "hyperscript": "registry:dt/hyperscript#0.0.0+20161005184000",
  "node": "registry:dt/node#7.0.0+20170322231424",
  "redux": "registry:dt/redux#3.5.2+20160703092728"
  }
}

I cannot find the right manner to declare this code.
I find a lot of examples using hyperscript and hyperscript-helpers on other framework like React and no examples mixing webpack, inferno and typescript.
Someone knows the right syntax?
The error was firing executing the line const html = hh(h);
best regards
Answer: The solution to this error's type is to change this tsconfig.json from:
{
"compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": ["es6", "es7", "dom"],

to:
{
"compilerOptions": {
    "module": "es6",
    "target": "es6",
    "lib": ["es6", "es7", "dom"],


Proof: are restriction to operators diagnolizable if the operator is?

Question: "Let $V$ be a vector space of finite dimension $n\ge1\ \ T:V\to V$ a linear operator and $S$ a T-invariant space of $V$. Consider the restriction $$T|_S:S\to S$$ and $$(T|_S)(w):=T(w) $$
If $T$ is a diagonal operator in $V$ prove that $T|_S$ will be diagolizable in $S$"
Ok so, as in matrix form the diagonal operator can be divided in "blocks" of  same eigenvalues, each block related to it`s eigenspace I thought about these blocks as T-invariant subspaces, and, as the matrix is diagonal the blocks must be diagonal too so the operator restricted to this eigenspaces would be diagonalizable.
My problem is basically how to work this ideas into the proof(Are them right?)
Thanks in advance.
Comment: Do you know that/how diagonalizability can be characterised using the minimal polynomial?
Comment: $\Pi_1^k(\mu_i-\lambda)^n $ (n at the power has a index i also), is it?
Answer: One way to turn that idea into a proof is to work in terms of a specific choice of eigenvectors which act as bases of the eigenspaces you mention.  To get there, I would use the characterization of a diagonalizable matrix as (taken from Diagonalizable Matrix)
<code>A matrix is diagonalizable if there exists a basis of V consisting of
eigenvectors of T. With respect to such a basis, T will be represented by a
diagonal matrix.
</code>
Now you can appeal to the definition of an eigenvector as well:
$$ Tv = \lambda v$$
to make statements about whether those eigenvectors are still eigenvectors of the restricted operator.
Answer: Ok, I came up with this trial now, and I'd like to know if it's acceptable in your opinion - my teacher is really strict when it comes to prove something:
Let $w\in S$ and $S=V(\lambda_k)$ a eigenspace of $T$ and $B=${$v_1,v_2,...,v_n $} a bases of eigenvectors of $V$ where $[T]_B$ is diagonal
As $S$ is a subspace of $V$ let $B^S=${$v_1,...,v_k $} be a bases of  $S$  $k\le n$.
By the definition of a eigenvector we have $$T(v)=\lambda v $$
And by the defiinition of a application of a restrict operator $$(T|_S)(w):=T(w)$$
If we take $w=\alpha_1v_1+...+\alpha_k v_k \rightarrow$
$T(w)=\alpha_1T(v_1)+...+\alpha_k T(v_k)$ and as all this $v_i$ are associated with the same eigenvalue $\lambda_k$ thus we have:
$T(w)=\lambda_k(\alpha_1v_1+...+\alpha_k v_k$) which in fact is in the subspace $S$ holding the definition of the strict operator
So $(T|_S)(w)=\lambda_k(\alpha_1v_1+...+\alpha_k v_k$)
Now at least, for a convenient choice  $w=v_i(1\le i \le k)$ as the  vectors of the bases $B^S$ we can see that:
$$(T|_S)(v_i)=\lambda_kv_i $$
definig eigenvectors of $T|_S$, hence it must be diagonalizable since it holds for every choice of $1\le i \le k$, the whole bases of $S$.
I think I may be missing something about algebraic-geometric multiplicity but at the same time I have the sensation that if $T(v)=\lambda v $ holds already it`d be kinda redundant.
Comment: Your proof looks fine to me.  I would point out in the beginning that B is a basis of eigenvectors.  You implicitly use that later, but that is the important thing about diagonalizable operators.
Answer: Yes, $T$ is diagonalizable iff for each eigenvalue $\lambda$ of $T$,$N(T-\lambda I)=N((T-\lambda I)^2)$ ($N(T)$ stands for null space of $T$).
And in any T-invariant subspace $W$,$N(T_W-\lambda I)=N((T_W-\lambda I)^2)$ still holds, so $T_W$ is diagonalizable.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/2062112)


Echoing admin menu child items

Question: When you click 'Structure' in Drupal admin the page displayed is a print of the child items of the 'Structure' menu item.
I imagine this behaviour is relatively simple to achieve? I have a custom menu item using hook_menu but what do I need to do in page_callback in order to achieve the same results?
Answer: <code>$items['admin/sponsorship'] = array(

    'title' => 'Sponsorship',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
);
</code>
Seems to have done the trick.

Echoing admin menu child items


Include txt file from dropbox to html file

Question: I have a txt file on my Dropbox account.
My webpage is hosted on a server and I can not upload files to it from home.
But I would like to insert some informations on my webpage and so I decided to write these notes on a txt file and upload it to my Dropbox.
Now, the problem is:

how to insert the txt file contents into my html file so that when I update the txt file simply using Dropbox, the webpage is also update?**

I have the file index.html and I tried to insert on it the tag
<?php file_get_contents("<address to my Dropbox file>"); ?>

which I found on other posts here. But nothing happens.
Answer: You need to share the file and get the public URL of it, and then use this url in the get call using jquery.
Take a look on this example from the Jquery.get documentation :

...

$.get('https://dl.dropbox.com/u/8032011/share/greetings.txt', function(data) {
  $('#result').html(data);
  alert('Load was performed.');
});

This link explains the use of public folder on dropbox : https://www.dropbox.com/help/16/en
Comment: take a look on this one : http://stackoverflow.com/questions/1458349/installing-jquery
Comment: take a look on this full example : https://github.com/hamilton-lima/javascript-samples/blob/master/jquery/le_arquivo_do_dropbox.html
Comment: for that you would need to keep loading the file or have another file with the last update :)
Comment: May I use the tag `` does not work.
Comment: Should I install something related to `Jquery`? I am only using my local apache server on my Linux machine.
Comment: It is working now. So I have to decide to use `php` or `html`. Since all my webpage was created in `html` I guess that I'll simply use your example to show the `txt` content on my page. Thanks.
Comment: The last question: Is it possible to reload the `html` page automatically when the Dropbox file is updated? So people don't need to press F5.
Answer: You can't run PHP scripts in HTML files, if your server supports PHP then change your file's extension to ".php" and that code will work.
 Otherwise (if you absolutely can't use PHP) you can still make this work by using embeded   javascript/jquery code that will load the dropbox file to your HTML page.
Comment: @Sigur You don't use the php file like that, I would recommend renaming `index.html` file to `index.php` , then you can simply use `file_get_contents()` function inside the HTML tag you want to fill in with dropbox data(exactly like you did in your original question.)
Comment: Thanks. I created now a `php` file with only this: `` How to use it on my `html` file?
Comment: If I use some css style it could affect the result? I don't know why but on a single `html` file with the code, everything is OK. But if I put the code on my file, nothing happens.
Comment: by code, did you mean CSS? anyway, I really don't think CSS has anything to do with your PHP code; unless you've done something wrong, which could be easily spotted if you edit your original question and put the whole `index.php` file here so we can see what's really going on.


Verificar se pessoa é maior de idade, em caso afirmativo deletá-la

Question: Preciso fazer uma consulta em banco de dados MYSQL para verificar se um usuário é maior de idade baseado em sua data de nascimento em relação à data atual.
Em caso de afirmativo o usuário deverá ser deletado da base de dados.
Comment: Então sugiro começar vendo o [histórico de buscas](https://pt.stackoverflow.com/search?tab=votes&q=%5bmysql%5d%20comparar%20datas) aqui do site mesmo, que possui várias perguntas que tratam da diferença entre datas no SQL e com isso você conseguirá ao menos definir um ponto de partida.
Comment: Aonde está a sua dúvida? O que você já tentou até então?
Comment: A dúvida é que nao sei como comparar a data atual com a data de nascimento para verificar se tem 18 anos ou não rsrs
Comment: Não faço nem ideia de onde começar
Answer: Primeiro, um exemplo de como obter um valor do tipo data no mysql.
SELECT STR_TO_DATE('2019-04-15', '%Y-%m-%d');

Exemplo de obter a diferença entre as data
SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');

Quanto ao DELETE, pode fazer assim:
DELETE FROM suaTabela WHERE TIMESTAMPDIFF(YEAR,'2002-05-01',CURDATE()) >=18;

É um bom norte. Bons estudos!
Comment: kkk eu teria feito o processo na linguagem de back-end


How do I make so my spinner target links to a website?

Question: Hey, I'm really new with android development just started a few hours ago. I need to make a application for a school project and it needs to be done soon.
So far have I made a spinner with some alternatives to choose from. But here is my problem.
How do I make so when I click on one of the targets listed in my spinner so it links to a webpage.
I don't know how to use "AdapterView.OnItemSelectedListener." or if it is necessary here or not.
I would be very thankful for some advices. thanks a head
Answer: You can try setting the onItemSelectedListener to your spinner:
EDIT:
<code>super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

  @Override
  public void onItemSelected(AdapterView<?> arg0, View arg1,
          int arg2, long arg3) {
      startActivity(new Intent(Intent.ACTION_VIEW,
             Uri.parse("http://yoururl.com")));
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {}

});
</code>
This will open the browser with your url.
Comment: Do I paste this in i src or in res- Layout/values?
And where do I write in the ID of the spinner lists target?
Thanks for help :)
Comment: You need to put this inside the Activity you have created in your src folder. Could you paste some of your code so I can more easily help you?
Comment: This is what I got under public void:

super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
Comment: I get syntax error saying: "Multiple markers at this line
 - Syntax error on token(s), misplaced construct(s)
 - Syntax error on token "setOnItemSelectedListener", = expected after this token" at spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
Comment: I've edited my answer, look at the code block. Be sure to create the Spinner-object from your layout before you set the listener.
Comment: Sorry for all the noobish questions but what would i write in the .xml file to create a spinner-object. I mean i already have a spinner with lots of objects on already but the "OnItemSelectedListener" still doesnt work im affraid :(
Comment: Take a look at this: http://developer.android.com/resources/tutorials/views/hello-spinner.html


the difference between 90° and 30° is 60°. then why is sine60° not equal to sine90°- sine30°?

Question: The difference between 90° and 30° is 60°. then why is sine60° not equal to sine90°- sine30°?
Comment: The difference between $5$ and $3$ is $2$. Then why is $2^2$ not equal to $5^2-3^2$?
Comment: $\sin$ is not a *linear* function, which may not be a satisfying answer, just repackaging the question into a form that has a common name. However, the most satisfying answer is probably just to compute what $\sin 90^\circ$ $\sin 30^\circ$, and $\sin 60^\circ$ are, and convince yourself they aren't equal. There is no reason that $\sin$ should be linear, a priori. Indeed many many functions are not linear.
Comment: Because $\sin(x-y)=\sin(x)-\sin(y)$ is not true.
Comment: Okay, I understand now. Thanks a lot everyone!
Answer: Because $\sin60^{\circ}=\frac{\sqrt3}{2}$, but $\sin90^{\circ}-\sin30^{\circ}=1-\frac{1}{2}=\frac{1}{2}$
and the contradiction in math does not exist.
Comment: @ Omar E. See my post. This is the answer.
Comment: Yes, but why is that? The difference between both points is still 60 degrees.

To be clear, I was asked to find the distance between a rotation that began at 90° to 30°. My instinct was to find the difference between the two (60°) then find the sine. What was wrong in my train of thought?
Answer: Because sine is not a linear function.
Comment: But $\sin0+\sin1=\sin(0+1)$.


mean hitting time of a level and growth rate of maximum process

Question: Let $X_t$ be the absolute value of Brownian motion starting at $0$, let $\tau_x$ be it's first hitting time of the level $x>0$, and let $M_t$ be it's running maximum up to time $t$. Suppose we knew that $E[\tau_x]=x^2$ and wanted to use this fact to get information on the growth rate of $E[M_t]$. Intuitively, since it takes an average of $x^2$ units of time to hit the level $x$, $M_{x^2}$ should be around $x$ on average. Hence, the growth of $E[M_t]$ should be of order $\sqrt{t}$. My question is how do you make this argument rigorous, preferably in a manner that generalizes to other processes beside Brownian motion.
Answer: I am assuming our Brownian motions start from $0$. It is a well-known theorem that $$P(M_t >x) = 2P(B_t>x).$$ This can be seen using the reflection principle. Let $\tau$ be a stopping time. Then the Brownian motion $B^*(t)$ reflected at $\tau$ is the Brownian motion up to $\tau$ after which it is reflected along the line $y=B_\tau$. Formally
$$
B^*(t) = B_t1_{t \le \tau} + (2B_{\tau}-B_{t})1_{\tau>t}
$$
It is known that $B^*(t)$ also has the distribution of the standard Brownian motion (show this!). Then
$$
P(M_t>x) = P(B_t>x) + P(\tau_x <t , B_t <x) = P(B_t>x) + P(B^*(t) >x) = 2P(B_t>x)
$$
You can obtain $E(M_t)$ by integrating the above over $x$ since $B_t$ is just  Nomal distribution with variance $t$.
Comment: While this is nice, it doesn't answer the question about using the order of growth of $E[\tau_x]$ in $x$ to determine the order of growth of $E[M_t]$ in $t$.
Comment: Well, one possible interpretations is $P(B_t>x) = P(\tau_x < t)$. Could you tell me what other process you have in mind? Because these two objects are not necessarily related in a nice way in all processes.


How to get Application path in spring MVC

Question: I am working in a spring mvc project which uploads an image and saves in the project folder which needs to be used in the project as .
The image file successfully comes to the controller but I'm unable to save the file in WebContent directory.
I would really appreciate help.
Regards Hari.
Item class
public class Item extends WebKinmelObject {
private String name;
private double price;
private String manufacturer;
private String description;
private String category;
private String imagePath;
private int quantity;
@Temporal(value=TemporalType.TIMESTAMP)
private Date addedDate;

public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
public String getManufacturer() {
    return manufacturer;
}
public void setManufacturer(String manufacturer) {
    this.manufacturer = manufacturer;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
private MultipartFile file;
public MultipartFile getFile() {
    return file;
}
@Transient
public void setFile(MultipartFile file) {
    this.file = file;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getImagePath() {
    return imagePath;
}
public void setImagePath(String imagePath) {
    this.imagePath = imagePath;
}
public int getQuantity() {
    return quantity;
}
public void setQuantity(int quantity) {
    this.quantity = quantity;
}
public Date getAddedDate() {
    return addedDate;
}
public void setAddedDate(Date addedDate) {
    this.addedDate = addedDate;
}

}
My controller goes like this.
@RequestMapping("admin/addItemAction")
public ModelAndView addItemAction(@ModelAttribute("item")Item formItem,HttpServletRequest req){
    MultipartFile uploadedFile=formItem.getFile();
    if(uploadedFile!=null){
        String fileName=uploadedFile.getOriginalFilename();
        try {
            //-- if uploaded file is empty
            if(fileName!=""){
                //String imagePath="/Users/hari/Documents/workspace/WebKinmel/WebContent/resources/upload/"+fileName;
                String imagePath="/Users/hari/git/local_WebKinmel/WebKinmel/WebContent/resources/upload/"+fileName;
                File f=new File(imagePath);
                formItem.setImagePath("/WebKinmel"+imagePath.substring(imagePath.indexOf("/resources")));
                formItem.setFile(null);
                FileOutputStream fos=new FileOutputStream(f);
                fos.write(uploadedFile.getBytes());
                fos.flush();
                fos.close();
                f.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("==>>The uploaded file cound not be saved");
        }
    }
    if(formItem.isPersisted()){

        // to be done if no image
        String fileName=uploadedFile.getOriginalFilename();
        if(fileName==""){
            Item i=(Item) WebKinmelServiceManager.find(formItem.getId(), Item.class);
            formItem.setImagePath(i.getImagePath());//transferring old image path if no image path found
        }
        Date date=new Date();
        formItem.setAddedDate(date);
        WebKinmelServiceManager.update(formItem);
    }
    else{
        Date date=new Date();
        formItem.setAddedDate(date);
        WebKinmelServiceManager.save(formItem);
    }
    System.out.println("object"+formItem+" saved");
    ModelAndView mav=new ModelAndView("admin/adminItem");
    addItemContent(mav);
    mav.addObject("recent", formItem);
    return mav;

}

I want to save the image in WebContent directory rather than saving in
'/Users/hari/git/local_WebKinmel/WebKinmel/WebContent/resources/upload/' directory
my servlet xml goes like this
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.hari.controller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>

</bean>
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<bean name="webkinmelProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
            <value>classpath*:webkinmel.properties</value>
    </property>
</bean>

Answer: As Shailendra said, you can use ServletContext to get real path of your context. Easiest way to get ServletContext is autoware it in controller class. For example:
    @Controller
    @RequestMapping("/")
    public class ExampleController{

        @Autowired
        ServletContext context;

    }

After that you can use context.getRealPath("/") in controller's methods to get root path of your app context. But, again, as Shailendra said, it will be better to use dedicated external folder instead of exploded war's folder.
I recommend you add property in you webkinmel.properties file with desired path:
webcontent.path=/Users/hari/git/local_WebKinmel/WebKinmel/

And use this property in you controller with spring injection:
@Controller
public class ControllerClass{

  @Value("${webcontent.path}")
  private String webcontentPath;

  ...
}

Or another way is pass property in config xml:
<bean name="myController" class="ControllerClass">
  <property name="webcontentPath" value="${webcontent.path}"/>
</bean>

To make folder accessible from browser, just add in you config xml:
<mvc:resources mapping="/web/**" location="file:${webcontent.path}"/>

For example you saved file hello.png to /Users/hari/git/local_WebKinmel/WebKinmel/. It will be accessible by url http://yourhost:8080/web/hello.png
Comment: Thank you shailendra but since i am using eclipse for development, it is giving me the output path as.
"/Users/hari/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WebKinmel/"

instead I need path something like
"/Users/hari/git/local_WebKinmel/WebKinmel/"

any idea :) ??
Comment: Could you please something about webkinmel.properties file. I am not so much familiar with that .
Comment: According to your servlet.xml you have _webkinmel.properties_ in classpath of the project. This file should contain properties as _name=value_. You can add any properties in to this file, and get it in controller classes.
Comment: I was just trying to, haven't added the file. don't know how to implement it
Comment: Okay got some idea to add value to properties file.. but how to access via controller
Comment: thank you. this comment solved my problem.
Answer: You can use ServletContext#getRealPath() to get the  path of the deployed/expanded WAR folder structure on the server file system.
Although saving an uploaded image inside the exploded war is not recommended. You should instead be using a dedicated external folder.
Comment: The package might not even be exploded.
Comment: @chrylis - yes you are right although most containers do create exploded structure but that cannot be depended upon, so it's always right to not add anything to the war content at runtime.
Comment: do you mean ==>ServletContext.getRealPath(), don't think ServletContext class has getRealPath() method, could you please elaborate :)
Comment: Please take a look at the doc in the link I have provided. I can see the method there.


What does the sentence "The only sub-algebras of $\mathbb{R}^{2}$ are $0,\mathbb{R}^{2},\mathbb{R}(0,1),\mathbb{R}(1,0),\mathbb{R}(1,1)$" mean?

Question: I started studying functional analysis a couple of days ago, I have
reached the Stone-Weierstrass theorem which is stated in my lecture
notes as

Let $X$ be a compact metric space, $A\subseteq C(X)$ a sub-algebra
  that contains the constant functions and separates between the points,
  then $\overline{A}=C(X)$

And the proof begins with a lemma that claims

The only sub-algebras of $\mathbb{R}^{2}$ are
  $0,\mathbb{R}^{2},\mathbb{R}(0,1),\mathbb{R}(1,0),\mathbb{R}(1,1)$

I don't understand the theorem statement and the notation in the lemma
- the notes never defined what an algebra or sub-algebra is (searching
"algebra" in Google yields many results and it seems there is
more than one meaning to this term) , and I am unfamiliar with the
notation $\mathbb{R}(0,1)$ etc'.
Can someone please explain, in this context, what is the meaning of
an algebra (or sub-algrbra) and of the notation ?
Answer: For any $\langle a,b\rangle\in\Bbb R^2$, $\Bbb R\langle a,b\rangle=\{\langle ra,rb\rangle:r\in\Bbb R\}$, so the last three sub-algebras in that list correspond to the $y$-axis, the $x$-axis, and the diagonal line $y=x$, respectively. The definition of algebra that you want appears to be this one: $\Bbb R^2$ under ordinary vector addition is an additive Abelian group, a ring (as a product of two rings), and an $\Bbb R$-module. You'll find the appropriate notion of sub-algebra at the link.
Answer: 'Algebra' and 'subalgebra' seem to be used in the sense of (associative commutative but not necessarily unital) algebras over $\mathbb{R}$. These are commutative rngs which are equipped with a compatible $\mathbb{R}$-vector space structure; more precisely, such a thing is a $\mathbb{R}$-vector space $A$ equipped with an extra binary operation $\times$ such that:

$\times$ is associative and commutative.
$(r x) \times y = x \times (r y)$ for all $x$ and $y$ in $A$ and $r$ in $\mathbb{R}$.
$(x + y) \times (z + w) = x \times z + x \times w + y \times z + y \times w$ for all $x$, $y$, $z$, and $w$ in $A$.

The notation $\mathbb{R} \vec{v}$ refers to the vector subspace spanned by $\vec{v}$. Notice that when $\vec{v} \times \vec{v} = \vec{v}$, the subspace $\mathbb{R} \vec{v}$ is automatically a subalgebra. It is not hard to check that the only such $\vec{v}$ in $\mathbb{R}^2$ are $(0, 0), (0, 1), (1, 0), (1, 1)$.
Answer: As for the statement of the theorem,

Let $X$ be a compact metric space, [...]

so far so good hopefully

[...] $A\subseteq C(X)$ a sub-algebra [...]

$C(X)$ refers to the set of continuous, real-valued functions on $X$. $A$ is a subset of $C(X)$ so the elements of $A$ are continuous, real-valued functions on $X$. A family of real functions $\mathscr{A}$ is an algebra if $f,g\in\mathscr{A}$ implies that each of $f+g\in\mathscr{A}$, $fg\in\mathscr{A}$ and $cf\in\mathscr{A}$ hold for all $c\in\mathbb{R}$. You can verify that $C(X)$ is an algebra. Then if $A\subseteq C(X)$ is an algebra, then we can say $A$ is a subalgebra of $C(X)$.

[...] that contains the constant functions [...]

So every constant function from $X$ to $\mathbb{R}$ is in $A$

[...] and separates between the points [...]

An algebra $\mathscr{A}$ of functions on a set $Y$ separates points if for each $x,y\in Y$ there exists $f\in\mathscr{A}$ such that $f(x)\ne f(y)$.

[...] then $\overline{A}=C(X)$.

$\overline{A}$ is the uniform closure of $A$, which means that it is the set of all functions $f$ such that $f$ is the limit of a uniformly convergent sequence of functions in $A$. So what this is really saying is that every element of $C(X)$ is the limit of a uniformly convergent sequence in $A$.


Bitbake how to downgrade version of glibc used?

Question: I need to downgrade the version of glibc in the project that is built by bitbake.
Currently, bitbake uses glibc2.28 for the project build. What do I need to do in order bitbake would use glibc2.24 in the build(instead glibc2.28)?
Answer: GLIBCVERSION is give in the file poky/meta/conf/distro/include/tcmode-default.inc. You can switch to morty branch as glibc_2.24 is available as part of morty branch of opemembedded. Updating version manually would require copying recipes of particular version and other adaptions for compatiblity


How to use yup validation on dynamic form using react-hook-form with useFieldArray

Question: I'm trying to create a dynamic form using react-hook-form's useFieldArray hook. The user should be able to add or remove fields, thus making it dynamic. I've looked at this tutorial for inspiration, but the missing piece is how to implement error validation to the state, which will be an array of objects: {email: string}[]. (The object will take more key/value pairs. I've left out the rest for simplicity.)
I've tried using yup as validation schema. It looks like this:
const schema = yup.array().of(
  yup.object().shape({
    email: yup.string().email().required(),
  }),
)

The implementation into react-hook-form is:
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm, useFieldArray, Controller } from 'react-hook-form'

const { register, control, handleSubmit, errors } = useForm({
  resolver: yupResolver(schema),
  mode: 'onChange',
})
const { fields, append, remove } = useFieldArray({
  control,
  name: 'users',
})

The form is more or less according to the tutorial in the link above.
When console logging the error object from useForm hook it is consistently giving an empty object {}. It doesn't seem like it works. I am probably missing something here. The question is what?
Answer: React Hook Form v7
yup with dynamic fields react hook form - useFieldArray
import { string, object, array } from 'yup';
const formSchema = {
  name: string().required("Name is required").min(7, 'Message'),
};

const schema = object({
  test: array()
   .of(object().shape(formSchema))
});

export default schema;

const methods = useForm({
  resolver: yupResolver(schema),
});

show the error

{errors?.test?.[index]?.name?.message}

Comment: Thanks for the code sample, Felipe. I got my dynamic fields validating now .
Answer: perhaps you want to use the context argument to switch your schema?

Context: This context object is mutable and will be injected into
resolver's second argument or Yup validation's context object.

import * as React from "react";
import { useForm } from "react-hook-form";
import * as Joi from "joi";

const validationSchema1 = Joi.object({
  username: Joi.string()
    .alphanum()
    .min(3)
    .max(30)
    .required()
});

const validationSchema2 = Joi.object({
  username: Joi.string()
    .alphanum()
    .min(3)
    .max(30)
    .required()
});

const App = () => {
  const [schemaContext, setSchemaContext] = useState({ schemaA: false })
  const { register, handleSubmit, errors } = useForm({
    context: schemaContext, // use the context switch here
    resolver: async (data, context) => {
      const { error, value: values } = context.is1 ? validationSchema1.validate(data, {
        abortEarly: false
      }) : validationSchema2.validate(data, {
        abortEarly: false
      });

      return {
        values: error ? {} : values,
        errors: error
          ? error.details.reduce((previous, currentError) => {
              return {
                ...previous,
                [currentError.path[0]]: currentError
              };
            }, {})
          : {}
      };
    }
  });

  const onSubmit = data => {
    console.log(data)
  };

  return (

resolver

      <form onSubmit={handleSubmit(onSubmit)}>
        Username
        <input type="text" name="username" ref={register} />
        {errors.username &&
errors.username.message
}
        <input type="submit" />
      </form>

  );
};

Answer: I used the useForm hook's resolver property method to identify the validation scheme I should use from the value of a field in my form.
The code below worked for my use case maybe it can help you
function formValidatorSchemaByPaymentModalityType(paymentModalityType?: ModalityTypes) {
    switch (paymentModalityType) {
        case ModalityTypes.CREDIT_CARD:
          return creditCardSchemaValidation;
        default:
        return defaultSchemaValidation;
    }
}

const methods = useForm({
    resolver: (data, context, options) => {
      const validatorSchema = formValidatorSchemaByPaymentModalityType(
        data.paymentType.value,
      )
      return yupResolver(validatorSchema)(data, context, options);
    },
});

Answer: I think you should specify your array name. like this:
{
  teammates: yupArray().of(
      yupObject().shape({
        email: stringSchemaBuilder("Email").email(),
        expertise: arraySchemaBuilder(false, "Expertise", true, 2, 5),
      })
  ),
};

where teammates is my array name

Answer: I had the same problem. I solved it by changing the controller name by referring to the register rules documentation!
Before:
`test[${index}].email`  // incorrect

After:
`test.${index}.email`  // correct

Answer: const { register, control, handleSubmit, formState: { errors } } = useForm({. resolver: yupResolver(schema),  mode: 'onChange' })

errors[`users[${index}].email`]


Handling an url inside flask rule

Question: I want my web to be able to handle URLs inside the rule,
just like:
http://127.0.0.1:5000/tiyee?url=https://tiyee.cn/iyu2
but getting an error:

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

I've tried with this code below but seems like it doesn't work
from flask import Flask, redirect
from tiyee import bypasser
app = Flask(__name__)

@app.route('/tiyee?url=<url>')
def _tiyee_redirect(url):
    bypassed_json = bypasser(url)
    return redirect(bypassed_json['bypassed_link'])

if __name__ == '__main__':
    app.run(debug=True, port=5000)

Q: Is there a way to add URL inside the route rule?
example:
example.com/tiyee?url=https://tiyee.cn/iyu2 and get the https://tiyee.cn/iyu2
Comment: what's your question?
Comment: is there a way to add url inside flask rule?
Comment: I suggest to pass it through query params like this https://stackoverflow.com/questions/71805698/how-to-make-a-put-request-with-a-full-url-link-as-a-path-parameter-using-flask/71805813#71805813
Answer: You are passing the url data in query. You will need to use request object to get the query value.
from flask import request
...

@app.route('/tiyee')
def _tiyee_redirect():
    _url = request.args.get('url')
    if _url is not None:
        bypassed_json = bypasser(_url)
        return redirect(bypassed_json['bypassed_link'])

Handling an url inside flask rule


Validation for yearly regression of students final grade

Question: I have data of a class of 50 students.  My dataset consists of historical data of students in previous years. Data includes presence, homework grades and final grade of previous 10 years (X, training dataset, has 500 elements).
I have a model trained with this data to predict the final grade.
What would be  more accurate way to validate my model? Training it with data a range of years (lets say 2005, 2010) and measuring the error of prediction of 2011 data. Or separating a random sample of the training data and estimating the prediction error of this validation sample?
Answer: Why are you not using year as a predictor for the model?  Maybe students are getting smarter (or dumber) over time -- hey, you never know!
As to your question of the more accurate way to validate, that is the tricky part.  You don't want to have a model that models the training data perfectly, but is so trained for that data, it returns bogus results for other data.  Generally, you want to reduce blocking effects in your training data.
In summary:

Recommend adding YEAR as a column in your data set.
Randomly pull a ValidationSet from the full data.  What % to pull is a matter of your choice.
Train your model on the leftover data.
Validate against your ValidationSet.

If you don't think you have enough data for separate test and validation sets, you might also consider cross-validation methods.
Comment: I can endorse most of this advice and like the "spirit" of it.  But I think most practitioners are finding more and more that your recommended method, "split-half" or "training set...test set" validation, is far inferior to more sophisticated cross-validation methods, such as k-fold, which with advances in software and computing power are becoming easier and easier to implement.


Adicionar um objeto a um arrey

Question: Estou tentando concatenar vários objetos para que ele formam um único arrey no meu projeto angular.
Irei mostra um pouco do código
selectFedd(user,feed){
      const key = user[0].userQueEuSigo
      feed.forEach(element => {
        if(element.keyUser == 2){
          this.publicacoes = [
              {
                keyUser:element.keyUser,
                id: element.id,
                user: element.user,
                photoUser:element.photoUser,
                photoPost: element.photoPost,
                curtidas: element.curtidas,
                comentarios: element.comentarios,
                pessoasQueCurtiu: element.pessoasQueCurtiu,
                totalComentarios:element.totalComentarios,
                like:element.like
              }
          ]
          console.log(this.publicacoes)
        }
      });
  }

essa função recebe como pare metro um arrey com vários objetos e nesse arrey eu seleciono apenas os que tem a keyUser == 2, ate ai tudo bem pois se eu executo so isso e dou um console.log, me retorna todas as 5 publicações que tem como keyUser o valor 2. Porem esse retorno são 5 objetos e eu estou com dificuldades para adicionar esses 5 objetos na minha variavel de nome publicacoes.
Vou deixar o meu publicacoes.model.ts aqui.
export interface Publicacao {
  keyUser: number,
  id: string,
  user:string,
  photoUser: string,
  photoPost: string,
  curtidas: number,
  comentarios: any[],
  pessoasQueCurtiu: any[],
  totalComentarios: number,
  like: boolean
}

no meu component.ts a minha variável está assim ::: publicacoes: Publicacao[] ela está como arrey pois estou iterando nela no meu template com o ngFor.
feed.component.ts
import { Component, OnInit } from '@angular/core';

import { Publicacao } from './publi/publi.model';
import { TestService } from '../test.service';
import { UserPrincipal } from './userPrincipal.model';

@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {

  publicacoes: Publicacao[]
  feedFull: Publicacao[]
  userPrincipal: UserPrincipal[]

  constructor(private testeService: TestService) { }

  ngOnInit(){
//essa função pega todos os usuarios registrados no banco de dados Firebase
    this.testeService.read_userPrincipal().subscribe(data => {
      this.userPrincipal = data.map(object => {
      return{
        token: object.payload.doc.id,
        bios: object.payload.doc.data()['bios'],
        id: object.payload.doc.data()['id'],
        imagePerfil: object.payload.doc.data()['imagePerfil'],
        nome: object.payload.doc.data()['nome'],
        seguidores: object.payload.doc.data()['seguidores'],
        seguindo: object.payload.doc.data()['seguindo'],
        totalPublicacoes: object.payload.doc.data()['totalPublicacoes'],
        user: object.payload.doc.data()['user'],
        userQueEuSigo: object.payload.doc.data()['userQueEuSigo'],
        publicacoes: object.payload.doc.data()['publicacoes']
      };})
        this.checkFollower(this.userPrincipal)
      });
  }
//essa checkFllower verifica se é um seguidor e retorna todas as publicações.
  checkFollower(primaryUser){
    const idPrimaryUser = 1//OK
    for(let i = 1; i < primaryUser.length; i++){ // for ta OK
      var arrey = primaryUser[i].userQueEuSigo
      if(arrey.indexOf(idPrimaryUser) == 0){
        this.testeService.carregar_publicacao().subscribe(data => {
          this.feedFull = data.map(publiObject => {
            return{
              keyUser: publiObject.payload.doc.data()['keyUser'],
              id: publiObject.payload.doc.data()['id'],
              user: publiObject.payload.doc.data()['user'],
              photoUser: publiObject.payload.doc.data()['photoUser'],
              photoPost: publiObject.payload.doc.data()['photoPost'],
              curtidas: publiObject.payload.doc.data()['curtidas'],
              comentarios: publiObject.payload.doc.data()['comentarios'],
              pessoasQueCurtiu: publiObject.payload.doc.data()['pessoasQueCurtiu'],
              totalComentarios: publiObject.payload.doc.data()['totalComentarios'],
              like: publiObject.payload.doc.data()['like']
            };})
              this.selectFedd(this.userPrincipal,this.feedFull)
           })
      }else{
        console.log('foi direto pro else')
      }
    }
  }

//essa é onde eu quero separar apenas as que tem a keyUser == 2
  selectFedd(user,feed){
      const key = user[0].userQueEuSigo
      feed.forEach(element => {
        if(element.keyUser == 2){
          this.publicacoes.push(element)
        }else{
          console.log('erro')
        }
      });
  }

}

Arquivo service
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable()

export class TestService {
  constructor(private firestore: AngularFirestore) { }
  /* create_NewIcecream : Cria um novo registro na coleção especificada usando o método add */
  criar_novo_user(record) {
    return this.firestore.collection('user').add(record);
  }
  /*read_Icecream: Chama o método snapshotChanges , que obterá registros e também será registrado para receber atualizações */
  read_userPrincipal(){
    return this.firestore.collection('user').snapshotChanges();
  }
  carregar_publicacao(){
    return this.firestore.collection('feed').snapshotChanges();
  }

}

Answer: Você não compreendeu direito as ferramentas que está utilizando, quando faz o forEach() e o if() vc já tem os objetos que precisa vindos da Api, não precisa criar o objeto passando as propriedades como fez, no caso aí seria apenas dar push. Adaptei um exemplo só pra demonstrar como pode ser feito com Vanilla para replicar aí com Angular:

let publicacoes = [];                  // sua variável publicações
let api = [                            // seria todos os objetos vindos da api
  {keyUser: 'ok', id: 1, user: 'Fulano'},
  {keyUser: 'no', id: 2, user: 'Ciclano'},   // esse não bate na condição do if
  {keyUser: 'ok', id: 3, user: 'Beltrano'}
];

api.forEach(elem => {
  if(elem.keyUser == 'ok') publicacoes.push(elem)  // insere no array os objetos
})

console.log(publicacoes)

Na classe do componente Angular seria basicamente:
public publicacoes: Publicacao;

selectFedd(user,feed){
  const key = user[0].userQueEuSigo
  feed.forEach(element => {
    if(element.keyUser == 2) this.publicacoes.push(element)
  });
  console.log(this.publicacoes)
}

Comment: ```
  selectFedd(user,feed){
      const key = user[0].userQueEuSigo
      feed.forEach(element => {
        if(element.keyUser == 2){
          this.publicacoes.push(element)
        }else{
          console.log('erro')
        }
      });
  }
```
usando desse modo não está funcionando, pois retorna o seguinte erro

ERROR TypeError: Cannot read property 'push' of undefined

desculpa pela demora
Comment: Editei a pergunta adicionando o feed.compent.ts e o test.service.ts completos
Comment: Estranho João, pq pelo erro que comentou não está achando a variável publicacoes. Aí realmente não sei o que seria!
Comment: viu a pergunta atualizada , ta foda esse erro kkkk
Comment: sabe como faz para pegar direto a publicação pela key no firebase?
Comment: pq eu poderia pegar direto pela key sabe
Comment: Putz não manjo nada de firebase, mas, já tentou tirar o tipo da variável e atribuir um array normal pra ver se vai tipo assim: **publicacoes = [ ]**
Comment: caraca kkk funcionou man funcionou carregou todas certinho, muito obrigado!!!! Estou refazendo o feed do instagram ja me resolveu um puta erro, so que não estou fazendo gerenciamento de sessão é só o feed mesmo. Muito obrigado
Comment: Legal que deu certo João, sucesso aí!

Adicionar um objeto a um arrey


When to prefix form id with colon

Question: I have two datatables in two forms, forma and formg. Inside each form there is a p:dataTable, groupsa and groupsg. In each datatable there is a custom column that displays an image(h:graphicImage) called fava and favg.
When the image is clicked, the images from the other datatable will be updated.

Without the colon I get an exception:
javax.faces.FacesException: Cannot find component with identifier "forma:agentsa:fava" referenced from "groupsg:0:favg".

What is the difference between formg:groupsg:favg and :formg:groupsg:favg?
I am using JSF2.0 and PrimeFaces 3.4.
Answer: The : prefix will make it an absolute client ID and thus it will be searched relative to the UIViewRoot instead of the closest parent NamingContainer. You should (must) use it when you want to refer a component which is not inside the same closest parent NamingContainer. The <h:form> and <h:dataTable> (and
) are NamingContainer components.
See also How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar" for a detailed explaination.
Answer: Use the colon at the beginning when you want to search for the ID from the root of the page. It is necessary when the component that is calling for the update is not inside the same NamingContainer of the component that is being updated.
Don't use it when you want to search relatively to the same NamingContainer. You can do that when both components (the one calling the update and the one being updated) are inside the same NamingContainer.
By the way, "NamingContainers" are all the components that prepend their ID to their child components, like <h:form>,
,
, etc. Just look at the generated HTML to see if the parent is prepending its ID to its childs.

NamingContainer Javadoc.
The algorithm that JSF uses for
finding components by their ID.
BalusC explains it in full detail
here.

When to prefix form id with colon


Type inference fails on parameterized types

Question: Say we have following types:
abstract class Generic_B

interface Generic_A<Generic_B>

class Concrete_B : Generic_B()

class Concrete_A : Generic_A<Concrete_B>

fun main(args: Array<String>) {
    val a = Concrete_A();
    foo(a);
}

fun foo(thing: Generic_A<Generic_B>) {
}

I'm getting an error saying:
Error:(27, 9) Kotlin: Type mismatch: inferred type is Concrete_A but Generic_A<Generic_B> was expected

I don't quite understand the error.
Concrete_A is an instance of Generic_A and also parameterized on a concrete instance of Generic_B.  As such, I feel like the type inference should match up.
I guess me questions are:

Why is the type inference not working? (is this a case of higher kinded polymorphism?)
How do I work around this?
Answer: Basically you just run into the issue that Generic_A<Generic_B> is not the same as Generic_A<Concrete_B>, which Concrete_A extends.
If you add the out variance to the thing parameter generic part, you'll have it working, as it would accept all subtypes of Generic_B:
fun foo(thing: Generic_A<out Generic_B>) {
}


Perfecting accents in Chopin's Impromptu

Question: I'm having a little difficulty in perfecting the following accents in Chopin's Impromptu. (Here's the sheet music I'm referencing for those interested.  )
If you look at the following picture, you'll notice how the acccents are placed at on the first note of each set of 4 in the right hand. This is rather natural to play and doesn't come with much difficulty (especially considering it's played with the thumb, which usually is rather strong.)

However, later in the piece Chopin mixes it up and places the accent on the second note of each set of 4.

This is where my difficulty appears. Maybe it's because I have a weak 5th finger, but I just cannot seem to get the same amount of emphasis on the accented note as I did in the previous bars where the accent was on the first note. (Especially at the high speeds at which this is supposed to be played.)
As I type this out I realize that the best solution may be to simply work on strengthening my 5th finger with various exercises. Any recommendations for any specific exercises or tips for playing this piece of music?
Comment: @sova brilliant. :) Now excuse me while I go reattach my pinky. It's still clutching the milk jug.
Comment: How are you playing it? From the finger? Or stiff finger and wrist rotation with a bit of forearm?
Comment: You can practice clenching your pinky+ring fingers and also strengthen them by carrying jugs of milk or water with them.
Answer: There is no need to strengthen your R5 for this passage.
It's not a question of force, but of control. This is a piano passage, so what you should so is reduce the energy in the three remaining notes. Then the highest note will automatically sound accented.
But even if you did have to increase force on the highest note, you wouldn't do it with an isolated finger movement, but in combination with a fitting wrist and arm movement. Practice the proper arm gesture, and your finger doesn't have to much more then in any other passage of octaves.
Answer: Keep in mind that, in that second passage, you're looking for a melodic phrase with that second note that imitates the melodic phrase in the first note in the earlier passage. So there are some deeper subtleties than just playing all the accented notes equally. Even in that second passage, you need to keep the idea of a primary accent on the first note and a secondary one on the third note, as in any standard 4/4 passage.
As Kilian says, it is more a matter of getting the passage soft enough and still having the control to accent the top note with the 5th finger.  Now, I do this by raising my 5th about two inches from the key and dropping it, with a slight arm supenation (about a quarter inch) to get added force.
One of the other technical difficulties with this accented note is that it doesn't fall at the same time as any note in the left hand (in this case, 1/3 of a 16th note before the second 8th note in the left hand).  The thumb accent falls at the same time as the first note in the 8th note triplet, of course.  It's another detail you have to account for in working out the passage, and it can trip you up if you're not paying attention.


Accessing to resources linked to a closed billing account at Google Cloud

Question: Hi all I have a GCP account that Google closed my billing account due to unpaid invoices.
It has been almost a year now that account remains closed. I need to know If I will have access to my resources in the project like my kubernetes clusters/workloads, DNZ zone, virtual machines etc after clearing out the payment issues and reopen the billing account?
It is almost not possible to access live chat so I hope I get an answer here.
Answer: Projects within GCP undergo a 30 day grace period before the resources are fully deleted. As the Project needs an active Billing account, which is automatically closed if there are unpaid invoices.
If the Project is already past 30 day grace period, the resources on that project are now fully deleted and cannot be recovered even if the Billing account is reestablished.
Comment: In general, this is true but not always. I have seen accounts not loose resources long after the 30 day grace period expired.
Comment: @Siegfred, are you sure about that? At the link in your reply says that it is for projects that shut down. In my situation project is still visible.
Comment: @Murat, Even though you didn't opt to shutdown your Project, it still needs an active Billing Account. If your resources are left unpaid, resources are sent back to the resource pool for reallocation to be deployed on Projects with active Billing Accounts.
Comment: @SiegfredV. so you mean that if the invoices gets paid tomorrow and billing account gets opened again, the resources will be allocated back to project so they will be available again?
Comment: @Murat, no, resources are only recoverable within the 30-day grace period after the Billing Account is closed, but as you said "It has been almost a year now". [At the end of the 30-day period, the project and all of its resources are deleted and cannot be recovered](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects). The project might still be visible, although its resources are deleted


How to use a cookie to save the clicked value grab the cookie every time the user opens the page

Question: I have following code to highlight table record with three different colors when user click a checkbox. How can I use a cookie to save the clicked value with  grab the cookie every time the user opens the page everytime? I haven't no idea how cookies are used. Answer would be really appreciate
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

        <input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" />
        Click me

        <input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" />
        Click me

        <input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" />
        Click me

Answer: localStorage is easier than cookie I thought . You can set and get by localStorage.setItem or localStorage.getItem and it will remain until you remove them !!!

Comment: Thank you very much Mr.David JorHpan. It worked well and I was trying with this for 2 days. Thank you very much.
Comment: My pleasure to help you
Answer: I'm assuming you want the values to be selected still even when the user goes to a different page on your site and then select them again once back in that page.
As stated here, you set the cookies using the document.cookie javascript property.
The property mentioned above, however, is a semicolon separated key-value pair. you'll have to manipulate the string in order to add/edit a value.
Once you've added the value that you want, you can once again read it and then set the rows you want to be selected.
To get the selected value, you could use $(data).val() and put it inside changeSoma(). From there, you could check if it's checked $(data).is(':checked'). If it's checked, add it to document.cookie like document.cookie = "key=value; key2=value2;"
Comment: How can I save the clicked value Mr.Bobby?
Answer: it easier using localStorage but since you're using jQuery then use jQuery cookie plugin
<!doctype html>

  <meta charset="utf-8">
  <title>Untitled Document</title>

        <input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" />
        Click me

        <input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" />
        Click me

        <input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" />
        Click me

Comment: Thank you for your effort Mr.ewwink.But this code neither highlight record nor stay the result after page refreshing


What do fsolve in this machine learning task?

Question: I am reading this book Building Machine Learning Systems with Python and can not understand   what function "fsolve" do in eample.  In example I have test data data and I built the model. My model is 0.08844*x^2 - 97.31*x + 2.853e+04. I need find what x when f(y) = 100000. I understand that need  find and use inverse function. But in book example they subtract 10000 from  model and after use fsolve. Why did the do it?
Comment: It looks like `fsolve` finds the root of the polynomial.
Answer: fsolve returns a value x, such that f(x) = 0.  In this case, it is desired to find a value x such that fbt2 = 100000.  Therefore, fbt2 - 100000 is used as the "f(x)" in fsolve, which therefore returns a value x such that fbt2 - 100000 = 0, which therefore solves fbt2 = 100000, as desired.


Locally Lipschitz, boundary

Question: I have a question about domains of $\mathbb{R}^d$.
I am reading A First Course in Sobolev Spaces by Giovanni Leoni.
This book introduces the following concept to describe the regularity of the boundary of a domain.
(Definition 12.9 in Leoni's book) The boundary $\partial \Omega$ of an open set $\Omega \subset \mathbb{R}^N$ is $locally $ $Lipschitz$ if for each $x_0 \in \partial \Omega$ there exist a neighborhood $A$ of $x_0$, local coordinates $y=(y',y_N) \in \mathbb{R}^{N-1} \times \mathbb{R}$, with $y=0$ at $x=x_0$, a Lipschitz function $f:\mathbb{R}^{N-1} \to \mathbb{R}$, and $r>0$, such that
\begin{equation*}
\Omega \cap A=\{(y',y_N) \in \Omega \cap A: y' \in Q(0,r), y_N>f(y') \},
\end{equation*}
where $Q(0,r)$ is the open ball centered at the origin with radius $r>0$.
My question
In the above definition, $f$ and $r>0$ depend on $x_0$. Therefore, we should write $f=f_{x_0}$, $r=r_{x_0}$.
Can we show the following?
Let $K \subset \partial \Omega$ be a compact subset. Then, $\inf_{x_0 \in K}r_{x_0}>0$ and there exists a positive number $M$ such that
\begin{equation*}
\sup_{x_0 \in K}\text{Lip}(f_{x_0})\le M,
\end{equation*}
where $\text{Lip}(f)$ is the Lipschitz constant of $f$.
I think this holds. But I couldn't prove... If you have a nice idea, please let me know.
Thanks in advance.
ADD
That is, I want to prove the following:
There exist positive numbers $r_K$ and $L_{K}$ such that
for each $x_0 \in K$ there exist a neighborhood $A$ of $x_0$, local coordinates $y=(y',y_N) \in \mathbb{R}^{N-1} \times \mathbb{R}$, with $y=0$ at $x=x_0$, a Lipschitz function $f:\mathbb{R}^{N-1} \to \mathbb{R}$ with $\text{Lip}(f) \le L_{K}$ and
\begin{equation*}
\Omega \cap A=\{(y',y_N) \in \Omega \cap A: y' \in Q(0,r_K), y_N>f(y') \},
\end{equation*}
where $Q(0,r_K)$ is the open ball centered at the origin with radius $r_K>0$.
Comment: Who is to say that r is necessarily a continuous function of $x_0$?
Comment: You mean we need additional assumptions to show $\inf_{x_{0} \in K}r_{x_0}>0$?
Comment: Just saying that $K$ is compact does not imply that every function on it attains its infimum. The function needs to have some amount of regularity for that.
Comment: Do you have an example of locally Lipschitz domain which does not satisfy $\inf_{x_0}r_{x_0}>0$?
Comment: I think domains which have smooth boundary satisfy the conditions $\inf_{x \in K}r_x$ and $\sup_{x \in K} \text{Lip}(f_{x_0})$ \le M.
Comment: My point is not to say that you are wrong (I suspect you are right in fact) but that it is not "free", you should try to argue that $r$ has some amount of continuity to it (lower semicontinuity would be enough).
Answer: For every point $x_0\in K$ you have an open neighborhood $A_{x_0}$ that contains $x_0$. Hence $K\subset\cup_{x_0\in K}A_{x_0}$ and so by compactness you can find $n_K$ points $x_1, \ldots, x_{n_K}\in K$ such that $K\subset\cup_{i=1}^{n_K} A_{x_i}$. So now take $L_K=\max_{i=1,\ldots,{n_K}} L_{x_i}$ and $r_K=\min_{i=1,\ldots,{n_K}}$.
If $x\in K$ then there exists $i\in\{1,\ldots,{n_K}\}$ such that $x\in A_{x_i}$.
EDIT Instead of working with cubes use balls (it does not make any difference). For each $x_0\in K$ find a ball $A_{x_0}=B(x_0,r_{x_0})$.  Hence $K\subset\cup_{x_0\in K}B(x_0,\frac{r_{x_0}}2)$ and so by compactness you can find $n_K$ points $x_1, \ldots, x_{n_K}\in K$ such that $K\subset\cup_{i=1}^{n_K} B(x_i,\frac{r_{x_i}}2)$. So now take $L_K=\max_{i=1,\ldots,{n_K}} L_{x_i}$ and $r_K=\min_{i=1,\ldots,{n_K}}\frac{r_{x_i}}2$.
If $x_0\in K$ then there exists $i\in\{1,\ldots,{n_K}\}$ such that $x_0\in B(x_i,\frac{r_{x_i}}2)$. Then $B(x_0,r_{K}) \subset B(x_i,r_{x_i})$. You can take as function $f$ the function $f_{x_i}$ but you will need to make a translation to change the origin into $x_0$.
You can use the same idea with cubes, it is just more cumbersome to write down.
Comment: How about $\inf_{x \in K}r_x>0$?
Comment: You can do the same. Just take $r_K=\min_{i=1,\dots,n}r_{x_i}>0$.
Comment: I cannot understand that it is proof. Please give me a proof.
Comment: I just edited it. Since you can cover $K$ with only finitely many $A_{x_i}$ for each $x_0\in K$ you must be in one of these finitely many $A_{x_i}$ .
Comment: Let $x_0 \in K$. From your argument, there exists a $i=1,\ldots,n$ such that $x_0 \in A_{x_i}$. Therefore, there exists a local coordinates $y=(y',y^N)$ with $y=0$ at $x=x_i$, a Lipschitz function $f$ such that $\Omega \cap A_{x_i}=\{(y',y^N) \in \Omega \cap A_{x_i}: y'\in Q(0,r_{x_i}), y^N >f(y')\}$.
Comment: This is not a proof I want.
Comment: We should prove the following: For any $x_0 \in K$, there exist a neighborhood $A_{x_{0}}$, a local coordinates $y=(y',y^N)$ with $y=0$ at $x=x_0$, a Lipschitz function $f$ with $\text{Lip}(f)\le L_K$ such that $\Omega \cap A_{x_0}=\{(y',y^N) \in \Omega \cap A_{x_0}: y'\in Q(0,r_{K}), y^N >f(y')\}$.
Comment: I'm asking how to prove this
Comment: I just replied.
Comment: I sincerely thank you for your polite and thorough response. I understood.

Locally Lipschitz, boundary


PMT equation result

Question: I want to calculate the PMT value. I have the following equation:
$$P =\frac{P_vR}{1-(1+R)^{-n_p}}$$
where present value $P_v=8262$, interest rate $R=0.875$ and number of periods $n_p=60$.
If I use the calculator, I get $-7229$. When I use the PMT function in Excel, I get $-177.58$. When I use this online calculator, I get $-177.58$. I don't understand which result is correct?
Answer: With the 177 values, the interest rate is 0.875% = 0.00875.
With the 7229 value, the interest rate is 0.875 = 87.5%.

PMT equation result


Can Transporter download screenshots from iTunes Connect?

Question: I have successfully downloaded metadata for one of my apps from iTunes Connect using Transporter with the following command:
iTMSTransporter -m lookupMetadata -u <username> -p <password> -vendor_id myAppSKU -destination ./

This creates a new folder called myAppSKU.itmsp which contains a single file called metadata.xml.  Is there any way to force Transporter to download the screenshot assets for my application to the same folder or must I do this by hand?
Answer: No, there is no such functionality for the iTMSTransporter. (at least not yet)
Source: The Transporter User Guide and the fact that I've been dealing quite a bit with iTMSTransporter for a project.
Comment: With Film and TV, the transporter adds a `read_only_value` element with a URL pointing to the given asset, image, video, etc...This isn't the case with apps? Please let me know, I'd like to [add it to my program](https://github.com/sshaw/itunes_store_transporter#using-itms).
Comment: Nope, the lookupmetadata method only returns the metadata.xml without the screenshot files, and it only references the images by their filename (no URLs).

(by the way, great work on your project sshaw, I had looked it up for a bit although we ended up not using it :) )
Answer: You can use fastlane's deliver tool. It can not only upload your app, metadata and screenshots, but also download your metadata or screenshots.


How can I avoid extraneous divs in my form?

Question: When I create a form using the form API, the resulting html includes all sorts of unwanted divs. For example, if I use:
$form = array(
    'myFieldset' => array(
        '#type' => 'fieldset'
    )
);

The resulting html looks like this:
<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">

        <fieldset class="form-wrapper" id="edit-myfieldset">

        </fieldset>
        <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
        <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
        <input type="hidden" name="form_id" value="form_Chercheur" />

</form>

As you can see, two extraneous divs are added here. They are making the javascript I'm writing uselessly complicated, so I was wondering if there was a way to remove the extraneous divs. Ideally, I would like to obtain something like this:
<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">
    <fieldset class="form-wrapper" id="edit-myfieldset">
    </fieldset>
    <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
    <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
    <input type="hidden" name="form_id" value="form_Chercheur" />
</form>

Is this possible?
Answer: The first
 is hard coded into the theme_form() function, so you can override that in your theme's template.php file if you want to. You should be aware, though, that the wrapping
 is actually there to ensure XHTML compliance; if you remove it your page will fail validation.
That said, this is the code to do it (replacing MYTHEME with the name of your theme):
function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }

  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}

The only change from the original function is the removal of the
 and
 from the last line, and the removal of the XHTML compliance comment as that no longer applies.
Overriding the fieldset theme is pretty much the same, except you'll be borrowing the code from theme_fieldset():
function MYTHEME_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }

  $output .= "</fieldset>\n";
  return $output;
}

Once you clear Drupal's caches the extraneous markup should just disappear.