How to set up html email from rules?

Question: I want to send a HTML email from rules but I cannot get it correct.
Installed mime, html, mail. Created rule. only a trigger and action send html email.
In the rule: no message key defined, subject is something like [node:nid], body is [node:body]
Made a template at campain monitor, now i have foo.html. Renamed foo.html to mimemail-message.tpl.php in default theme directory and put [node:id] and [node:body] on the correct place. Soo, the css is in the tpl file.
1) When testing I get an html email (logo is visible) but no colors.
Installed and configured: sites/all/libraries/emogrifier/emogrifier.php
Mailsystem is using mime, mime is using full html filter including emogrifier.
No change in the result.
I read the message with gmail. Adblockes disabled.
Any suggestion what to do ?
2) How to get replacement of the tokens. Which tokens are available for this tpl file?
Answer: I forgot to enable the module  mimemail_compress. After enabling this it was solved.
Comment: Done thxs. Gewoon vanuit NL
Comment: Welcome back ...

How to set up html email from rules?


Some input files use or override a deprecated API Flutter build android

Question: I have a flutter project and I want to build it in android studio. I build it with this command in the terminal:
flutter build apk --release
I'm getting this error report:
Note: C:\Users\Jovik\AppData\Roaming\Pub\Cache\hosted\pub.dartlang.org\path_provider-1.5.1\android\src\main\java\io\flutter\plugins\pathprovider\PathProviderPlugin.java uses or overrides
 a deprecated API.
Note: Recompile with -Xlint: deprecation for details.
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint: deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint: unchecked for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint: unchecked for details.
C:\Users\Jovik\AppData\Roaming\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.6\android\src\main\java\io\flutter\plugins\sharedpreferences\SharedPreferencesPlugin.java:25: warn
ing: [deprecation] getFlutterEngine() in FlutterPluginBinding has been deprecated
    setupChannel(binding.getFlutterEngine().getDartExecutor(), binding.getApplicationContext());

I'm not a flutter developer so I have no special knowledge of these technologies. I have upgraded flutter and the flutter doctor did not find any error what problem? Could you help me too? Give advice on what I'm doing wrong.
Comment: This is warning not an error, you can continue or try to fix it by yourself, by pulling the shared preference to your machine
Comment: try this:
add below code in Android/app/build.gradle file

configurations {
compile.exclude group: 'com.google.zxing'
}
Answer: This is a known issue with the shared_preferences plugin with flutter. This issue has been addressed about 20 days ago. Make sure that you are using the newest version of shared_preferences (0.5.6+3) and update to reflect this in your pubspec.yaml.
Comment: Try running `flutter clean` and then also running `flutter upgrade`.
Comment: Yeah you are right.In my case it was 0.5.6.I updated it to 0.5.6+3 and typed in terminal flutter pub get then rebuilded it but i'm still getting this error.What do you advice?
Comment: At the time of this writing, flutter firebase messaging has the same problem. I am using the latest version. Conclusion: ignore the warning message. It is the responsibility of the flutter library's programmer, not us.
Comment: It's not so really clever to mention "20 days ago" in a comment like this...


How to change view REST export format

Question: This is my settings in view.

Data what I have is now in this format:
[{"created":"1551709414","field_iot_integer":"43"},
{"created":"1551709404","field_iot_integer":"98"},
{"created":"1551709392","field_iot_integer":"58"},
{"created":"1551709382","field_iot_integer":"4"},
{"created":"1551709373","field_iot_integer":"65"},
{"created":"1551709356","field_iot_integer":"23"}]

I would like to change this format in this, rid of all comments. :
[[1551709414,43],
[1551709404,98],
[1551709392,58],
[1551709382,4],
[1551709373,65],
[1551709356,23]]

How I can achieve this?
Answer: To change the structure of the Serializer output you should create a custom Serializer here is the steps of your use case:

Create CustomSerializer extends the Drupal\rest\Plugin\views\style\Serializer and update the render method to your needs.

Create MY_MODULE/Plugin/views/style/CustomSerializer.php

namespace Drupal\MY_MODULE\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "custom_serializer",
 *   title = @Translation("Custom serializer"),
 *   help = @Translation("Serializes views row data using the Serializer
 *   component."), display_types = {"data"}
 * )
 */
class CustomSerializer extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $row_render = $this->view->rowPlugin->render($row);
      $iot_integer = 0;
      if (isset($row_render["field_iot_integer"]) && $row_render["field_iot_integer"] instanceof \Drupal\Core\Render\Markup){
        $iot_integer = (int) $row_render["field_iot_integer"]->__toString();
      }
     $rows[] = [
        $row_render["created"]->__toString(),
       $iot_integer
      ];
    }
    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }
    return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);
  }
}

Clear Cache:
Go to your view and change the format from Serializer to Custom serializer like

The result:
Comment: you are welcome, glad that help.
Comment: Thank you a lot. This is very good. I understood that I was need to extend class Serializer but didn't know to write function.
Comment: Hi i have the same problem, but when i've created those files i dont have that option "Custom serializer" in views, could you please help me?
Comment: Did you put the files in the right structure, and you check that your module is enabled and did you cleared the cache ?

How to change view REST export format


Ruby on rails incorrectly dumps all the postgresql table content

Question: I'm realatively new to ruby on rails and im really having problems with a simple for-loop.
I'm doing this:
Inside posts_controller.rb
@post = Post.all.order("created_at DESC")

Inside posts/index.html.erb (the view related to the controller)
<%= @post.each do |post| %>

  <%= link_to post.title, post %>

"Published "
  <%= time_ago_in_words(post.created_at) %>

by user.email
  <%= post.user.email %>

<% end %>

But the output is (I copied just the important part)
primer pst de ET
"Published " 1 day
by user.email firstname.lastname@example.com

primer post de cocina
"Published " 1 day
by user.email firstname.lastname@example.com

[#<Post id: 14, title: "La tercera es la vencida", content: "
, #<Post id: 13, title: "segundo post con status", content: "
ahora ´si qu...", created_at: "2018-12-23 03:05:32", updated_at: "2018-12-23 03:05:32", user_id: 1, category: "Endless Tower", thumbnail: nil, status: nil>, #<Post id: 12, title: "Segundo post COCINA", content: "
Esto es el primer post COCINA con imágen...", created_at: "2018-12-23 02:53:06", updated_at: "2018-12-23 02:53:06", user_id: 1, category: "Cocina", thumbnail: nil, status: nil>, #<Post id: 11, title: "primer post con status", content: "gtgtrhtgr", created_at: "2018-12-23 02:31:51", updated_at: "2018-12-23 02:31:51", user_id: 1, category: "", thumbnail: nil, status: nil>, #<Post id: 10, title: "primer post economía", content: "f3rggg ecoooooo", created_at: "2018-12-23 02:19:42", updated_at: "2018-12-23 02:19:42", user_id: 1, category: "Economía", thumbnail: nil, status: nil>, #<Post id: 9, title: "primer pst de ET", content: "ET SE HACE UNA VEZ A LA SEMAN", created_at: "2018-12-23 02:17:04", updated_at: "2018-12-23 02:17:04", user_id: 1, category: "Endless Tower", thumbnail: nil, status: nil>, #<Post id: 8, title: "primer post de cocina", content: "wfowrffmweew COCINAAAAAA", created_at: "2018-12-23 02:00:39", updated_at: "2018-12-23 02:00:39", user_id: 1, category: "Cocina", thumbnail: nil, status: nil>]
AQUÍ TERMINA EL RENDER INDIVIDUAL

So it dumps all the database content at the end and I realy don't know why.
I clearly don't want the user to see the table content but I don't know whats wrong with the code above.
I know it's probably a very basic question, but i can't find the answer yet. Please help me.
Thanks for yor help :)
EDIT: here is the full controller code
class PostsController < ApplicationController

  # La siguiente línea establece que se llamará al método <find_post>
  # antes de llamar a los métodos <show>, <edit>, <update>, <destroy>
  before_action :find_post, only: [:show, :edit, :update, :destroy]
  before_action :stablish_categories_and_thumbnail

  def index
    @post = Post.all.order("created_at DESC")
  end

  def show
  end

  def new
    @post = current_user.posts.build
  end

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to @post
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to @post
    else
      render 'edit'
    end
  end

  def destroy
    @post.destroy
    redirect_to root_path
  end

  private
  def post_params
    params.require(:post).permit(:title, :content, :category, :status, :thumbnail)
  end

  def find_post
    @post = Post.find(params[:id])
  end

  def stablish_categories_and_thumbnail
    # Esto es lo que hay que ir rellenando luego con las categorías finales
    @categories = ['Cocina',
                   'Endless Tower',
                   'Economía',
                   'rangos de aventurero']

    @thumbnails_list = ['img1', 'img2', 'img3', 'img4']
  end

end

Comment: show full controller code
Answer: Remove the = sign from your posts/index.html.erb:
<% @post.each do |post| %>

instead of
<%= @post.each do |post| %>

<%= ... %> will evaluate the statement/block and print the result. <% ... %> will only evaluate and not print it. For example -
<%= a = 5 %> will assign and print '5' on the page.
<% a = 5 %> will only assign '5' to the local variable a but not print it.
Comment: It worked. Thanks. What does de '=' do in this context?


Android create a PreferenceFragment without a PreferenceActivity

Question: I added a side menu to my Application and I managed to change the content with fragments. Now I am trying to do the Preferences, but I don't want to use a PreferenceActivity because I want to do my application with fragments because I don't want to do the NavigationDrawer twice (For my main activity displaying the fragments and for the PreferenceActivity).
I found the class PreferenceFragment but after alot of research I found out that appearantly it just is a part of the SettingsActivity and when I try to addPreferenceFromResouce in the PreferenceFragment and then launch the fragment, it crashes.
So basically I am trying to find a way to display a SettingsFragment without any extra activity just by calling fragmentManager.beginTransaction().replace(R.id.contentFrame, settingsFragment).commit() just as I do with my different fragments.
I hope I asked my question understandable (I am sorry if I didn't). Thanks for your time and your help.
Comment: Did you get any answer?
Comment: I found an answer myself. I will include it.
Answer: I found the solution myself now. It wasn't very hard.
I simply created a normal PreferenceFragment and you can use it like any other fragment without a PreferenceActivity.
public class PreferenceFragment extends android.preference.PreferenceFragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
}}

I then replaced it using
getFragmentManager().beginTransaction().replace(R.id.contentFrame, preferenceFragment).commit();

as you normally would.
This worked great for me. I hope it also does for you.
Comment: Doesn't work for me. I have a tabbed activity and it conflicts with the tabs.


How do I delete/remove a broken configuration?

Question: I'm using Layout Builder to manage the display of a content type.
I was playing around with the config and adding different things, and something I added caused the page to crash and now I get this error:

The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityMalformedException: The "node" entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\EntityBase->toUrl() (line 191 of core/lib/Drupal/Core/Entity/EntityBase.php). node_tokens('node', Array, Array, Array, Object)

This error persists every time I click "Manage Display" for that content type; I rebuilt the cache with Drush and cleared my browser cache, but I still get the error when I go to edit the display settings.  I get the error when I log in with a different browser, too, and also when I revert the config.
I am working on this site locally, so I can pull from the dev server, but is there another way to reset my "unsaved changes" locally so that I don't have to wait for the pull to complete?
Comment: Can you get a full error message with backtrace to see which code is trying to get a URI from a node without ID?
Comment: It's DB related, you don't need to pull the code base, just import the dev db again assuming you haven't made any config changes that you want to push.
Answer: Layout builder stores in-progress modifications to the layout config in the key_value_expire table. Whenever Layout Builder is loaded (e.g. Manage Display, Page Manager, etc.), it first checks that table if there is an in-progress entry for the layout you're about to edit. If it exists, it tries to load that, otherwise it loads the one saved in config.
The problem is, that in-progress config may contain bad data (e.g. a block that was added but has bad implementation) or outdated data (e.g. a block that you were working on, but whose implementation has already been deleted). This can cause Layout Builder to fail loading. As far as I know, Drupal has no way of guarding or recovering from this from the admin side nor does a cache rebuild help.
One way to recover is to load a copy of the DB prior to your changes, but that may take forever and blow away any other work in progress you have. Another is to dive into the key_value_expire table and look for that in-progress entry, delete it, and reload Layout Builder.


How to override the system timezone in settings.php?

Question: I'm trying to override the site's timezone in settings.local.php.
Looking at the config file, this should be simple:
$ more system.date.yml
country:
  default: ''
first_day: 0
timezone:
  default: UTC
  user:
    configurable: true
    warn: false
    default: 0

but I've trying various combinations of this and none of them work:
$config['system.date']['timezone']['default'] = 'Europe/London';
$config['system.date.timezone.default'] = 'Europe/London';

Answer: The first example ($config['system.date']['timezone']['default'] = 'Europe/London';) is the correct way to override config values in your settings.php file.
It sounds like you've hit an issue noted in the config override system docs:

Note that values overridden via $config within settings.php will not be viewable from the Drupal administration interface (until #2408549: There is no indication on configuration forms if there are overridden values is fixed, until then you can use Configuration Override Warn or Config Override Inspector) or from inspection via drush (unless you add the --include-overridden flag). The administration interface displays the values stored in configuration so that you can stage changes to other environments that don't have the overrides.

So if you view /admin/config/regional/settings page or the drush cget system.date timezone.default command, it won't show the overridden value.
You can try something like drush cget --include-overridden system.date timezone.default or
drush eval 'print \Drupal::config("system.date")->get("timezone.default");' to confirm your overridden value is actually being set in your settings.php


How to remove h1 tag from Drupal Garland theme in the header

Question: I was shocked to see Bing Webmaster Tools notification that my site: http://www.articlesdirectoryindia.com using Garland theme has two H1 tags and that only one should be there for SEO reasons.
Actually the site name : "Free Articles Directory India" is wrapped within h1 on all pages in the header which I want remove.
I want to know if there is any standard & tested workaround for removing this h1 and replacing this with some div etc?
I tried to change h1 to div for 10 minutes but I could not do it. Even if I'm able to it'd be difficult to test of all browser versions.
Answer: if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }

These are the lines 39-45 in Garland Themes page.tpl.php.
This is probably the h1 tag you're talking about. If you want to change it to div it should look like this afterwards:
if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }

Comment: What do you mean with html/css code? The answer Volker gave is the best solution to this problem.
Comment: @JurgenR yes but I need some tested css too to display the title similarly. I had already tried this before posting here. I'm not able to make the title display in the same way.
Comment: So you did apply all css-styles of the former H1 to your new div?
Comment: You could post your css of the h1 and the div to compare...


Time series Data : Regress absolute values or regress the %growth of the values?

Question: I am doing a time-series data analysis. The idea is to produce a forecast from the regression output.
I am regressing Air traffic passengers of country A with GDP/capita of country A.
I am getting very high R² (0,97) by regressing absolute values of Air traffic passengers of country A with GDP/capita of country A (p.value<0,05)
I am getting low R²(0,35) by regressing the same variables but that time, by taking the %growth of those variables. (p.value<0,05)
What is the most accurate in this case? regress absolute values or regress the %growth?
Comment: You are right, absolute values is not precise enough and can have other meanings. When I said "absolute" I meant the real value of the gdp/capita and the real number of passengers (in units)
Answer: Use the observed values as there may be lag structure needed for GDP (X) that may be different than the lag structure need for air traffic passenger data (Y) . You can always subsequently express the change in passenger forecast as a percentage of the previous value as it relates to the change in GDP as it relates to the previous value of GDP .
Finally to get correct/honest prediction limits for passenger data (Y) you may/will need to account for the uncertainty in GDP (X) predictions and possible re-occurring anomalies.
You might want to read https://autobox.com/pdfs/regvsbox-old.pdf which discusses some of the opportunities that are available when you have time series data and some of the pitfalls when you use simple OLS.
I surmise you ran a simple OLS of Y versus X and obtained .97 as the Rsq AND then
you created two new series Y1 and X1 where Y1=[Y(t)-Y(t-1)]/Y(t-1)  and X1=[X(t)-X(t-1)]/X(t-1) and obtained .35 when you regressed Y1 and X1 . This specification is probably suspect for a ton of reasons whereas a SARMAX https://autobox.com/pdfs/SARMAX.pdf is much more general approach. Your specification of the model (two ratios)  is a possible model but not probable because it is based upon presumption.
Comment: It could BUT it is always IMHO much cleaner to use observed data rather than derived data (secondary data) due to possible obfuscation (KISS).
Comment: Many thanks for this IrishStat. though, I don't undersand why use absolute values and not %growth would allow a lag between passengers and GDP/capita?
Comment: Noted, never heard about the obfuscation. Thank you again for that.
Comment: If you are happy with my response please accept it to close the question


If $a >1$, $b >1$ and $p = \frac{\log_b{(\log_b{a})}}{\log_b{a}}$, then what's $a^p$?

Question:
If $a >1$, $b >1$ and $p = \frac{\log_b{(\log_b{a})}}{\log_b{a}}$, then what's $a^p$?

My steps:
$$a^p=a^{\frac{\log_b{(\log_b{a})}}{\log_b{a}}}$$
But from then I had no idea what to do and would like assistance.
Answer: We have by change of base
$$
\frac{\log_b(\log_b(a))}{\log_b(a)} = \log_a(\log_b(a))
$$
Therefore,
$$
a^p = \log_b(a)
$$
Answer: Hint: $p = \frac{\log_b{(\log_b{a})}}{\log_b{a}},$ so $p\log_b{a} = \log_b{(\log_b{a})},$ and finally $\log_b{a^p} = \log_b{(\log_b{a})}.$
Answer: $ p = \frac{\log_b{(\log_b{a})}}{\log_b{a}} => p = \log_a{(\log_b(a))} => a^p = \log_b{a} $ . Hope this helps .
Answer: Hint: since the "outer" logarithms are $\log_b {(\text{stuff})}$ you might think that you need $b^{\text{something}}$ rather than $a^{\text{something}}$ - fortunately, using logarithms, you can write $a=b^{?}$


Git hook for unstaged changes/file changes

Question: I'm looking to write a script that monitors all files/folders tracked by git to notify me if any of them have been changed. I'm looking for file changes and not necessarily staged changes.
I've been combing through various SO questions and documentations, but I can't find any relevant examples for implementing a file system watcher based off of git that would be efficient, since I might want to implement this across a multitude of repositories and possibly hundreds of files all on one system without being extremely inefficient.
Is git even the right solution for this? Would I be better off using fswatch even across many, many files?
Many thanks
Comment: Git itself doesn't watch the file system and as such also doesn't provide any hooks when files change. It only inspects the file system whenever a git command is executed. If you need to be notified about changes proactively, you'll need to use another tool. Many IDEs will watch the project directory like you describe though, so maybe that's a possible approach? What are you trying to achieve, it's possible that this is a [XY problem](https://xyproblem.info).
Comment: Yes, that's what I'm saying.
Comment: @JoachimSauer So you're implying that unstaged changes are not detected on file write and only when another git command is executed?
Answer: Git itself doesn't watch the file system (*) and as such also doesn't provide any hooks when files change. It only inspects the file system whenever a git command is executed.
Therefore there aren't (and can't be) any hooks that execute on file change. You'll need to find another way to watch the file system, if you need this.
(*) Apparently there is a way to actually use file system monitoring in git, but that only seems to be used to speed up git status (and other operations) and still doesn't mean that git actively monitors changes. It just replaces "check each file for modification" with "check the list of changed files since the last time for modification".
Comment: There are some file system monitoring things for Git, which are still somewhat experimental. They probably won't help the OP any though.
Comment: @torek: if you mean the `core.fsmonitor` feature: I didn't know of that and added a mention to my answer. But from what I read this does indeed not do what OP wants.
Comment: Yes. The fsmonitor stuff is ... not ready for prime time, I would say. :-) It's really hard to do this well: different OSes have different capabilities and methods of doing FS monitoring, and if you have multiple repositories, it would be nice to have a single monitor for multiple repos. There are potential security / privacy issues as well. It's a nice idea that maybe we can avoid stat-ing a million files in a big checkout, but it's hard.


Injection from non-separable to separable subspaces

Question: Let $\Gamma$ be an uncountable set (possibly of cardinality $\aleph_1$). Is there an injective bounded linear operator $T\colon c_0(\Gamma)\to X$, where
a) $X$ is some separable Banach space
b) $X=c_0$?
Thank you in advance.
EDIT: This might be useful as well: Johnson and Zippin proved that each quotient of $c_0$ is in fact its subspace. Is there a similiar result for general $c_0(\Gamma)$ spaces?
EDIT 2: Another hint: If $T_1\colon Y\to c_0(\Gamma)$ is injective, then there exists an injective operator $S\colon Y\to c_0(\Gamma)$ with dense range.
Comment: An obvious point that might as well be stated: $\Gamma$ must have cardinality at most $2^{\aleph_0}$, simply for an injective map to exist.
Comment: Perhaps also worth mentioning is that it is possible to have an injective bounded linear operator from a nonseparable Banach space to $c_0$.  E.g., define $T:\ell^\infty\to c_0$ by $T(x_0,x_1,x_2,\ldots)=(x_0,\frac{1}{2}x_1,\frac{1}{3}x_2,\ldots)$.
Comment: Thanks, however $c_0(\omega_1)$ does not embed into $\ell^\infty$ (unlike $\ell^1(2^{\aleph_0})$). This is by Pełczyński's theorem: $\ell^{\infty}(\omega_1)$ would have to embed into $\ell^\infty$ as well which is not the case.
Answer: The answer is no in both cases. To see why, I suggest first observing that every separable Banach space $X$ admits a one-to-one continuous linear mapping into Hilbert space; consider, e.g., an isomorphic embedding of $X$ into $\ell_\infty$ composed with a one-to-one diagonal operator from $\ell_\infty$ into $\ell_2$. It thus suffices to show that $c_0(\omega_1)$ does not admit a one-to-one continuous linear map into any Hilbert space; for this, there may be many references, but the one that comes to mind for me is Olagunju's paper A Banach space that cannot be made into a BIP space, Proc. Camb. Phil. Soc. 63 (1967), 949-950 (Olagunju actually shows that $\ell_\infty([0,1])$ does not admit a one-to-one continuous linear operator into any Hilbert space, but you will see that the same argument works for $c_0(\omega_1)$).
Comment: One day, if I have time, I might distill Olagunju's argument and explicate it here, as it's not that long or complicated.
Answer: Assume that there exists such an injective bounded linear operator $T \colon c_0(\Gamma) \rightarrow X$ that a) is satisfied. Then $T \colon c_0(\Gamma) \rightarrow T(c_0(\Gamma))$ is bijective. Since $T(c_0(\Gamma))$ is a subspace of $X$ it is separable. Let  $Q$ be a countable set such that $T(c_0(\Gamma))= \text{cl}Q$. For the inverse $T^{-1} \colon T(c_0(\Gamma)) \rightarrow c_0(\Gamma)$ which is a continuous bijection we have that $T^{-1}(Q)$ is countable and it is  dense set in $c_0(\Gamma)$ which is a contradiction since $c_0(\Gamma)$ is not separable.
Thus a) and b) cannot be satisfied.
Comment: $T^{-1}$ is not continuous.  You also seem to assum that $T(c_0(\Gamma))$ is closed.  Am I misunderstanding?
Comment: yep, you're right I was trying to apply Banach inverse theorem, but for this the assumption that $T(c_0(\Gamma))$ is closed is required.


Google Cloud VPN Confusion

Question: I have a scenario where I need to connect 1 client company with my GCE via Google VPN.
My GCE IP address is 10.240.0.3/16 and public IP (lets assume) x.x.x.x
now the client requirement is they need public  IP on GCE directly, instead of Private IP .As per their policy since there are chances that private IP can be similar on multiple customer therefore they does not allow Private IP as encryption domain they only allow public IP.
To clear their requirement more they  need the setup like this.
GCE[Public IP]--------VPN[Public IP]<------------>[Public IP] ClientVPN
now my question is how does it work. How can I assign Public IP directly to GCE. And if not can I share NATed public IP of GCE as direct public IP of it.  Like below.
GCE-[Private IP]---------[NAT][Public IP]------------VPN[public IP]--------------[Public IP]ClientVPN
the main problem is due to the above reason we have no other way out of this instead of fulfilling client requirement. This problem seems like a show stopper to us. kindly guide me and suggest what is your best way out of this situation. I will be very thankful.
Thanks,
Yousuf
Answer: What you're looking to do will work with a VPN that supports Port Address Translation (PAT). Google Cloud VPN does not support this feature at the moment.
You can configure any open VPN software that supports this feature on a GCE instance. At this link, you can find an example on how to do this.

Google Cloud VPN Confusion


How do I list Node.js version and path currently being used in npm?

Question: I'm currently running into the same error as this Stackoverflow question had: SyntaxError: Use of const in strict mode?, although I'm getting it while trying to install Flux.
I've already updated my system's Node.js version with the commands shown in the linked Stackoverflow question.
npm cache clean -f
sudo npm install -g n
sudo n stable

When I run node --version I get the correct version, v8.2.1. However, when I install modules via npm, I still get warnings such as
npm WARN engine firstname.lastname@example.com: wanted: {"node":">=4"} (current: {"node":"v0.10.25","npm":"1.3.10"})

...which suggests that npm is still using an old version of Node.
Is there a way that I can find the version of Node seen by npm, and can I determine the directory where it is installed to?
Comment: What does `which npm` print?
Comment: check that `nodejs --version` also returns the correct version
Answer: I just tried npm info which isn't a thing evidently, because I got all errors. But the first line was my OS version, second was PATH to node.exe and PATH to npm-cli.js, third was node version, fourth was npm version. Then invalid package.json, etc, etc
I'm sure there's a right way, but I think it showed me everything you are hoping to see...
Forgive me for suggesting bad answer. Maybe just check your npm-debug.log
Perhaps you can find answers to your questions there.
** EDIT
I found something in npm help
try npm config list
Comment: `npm config list` gave me the `node bin location`, and also led me to `npm config ls -l` which contained a `node-version` string. As it turns out, npm is using an absolute path to /usr/bin/nodejs. The latest version of node is installed to /usr/local/bin/node with a symlink to /usr/local/bin/nodejs, but npm seems happy to ignore my $PATH variable entirely. Now I just need to find a way to point npm to the proper directory and I'm set.


Change the features of Prophet plot

Question: While using model.plot(forecast) the figure that appears has small labels and x/y values.
Is there any way to customize customize prophet's figures ?
Answer: I found there is a way to customize the options in fbprophet such as increasing size of labels or tick values.
fig = model.plot(forecast, xlabel='Date', ylabel='Value')
ax = fig.gca()
ax.set_title("Title", size=34)
ax.set_xlabel("X", size=34)
ax.set_ylabel("Y", size=34)
ax.tick_params(axis="x", labelsize=24)
ax.tick_params(axis="y", labelsize=24)

Answer: The Prophet.plot is quite limiting.
However, the fbprophet.plot.plot function allows the option of specifying the figure size. The default is (10, 6) e.g.
from fbprophet.plot import plot

plot(model, forecast, figsize=(20, 12))

Change the features of Prophet plot


How to create a real-time React application?

Question: I want to create a real-time news application. Just think of a list of countries and the news about that country next to the country name. But the news column should be automatically updated when new news is added to the API.
For Example, I have this endpoint: https://newsdata.io/api/1/news?apikey=YOUR_API_KEY&country=au
In this case, the country is Austria. How can my react application automatically checks the server and fetch the data if there is an update?
I don't want to use setInterval to check it in specific time ranges, can socket io be used in this case?
Comment: Yeah you will want to go with a socket. This will allow your server to push new data out to the react app. You would have your react app subscribe to some service in the socket then anything subscribed to that service on the server would get the pushed data.
Comment: [Server-side events might be better.](https://ably.com/blog/websockets-vs-sse)
Answer: You can use "socket.io-client" for your react app and  "socket.io" for your node server. Your server can raise an event that the react app can handle with the help of "socket.io-client" after each update of the API


How to create a JSON CustomTypeAdapter in Apollo GraphQL on Android with Kotlin

Question: I'm struggling to figure out how to add a CustomTypeAdapter to my ApolloClient.
For a mutation, our server is expecting json input. The corresponding iOS app is passing in a json string.
When I pass in a string I get a message asking if I've forgotten to add a customtype.
Here is my attempt:
build.gradle
apollo {
        useSemanticNaming = true
        customTypeMapping['ISOTime'] = "java.util.Date"
        customTypeMapping['JSON'] = "java.lang.JSONObject"
    }

Here's where it is instantiated.
val jsonCustomTypeAdapter = object : CustomTypeAdapter<JSONObject> {
                override fun decode(value: CustomTypeValue<*>): JSONObject {
                    return JSONObject()
                }

                override fun encode(value: JSONObject): CustomTypeValue<*> {
                    return CustomTypeValue.GraphQLJsonString(value.toString())
                }
            }

 mApolloClient = ApolloClient
                .builder()
                .serverUrl(baseUrl)
                .addCustomTypeAdapter(jsonCustomTypeAdapter)
                .normalizedCache(cacheFactory, CacheKeyResolver.DEFAULT)
                .httpCache(ApolloHttpCache(cacheStore, null))
                .okHttpClient(mHttpClient)
                .build()

It seems Apollo has generated a CustomType enum implementing ScalarType but I'm not sure if or how to use it.
@Generated("Apollo GraphQL")
public enum CustomType implements ScalarType {
  JSON {
    @Override
    public String typeName() {
      return "Json";
    }

    @Override
    public Class javaType() {
      return Object.class;
    }
  },

  ID {
    @Override
    public String typeName() {
      return "ID";
    }

    @Override
    public Class javaType() {
      return String.class;
    }
  }
}

I've attempted the example given on the apolloandroid github  but it hasn't worked for me and it is in Java and after I convert it to Kotlin, it doesn't compile.
Any hints or direction to persue would be appreciated. Thanks.
Answer: It turns out Apollo had auto generated the type and all I had to do was declare it correctly in the build.gradle. I didn't need to add any custom type adapter to the ApolloClient.
NOTE: The type Json was provided by our server.
apollo {
        useSemanticNaming = true
        customTypeMapping['ISOTime'] = "java.util.Date"
        customTypeMapping['Json'] = "java.lang.String"
    }


Relation between mod 2 Betti numbers and integral cohomology

Question: Let $M$ be an orientable connected manifold of finite type. My question is that if $H^{i}(M,\mathbb{Z}_{2})$ is non-zero, then can we say that $H^{i}(M,\mathbb{Z})$ is non-zero? I know that this is not true for non-orientable manifold. For example $\mathbb{R}\text{P}^{2n}.$
Answer: I believe that "$H^i(M;\mathbb{Z}/2)$ non-zero $\implies H^i(M;\mathbb{Z})$ non-zero" does not necessarily hold: note that this statement is equivalent to "$H^i(M;\mathbb{Z})\cong0 \implies H^i(M;\mathbb{Z}/2)\cong0$." However, if we take $M$ to be the orientable $5$-manifold $\mathbb{R}P^5$, then for $i=3$ we indeed have $H^3(\mathbb{R}P^5,\mathbb{Z})\cong0$, but by the UCT
\begin{align}
H^3(\mathbb{R}P^5;\mathbb{Z}/2) &\cong \text{Ext}_\mathbb{Z}^1(H_2(\mathbb{R}P^5;\mathbb{Z}),\mathbb{Z}/2) \oplus \text{Hom}_\mathbb{Z}(H_3(\mathbb{R}P^5;\mathbb{Z}),\mathbb{Z}/2)\\
&\cong \text{Ext}_\mathbb{Z}^1(0,\mathbb{Z}/2) \oplus \text{Hom}_\mathbb{Z}(\mathbb{Z}/2,\mathbb{Z}/2)\\
&\cong \mathbb{Z}/2,
\end{align}
which is non-zero. I hope this is helpful!
Answer: This can fail already for $i = 1$.
It follows from the Universal Coefficient Theorem that $H^1(M; G) \cong \operatorname{Hom}(\pi_1(M), G)$ for any abelian group $G$. There are many groups which admit a non-zero homomorphism to $\mathbb{Z}_2$, but not to $\mathbb{Z}$. So any orientable manifold whose fundamental group is such a group will demonstrate that your question has a negative answer.
Example: For any $n > 0$, the manifold $\mathbb{RP}^{2n+1}$ is orientable with $\pi_1(\mathbb{RP}^{2n+1}) \cong \mathbb{Z}_2$ so $H^1(\mathbb{RP}^{2n+1}; \mathbb{Z}_2) \cong \operatorname{Hom}(\mathbb{Z}_2, \mathbb{Z}_2) \cong \mathbb{Z}_2$ while $H^1(\mathbb{RP}^{2n+1}; \mathbb{Z}) \cong \operatorname{Hom}(\mathbb{Z}_2, \mathbb{Z}) = 0$.

In general, if $H^i(M; \mathbb{Z}_2) \neq 0$ and $H^i(M; \mathbb{Z}) = 0$, then $H^{i+1}(M; \mathbb{Z}) \neq 0$. To see this, note that by the Universal Coefficient Theorem, we have
$$0 \to \operatorname{Ext}(H_{i-1}(M; \mathbb{Z}), \mathbb{Z}) \to H^i(M; \mathbb{Z}) \to \operatorname{Hom}(H_i(M; \mathbb{Z}), \mathbb{Z}) \to 0$$
If $H^i(M; \mathbb{Z}) = 0$, then $H_{i-1}(M; \mathbb{Z})$ is torsion-free and $H_i(M; \mathbb{Z})$ is torsion. By the Universal Coefficient Thereom for $H^i(M; \mathbb{Z})$, we see that $H^i(M; \mathbb{Z}_2) \cong \operatorname{Hom}(H_i(M; \mathbb{Z}), \mathbb{Z}_2)$. So if $H^i(M; \mathbb{Z}_2) \neq 0$, then $H_i(M; \mathbb{Z}) \neq 0$. Now by the Universal Coefficient Theorem for $H^{i+1}(M; \mathbb{Z})$, there is an injection $\operatorname{Ext}(H_i(M; \mathbb{Z}), \mathbb{Z}) \to H^{i+1}(M; \mathbb{Z})$. Since $H_i(M; \mathbb{Z})$ is a non-zero torsion group, we see that $\operatorname{Ext}(H_i(M; \mathbb{Z}), \mathbb{Z}) \neq 0$ and hence $H^{i+1}(M; \mathbb{Z}) \neq 0$.
Example: For $n > 0$, it was observed in the previous example that $H^1(\mathbb{RP}^{2n+1}; \mathbb{Z}_2) \neq 0$ and $H^1(\mathbb{RP}^{2n+1}; \mathbb{Z}) = 0$. In this case, we have $H^2(\mathbb{RP}^{2n+1}; \mathbb{Z}) \cong \mathbb{Z}_2 \neq 0$.


Problems with composer when creating docker image from laravel project

Question: Im new to docker but i have read som guides and tried to create a docker image
from my laravel project.
The docker command im running is

sudo docker build -t docker-image .

and this is my Dockerfile:
FROM composer:1.8.5 as build
WORKDIR /app
COPY . /app
RUN composer install

FROM php:7.3-apache
EXPOSE 80
COPY --from=build /app /app
COPY vhost.conf /etc/apache2/sites-available/000-default.conf
RUN chown -R www-data:www-data /app && a2enmod rewrite

The error comes during step 4/9 Run composer install:

[ErrorException]
  file_put_contents(/app/vendor/bin/generate-defuse-key): failed to open
  stream: No such file or directory

the file exists in /vendor/bin/
can anyone tell me what i am doing wrong?
Comment: Are you open to use laravel with nginx?
Comment: @vikash, it's erroring before the apache step.
Comment: @pei-turn, Try building the composer step without running the install, then run the container and try to install manually from inside. That will give you better insight into what's going on.
Comment: @pei-turn just added the nginx docker settings for laravel application with docker-compose.. please do follow... let me know if you still getting any issue.
Answer: If you would like to run your laravel application with nginx you can use the following docker settings.
Here I supposed your application at: /var/www/laravelapp
So the file coposition would be as follow:
1. Your docker-compose file: /var/www/laravelapp/docker-compose.yml
version: "3.1"
services:
  webserver:
    image: nginx:alpine
    restart: always
    container_name: laravel-webserver
    working_dir: /application
    volumes:
        - /var/www/laravelapp:/application
        - /var/www/laravelapp/docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
    ports:
      - "82:80"
    env_file:
      - .env
    networks:
      - intranet

  php-fpm:
    build: docker/php-fpm
    restart: always
    container_name: laravel-fpm
    working_dir: /application
    volumes:
      - /var/www/laravelapp:/application
    env_file:
      - .env
    networks:
      - intranet

networks:
  intranet:
    external: false

2. Nginx dockerfile /var/www/laravelapp/docker/Dockerfile
FROM phpdockerio/php71-fpm:latest

# Install selected extensions and other stuff
RUN apt-get update \
    && apt-get -y --no-install-recommends install  php7.1-mysql php7.1-mbstring php7.1-gd git \
    && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

WORKDIR "/application"

3. Nginx host settings /var/www/laravelapp/docker/nginx/nginx.conf

server {
    listen 80 default;

    client_max_body_size 108M;

    access_log /var/log/nginx/application.access.log;

    root /application/public;
    index index.php;

    if (!-e $request_filename) {
        rewrite ^.*$ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass php-fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

}

Let me know if still you getting any issue.
Comment: @JamesBond this is the complete configuration for running laravel project with docker.
Answer: I found the problem it was not a docker, composer or laravel problem but a git problem.
the problem was that git could not create a symlink and i missed the error when checking out the project. i found it when i did all the steps again.


Tools in Data Science

Question: I am a new one in Data Science and Machine Learning. I have some experience in Java, Python, SQL, Jupyter and most polular libraries like scikit-learn, numpy, pandas, tensorflow, keras. What tools would you recommend else? And what OS is more suitable for DS (I've heard that Debian)?
Answer: A few essential packages come to mind that every Python statisticians must know:
SciPy, which is based on NumPy, extends NumPy capabilities. You can do linear algebra, probability theory, integral calculus and many more tasks with SciPy.
StatsModels - estimating of statistical models, conducting statistical tests, and statistical data exploration.
Matplotlib - 2-dimensional static plotting, from histograms and scatterplots to non-Cartesian coordinates graphs
Seaborn - high-level API based on matplotlib. It has better default settings for statistical charts, along with a rich collection of visualizations including some complex types like time series, jointplots, and violin diagrams.

Tools in Data Science


Carregar html apenas 1 vez após o 3° parágrafo do texto com jquery?

Question: Tenho esse exemplo mais gostaria que não repetisse, gostaria que aparecesse só uma vez!

$('p').each(function(i) {
  var pos = i + 1;
  console.log(pos, pos % 3, this)
  if (pos % 3 == 0) {
    $('
', {
      class: 'anuncio',
      html: '
Div inserida!
'
    }).insertAfter(this);
  }
});

    $('#phtur').hide().delay(10000).slideToggle('slow');
    $('#phtur').click(function(){
        $("#phtur").slideToggle('slow');

});

 1

 2

 3

 4

 5

 6

 7

Answer: Se trocar:
if (pos % 3 == 0)
por
if (pos == 0)
Resolveria seu problema
Comment: Valeu, deu certo! OBG


Scheduling a module to run at a specific time

Question: Is there any way to schedule a particular sub-module to run at a specific time? I found hook_cron but it seems to rely on a scheduled cron job in crontab to run cron.php and then cron.php calls hook_cron. I have multiple sub-modules that I would like to schedule to run, all at different times. The scheduled times are user-inputted from the front and processed in the main module. Because of this, for hook_cron to work, I would need to pass in parameters from the main module (based on what the user inputted)
Any help is appreciated.
I am using Drupal 6
Answer: Depending on how detailled your specific time is, you could still use hook_cron. For example, let's say the normal cron runs every hour, you could check date('H') in your module and only if it equals a predefined value, the cron function in your submodule will be executed.
function MYMODULE_cron() {
  if (date('H') == 3) {
    // this code will only be executed between 3:00am and 3:59am
    // do your stuff
  }
}

Comment: I updated the question with more details; sorry I did not mention it; basically I need to pass in parameters to hook_cron to set the times.
Answer: Take a look at Ultimate Cron - I think it does what you want.
Comment: thanks...will check it out and also with management if additional 3rd party modules are ok.


Pesquisa que mostra o conteúdo de uma div

Question: Estou tentando criar um site que vai me ajudar aqui no trabalho, que é o seguinte:
Queria que aparecesse na página inicial somente uma caixa de pesquisa, nada mais. Todo conteúdo necessário só iria aparecer conforme eu pesquisasse.
Ex: Ao pesquisar por "receita de pão cru" apareceria minha div com o título e a receita completa, que eu já teria escrito.
Principais perguntas:
Poderiam ao menos iluminar meu caminho para eu prosseguir?
Tem como eu fazer isso sem precisar mexer com SQL? (Não entendo nada de SQL)
Há uma forma de eu criar um monte de DIV e esconde-las, aparecendo-as somente ao serem pesquisadas?
Answer: Aqui tem um exemplo de como fazer isso com Jquery:

  <title>Pesquisar</title>

  <input type="text" id="search-criteria"/>
  <input type="button" id="search" value="Pesquisar"/>

João da Silva

Lucas Santos

Matheus Gonçalves

Comment: PQPPPPP QUE FODA!!! ERA EXATAMENTE ISSO QUE EU QUERIAA!!!!! MUITO OBRIGADO
Answer: Tente o código abaixo: digite doce, ou bolo, etc.

 $(function(){
   var data = {
    "receita":
       [
           {
               "nome":"Doce de Leite Ninho",
               "ingredientes":"200 g de biscoito de maisena.
4 colheres (sopa) de manteiga derretida.
2 caixas de creme de leite.
1 xícara de leite ninho.
24 g de
elatina incolor sem sabor.
200 g de creme de avelã
leite em pó a gosto para finalizar.",
           },
           {
            "nome":"Bolo de Batata Doce",
               "ingredientes":"3 ovos.
1 xícara (chá) de manteiga da terra (manteiga de garrafa)
2 xícaras (chá) de açúcar.
3 xícaras (chá) de farinha de trigo.
3
ícaras (chá) de leite.
1 xícara (chá) de coco ralado.
1 xícara (chá) de leite de coco.
1,5 kg de batata-doce cozida e espremida.",
           },
       ]}

       $("button").click(function(){
        $("#resultado").empty();
        $.each(data.receita, function(i,v){
         var txt = v.nome.toLowerCase();
         var n = txt.indexOf( $("#dsPesquisa").val().toLowerCase() );
         if( ( n >= 0 ) && ( $("#dsPesquisa").val().length >= 3 ) )
          $("#resultado").append('
' + v.nome + '
' + '
' + v.ingredientes + '
')
        })
        return false;
       })

 })
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Hello, world!</title>

Pesquisa de Receitas

      <form name="pesquisa" id="pesquisa">
       <input type="text" name="dsPesquisa" id="dsPesquisa">
       <button>Ok</button>
      </form>


Trying to update windows defender from UNC path continuously fails

Question: I'm trying to update Windows Defender (on Win 10) using definistions stored on a UNC path.
I'm setting the path the the mpam-fe.exe file like this
Set-MpPreference -SignatureDefinitionUpdateFileSharesSources \\path\to\mpam.exe

Then I'm running Get-MpPreference to verify that the path was set (it is). Once I verify that the path is correct for SignatureDefinitionUpdateFileSharesSources I run
Update-MpSignature -UpdateSource FileShares

I instantly get the error
Update-MpSignature : Virus and spyware definitions update was completed with errors.
At line:1 char:1
+ Update-MpSignature -UpdateSource FileShares
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound:    (MSFT_MpSignature:ROOT\Microsoft\...SFT_MpSignature) [Update-MpSignature], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070002,Update-MpSignature

This failure happens almost instantly. Just to verify that the specific powershell instance can access the fileshare in question - I followed it up by just executing the mpam-fe.exe file and it worked.
Comment: Do the permissions on the share include "Domain Computers" so the Defender service can read the data?
Comment: Are you actually specifying the name of the executable mpamfe.exe in the source or are you just specifying the path to the source folder? The source folder is supposed to have more than just the mpamfe.exe file.
Comment: @Clayton No, the permissions aren't set like that but now that you mention it - it completely makes sense that they would need to be. I will tweak the folder permissions so that all domain computers can access and re-test
Comment: @Appleoddity No, i'm only specifying the folder that contains mpam-fe.exe. With that said, there is absolutely nothing else in that folder but from your comment I'm gathering there should be?
Answer: I have never done this before, but your question made me curious and I started doing some testing. I was able to reproduce your issue. It's clear that not many people do this, because there is zero coherent information on the internet about how to do this. So, it's no surprise you're getting nowhere.
So, here is what I discovered while using Process Monitor. I was able to successfully get Defender to update from a file source.

First, the update packages consist of three files: mpam-fe.exe,
mpam-d.exe, and nis_full.exe. I tried using just mpam-fe.exe
and it failed.
Second, there are 32-bit and 64-bit versions of updates. When you run
the Update-MPSignature command it expects to find the updates under
the x64 or x86 folder in your source path. So, you need to create
the additional folders under your source path and place the update
files in there.
Third, the process that updates Windows Defender is wmiprvse.exe
(WMI) - it runs as Local System. Be aware that the connection is made
to the file source using the computer account and not a user account.
I tried several different things to try to get it to connect to a
file share on a domain joined server. This included adding the
computer account, domain computers, Everyone, and Anonymous.
Nothing worked. It failed every time with Access Denied. I was only
able to get it to work when I put the files on my NAS which has zero
security restrictions.

Here's a script that can assist with downloading the update packages: https://www.powershellgallery.com/packages/SignatureDownloadCustomTask/1.4
Here are other references I used to get this to work:
https://technet.microsoft.com/en-us/itpro/powershell/windows/defender/update-mpsignature?f=255&MSPPError=-2147217396
https://technet.microsoft.com/en-us/itpro/powershell/windows/defender/set-mppreference
How to grant network access to LocalSystem account?
https://docs.microsoft.com/en-us/windows/threat-protection/windows-defender-antivirus/manage-protection-updates-windows-defender-antivirus
https://docs.microsoft.com/en-us/windows/threat-protection/windows-defender-antivirus/deployment-vdi-windows-defender-antivirus
http://ccmexec.com/2016/01/download-and-deploy-windows-defender-definitions-for-windows-10-during-osd/
Comment: Wow, thanks. I believe your post is very likely to be the single largest repository of info on the internet regarding this process. In specific, what you posted about the folder structure and needed files is the only place I've found this (and I've specifically looked into that when I was getting failures even when using localhost as the unc path).
Comment: I used the PS script to download the needed files. Once I had the files downloaded to a drive on my system I set the fileshare path as \\127.0.0.1\c$\folder. It was still failing at this point through powershell but when I went into defender itself and ran the update it was successful (and I know it didn't pull it down over the internet because this machine has no connection outside the intranet)
Comment: Ok, did you download the files for your specific architecture to \\127.0.0.1\c$\folder\x64 or x86? I did my testing from powershell, so it should work. Just make sure you downloaded all 3 files to the proper x86 or x64 folder and make sure there aren't any security problems with the share. It's worth noting that I found you don't have to use a UNC path. If you want, you could just specify `C:\folder` for testing purposes.
Comment: Yeah, I created the x64 folder - then dropped the 3 files in there. I then ran "Update-MpSignature -UpdateSource FileShares". It still failed, but this time it at least brought up a progress bar and seemed like it was working for a bit  before giving me a different error (Permission Denied). I'm sure it just had something to do with the context that I was running powershell in. When I went into Defender itself and told it to update, it pulled the files from the fileshare and updated.
Answer: I've had this exact issue. The issue was resolved by creating a x64 folder in the share and moving the definitions to that folder. I can't find this requirement anywhere but it works. SCEP uses this folder structure so that's where I got the idea. Even the script provided by Microsoft doesn't create the architecture folder!
Server setup:

File share (e.g. \\Server\Share$) with full share permissions and Read permissions for Everyone (Domain Computers not required!)
Folder x64 containing 64-bit definition files (e.g. \\Server\Share$\x64\mpam-fe.exe)

Client setup (powershell):
Set-MpPreference -SignatureDefinitionUpdateFileSharesSources \\Server\Share$
Set-MpPreference -SignatureFallbackOrder 'FileShares'
Update-MPSignature

Answer: Appleoddity's answer gives everything you need. Some caveats though;

Update-MpSignature never worked for me in powershell. I spent a lot of time trying to set up the environment for these updates to work and was using Update-MpSignature as the test.
Once I actually run Defender/MSE's built in update function and realized that the update worked correctly in a situation where Update-MpSignature was failing I started backtracking and testing other scenarios which I though weren't working because they were failing through powershell

So basically, as you work through the issue using Appleoddity's guide make sure not to rely solely on powershell and Update-MpSignature to test what you're doing. YMMV but it my case I was never able to succesfully run Update-MpSignature. I had jumped to the conclusion that I had set something up wrong, but after more testing I saw that defender itself was updating without issue and only powershell was having problems.
Answer: Permission Denied Message is caused by Access Denied to the LogFile
C:\Windows\Temp\MpSigStub.log

Just delete this LogFile before running
Update-MpSignature -UpdateSource FileShares -Verbose

Answer: Here is the powershell script I have running hourly on a server, then I just point my clients to it.  The big point was NOT to extract the file.  Windows Defender points to the exe itself.
$vdmpathbase = 'E:\VirusDef\latest\x64'
$vdmpackage = $vdmpathbase + '\mpam-fe.exe'
cmd /c "del $vdmpackage /q"
Invoke-WebRequest -Uri 'https://go.microsoft.com/fwlink/?LinkID=121721&arch=x64' -OutFile $vdmpackage

Answer: Another caveat...
The Defender GUI runs the update download as one of two processes:

MSascui.exe - which uses the current session account (this one can usually access the file share as most defender update file shares would allow read to all)
Msmpeng.exe - which uses the NT AUTHORITY/SYSTEM account (this will have the computer name account, which in most domain-based systems will also allow access)

For the Update-MpSignature cmdlet, it's a bit different.  It runs the update download as wmiprvse.exe which uses NT AUTHORITY/LOCAL SYSTEM.  This account has minimum privileges on the computer and uses anonymous credentials on the network.  Generally speaking, most network shares won't be configured for anonymous access, so this is why you can get the GUI to work, but the cmdlet doesn't.


Fazer processamento no front-end ou no back-end?

Question: Na arquitetura de separação do client-side e do server-side, é comum a dúvida de quem é a responsabilidade de realizar alguns processamentos.
De um lado, processar no client-side pode ser benéfico para a performance do server-side, que se encarrega de entregar o recurso para que seja consumido, formatado e talvez processado no front-end.
Do outro lado, o server-side. Colocar processamento no server-side tem a vantagem de escalar e depender de recursos gerenciados pela própria organização.
Contextualizando em REST
Nos princípios da arquitetura REST, o back-end é responsável para a entrega do recurso, por exemplo:
<code>GET vnb.rs/api/produtos/1
{
  "nome": "Caneca",
  "variações": [
    {
      "cor": "azul",
      "preço": 15.00
    },
    {
      "cor": "vermelha",
      "preço": 18.00
    }
  ]
}
</code>
Se eu precisasse do valor mínimo e máximo das variações (de 15,00 a 18,00 reais) dessa caneca, o responsável por esse cálculo seria do front-end ou do back-end?
O que define que tipo de dado pode ser processado no lado do cliente?
Comment: Acredito que em geral quanto mais no lado do cliente melhor, mas há casos em que isso pode mudar, se o sua aplicação é focada para usuários que não possuem máquinas muito potentes, uma ferramenta para ser usada com aplicações pesadas ou você está fazendo um sistema interno para uma empresa sustentável que ainda usa windows xp
Comment: Interessante notar que até poucos anos atrás, o processamento das informações era feito quase que exclusivamente no servidor, pois era difícil o cliente ter uma máquina que suportasse bem o trabalho. Hoje já estamos numa realidade diferente: até smartphones possuem capacidade para realizar funções pesadas, o que permite passar para o cliente boa parte da responsabilidade, salvando recursos do servidor e reduzindo o custo do projeto (*#UseThePlatform*).
Comment: Não tenho uma resposta completa, mas um argumento para favorecer server-side rendering é que as engines de busca só vão conseguir indexar seu site direito se as informações já estiverem no HTML.
Comment: Interessante seu questionamento, @Pedro. Hoje existe o pre-render de páginas, muito útil para indexação de Single-page applications. Essa é a grande dificuldade para os SPAs em geral.
Comment: O que está disponível no lado do cliente :) E talvez essa seja mesmo a resposta, salvo eu não ter entendido a pergunta
Comment: Concordo com o @Guilherme, acho que o nível de responsabilidade referente a processamento no lado do cliente depende muito do negócio e do tipo de aplicação que você quer desenvolver. Se o seu sistema for atender computadores de supermercados que ainda possuem Windows 95, é bom tirar a responsabilidade de processar dados desse caras.
Answer: Depende muito do que se propõem a aplicação, mas considerando um sistema criado para web onde a indexação por sites de buscas é basicamente irrelevante (já que é um sistema e não um site), eu uso a seguinte estratégia:

O back-end fica responsável apenas por responder os requests com dados puros (em json, por exemplo) e realizar o que o back-end sempre faz (validações, processos, manipulação de dados). Ou seja, ele evita montar views dinâmicas.
Nas views, eu não utilizo loops nem condições em back-end, eu envio o básico (um html com uma chamada de script dentro) e deixo isso para ser montado pelo meu framework javascript, no lado do cliente.

Essa estratégia causam alguns impactos, como:

O servidor não precisa processar coisas à mais, aliviando os processos (parece que não, mas em gerações de relatórios isso pode ser um diferencial).
Os dados que trafegam entre servidor e cliente são apenas dados puros, nada de tags e informações que podem ser construídas no cliente. Imagine uma tela com 1000 registros, voltando mil "tr's" e "td's" ao invés de retornar apenas a string dos dados e montar na tela, há um ganho de performance se a internet do cara não ajudar muito.
Como eu monto tudo no cliente, eu consigo dar um feedback melhor dos processos que estão ocorrendo no cliente. Por exemplo: o cliente me pede um relatório, faço uma requisição no back-end e ai eu consigo informar que estou coletando as informações, quando ela chega, posso informar que estou processando as informações.

O que pode impactar é a performasse do lado do cliente, quando a máquina dele não é boa para processar muitas informações e causa uma lentidão. Mas neste caso seria preciso analisar quantos clientes isso ocorre, se realmente é um grande impacto, qual a frequência que este cliente tem esse problema e etc.
Eu utilizo essa estratégia a alguns anos e já implementei em uma empresa de rastreamento de veículos, onde os relatórios eram gigantescos. Posso lhe dizer que obtive um feedback ótimo por parte, tanto dos clientes, quanto da diretoria. Já que o servidor ficou aliviado de montar views, deixando que processos em paralelo consigam executar mais rapidamente, e os clientes tiveram feedback's melhores do que estava acontecendo na tela.
Comment: Quanto a esse feedback, acredito que não faria diferença entre ele esperar 1s pelo servidor e 1s pela máquina ou 2s pelo servidor (na maioria dos casos), em alguns casos é possível mostrar pequenas partes desses relatórios (ou qualquer outro dado), o que seria interessante, o cliente olha uma parte e quando terminar a próxima já estará pronta


How can I use Drush to sanitize a database on a remote server?

Question: I'm on Pantheon and I want to run some custom SQL queries to sanitize my dev server.
I have the queries in a file, custom_sanitize.sqlqueries.
It looks something like this:
UPDATE user__field_useragent SET field_useragent_value = 'Sputnik';
UPDATE node__field_useragent SET field_useragent_value = 'Sputnik';
UPDATE node_revision__field_useragent SET field_useragent_value = 'Sputnik';

TRUNCATE TABLE watchdog;

Goal
I want to run these queries on a remote server with a single Drush command.
My Current Workaround
I connect to the database with Sequel Pro, cut and paste the queries in, and run them.
What I tried
Based on the Drush 8 sql-query documentation, I tried to execute my file like this:
drush @alias.dev sql-query --file=custom_sanitize.sqlqueries

This fails:
failed to open stream: No     [warning]
such file or directory drush.inc:904

I assume this is because my local drush calls the remote drush on the server, and the file path is different.
So then I tried to input the content of the file this way:
`drush @alias.dev sql-connect` < custom_sanitize.sqlqueries

This fails with the following message:
-bash: PTY: command not found

So then I tried inputting the queries in at the command line:
drush @alias.dev sql-query "UPDATE node_revision__field_useragent SET field_useragent_value = 'Sputnik';TRUNCATE TABLE watchdog;"

This also fails:
PTY allocation request failed on channel 0
Command not supported as typed.

I also tried using hook_drush_sql_sync_sanitize(), but I couldn't get my hook picked up by the drush on Pantheon.
Answer: You can use sql-cli command for that:

drush @alias.dev sql-cli < custom_sanitize.sql
Comment: I tried that but i get the following output when sending a `.sql` file with a single line about truncating the watchdog table: `Pseudo-terminal will not be allocated because stdin is not a terminal.
TRUNCATE TABLE watchdog;

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

TERM environment variable not set.`  On the server, the watchdog table is not truncated.
Comment: can you ssh to the remote? It seems it is rather an ssh problem than drush.
Comment: No `ssh` on Pantheon, alas.
Comment: Then, I guess, you are out of luck, unless there are some instructions special to Pantheon. I have no experience with Pantheon, so I cannot help any further. Did you ask the Pantheon support about that?
Answer: Pantheon's terminus can skip drush, and pipe SQL directly into a "mysql connection command"
echo 'UPDATE users SET pass="12345"' | `terminus connection:info mysite.dev --field=mysql_command`

(source)
Answer: You could use the db_sanitization Quicksilver example, and sanitize automatically every time you pulled the database into your dev environment.
If that doesn't work for you, open a ticket with Pantheon, and I will look at it on Monday (if someone else doesn't help you sooner than that).
Comment: Alas, the example didn't work for me (in Drupal 8).  I opened a ticket.
Answer: As a workaround, you can input the queries one by one:
drush @alias.dev sql-query "TRUNCATE table watchdog"

So, you can change every query in custom_sanitize.sqlqueries to be drush @alias.dev sql-query "myquery", and then execute that file.


Confidence interval for sum of independent but not identical bernoulli RVs with small sample size

Question: I have a small sample size (5 <= N <= 10), and for each sample i, we observe independent $Y_{i}$ where $Y_{i}$ is the sum of 7 independent yes/no responses (i.e. bernoulli experiments), where each response is independent but has a different probability of success. Formally, $Y_{i} = \sum_{j=1}^{7} W_{ij}$ and $W_{ij} \sim Bernoulli(p_{j})$. My goal is to perform inference on $E[Y_{i}]$, which I believe is $\sum_{j=1}^{7} p_{j}$. The small sample size also makes this challenging. For any individual $p_{j}$ you could do something like the Agresti-Coull interval to get a confidence interval, but I'd be interested if there are thoughts on how your approach would change when performing inference on the sum of these probabilities.
Comment: This is called the [Poisson binomial distribution](https://en.wikipedia.org/wiki/Poisson_binomial_distribution).  Perusing that tag might help you!
Comment: @kjetilbhalvorsen thank you, this looks very promising!
Answer: The paper "Simple Buehler-optimal confidence intervals on the average success probability of independent Bernoulli trials" by Bancal and Sekatski (https://arxiv.org/pdf/2212.12558.pdf) would provide one solution.
That paper studies the following problem: given $m$ independent but non-identical Bernoulli draws, produce a one-sided confidence interval for the average of the Bernoulli parameters.
To apply this to your problem, consider that you have $m=7N$ independent Bernoulli draws in the form of $W\in \mathbb{R}^{N\times 7}$, each with $W_{ij}\sim \mathrm{Bernoulli}(q_{ij})$.  In your special case we have that $q_{ij}=p_j$.  The paper above gives you a way to put a confidence interval on what they call $\bar q = \sum_{i=1}^N \sum_{j=1}^7 q_{ij} / (7N) = \sum_{j=1}^N p_{j} / 7$.  That, in turn, implies a confidence interval on $\sum_{j=1}^N p_j = 7\bar q$ (just multiply the confidence interval from the paper by 7).
Note. It might be possible to use the fact that $q_{ij}=p_j$ to enable tighter confidence intervals.  Not sure.


What exactly defines a database as a "SQL database"?

Question: From what I understand, Microsoft SQL Server, MySQL, etc., are all "SQL databases", their syntax is about 90% similar, and their underlying implementation is different. I'm curious what exactly defines a SQL database.
Is there a SQL language standard that "SQL databases" extend? Or was SQL originally defined as "the language that Microsoft SQL Server reads" and then engines that read variations of the language became known as "SQL databases"?
Comment: May be of value to know about the concept of Relational Database, see for example:https://en.wikipedia.org/wiki/Codd%27s_12_rules
Comment: Voting to close this question as off-topic because it has nothing to do with programming. There's no code, and no evidence of research.
Answer: From here: https://en.wikipedia.org/wiki/SQL

SQL became a standard of the American National Standards Institute
  (ANSI) in 1986, and of the International Organization for
  Standardization (ISO) in 1987.

And a bit more from here: https://en.wikipedia.org/wiki/ISO_9075

<code>SQL:1999 is the ISO/IEC 9075:1999 standard of 1999.
SQL:2003 is the ISO/IEC 9075:2003 standard of 2003.
SQL:2006 is the ISO/IEC 9075:2006 standard of 2006.
SQL:2008 is the ISO/IEC 9075:2008 standard of 2008.
SQL:2011 is the ISO/IEC 9075:2011 standard of 2011.
</code>

So the answer is Yes. The SQL language has a couple of standards.
The history is a bit more complex. It started with this step:

SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s.

(From: https://en.wikipedia.org/wiki/SQL#History)


Mailchimp like email templates for individual email / transactional email

Question: Please, see the screenshot (of an email) that I received for my transaction.
I would like to create the similar email template for the users who interact on my site.
I really like mailchimp and it is email templates.  But I cannot send a transactional email, triggered by the recipient's action like purchase confirmations etc.  I came to know about mandrill, but I could not sign up for mandrill.
I want to know how these email templates (refer above screenshot) are created... is there any free website that I can use?
Answer: There is also something called Mautic. This is an open source marketing automation tool. Which has lots of possibilities and where you can also use your own email templates.
Hope this helps in a way!


How to select the "best" distribution of the errors in linear data?

Question: The maximum likelihood estimator for linear data $y_i = \beta x_i + \epsilon_i$ with i.i.d. normally distributed errors $\epsilon_i \sim \mathcal{N}(0,\sigma^2)$  is ordinary least squares, i.e.
$$\hat{\beta}_{\text{Normal}} = \text{argmin}_\beta \sum_i (y_i-\beta x_i)^2.$$
However, if the errors are Laplace distributed, $\epsilon_i \sim \mathcal{L}(0, b)$, the MLE turns out to be
$$\hat{\beta}_{\text{Laplace}} = \text{argmin}_\beta \sum_i |y_i-\beta x_i|,$$
which is L1 regression. In principle, I don't see anything preventing our errors from following any zero-mean distribution, and deriving an appropriate minimization problem, either analytically or computationally.
However, how can we find the distribution of the errors? For example, suppose we fit an L1 regression to the data and a statistical test confirms the residuals $r_i$ are Laplace distributed. Then we can be reasonably confident that we selected the "right type of regression" (L1 regression rather than, say, OLS). But what if we perform a robust regression and the residuals $r_i$ don't look Laplace distributed?
In general, is there some sort of procedure for selecting the "best" distribution for $\epsilon_i$, in the sense that when you solve the corresponding minimization problem for $\hat{\beta}$, the residuals $r_i = y_i - \hat{\beta}x_i$ follow the same distribution you initially assumed the errors $\epsilon_i$ would follow?
Comment: Note that L1-regression (i.e. with absolute value loss function as derived from the Laplace distribution) is not robust against leverage points (which also cause the biggest issues with LS-regression), so if you are after properly robust regression, you should go for something else, such as the MM-estimator.
Comment: No statistical test can ever confirm that any model holds (no test can prove that the null hypothesis is true). Worse, whatever any test says, there is always the possibility that model assumptions are critically violated and we can't see it (e.g. by irregular dependence).
Comment: Why would Laplace errors/[minimum absolute deviation estimation](https://stats.stackexchange.com/q/46019) be considered "robust regression"? If anything, that term would apply to [regression with t-distributed errors](https://stats.stackexchange.com/q/120776).
Comment: @Durden Hmm, my mistake, I could have swore I heard the absolute error regression called "robust regression" before, but now I can't seem to find a source on it. I must have been misremembering.
Answer: You can always try different distributions and compare (penalized) likelihoods to get a measure of what fits best. This provides a solution, but can be criticized for being purely data-based as opposed to theory-based. Also many models will fit nearly equally well, so it is not at all definitive. You also have to take care when comparing models with transformed Y versus non-transformed Y, and you have to take care when comparing discrete versus continuous models. Nevertheless, it provides an answer, and there are several worked examples in here https://www.google.com/books/edition/Understanding_Regression_Analysis/y3jtDwAAQBAJ?hl=en using this approach.
One bad idea is to fit a distribution to the residuals. While you will find many people on this site stating that the distribution assumption refers to the errors, and not to Y, this statement can be misleading and lead to bad practice. It is misleading in the sense that the assumption really refers to the conditional distributions of the errors, which equivalently means that it refers to the conditional distributions of the Y's.
So if one were to fit a distribution to the residuals in the hypothetical case where the conditional distributions were normal but heteroscedastic, one would likely conclude that the distribution was heavy-tailed rather than normal.
Further, if the Y data were discrete, and a distribution was found using the residuals, a continuous model would be chosen incorrectly.
Answer: The first thing to understand about issues like this one is that statistical models live in the land of mathematics rather than in real life, and in real life no statistical model is ever fulfilled (arguably frequentist probabilities don't really exist in the first place, let alone i.i.d. residuals, continuous distributions, and whatnot).
So in any real situation, neither will the normal be the "true" error distribution, nor the Laplace, nor actually anything that can be written down.
The reason why we use model-based theory is that it gives us an idea what to do, which will work well in an idealised situation in the world of mathematics. This is is at least something, even though it doesn't guarantee us that the method will work well in reality. But the idea that in order to apply a method derived from a model-based approach, the model must be true in reality is wrong (if that were the case, we could never apply anything).
Both the LS-regression and the L1-regression (the ML for Laplace) fit a regression line/hyperplane to the data in a well defined and intuitively reasonable way (minimising the sum of squared, or unsquared deviations). When it comes to choosing between them (or even other methods such as proper breakdown robust estimators such as MM), we need to use all understanding that we have, which includes model-based theoretical results, but also other things, like regarding the way how outliers affect both of these estimators (the LS somewhat more), numerical instability of L1, potentially good asymptotic properties of the LS-estimator and derived inference for many non-normal distributions due to the central limit theorem.
Obviously we may hope that if data look roughly like following the assumed model, we will be better off than if they don't, so comparing the data with the assumed model makes some sense, but it has severe limitations. For example, if you take any well defined distance between distributions, it is not true in general that the LS-estimator will work the better, the closer the empirical residual distribution is to the normal distribution.
The task of model diagnostics is not to find out any "best" model for the errors, but rather to see whether the data have characteristics (such as outliers) that will lead to potentially misleading results, which also needs to take into account how in the real situation of interest results are going to be interpreted and used, and whether it for example is possible to monitor the data generating process in such a way that erroneous observations that are potential outliers can be reliably spotted and removed before analysis.


Help me to understand more interesting improv techniques

Question: Question for all, doesn't have to be specific to jazz.
I love to improvise, and I'm definitely not new to it. This is something that I have been doing for many years.
I'm in a bit of a rut at the moment: I can't think of new things to do in my improvisations.
I generally mix a few different ideas when improvising -
really strong with good pentatonic soloing, this kind of vibe:

a strong point, but not quite as fun, I implement a lot of short arpeggiated 7ths and 9ths interpsersed between these pentatonic noodlings.
I often connect with chromaticism and enclosures.
I also like to shred through blues scales, interspersed with petermartin style pentatonic shredding.
to articulate my improv picture a gmaj251.
over the 2 I might descend through a and e pentatonic with some chromaticism, arpeggiate through a 5#9b11, and then descend through the 1 with pentatonic, rising through the g with an arpeggio to the 9th that descends chromatically to the 7.
Generally my improv follows these ideas with some variation.
I really like playing the super experimental high energy modern jazz solos. anyone have suggestions for playing that fits that vibe?
Comment: Does this answer your question? [How to learn piano improvisation](https://music.stackexchange.com/questions/9386/how-to-learn-piano-improvisation). This forum is full of relevant questions and answers. You could start by working your way through them.
Comment: Please check out what already exists here - there's plenty of meat to chew through!
Answer: This is a very broad question to answer but I will make one suggestion to you and if you are unaware of this it will help you develop a lot more color and sophistication in your playing.
My suggestion is to learn and use some of the modes of the ascending melodic minor scale, also called the jazz minor scale. This scale has several modes that are extremely useful for advanced contemporary harmony. Here are all of them:

Melodic minor: 1 2 b3 4 5 6 7 8

Dorian b2: 1 b2 b3 4 5 6 b7 8

Lydian augmented: 1 2 3 #4 #5 6 7 8

Lydian dominant: 1 2 3 #4 5 6 b7 8

Mixolydian b6: 1 2 3 4 5 b6 b7 8

Locrian natural 2: 1 2 b3 4 b5 b6 b7 8

Super locrian (Altered scale): 1 b2 b3 b4 b5 b6 b7
(Referred to by jazz players as 1 b9 #9 3 #11/b5 b13 b7 8)

Out of all of these, 1,4,6 and 7 are the most useful.
Mode 1 works well on m6, m6/9 and m(maj7) chords
Mode 4 works well for 9, #11 and 13
Mode 6  Works well for m7b5 chords
Mode 7 works well for chords with altered tensions
There are uses for the other three, for example Mode 3 can be used for +maj7 chords but +maj7 chords are not that commonly used. The four I mentioned are by far the most common.
I like the way the jazz minor scale sounds and feels so sometimes I conceptualize these scales by playing a jazz minor scale on different chord tones in order to access the different modes, for example, if I'm playing a:
C13#11 I will play a jazz minor scale built on the 5th, or a G jazz minor scale.
Cm7b5 I will play a jazz minor scale built on the b3,or an Eb jazz minor scale.
C7 alt I will play a jazz minor scale built on the b2, or a Db jazz minor scale


php Storing S_SESSIONS with same name passed through ajax

Question: I have jquery onclick triger that pass:
var product = id;
var name = name;
$.post("./shop/basket.php", {"product": product,"name": name});

to basket.php where I store:
$_SESSION['product'] = $_POST['product'].'-'.$_POST['name'];

But each time a new click is generated it rewrites the S_SESSION instead of adding it as new $_SESSION.
How to store all values in $_SESSION['product'] so I can loop it later and extract each $_SESSION['product'] ?
Thank you in advance
Comment: wow.. `$_SESSION['product'][] = ....`
Answer: $_SESSION['product'][]=$_POST['product'].'-'.$_POST['name'];
//[] makes it multi-dimensional so you can hold multiple product values

To loop through the values use foreach():
foreach($_SESSION['product'] as $key=>$val){
    echo $key.' - '.$val."
";
}

Comment: I tried this before I post the question but when I loop it echo prints only 1 $_SESSION - 0 - 793-Unisex - is it possible on page refresh to loose data?
Comment: @thecore7 No, unless you have a `session_destroy()` somewhere at the end of your code. Could you paste your full code?


after specific seconds android request to the servlet for retrieving the new data if new data is available

Question: i just creating an android ap. so in that i created a connection with http to servlet. but i want that request is pass automatic after few seconds. so help me to find solution.
this is my connector class
public String Intraday() {
    String url = URL+"?flag="+"intra";
    httpPost = new HttpPost(url);
    try{
        HttpResponse httpResponse = httpclient.execute(httpPost);
        int statuscode = httpResponse.getStatusLine().getStatusCode();
        if(statuscode == 200){
            String responceMsg = getResponse(httpResponse);
            return responceMsg;
        }else{
            return null;
        }
    }catch(ClientProtocolException e){
        Log.e(TAG, e.getMessage(),e);
    }catch (IOException e) {
        Log.e(TAG, e.getMessage(),e);
    }
    return null;
}

this is the class from i calling my connector class now tell me where i put the code of thread??
try
        {
        String str = Connector.getInstance().Intraday();  //now tell me where i write

        String st = new String(str);
        Log.e("Main",st);
        String[] rows  = st.split("_");
        TableLayout tableLayout = (TableLayout)findViewById(R.id.tab);
        tableLayout.removeAllViews();

        for(int i=0;i<rows.length;i++){
            String row  = rows[i];
            TableRow tableRow = new TableRow(getApplicationContext());
            final String[] cols = row.split(";");
            IntraThread popup = null;
            Handler handler = null;

            for (int j = 0; j < cols.length; j++) {

                final String col = cols[j];
                final TextView columsView = new TextView(getApplicationContext());
                columsView.setText(String.format("%7s", col));
                tableRow.addView(columsView);

                if(j==0)
                {
                    head= col;
                }
                if(j==2)
                {
                    price = Integer.parseInt(col);
                }
                if(j==4)
                {
                    target = Integer.parseInt(col);
                }

                if(j==5)
                {
                    handler = new Handler();
                    ltp = Integer.parseInt(col);
                    popup = new IntraThread(handler,head, target,ltp,price,Intraday.this,columsView);

                }
                if(j==6){

                    popup.setColumnViewexit(columsView);
                    handler.postDelayed(popup, 300);
                }

            }
            tableLayout.addView(tableRow);
        }
    }

    catch(Exception e)
    {
        Log.e("Main",e.toString());
    }

Comment: @T0X1C: I've updated my question. Take a look.
Answer: Here is short of dummy code modify it to suit  your needs
    String str;
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            while(true)
            {
                str = Connector.getInstance().Intraday();  //This is edited code
                Thread.sleep(few seconds);
            }
        }
    }).start();

Replace the first line in Try String str = Connector.getInstance().Intraday();  //now tell me where i write with the code above provided
Comment: i modify my code. bt create fatal error of thread....My method in another class and i called it from another class.. so where i write this.. plz guide me..
Comment: You will write this code in the class from where you are calling the method and wrap Thread.sleep using try catch
Comment: I have changed the answer implement that if its still not clear reply I will try to make it more clearer to you
Comment: i just modify str as final.. bt "error The final local variable str cannot be assigned, since it is defined in an enclosing type"
Comment: 02-28 12:23:54.524: ERROR/AndroidRuntime(464): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Comment: debug your code and tell on which line its appearing it simple related to some other problem not this one
Comment: android makes problem when handler is initilize in run() so i just initialize handler out of thread so now its working.... thank you so much.. really..


There are no primary or candidate keys in the referenced table in sql server 2008

Question: ClassCode Table
CREATE TABLE [dbo].[ClassCode](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ClassName] [nvarchar](50) NOT NULL,
[ClassRange] [int] NOT NULL,
[ClassDuration] numeric(38,2) NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL,
 CONSTRAINT [PK_ClassCode] PRIMARY KEY CLUSTERED
(
    [SchoolCode] ASC,
    [ClassCode] ASC,
    [ClassRange]
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ExamDeclaration Table
CREATE TABLE [dbo].[ExamDeclaration](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ExamCode] [nvarchar](4) NOT NULL,
[RegistationFess] numeric(38,2) NOT NULL,
[RegistatinStartDate] [date] NOT NULL,
[RegistatinEndDate] [date] NOT NULL,
[ExamStartDate] [date] NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL
 CONSTRAINT [PK_ExamDeclaration] PRIMARY KEY CLUSTERED
(
    [SchoolCode] ASC,
    [ClassCode] ASC,
    [ExamCode] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[ExamDeclaration]  WITH CHECK ADD  CONSTRAINT [FK_ExamDeclaration_ClassCode] FOREIGN KEY([ClassCode])
REFERENCES [dbo].[ClassCode] ([ClassCode])
GO

ALTER TABLE [dbo].[ExamDeclaration] CHECK CONSTRAINT [FK_ExamDeclaration_ClassCode]
GO

I am trying to set Foreign key ClassCode
but got this error

Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
  keys in the referenced table 'dbo.ClassCode' that match the
  referencing column list in the foreign key
  'FK_ExamDeclaration_ClassCode'. Msg 1750, Level 16, State 0, Line 2
  Could not create constraint. See previous errors. Msg 4917, Level 16,
  State 0, Line 2 Constraint 'FK_ExamDeclaration_ClassCode' does not
  exist. Msg 4916, Level 16, State 0, Line 2 Could not enable or disable
  the constraint. See previous errors.

What is the problem in these two tables?
thank you..
Comment: You can't reference only a portion of a composite key with a foreign key. The primary key in ClassCode is 3 columns but you are trying to only reference the ClassCode as your foreign key in ExamDeclaration.
Comment: You must have claacode as pk or unique index in reference table classcode. You have not such pk.
Answer: Your foreign key must match exactly the primary key!
If you declare the primary key like this PK(X int,Y int, Z int), then the FK must be declared like this: FK (a int, b int, c int) references MyTable(X,Y,Z).
In your case, your Pk is (SchoolCode, ClassCode, ClassRange). This means you should declare FK like this:
ALTER TABLE [dbo].[ExamDeclaration]  WITH CHECK ADD  CONSTRAINT [FK_ExamDeclaration_ClassCode] FOREIGN KEY(SchoolCode, ClassCode, ClassRange)
REFERENCES [dbo].[ClassCode] (SchoolCode, ClassCode, ClassRange)
GO

Modify your table ExamDeclaration, add column 'ClassRange'.


Importar Vue ou outros componentes em componentes filho

Question: Tenho uma aplicação em VueJs2, na qual tenho um app.js, aonde instâncio o Vue e faço os imports (Templates, plugins, etc). Acontece que alguns plugins/libs eu consigo utilizar normalmente dentro de componentes filho (axios, por exemplo), já outros eu preciso fazer o import/use novamente dentro do componente. Exemplo: Vuex.
Meu app.js
//Vue
import Vue from 'vue'

//Axios
import axios from 'axios'

//Vuex
import Vuex from 'vuex'
Vue.use(Vuex)

...

//Main
new Vue({
    router,
    render: h => h(App)
}).$mount('#app')

Nesse contexto eu consigo utilizar o axios dentro dos componentes, normalmente. Sem necessidade de "re-importar" dentro do componente. Ele fica global.
Um componente qualquer (importado no meu app.js e funcionando)

No contexto acima, se eu tentar usar um Vuex, eu não consegueria. Como já mencionado, eu conseguiria (e consigo) usar o axios ou outra lib.
Dessa forma dá certo

Obrigatóriamente preciso inserir o Vue, inclusive. Se eu só importar o Vuex, ele acusa erro na falta do Vue.
O Vuex é só um exemplo. Ocorre com outras libs. Estou tendo essa dificuldade e não quero re-importar os plugins/libs... a não ser que realmente esse seja o jeito certo (e gostaria de saber pq no app.js não fica global).
Obrigado
Answer: Você pode passar sua store do Vuex na criação do app da mesma maneira que passa o router. Algo assim:
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = Vuex.Store({
    state: {
        propriedade: 'valor'
    },
    mutations: {
        // ...
    }
});

const app = new Vue({
    store // ou store: store
}).$mount('#app');

Depois, dentro de um método de componente, você pode se referir à store assim com this.$store.
Comment: Sim, de qualquer lugar onde você possa acessar o `this` do componente @MarcoGarcia
Comment: Ótima resposta! Obrigado.
Comment: Só uma dúvida: vc diz "dentro de um método de componente" ... eu poderia utilizar uma store fora de um método (mounted, created, etc.) ?
Answer: Vue.use faz o plugin se torna "parte" do Vue, passando a ser global(Acredito que seja isso que acontece). Logo oq vc "usou" var estar disponivel na propria instancia do Vue.
No caso do Vuex voce pode acessar com this.$store
No caso do Router voce pode acessar com this.$router


When using custom twig expressions to rewrite view title, the breadcrumb shows the twig expression without replacing it

Question: In some of the views, I needed to customize the title using twig. For example {{ title }} which would read the title of the first row in the view result and place it in the page title. This works fine.
The problem is with the breadcrumb. It shows as Some Parent page > {{ title }} without replacing the {{ title }} with its actual value.
I guess a solution could be something along the lines of placing some code in THEME_preprocess_breadcrumb, but I am not sure what to write there exactly. But shouldn't this functionality be something out of the box?
P.S. Not all my views are using {{ title }}, actually some of them are a little more complex, and some views are parents of other views path-wise. So solutions like in this Q doesn't help.
Answer: I had a similar issue where I needed my view title to be {{ field_first_name }} {{ field_last_name }}. The head title tag and page title were correct, but the twig variable's value wasn't being rendered for the breadcrumb.
I ended up writing a tiny module in which I get the title then set the title to the title. Somehow, doing this in post_render makes the twig get rendered correctly in the breadcrumb. Hopefully someone will come along and tell us why this works or why it was needed.
?php
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_render().
 */
function peopleview_views_post_render(ViewExecutable $view) {
 if ($view->id() == 'people') {
  $title = $view->getTitle();
  // Set the view title.
  $view->setTitle($title);
  // Set the route title.
  $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
  $route->setDefault('_title', $title);
 }
}

Comment: Doesn't make sense to me that those folks don't do that already in core!
Comment: I have a view that is matching a node and a contextual filter and using two values from the referenced node field in the title. Page title was fine but the meta one was showing something like "bla {{ bla }} bla bla {{ bla }}"

I used that function to solve it. Why isn't this issue solved yet? Or was I doing it wrong initially.


Fluid force on the surface of a dam.

Question: The figure to the right shows the shape and dimensions of a small dam. Assuming the water level is at the top of the dam, find the total force on the face of the dam. Use 1000 kg/m3 for the density of water and 9.8 m/s2 for the acceleration due to gravity.
Here's the image for the dam.
I know the formula for the integral for fluid force but I just can't figure out a width for any y on the trapezoid. Please help.
Answer: The width depends linearly on the height $h$.  At the top ($h=36$) it's 48,  and at the bottom ($h=0$) it's 24.  So the width is $w-w_0=m(h-h_0)$, where $m=(48-24) / (36-0)$ and you can take $w_0=24$, $h_0=0$.  Plugging these numbers in gives $w=\frac{2}{3}h+24$.

Fluid force on the surface of a dam.


complex numbers equation, find all z...

Question: So i have to find all $z\in \mathbb{C}$
that solve these two equations(separately)
first:
$\bar{z}+z=i(\bar{z}-z)$
second:
$\bar{z}+z^n=i(\bar{z}-z^n), \forall n \in\mathbb{N}$
So basically, i think that first one is solved with just defining $z=a+bi$ and the second one with moivre formule, but i'm not sure.
(But i also want to know if it's possible to solve the second one after i solve the first, and try for few other $n$ and then prove with induction that it works, or is that wrong?)
Answer: $\bar{z} + z^n =i(\bar{z} - z^n ) \Longleftrightarrow (1-i) \bar{z} + (1+i)z^n =0 \Longleftrightarrow 2\bar{z} +2i z^n = 0 \Longleftrightarrow \bar{z} +iz^n =0\Longleftrightarrow |z|^2 +iz^{n+1} =0 \Longrightarrow (z^{n+1} \in i\mathbb{R}_+ \wedge ( n+1 =2 \vee |z|=1 )) $
Since the case $n=1 $ and $z^2 \in i\mathbb{R}_+ $ is trivial. We considel only the case $|z|=1$ i.e. $z=\cos \varphi +i\sin \varphi. $ Because $z^{n+1} \in i\mathbb{R}_+$ we get $$\cos (n+1)\varphi =0 $$ and $$\sin (n+1)\varphi \geqslant 0$$ thus $$\varphi =\frac{\pi}{2(n+1)} + \frac{2k\pi}{n+1} $$ hence $$z=\cos \left(\frac{\pi}{2(n+1)} + \frac{2k\pi}{n+1}\right) +i\sin \left(\frac{\pi}{2(n+1)} + \frac{2k\pi}{n+1}\right).$$
Comment: I've got another question @MotylaNogaTomkaMazura what does $i\mathbb{R}_+ $ mean?
Comment: $i\mathbb{R}_+ =\{ti :t\geqslant 0\}$
Answer: Let $m,n\in \mathbb{N}$ and $m\neq n$, we have two equations:
$$\begin{cases}
\bar{z}+z^{m}=i(\bar{z}-z^{m}) &  \\
\bar{z}+z^{n}=i(\bar{z}-z^{n}) &
\end{cases}$$
Then we have,
$$z^{m}-z^{n}=i(z^{n}-z^{m})$$
If $z^{m}\neq z^{n}$, we have $-1 = i$, a contradiction.
Therefore $z^{m}=z^{n}, \forall m,n\in \mathbb{N}$.
Take $m=1,n=2$, we have $z=0,1$ .
But only $z=0$ satisfies the equation $\bar{z}+z^{n}=i(\bar{z}-z^{n})$.
Comment: I think that the answer should be in relation with natural numbers,while we always had that way. By the way,look at the other answer,i came to the same conclusion afterward as that person.

complex numbers equation, find all z...


Change content of $page['content'] variable

Question: I have overwritten my login page with a file named page--user--login.tpl.php. Now I have this:

    <section<?php print $content_column_class; ?>>

Xmed.be Stocksolutions

"We help you Xchange your stock"

      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>

<?php print render($action_links); ?>

      <?php endif; ?>
      <?php print render($page['content']); ?>
      NO ACCOUNT? REGISTER
      FORGOT PASSWORD?

As you can see I added two links at the end (register and password). But I would like them to be inside $page['content'], so that they are in the section. How can I edit the $content variable, loop through it or something?
UPDATE:
Now I've added in my template.php:
function hook_form_user_login_alter(&$form, &$form_state, $form_id) {
    var_dump('test');
}

But I'm not getting test around my form (also looked in html).
I've also already tried:
function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

But no result or something ...
Comment: You mean $page['content'], not $content...
Comment: yes, sorry. Changed it.
Answer: You can use hook_page_alter to add them into the content array:
function YOUR_MODULE_page_alter(&$page) {

  // Check if this is the correct page.
  if(!isset($page['content']['system_main']['#form_id']) || $page['content']['system_main']['#form_id'] != 'user_login') return;

  // Add links.
  $page['content']['system_main']['register'] = array(
    '#markup' => '
NO ACCOUNT? REGISTER
',
    '#weight' => 20
  );
  $page['content']['system_main']['password'] = array(
    '#markup' => '
FORGOT PASSWORD?
',
    '#weight' => 21
  );

}

Another option here would be to use hook_form_alter instead. Although hook_form_FORM_ID_alter may well be the most efficient option as it will only run for this specific form removing any overhead from other pages.
Comment: And I add this in my template.php from my subtheme?
Comment: Yes, I think you can add any alter hook in template.php.
Comment: I've updated my begin topic ..
Comment: Replace the work hook with your theme name.
Comment: Maybe read [Understanding the hook system for Drupal modules](https://drupal.org/node/292) and [Drupal Hooks Explained](http://www.wintercreative.com/blog/2014/04/07/drupal-hooks-explained.html) or maybe even [A Very Introduction to Drupal's hook_form_alter()](http://websmiths.co/blog/very-introduction-drupals-hookformalter)