High-level time-series question: How does one study a series' trend?

Question: I want to understand a series' trend, not the deviations from the trend. I would like to do analysis on the trend, such as run a multivariate regression, but every time-series source I read online says that we must decompose (or difference) the data and run the analysis on the stationary data. But that's not what I want to do. I want to inspect the trend itself.
For example, if I want to study manufacturing jobs in the United States, I would see that it increased until around 1980, then started to decline. If I wanted to run an analysis on this, a source would tell me to detrend the data, etc. But what if I want to understand and explain the forces underlying trend? I want to look for the reasons for the increase and then the eventual reversal in the trend and subsequent decline. How would I run an analysis on that? Pretty much, I would like to study the serial correlation, not remove it.
I don't expect an in-depth lecture on time-series. If you could provide some explanation and links to sources, that would be great.
Answer: Please see https://stats.stackexchange.com/search?q=user%3A3382+trends for a number of my posts on this subject. Generally speaking a trend may be due to some unspecified causal variable and can be treated as either a stochastic or deterministic model. The stochastic model for a trend is simply a differenced model with a steady state constant (drift) . A deterministic model for trend could contain predictor series containing the counting numbers eg. 1,2,3,4,... to deal with observed data like 11,12,13,14,15,17,19,21,23,25 ....
You ask "But what if I want to understand and explain the forces underlying trend? I want to look for the reasons for the increase and then the eventual reversal in the trend and subsequent decline." First one needs to identify the time points where the significant trend changes occurred and then attempt to investigate/understand/blame possible omitted causal factors "explaining" the observed breakpoints in trend.
Differencing should not be done willy-nilly as the trend may be deterministic in form.
Deviations from trend are important to be be able to identify trends e.g. pulses and memory effects need to be considered in the identification of trends.
Comment: Could you explicitly show how this responds to the question?  In its current form it seems to brush aside the OP's stated concerns about the information lost in differencing and their objective of estimating rates of change rather than the values themselves.
Comment: Thanks for your response. I checked the link and found some interesting hints, but the questions that alluded to similar issues seemed to deal with univariate models.
Comment: Also, to clarify, it is the deterministic trend that I want to explain, not write off by using integers as a predictor. I'm also assuming that the trend is not stochastic. You state: "First one needs to identify the time points where the significant trend changes occurred and then attempt to investigate/understand/blame possible omitted causal factors "explaining" the observed breakpoints in trend." This touches on my question, as does orcmor's answer. Could you elaborate on this?
Comment: And finally, more generally, if there were no change to the deterministic trend, would there still be a way to investigate what variable (real world mechanism) is behind the trend and to measure it, or them, using a multivariate analysis?
Comment: no to your second comment . A deterministic trend (no counting numbers) is simply a permanent steady state constant . If you had a series 1,2,3,4,5,9,10,11,12.., the steady state constant would be a "1" with a pulse at period 6 of "3" representing a temporary change in trend. This  "3" would be found via Intervention Detection schemes. If you wish to continue this discussion please feel free to contact me .
Comment: Thanks! I will probably take you up on that after doing a bit more research within the next few days.
Answer: Maybe regime switching models are what you are looking for.
As for the trends in a time series, you can put breakpoints on the regime switching points (e.g. reversals) and calculate the trend coefficients in a straightforward manner. Then, you could look into the relation between your factors and the sign and magnitude of the trends.
Be cautious in using non-detrended time-series directly though. The problem with that is that it tends to show spurious relationships.
Comment: Thanks. Based on a cursory glance, I am not sure if this answers my question, but it is certainly a step in the right direction. I AM trying to explain changes in the underlying deterministic trend and this appears to touch on that. I'll need some more time to study the material before selecting this answer. I gave it an upvote but I don't yet have the points on CV for it to show up.


Laravel Validator: same not working

Question: I am using Laravel and validation:
    $validator = Validator::make(
        array('password' => $input['account_password']),
        array('password' => 'same:plain_text_password')
    );

    if ($validator->fails())
    {
        $response = ['success' => false, 'errors' => $validator->messages()];
        return $response;
    }

If I use the same input in both fields, it returns as a fail, yet if I provide no input for the password field / different data then it returns true?
What happening here?
Comment: Why are you doing a plain text password at all????
Answer: Your validator array names are wrong. You've used password twice:
$validator = Validator::make(
        array('account_password' => $input['account_password']),
        array('password' => 'same:account_password')
    );

Comment: @Lovelock - did that answer your question? Do you need any more info?

Laravel Validator: same not working


Como fazer stream vídeo com pedido de intervalo?

Question: Eu tenho um vídeo salvo no banco de dados com tipo VARBINARY(MAX).
Como eu posso fazer um range request ?
O código a seguir obtem o vídeo completo do banco de dados e joga na variável video_byte; Isso é um problema para o vídeo grande, para evitar isso preciso montar range requests. Segue o código a seguir como eu estou fazendo agora:
public async Task<IActionResult> GetStreamVideo()
{
    var result = await _context.Files
        .Where(x => x.Id == 1)
        .SingleOrDefaultAsync();

    byte[] video_byte = result.Video;
    if (video_byte == null)
    {
        return BadRequest();
    }
    return File(video_byte, "video/mp4");
}

Como eu posso obter pedaço por pedaço em asp.net core ?
O código a seguir funciona muito bem no asp.net mvc normal(sem core), e também uso a biblioteca: https://github.com/tpeczek/Lib.Web.Mvc
[HttpGet]
public ActionResult GetStreamVideo()
{
    byte[] test = null;
    DateTime lastModificationDate = DateTime.MinValue;

    using (var ctx = new Entities())
    {
        var result = ctx.Files.Where(x => x.Id == 1).SingleOrDefault();

        test = result.Video;
        lastModificationDate = result.LastModificationDate;
    }

    return new RangeFileContentResult(test, "video/mp4", "Name.mp4", lastModificationDate);
}

Comment: [Tenho um exemplo aqui](https://github.com/Wurthma/GerenciadorDocumentoWebAPI/blob/master/GED/Controllers/MediaController.cs) que pode ser útil pra você. Adaptei de outro exemplo que está documentado no meu código. Não vou conseguir responder agora, mas se disser que é útil posso tentar adaptar algo pro seu cenário se tiver diferenças.
Comment: @GeorgeWurthmann vou olhar o link, obrigado.
Comment: @GeorgeWurthmann olhei no seu código, na linha onde tem `SingleOrDefault();` não vai obter o vídeo completo ?
Comment: Nessa linha ele não está pegando o arquivo, apenas o registro no BD referente ao vídeo. Nesse registro tem o caminho onde o arquivo está armazenado o arquivo ele lê um pouco mais abaixo em 'fileInfo'  e esse arquivo é retornado em ranges para streaming, é isso que precisa?
Comment: @GeorgeWurthmann Isso, mesmo ! A ideia é não obter o vídeo completo e sim pedaço por pedaço. Porque no meu código ele está retornando byte_array completo do banco de dados. O select demora uns 20 segundos. Isso é um problema.
Comment: Entendi Matheus, mas o meu exemplo não contorna esse problema, meu arquivo não fica salvo no BD... no exemplo o BD armazena apenas o caminho físico dele pra depois ele ser carregado, qual é o BD utilizado?
Comment: @GeorgeWurthmann MS Sql Server 17
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/90783/discussion-between-matheus-miranda-and-george-wurthmann).
Answer: Isto pode ser feito, consultando os headers do pedido. Mais especificamente o header Range. Daí, você pode usar ByteRangeStreamContent para retornar apenas uma porção do video. Em termos de base de dados não pode fazer básicamente nada, uma vez que não é possível saber onde se encontra a porção do video que você está à procura de forma determinística, pelo menos não duma forma simples.
var range = Request.Headers.Range?.Ranges?.FirstOrDefault();
if (range != null)
{
    var stream = File.Open(record.FilePath, FileMode.Open,
        FileAccess.Read, FileShare.Read);
    var response = Request.CreateResponse(HttpStatusCode.PartialContent);
    response.Content = new ByteRangeStreamContent(stream, new RangeHeaderValue(range.From, range.To), "audio/mp3");
    return ResponseMessage(response);
}
else
{
    var stream = File.Open(record.FilePath, FileMode.Open,
        FileAccess.Read, FileShare.Read);
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return ResponseMessage(response);
}


postfix: connect to Milter service inet:127.0.0.1:8891: Connection refused

Question: I noticed that there is a error with milter if I type service postfix status :
Jul 01 17:39:01 mail postfix/cleanup[13921]: warning: connect to Milter service inet:127.0.0.1:8891: Connection refused

but what does that mean and how do I fix that? It is related to DKIM? Because I tried to set it up and it's still not working. which files  do you need to help? Here is my opendkim.conf:
## CONFIGURATION OPTIONS

# Specifies the path to the process ID file.
PidFile /var/run/opendkim/opendkim.pid

# Selects operating modes. Valid modes are s (signer) and v (verifier). Default is v.
Mode    sv

# Log activity to the system log.
Syslog  yes

# Log additional entries indicating successful signing or verification of messages.
SyslogSuccess yes

# If logging is enabled, include detailed logging about why or why not a message was
# signed or verified. This causes a large increase in the amount of log data generated
# for each message, so it should be limited to debugging use only.
#LogWhy yes

# Attempt to become the specified user before starting operations.
UserID  opendkim:opendkim

# Create a socket through which your MTA can communicate.
Socket  inet:firstname.lastname@example.com

# Required to use local socket with MTAs that access the socket as a non-
# privileged user (e.g. Postfix)
Umask   002

# This specifies a file in which to store DKIM transaction statistics.
#Statistics              /var/spool/opendkim/stats.dat

## SIGNING OPTIONS

# Selects the canonicalization method(s) to be used when signing messages.
Canonicalization        relaxed/simple

# Domain(s) whose mail should be signed by this filter. Mail from other domains will
# be verified rather than being signed. Uncomment and use your domain name.
# This parameter is not required if a SigningTable is in use.
# Domain                  DOMAIN.de

# Defines the name of the selector to be used when signing messages.
Selector                default

# Gives the location of a private key to be used for signing ALL messages.
#ORIG (AUSGEKLAMMERT): KeyFile                 /etc/opendkim/keys/default.private
KeyFile                 /etc/opendkim/keys/default.private

# Gives the location of a file mapping key names to signing keys. In simple terms,
# this tells OpenDKIM where to find your keys. If present, overrides any KeyFile
# setting in the configuration file.
KeyTable                 refile:/etc/opendkim/KeyTable

# Defines a table used to select one or more signatures to apply to a message based
# on the address found in the From: header field. In simple terms, this tells
# OpenDKIM how to use your keys.
SigningTable                 refile:/etc/opendkim/SigningTable

# Identifies a set of "external" hosts that may send mail through the server as one
# of the signing domains without credentials as such.
ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts

# Identifies a set internal hosts whose mail should be signed rather than verified.
InternalHosts           refile:/etc/opendkim/TrustedHosts

Answer: As Esa answered, it is related to OpenDKIM.
However, through looking at the Service file (Ubuntu 16.04, using systemctl) I noticed that the service uses a file located in /etc/default/opendkim
# Command-line options specified here will override the contents of
# /etc/opendkim.conf. See opendkim(8) for a complete list of options.
#DAEMON_OPTS=""
#
# Uncomment to specify an alternate socket
# Note that setting this will override any Socket value in opendkim.conf
# default:
SOCKET="local:/var/run/opendkim/opendkim.sock"
# listen on all interfaces on port 54321:
#SOCKET="inet:54321"
# listen on loopback on port 12345:
#SOCKET="inet:12345@localhost"
# listen on 192.0.2.1 on port 12345:
#SOCKET="inet:firstname.lastname@example.com"

Note line 6, which states that settings here will override any Socket value in opendkim.conf
I tried simply commenting out all the lines in here to revert it back to the config, but it didn't seem to work for me.
To fix this, modify the file to set the SOCKET environment variable to what you need.
# Command-line options specified here will override the contents of
# /etc/opendkim.conf. See opendkim(8) for a complete list of options.
#DAEMON_OPTS=""
#
# Uncomment to specify an alternate socket
# Note that setting this will override any Socket value in opendkim.conf
# default:
#SOCKET="local:/var/run/opendkim/opendkim.sock"
# listen on all interfaces on port 54321:
#SOCKET="inet:54321"
# listen on loopback on port 12345:
SOCKET="inet:8891@localhost"
# listen on 192.0.2.1 on port 12345:
#SOCKET="inet:email@example.com"

Finally, restart opendkim with sudo service opendkim restart
TLDR:
sudo nano /etc/default/opendkim, edit the SOCKET setting, then restart opendkim.
Answer: OpenDKIM is a different service. See whether it's running or not. You could try
sudo service opendkim restart

and see if that results in an error.
Given that you have Socket  inet:email@example.com and Postfix is trying to connect to port 8891, the configuration seems ok. You could use netstat -l or lsof -i to check that OpenDKIM is actually listening on port 8891.
Comment: seems that you could try `Socket /var/run/opendkim/opendkim.sock`
Comment: OpenDKIM is running, no error. But I dont see OpenDKIM on any of this commands :/ I just see this : unix  2      [ ACC ]     STREAM     HÖRT         196526   /var/run/opendkim/opendkim.sock
Comment: Then it seems like the `Socket` is configured to `local` somewhere else. Strange...
Comment: what should I do? what config files you need?
Answer: In my situation, for two distinct Ubuntu and Debian servers, the problem was a broken systemd service file for opendkim.
The config files were absolutely ok but the service file was probably generated by an old version.
To regenerate the service file and reslove the problem, just run this command:
sudo /lib/opendkim/opendkim.service.generate

Then reload
sudo systemctl daemon-reload
sudo service opendkim restart

See here: https://serverfault.com/a/847442/84962
Answer: The only solution that worked for me with Ubuntu 16.04....

Set the corecrect SOCKET value in /etc/default/opendkim.
Remove the SOCKET entry in /etc/opendkim.conf

Then, of course, sudo systemctl restart opendkim


Execute multiple conditions when the cursor is clicked within div

Question: My task: Initially, all three elements in the example are in the default value. When you click the mouse on the div (id="main") "first element" (or any other), I want the color of this div to change from green to red and the inscription "Active" to appear in this div. Next, when you click on the "second element" (or "third element") div, the value of the div with "first element" should become default, and the borders of the "second element" (or "third element") should turn red and the inscription "Active" should appear. However, when you press the "submenu" button, the above actions should not occur (that is, when you press this button, the borders should not turn red and the word "Active" should not appear).
https://codesandbox.io/p/sandbox/suspicious-platform-vj5td9
    const data = [
  { id: "1", title: "first element" },
  { id: "2", title: "second element" },
  { id: "3", title: "third element" },
];

export default function App() {
  return (

      {data.map((item) => (

{item.title}

          <button>submenu</button>

      ))}

  );
}

If I haven't explained something clearly, you can ask me any questions.
Comment: What have you attempted to achieve this? You are expected to make an attempt.
Comment: Please see [ask]. We're not a free coding service.
Comment: FYI, you're repeating ID values, which is invalid HTML (and about anywhere in life--IDs must be unique or they don't ID anything). It seems odd that you'd repeat a "main" element anyway.
Comment: I can't quite tell if this is a duplicate of, or simply related to, the previous question: https://stackoverflow.com/a/77587445/82548
Answer: I edit your code like below.
code sandbox
import { useState } from "react";
import "./styles.css";

const data = [
  { id: "1", title: "first element" },
  { id: "2", title: "second element" },
  { id: "3", title: "third element" },
];

export default function App() {
  const [active, setActive] = useState(null);
  return (

      {data.map((item) => (

 setActive(item.id)}
          >
            {item.id == active ? "active" : item.title}

          <button>submenu</button>

      ))}

  );
}

Comment: @Adrid Thanks for the answer. But unfortunately, you did not quite understand my question. I meant to make a div active (that is, make the borders red and display the word "active") by clicking on it (any place inside the div, except the submenu button). And when you click on the submenu button, nothing should happen
Comment: I just edited the code.
Comment: @Adrid Sorry, but the "submenu" button must be within the red border. That is, the red border should wrap the inscription "... element" or "active" (depending on the state), as well as the "submenu" button
Comment: @Paul, Put button in `div` element with `active` class. I think you don't try anything yourself to solve this problem.


NotSerializableException org.neo4j.kernel.EmbeddedGraphDatabase

Question: I am working with neo4j to create graph, taking data from mongodb as document. Standalone code is working fine without storm. But while integrating it with storm, I am getting -

java.io.NotSerializableException: org.neo4j.kernel.EmbeddedGraphDatabase

exception. Dont know the exact reason why i am getting this. If anybody faced such issue please let me know how to resolve it.
Answer: Because you are trying to pass an object to the serializer that does not implement Serializable interface.
Comment: I am not serializing  anything. But i too had the same thought so i serialized all classes which is getting used. Still i am getting the same exception.
Comment: @shaw.ram Seems that `neo4j` takes some class somewhere and tries to serialize it but fails. So check the documentation of it.
Answer: You have to share more details. Most probably you're trying to serialize a Neo4j Node or Relationship object which holds a reference to a non-serializable GraphDatabaseService.
Comment: From bolt in execute method, i was calling method to create the graph and passing parameter as document which i was getting from mongodb and GraphDatabaseService object. Now i am passing only document as parameter. I am now creating GraphDatabaseService object in the static block of class where i am creating the graph. Issue is resolved. Thanks Michael for your suggestion.
Answer: All classes that are used for attributes/fields in Storm must implement the interface Serializable. I assume that you are using a object of type EmbeddedGraphDatabase within Collector.emit(new Values(...)) (either directly or in a nested way).
Comment: EmbeddedGraphDatabase is the API of Neo4j which is not implementing Serializable interface. I am using it into the bolt while loading to create it's object only once. But at runtime getting NotSerializable exception. Can You tell, what to do to work with such API do not inplement Serializable interface into storm.
Comment: I guess you have a class member variable of type `EmbeddedGraphDatabase`. If you initialize this variable not on the client but after the topology got deployed (ie, in open() or prepare()), you can simple declare the member `transient` which excludes is from serialization.


Calculating level of confidence from an interval estimate

Question: I've recently been having trouble with this question on calculating confidence levels and am just wondering if anyone had any ideas on how to solve it.
"A market research company conducted a telephone survey of 255 Chicago households to determine the proportion of households seeking to purchase a new car in the next two years. An interval estimate of 0.151 to 0.289 was calculated. Determine the level of confidence."
Comment: Please read the info of [`self-study`](http://stats.stackexchange.com/tags/self-study/info) tag. Adding this tag might be helpful.
Answer: If it can be solved they are assuming something like (a) the interval is symmetric so you know the central estimate (b) they are using the normal approximation which involves $p$, $q = 1 - p$' and $n$ all of which you know. Of course if that is not what they are assuming it may be unsolvable.
Answer: This question appears to be asking for confidence limits (CL) from confidence interval (CI). The problem actually has no solution without making a lot of unstated assumptions. A confidence interval is sometimes the 95% range of standard error of the mean for a normal distribution. Standard error is $SE=\frac{\sigma}{\sqrt{n}}$, where $\sigma$ is the population standard deviation, and $n$ is the sample size. Then 95%, and only 95% CI is $\mu +/- 1.96 SE$. Thus, $(\mu + 1.96 SE) +(\mu - 1.96 SE)=2\mu$ and $(\mu + 1.96 SE) -(\mu - 1.96 SE)=3.92SE$. From this find the mean $\mu$ and the standard error $SE$. Then $\sigma=\sqrt{n}SE$, and the 95% and only the 95% CL are $\mu+/-1.96\sigma$ for a normal distribution.


Como evitar o componente Chips do Materialize em branco?

Question: Estou usando o chips do materialize no meu projeto, mas queria evitar esse comportamento padrão de adicionar a tag mesmo vazia, por exemplo:

Como faço para impedir isto e inserir a tag somente quando tiver pelo menos um caractere?
O que cheguei mais próximo foi:
$('.chips').on('chip.add', function(e, chip){
        console.log(chip);

        var chip = chip.tag;

        if(!chip.trim()){
           alert('CHIP VAZIO!');
           //aqui gostaria de fazer algo do tipo chip.remove() porém da erro
        }
    });

Comment: Amigo coloca no mínimo a versão do Materialize que está usado e o seu HTML, só com a imagem não da para te ajudar muito
Comment: @hugocsl esse exemplo é do próprio materialize.
Comment: O Materialize tem muitas "falhas", pontas soltas que não foram amarradas - não sei dizer se por falta de desconhecimento ou se era objetivo deles mesmo. Parece que foi feita às pressas e de forma que ficasse visivelmente agradável. Nas `options` do seu elemento, existe a propriedade `onChipAdd`. Tente utilizá-la para validar o valor adicionado.
Comment: Na página da documentação tem o JS, eu não manjo muito, mas acredito que alguém mais experiente vai saber te ajudar https://materializecss.com/chips.html no final da página te os scrpts...
Comment: vou pesquisar melhor..
Comment: @AndersonCarlosWoss fiz através de on chip add, porém não encontrei nenhuma maneira de excluir este chip através do código. Sabe de algo?
Answer: Verifique se o nó de texto do chip está vazio utilizando o método .trim(). Se apenas espaços forem digitados, o trim() irá eliminá-los e tornará null o chip.
Para isso você utiliza o callback do método onChipAdd:
$('.chips').chips({
    onChipAdd: function(e, c){
      if(!c.firstChild.textContent.trim()) c.remove();
    }
});

O segundo parâmetro (c) retorna o HTML do chip criado. O primeiro nó (firstChild) é o texto. Se for vazio remova-o com .remove().
Teste:

$('.chips').chips({
    onChipAdd: function(e, c){
      if(!c.firstChild.textContent.trim()) c.remove();
    }
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

   <input class="custom-class" placeholder="Digite as tags">

Comment: Fiz conforme você falou, porém da esse erro:  Cannot read property 'textContent' of undefined
Comment: Estou fazendo assim:   $('.chips').on('chip.add', function(e, c){
            if(!c.firstChild.textContent.trim()) c.remove();
        });
Comment: Não sei se a versão do materialize influencia, pq quando faço $('.chips').chips({)}; não reconhece...
Comment: Do jeito que vc está fazendo está entrando no `console.log(chip);`?
Comment: Sim, me retorna dessa maneira: {tag: "ksdsd"}
Comment: Qual a versão que vc está usando e como está inicializando o plugin?
Comment: Inicializo assim:  $('.chips').material_chip('data');

        $('.chips').material_chip(); Estou usando a versão: Materialize v0.100.2.
Comment: Use isto: `$(".chip:last").remove();`
Comment: Funcionou!! Muito obrigada!


Importing GPO WMI filter .mof file

Question: I've got a couple of exported GPO WMI filters off an AD domain as .MOF files. I see that I can import them using the Group Policy Management console but would rather like to re-import them via a script to automate the entire process.
I have not been able to find any decent documentation on how this works and the scripts available on TechNet1 are mostly going by reading property values from the source directory and writing them to the destination.
I would like to retain the ability to use GPMC to restore WMI filter backups manually, if needed. So an approach to simply use the .mof files created by GPMC upon WMI filter export is required.

1 Interestingly, different Microsoft employees have apparently worked on similar problems over the years, all coming to similar solutions published on TechNet:

https://blogs.technet.microsoft.com/manny/2012/02/04/exporting-and-importing-wmi-filters-with-powershell-part-1-export/
https://blogs.technet.microsoft.com/ashleymcglone/2014/08/11/gpo-migration-with-powershell-now-including-wmi-filters/
https://blogs.technet.microsoft.com/askds/2008/05/16/bulk-exporting-and-importing-wmi-filters-for-group-policy/
Answer: A .mof is an input file to the mofcomp utility which is present on every Windows system. You just need to provide the file name and the corresponding namespace as parameters to make it work.
The file name is obviously the easy part - this is something you specify when exporting the WMI filter. But mofcomp would not run the .mof export without the correct namespace as it does not know where to find the MSFT_SomFilter class which is being instantiated:
C:\Users\john>mofcomp wmi-filter-export.mof
Microsoft (R) MOF Compiler Version 10.0.14393.0
Copyright (c) Microsoft Corp. 1997-2006. All rights reserved.
Parsing MOF file: wmi-filter-export.mof
MOF file has been successfully parsed
Storing data in the repository...
An error occurred while resolving the alias for object 1 defined on lines 2 - 18:
0X80041002 Class, instance, or property 'MSFT_SomFilter' was not found.
Compiler returned error 0x80041002

Just searching the net for the class name MSFT_SomFilter will get you the link of the class documentation on MSDN which conveniently states:
| Namespace |  Root\policy |

So just call mofcomp with the appropriate namespace and see it do the work. You likely will need to run this on your Domain Controller with administrative rights (i.e. elevated).
C:\Users\john>mofcomp -N:root\Policy wmi-filter-export.mof
Microsoft (R) MOF Compiler Version 10.0.14393.0
Copyright (c) Microsoft Corp. 1997-2006. All rights reserved.
Parsing MOF file: wmi-filter-export.mof
MOF file has been successfully parsed
Storing data in the repository...
WARNING: File wmi-filter-export.mof does not contain #PRAGMA AUTORECOVER.
If the WMI repository is rebuilt in the future, the contents of this MOF file will not be included in the new WMI repository.
To include this MOF file when the WMI Repository is automatically reconstructed, place the #PRAGMA AUTORECOVER statement on the first line of the MOF file.
Done!

Note that if a WMI Filter with the same GUID as the one defined by the ID = <GUID> line the .mof already exists, it will be overwritten. If the GUID is not yet in use, a new WMI filter will be created.
The #PRAGMA AUTORECOVER warning has no real substance here - no new classes are being defined by the .mof, so nothing is lost in the case of a WMI repository rebuild.
Comment: Here's a helpful link if you get errors: https://docs.microsoft.com/en-us/previous-versions/tn-archive/ff406382(v=msdn.10)?redirectedfrom=MSDN#im-getting-an-0x80041013-provider-not-found-or-an-0x80041014-component-failed-to-initialize-error
Comment: Unfortunately I am getting `Error Number: 0x80041014, Facility: WMI` `Description: Initialization failure` when trying to import my .mof files and the link I provided did not resolve the issue.

Importing GPO WMI filter .mof file


Can I reload a single systemd unit/service file after its modification without reloading all unit files?

Question: Can I reload a single systemd unit/service file after its modification (in [Service] section) without reloading all unit files? By online search, everyone talk about systemctl daemon-reload or systemctl --user daemon-reload. This makes me feel really bad. I only want to reload one unit file configuration instead of many. Is that possible to reload the modified one only in systemd? Thanks a lot.
Comment: Are you confusing `reload` with `daemon-reload`? Or in other words, why just only `daemon-reload` a single unit/service?
Comment: @Thomas I am not confusing reload and daemon-reload. I just want to daemon-reload a single unit service file because I modified the unit service file (the [Service] section). I heard `daemon-reload` will rerun all generators and reload all unit files from [this link](https://www.freedesktop.org/software/systemd/man/systemctl.html#daemon-reload). Thanks.
Comment: `daemon-reload` it not harmful and won't do a `systemctl reload ...`. As far as I know you cannot daemon-reload a single unit.
Comment: @Thomas ok thanks. I just friendly clarify once again I am NOT looking for `systemctl reload` at all. I am looking for `daemon-reload` a single unit file only. And thanks for the comment. That means it's not doable then. If you are sure it's not doable, you can provide it as the answer. I can then accept it.
Answer: systemctl daemon-reload cannot be run on a single unit file. What it does is reloading the systemd configurations of unit files, rerun all generators and recreates the dependency tree.
I guess since the dependency tree is regenerated it doesn't make sense to run this on a single unit as several unit files may have changed and the dependency tree then could be wrong.


Custom Atom feeds using Views

Question: I'm wondering if there's a way to make a view render an Atom feed with custom fields, that would output something similar to this:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" ... xml:lang="en-US">
   <title type="text">my atom feed</title>
   <subtitle type="text">my atom feed subtitle</subtitle>
   <id>the feed's url</id>
   <rights type="text">some copyright</rights>
   <updated>2013-06-14T02:29:00Z</updated>
   <author>
      <name>me</name>
   </author>
   <generator>my feed generator</generator>
   <link rel="alternate" type="text/html" href="my site's url" />
   <link rel="self" href="the feed's url" />
   <my:field1>value1</my:field1>
   <entry type="my_type_1">
      <id>an article's url</id>
      <title type="html">article title</title>
      article summary
      <published>2013-06-14T01:16:00Z</published>
      <updated>2013-06-14T01:47:40Z</updated>
      <author>
         <name>someone</name>
         <uri>the guy's bio page url</uri>
      </author>
      <content type="html">full body content in <strong>html</strong></content>
      <my:numeric_field>2</my:numeric_field>
      <my:yet_another_custom_field>hi there</my:yet_another_custom_field>
   </entry>
   <entry> ... </entry>
</feed>

The views_rss module can do stuff like this (in fact, I've already accomplished a lot using its hooks to define the fields, and field formatters to do stuff like <author><name>name taken from a user reference field in the node</name><uri>the user's url</uri></author>, but I can't find a similar module that provides the same functionality for Atom feeds.
Is there such a module out there? I've tried atom and views_atom without success. If not, how hard would it be to implement it? I guess this would involve making a "views plugin", with which I'm not really familiar.
Answer: You don't need a module to do that. You can use .tpl files to wrap rows in <entry> tags, fields in their tags and so on. It may be a bit less intuitive and more exhausting at first, but in the long run you will get exactly what you ask for, without compromises modules call for.

Custom Atom feeds using Views


The organization as a unit of analysis and sampling issue

Question: I'm doing a quantitative study entitled "Technology Transfer and Competitive Advantages in Oil and Gas Companies".
In my study, the unit of analysis is the organization and there are only 9 oil and gas companies in my country. The respondents will be randomly selected from the managerial level (stratified) based on the size of each company. The total number of employees in managerial level is 3,336 and the sample size is 959.
I'm going to use Structure Equation Modeling for the analysis.
My question is, taking into consideration the unit of analysis is the "organization", does the sample size "959" represent the population (9 companies), and is it enough? Is this the right methodology?
My friends told me that if the unit of analysis is organization and I have only 9 companies, so one person from each organization will represent the organization. That means I will have only 9 respondents, which is not enough for the study.
Answer: It sounds like your unit of analysis is the individual, not the organization.  That means your sample size will be 959.  Since you're using SEM, I assume that you're also planning on treating your data as hierarchical -- that is, people nested in companies.  Then you can include individual level terms as well as company level terms in your model.  Since you only have 9 companies, however, you can probably only include about 3-4 company level terms in your model.
Hope that helps.
Jake


Hide navigation bar, but show Actionbar in Android 3.0 >

Question: I'm trying to hide the navigation bar (where battery status, time, notifications and other stuff is shown), but I want to keep the actionbar.
How can I manage it?
<code> <item name="android:windowNoTitle">true</item>
</code>
This method hides everything...
Thank you!
Answer: Found it myself:
<code>// Hide the Status Bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
</code>
From another question (android - How to Hide the stausbar)


Populate fields when a checkbox is clicked on a form

Question: I have a regular drupal 7 form (based on a content type called guests) where I need a "Bring my partner" checkbox. When the checkbox is clicked, a field collection field (first name/last name/address) needs to be prefilled basing on the details for the currently logged-in user. (Partner details are in my user account details.)
Can this be done in hook_form_alter()? Is there any other way to achieve this?
Comment: prefill as in it will automatically add these using javascript or do you want to add these values to the form data after it is submitted?
Comment: https://drupal.org/project/prepopulate
Comment: http://drupal.stackexchange.com/questions/37867/how-to-pre-populate-a-field-with-the-current-users-name
Answer: You could do this with hook_form_alter and add a state to the field that needs to be hidden.
$form["first_name"] = array(
    "#states" => array(
        "invisible" => array(
            ":input[name='bring_parter']" => array(
                "checked" => FALSE,
            )
        )
    ),
);

What this does is hides the "first_name" unless "bring_partner" is checked. More info here


Gem will_paginate não carrega quando é feito deploy no Heroku

Question: <code>Initializing repository, done.
Counting objects: 3605, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1035/1035), done.
Writing objects: 100% (3605/3605), 7.57 MiB | 71.00 KiB/s, done.
Total 3605 (delta 2463), reused 3605 (delta 2463)

-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using 1.5.2
       New app detected loading default bundler cache
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
       Fetching gem metadata from http://rubygems.org/.......
       Fetching additional metadata from http://rubygems.org/..
       Fetching github.com/mislav/will_paginate.git
</code>
Comment: Por favor, explique melhor o que você está tentando fazer e adicione mais detalhes à sua pergunta. Lembre-se que o esforço de alguém ao responder será diretamente proporcional ao seu esforço em perguntar.
Comment: seria interessante também adicionar o conteúdo do seu `Gemfile`
Answer: Resolvido, o problema estava no Gemfile mesmo, a gem estava chamando uma versão errada, ao inserir a versão correta funcionou perfeitamente.
Comment: Você poderia acrescentar mais detalhes como o problema foi solucionado no gemfile? Depois disso, você pode aceitar sua resposta como a certa, aqui do lado esquerdo.


How do retrieve vales from HTML Post method to Java with freemarker?

Question: I am trying to create a simple registration form and insert the data from the user into mongodb.

  <meta charset="UTF-8">
  <title>Sign Up</title>
  <link href="/css/main.css" rel="stylesheet">

Sign Up

<#if user?? >
Your submitted data

Name: ${user.user_id}

Password: ${user.password}

Email: ${user.email}

<#else>
<form action="/form" method="post">
  First name:

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

  Pasword:

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

  Email:

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

  <input type="submit" value="Submit">
</form>
</#if>

I have a User class, and I want to create an instance of it, to fetch the data and insert it to mongodb. This is the part I don't know how to do. How do I create the controller to pass the data from HTML to the User instance?
This is what I have so far -
//sign up page
        Spark.get(new Route("signup") {
            @Override
            public Object handle(Request request, Response response) {
                StringWriter writer = new StringWriter();
                User user = new User(); // create user to fetch results
                try{
                    Template signupTemplate = configuration.getTemplate("signup.ftl");

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
            }

How do I go on from here? Can I do that only with freemarker and sparkjava?
Answer: To post form data to server, you should define a spark route to listen for POST method.
A spark route comprises of three entities (see doc's),

verb: get, post, put, delete etc.
path: Request path for which the Route applies
callback: Handler class that will be invoked when the incoming request matches the path.

In your case it should be,
Spark.post("/form", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            // process request and return response
        }
    });

If your working with Java 8, you could simplify the above,
Spark.post("/form", (request, response) -> {
        // process request and return response
    });

Now to read form data, you could do so by fetching the raw request(HttpServletRequest) and using getParameter() inside the handle method.
HttpServletRequest httpRequest = request.raw();
String name = httpRequest.getParameter("Name");
String email = httpRequest.getParameter("email");


How do I keep my paragraphs separate?

Question: I am writing a word limit function for my custom blog.  I want to limit the words on the index page and remove any formatting.  At the moment my code is:
function limit_words($string, $word_limit){
  // Check if the string is too long
  $text=strip_tags($string);
  $words=explode(" ", $text);
  $size=sizeof($words);

  // Run the script
  if ($size >= $word_limit){
    return implode(" ", array_splice($words, 0, $word_limit).' Read more ...');
  }
  else { return $text; }
}

It works great, unless I have more than one paragraph.  If my first paragraph is, say, 20 words and my limit is 50, it will strip the tags and the spaces, but then will bring the last word of the first paragraph and the first word of the second paragraph together as one word.  Is there a way to make sure that the paragraphs have spaces between them?  I am a novice, so if it is a simple solution, do tell me that it is that simple and I shall lock myself in the cellar until it sinks in.  Or something similar.
Comment: Put paragraph text in `p` tag & style accordingly.
Answer: View the html-source, probably your text has Newline as delimiter between paragraphs, which doesn't mean much for html. And debug: Print out the array of words, look at the paragraph limit. The newline sign is no space " ", so it stays "one word".
If it is a newline, search-replace it by
 for showing in html or use paragraphs.
Comment: That has solved my problem - my code (pulled from my database) had gone onto one line.  It has higlighted another issue - keeping my lines separate when I call them in my editor.  That doesn't seem to play ball.
Comment: Well, part of the honour goes to Rikesh, I just unzipped his comment. ;-)

How do I keep my paragraphs separate?


RotateAnimation : Listen to every Angle Change

Question: I have a View to which I have added a RotateAnimation and it is working perfectly. The only question that I have is that, is there a way to listen to every angle change. I know I can add an AnimationListener and use the following listeners,
rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });

And also I can use View.getRotation() to get the angle of the view. But the functionality of the app changes w.r.t time calculated from the preferences selected by the user.
What I am looking for is a listener which can listen to every angle change.
Something like, onRotateAngleChange(int currentAngle).
Any pointers on any such methods or any workaround that I can use would be a great help.
Regards.
EDIT : Final Hint/Code that worked.
Thanks to @yakobom for the pointer.
rotateAnimation = new RotateAnimation(fromDegrees, toDegrees){
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            float degrees = fromDegrees + ((toDegrees - fromDegrees) * interpolatedTime);
            //Do what you want to do with your angle here.
        }
    };

Answer: All you need to do is implement applyTransformation, something like this:
    RotateAnimation rotateAnim = new RotateAnimation (...) {
                 @Override
                 public void applyTransformation(float interpolatedTime, Transformation t)
                 {
                      super.applyTransformation(interpolatedTime, t);

                       <your code here>
                 }

Comment: Hey, can you please elaborate, from where I can get the real time angle? I mean `interpolatedTime` or `t` and how? I searched for it but couldn't find anything.
Comment: Thank man it worked. I had to look into the Java code of Rotate Animation to understand what you meant. (Y).
Answer: It's not possible to add an update listener for RotationAnimation however you can achieve the same result by using an ObjectAnimator
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", initialValue, finalValue);
animator.setDuration(duration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            currentRotation = valueAnimator.getAnimatedValue("rotation");
            //do something
        }
    });

Alternatively if you're targeting API 19 or higher you can use the Animation apis in Kitkat added to make this much simpler as follows:
view.animate().rotationBy(finalValue - initalValue).setUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            currentRotation = valueAnimator.getAnimatedValue("rotation");
            //do something
        }
    });

Comment: Hey, I added `Log.d("YO", valueAnimator.getAnimatedValue("rotation").toString());` in the `//do domething` part but it was not logging values during the animation. Plus, do you know how I can fix one end of the view in ObjectAnimator, I was able to set pivot in RotateAnimation.
Comment: Hey, Thanks for the answer but @yakobom 's answer was more to the point.


paired t-test for multiple groups

Question: I have had a particular problem that I haven't been able to solve.
Here is the scenario: I would like to perform a paired t-test of sorts on multiple groups. Instead of before and after conditions, there are multiple conditions (ex: treatment 1, treatment 2, treatment 3 etc). Each subject appears in each 'group'. I have tried to use ANOVA, but this method averages data of all subjects within each condition, then compares their means. However, I would like to look at the differences of individual subjects between the conditions, and compare those between subjects. To me, it sounds like a paired t-test for of 2+ groups. I am using n=4. I hope that makes sense.
thanks for any input
Comment: Can you describe the study design better? Is this a cross-over design? An AB design? Pre-post randomized design for differences in differences?
Comment: Have you heard of MANOVA (multivariate analysis of variance. For each subject you have a k dimensional vector k=4 in your case.  I think this will let you include all the results for the patients in a single vecotr.
Comment: Thanks for the reply. I'm not sure what the proper terminology is. Currently, it is two sets of paired t-tests, but using the same n=4 overall. It compares scores of conditions A vs B and C vs D (all using the same unit of measurements). But now I want to compare A & D and C & B as well. My options as far as I can see are reusing the data two make four graphs (I'm hesitant about this) or perhaps combining all 4 sets on the same graph (but I'm not sure how to mathematically compare them).
Comment: In the usual ANOVA that sounds like testing contrasts.  This can be done but whenever you do this you need to take account of the multiple testing and adjust p-values.
Answer: The test you are looking for is one-way repeated measures ANOVA. That is equivalent to two-way ANOVA, with repeated measures in one factor, with no replication. Following the ANOVA, you'll want to run followup tests to make the comparisons you are asking for, while adjusting for multiple comparisons.

paired t-test for multiple groups


$(...).offest is not a function

Question: I am baffled to why I am experiencing this error, maybe its a bug with Jquery or maybe I'm blind, but Jquery has loaded and I can access the offset function after selecting an element?

Uncaught TypeError: $(...).offest is not a function

According to w3, I've used the function correctly.
Current code
var off = $("#canvas").offest();
var xPos = off.left + ( jqo.outerWidth(true)/2 );
var yPos = off.top + ( jqo.outerHeight(true)/2 );
console.log(yPos, xPos);

Comment: You've spelt `offset()` incorrectly...
Comment: You have written "offest", where as should be "offset".
Answer: You have typo. Use offset instead of offest:
var off = $("#canvas").offset();

$(...).offest is not a function


getting number of hours until the next event

Question: I've got a table with this data:
[ID]  [event_name]  [last_event]
 1     stats         2011-01-01 01:47:32

last_event is a timestamp. The event occurs every 48 hours (it's a cron job). I'd like to show my users the number of hours until the event executes again.
So far I've got:
SELECT (lastFinish + INTERVAL 48 HOUR) FROM `cron_status`

which gives me the exact time and date of the next occurence: 2011-01-03 01:47:32. So I figured if I subtracted the current datetime...
SELECT ((lastFinish + INTERVAL 48 HOUR) - SYSDATE()) FROM `cron_status`

which (I think?) gives me the difference in unix time: 1980015. But if I divide that by 3600 to convert the seconds to hours...
SELECT (((lastFinish + INTERVAL 48 HOUR) - SYSDATE())/3600) FROM `cron_status`

I get numbers an order of magnitude too high: 549.99.
Where am I going wrong? The target is returning the number of hours until the next execution.
Thank you!
Answer: The result can be obtained directly, using the timediff() MySQL function:
  SELECT timediff(lastFinish + INTERVAL 48 HOUR, now()) FROM cron_status;

should display the time as hh:mm:ss. Assuming lastFinish is a datetime.
In order to get the answer in hours instead,
  SELECT timestampdiff(HOUR, now(), lastFinish + INTERVAL 48 HOUR) FROM cron_status;

Note that timediff does arg1 - arg2 while timestampdiff does arg2 - arg1.


Proof by induction $nx^n<1$

Question: I'm having trouble with this induction, and I'm not sure how to use the inductive step to my advantage in solving this problem.
So I need to prove $nx^n<1$, where $n$ is a natural number (N1), and $0<x<1/2$.
The basecase worked out, and in the inductive hypothesis I just changed $n$ to $k$. So we got $kx^k<1$.
Now the inductive step, I got $(k+1)x^{k+1}>1$, and I'm having trouble understanding how to use the inductive hypothesis. Should I manipulate the hypothesis in to a form where it can be plugged in? Should I make a triangle inequality?
I'm very lost with this so any help is greatly appreciated!
Answer: Hint :
$$(k+1)x^{k+1} = (kx^k) \times x + x^{k+1}$$
Comment: You will need to use $0 < x < \frac12$
Answer: Suggestion for a simpler proof:
First note that hypothesis on $x$ imply that
$$0<nx^n<\frac n{2^n}, $$
so all you have to prove is that $\dfrac n{2^n}<1$ for all $n\in\mathbf N$.
Another observation: $\dfrac{n}{2^n}$ is decreasing for all $n\ge 1$.
Answer: I don't know why you get $\left(k + 1\right) x ^ {k + 1} > 1$.
You should get $\left(k + 1\right) x ^ {k + 1} = k x ^ {k + 1} + x ^ {k + 1} < x + x ^ {k + 1} = x \left(1 + x ^ k\right) < \dfrac{1}{2} \left(1 + \dfrac{1}{2 ^ k}\right) = \dfrac{2 ^ k + 1}{2 ^ {k + 1}} < 1$.

Proof by induction $nx^n<1$


Maximum length of a string that has no substring divisible by a prime number $p$ is $p-1$?

Question:
What is the maximum length of a string of nonzero digits that has no substring that is divisible by a given prime number?

I want to find a string of length n which has no substring divisible by the given prime number p (the string cannot have zeroes). I coded in c++ and for some prime numbers p I noticed the following property:
The maximum length possible for that desired string is p-1. Does that property hold for every prime number?
These are the prime numbers that I have tested:
2, 3, 5, 7, 11, 13
For all of these prime numbers except 2 and 5, length of the longest string which has no substring divisible by that prime number is (that prime number - 1 ). For example for 13 we have string "111112115541" which has no substring divisible by 13. Length of this string is 12 and my code says there is no such string with length 13. So 12 is maximum.
I can't check this for 17. Because my code takes very time to execute and cannot realize that property is correct or not. Actually I have found the desired string for 17 with length 16 and if my code says that there is no such string with length 17 then that property is also holds for 17.
BTW For all prime numbers p <= 97 my code has found that desired string with length (p-1). But I don't know that this length is maximum or not. I'm only sure about 3, 7, 11, 13 .
Comment: Can the string have zeroes?
Comment: @barto No. Sorry!. Strig cannot have zero.
Comment: @barto: Any zero in the string would constitute a substring divisible by $p$ (since everything divides $0$).
Comment: @Lnxdx: What does your search code say for $p=101$? I can vaguely imagine a systematic construction of length-$(p-1)$ strings that might get in trouble for the first time at $p=101$.
Comment: @HenningMakholm i found a string of length 95 for p=101
Comment: @HenningMakholm and it's running for length=96.
Comment: @HenningMakholm ans answer for length=96 also found. But takes 36.234 seconds to execute.
Comment: Hmm, so we won't learn that a length-100 string _doesn't_ exist that way. I withdraw my request. (Or does $p=101$ seem to be significantly harder than $p=97$?)
Answer: Upper bound. If $p$ does not divide $10$, then there can be no such string of digits longer than $p-1$.
Namely, consider all suffixes of your string (including the empty string) and compute the remainder of each of them (interpreted as a number) modulo $p$. If the string is longer than $p-1$ then there are more than $p$ different suffixes; by the pigeonhole principle two of them will have the same remainder. Subtract them! You get a number of the form $b\cdot 10^n$ where $b$ is a substring of your original string, such that $p\mid b\cdot 10^n$. Since $p$ doesn't divide $10^n$, it must divide $b$.
Comment: And this generalizes to any integer $p$ coprime to $10$!


Google-checkout notification callbacks

Question: I have problem with Notification API callbacks. I've implemented callbacks in Sandbox account without problems, but when I switched into production no notification arrived and Integration console is empty. I set up SSL url...
Thanks for help.
Tomas
Answer: When "switching" to production, did you:

check if you are using your production merchant id and key?
check if you have adjusted the urls where you POST data to (urls are also different for sandbox and production)?
Comment: Production account is different from sandbox. I'm just waiting for notification callbacks from Google Notofication service. I set up integration link into integration section. Thanks.

Google-checkout notification callbacks


Declaração if vazia em função

Question: É possível criar uma função que termine com um if statement vazio e permita que o código que chamou essa função determine a ação do if?
Exemplo:
def if():
    if x>6:

x = input("Valor de x")

if()
    print(x)

x = input("Valor de x")

if()
    x = x*2

Neste código o if() criaria a condição if x>6 e o que segue criaria a ação caso a condição seja atendida, porém ele não funciona pois o "if x>6:" expecta algo subsequente.
Se não, existe outra forma de criar um mecanismo que funcione do mesmo modo?
Answer: Acho que é isto que deseja.
def filtro(p):
    if p > 6:
        return True
    return False

x = int(input("Valor de x"))
if filtro(x): print(x)
x = int(input("Valor de x"))
if filtro(x): x = x * 2
print(x)
x = int(input("Valor de x"))
if filtro(x): x = x * 2
print(x)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Poderia usar lambda, mas acho que não é o mais adequado para este caso, especialmente quando tem que executar uma ação com efeito colateral como na segunda ação que atribui valor para a variável.
Comment: Obrigado pela resposta. O 'return false' em filtro(p) é necessário?
Answer: Não como vocẽ está imaginando - qualquer comando que termina com : no Python cria um bloco - e esse bloco tem que ter expressões e comandos, senão é um erro de sintaxe.
Atualização:
passar funções como parâmetro, como descrevo abaixo, exceto em linguagens especializadas chamadas "funcionais" pode ser considerado um pouco avançado. Para quem está aprendendo o básico de uma linguagem principalmente imperativa, como o Python, o melhor é que sua função faça todos os testes que podem ser tão complicados quanto se queira, e retorne um valor True ou False - você faz um if no ponto em que chama a função e testa o retorno da mesma - principalmente se quer alterar variáveis locais.
(essa é a ideia principal na resposta do  Maniero, que escreveu independente da minha resposta original, que continua abaixo)
Quando não queremos fazer nada no bloco (por exemplo, as vezes num except: , para um rro que sabemos que pode acontecer e não é algo essencial), existe o comando pass, que simplesmente não faz nada.
No entanto, em Python, funções são objetos como qualquer outro, e podem ser passadas como parâmetros. Então dá para fazer algo como o que você quer passando como parâmetro para a primeira função uma segunda função que faz a ação desejada.
def if_(x, func):
    if x>6:
       return func(x)
    return None

def imprime(x):
    print(x)

def x_quadrado(x):
    return x ** 2

x = int(input("Valor de x"))

if_(x, imprime)

x = input("Valor de x")

quadrado = if_(x, x_quadrado)
print(quadrado)

Note que nesse caso, como não estamos chamando as fuções "imprime" e "x_quadrado" na hora de chamar a função, não usamos parenteses após seu nome: o Python trata as funções exatamente como trata qualquer variável.
Dentro da função, o segundo parâmetro tem o nome func e vai receber a função passada. Só quando fazemos func(...) é que a função é de fato chamada.
Além disso, para tarefas muito curtas, existe a palavra chave lambda que permite escrever "mini-funções" em uma única linha de código, dentro de uma expressão. Uma função criada com lambda não precisa ter um nome em uma variável e pode ser declarada direto na chamada a primeira função. Lambdas não precisam do comando "return": elas tem uma única expressão e seu resultado é que é retornado. Então dá pra escrever assim:
if_(x, lambda x: print(x))

Mas essa forma por vezes diminui a legibilidade - na maior parte dos casos o recomendado é criar uma outra função com def mesmo.

Declaração if vazia em função


Example of straight line and a point in $\Bbb R^3$ such that there are infinitely many planes passing through it

Question: Give an example of a straight line $l$ in $\mathbb R^3$, given by a system of two equations, and a point $(a,b,c)\in \mathbb R^3$ such that there are infinitely many planes in $\mathbb R^3$ passing through $l$ and $(a,b,c)$. Justify your answer.
Straight line defined by $x−y=1,y−z=2$ and point $(1,2,3)$ (from a previous question) rather than point $(1,2,3)$ can we just give any point on the line because as long as its on the straight line there will be infinitely many planes?
Is this correct logic? its a strange question, I have never attempted one like this before so sorry if the answer is trivial.
Answer: That point isn't on that line (just plug it in).
Other than that, yes, you could take any point on the line.
Comment: So could I just state any point on the line with an explanation centred around the fact that you'll get infinitely many planes if and only if they lie on a straight line.
Comment: @Jack: Well, the "only if" part is true, but you don't need it; they just asked for *any* such point and line. So it's enough to argue that there are infinitely many planes passing through a given line, and that if the point is on the line then they all also pass through the point.
Comment: This seems right to me, the question was on an old test paper and is worth 6/60...so I'd presume that explanation would be proficient
Answer:
can we just give any point on the line because as long as its on the straight line there will be infinitely many planes?

I'm not sure if this is enough of a justification or rigorous enough. It merely states that "the solution is correct, because it fullfills all requirements of the task", but it doesn't show how that's the case.
Comment: I must admit I do find the question a bit odd, if its not a case of stating a point on the line what else could be done?


Ways of console pausing

Question: As I'm new to C#, I searched Google for various stuff which I used to use in C++. One of them is a pause possibility in a console app.
A lot of people suggested different ways like
System.Console.ReadKey(true);
System.Console.WriteLine();

Others even showed self-made functions which 'should' be more efficient than others.
And that's a real headache to decide which one is a better solution.
Could anyone give any examples of how C# interpret them and which way should be the most efficient?
Comment: If I may ask - why should *pausing* be efficient!?
Comment: @RnD: the exercise is pointless. There will never be some theoretical situation where efficient pausing is necessary, and even if there were some corner case where it was, you'd be better off spending your time thinking about real problems. This is a case of micro-optimization and premature optimization, both of which are bad.
Comment: I know that it doesn't make huge different in small apps, but thinking theoretical, which is better.
Comment: Why would you pause it is the first question you should ask yourself.
Comment: Homework assignment, need to print out something in the end of calculations, can't do that without pausing it, right?
Answer: Run the program using any of the following methods:

ctrl + F5

OR as Rajesh suggested

Console.ReadKey() //pauses for any key
Console.ReadLine() //pauses for enter key
Comment: ctrl + F5 did the job!
Answer: I usually use do and while to pause the console. Then, if necessary, the console should resume if you press a specific key.
Example
do
{

/*  while (!Console.KeyAvailable) //Continue if pressing a Key press is not available in the input stream
    {
        //Do Something While Paused
    }
*/

} while (Console.ReadKey(true).Key != ConsoleKey.Escape); //Resume if Escape was pressed

If you leave this as //Do Something While Paused, the console will only resume if the Esc key was pressed doing nothing while paused.
However, if you would not like the console application to resume, you can use while (true); instead of while (Console.ReadKey(true).Key != ConsoleKey.Escape);
Example
do
{
    //break; //Resume
} while (true); //Continue while True (Always True)

Notice: The console application will pause because by doing do { } while (Condition); you are simply telling the console application that you are doing something. So, the console application will wait for the operation to execute. Then, normally close when there's nothing to do.
Notice: The while is used to loop. So, the application will not close unless the condition becomes false.
Thanks,
I hope you find this helpful :)
Answer: If you're talking about the built-in "pause" command, you could always call it -- even though it's ugly.
Here's what I use:
static void Pause()
{
    Console.WriteLine();
    var pauseProc = Process.Start(
        new ProcessStartInfo()
            {
                FileName = "cmd",
                Arguments = "/C pause",
                UseShellExecute = false
            });
    pauseProc.WaitForExit();
}

Normally like so:
if (Environment.UserInteractive())
    Pause();

Hope this helps.
Comment: The built-in `pause` command just waits for a keypress. Why would you launch an external process to wait for a keypress, when you're in a programming language that can just wait for a keypress?
Comment: Good point, and this was asked & answered 11 years ago. Guess I either mis-read the question at the time, or took it as a programming challenge to call `pause`? Either way, be careful with that "just", I'm sure there's plenty of good logic behind there. Good necromancing though, take your badge! :)
Answer: Or you can use what Pat did but for Arguments instead of
Arguments = "/C pause"

you can use
Arguments = "/C TIMEOUT /t 4 /nobreak > NUL"

where number 4 is number of seconds console will pause before executing rest of the program.
And the whole function would be
static void Pause(int sec)
    {
        Console.WriteLine();
        var pauseProc = Process.Start(
            new ProcessStartInfo()
            {
                FileName = "cmd",
                Arguments = "/C TIMEOUT /t " + sec + " /nobreak > NUL",
                UseShellExecute = false
            });
        pauseProc.WaitForExit();
    }

and you will call it with Pause function with number of seconds to pause.
Pause(4);

Hope it helps.
Answer: you can write "Console.ReadLine();" this too for pupose.
Comment: This is already covered in the [answer by Rajesh](//stackoverflow.com/a/31239421/1677912). If you found an answer helpful, you should [upvote that answer](//stackoverflow.com/help/privileges/vote-up) when you have earned that privilege.

Ways of console pausing


Solving interest Compounded Continuously with Calculus

Question: The question is: Suppose you deposited $4000 at 6% interest compounded continuously. Find the average value of your account during the first 2 years.
$$
A = P \left( 1+\frac{r}{n} \right)^{nt} \,\, .
$$
I used this equation above and integrated it from 0 to 2, then divided by 2. I got 4494.4, 2247.2, and 4242.4, but none of them is right.
Comment: Why are you trying random numbers?
Comment: well the 4242 was pretty close @InterstellarProbe
Comment: Did you actually use any formula to try to solve the problem?
Comment: @saulspatz I edit my post and add a picture of the formula that I used. I can't quite figure out how to format the formula or equation yet, so I attached the picture instead.
Comment: @SakethMalyala So it seems like I used the wrong formula?
Comment: Here's a {mathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)  The formula you linked is not the formula for continuous compounding.  Look at Saketh's answer to see the right formula.
Comment: your formula is correct! however, continuous compounding means n is basically infinite
Comment: when n is infinity, your expression (1+r/n)^nt is equal to e^rt
Comment: yearly measn n=1, monthly means n=12, daily means n=365, and continuous, means n is infinity
Answer: Well, the value of your account at any time is given by $f(t) = 4000e^{0.06t}$, the formula of continuous compounding is $e^{rt}$.
Then, the average value of your integral would be $\displaystyle \frac{1}{2}\int_0^2f(t)\,dt.$
This is equal to $\boxed{$4249.895}$


Basic CHMOD restriction

Question: i have an uploads folder on my website.
What i want to do is restrict users from accessing like i dont want them to go to www.mysite.com/uploads/ and see the files in there and it should show forbidden, but they should be able to download via my website, for example www.mysite.com/downloads.php?id=1
If thats not possible, how can i atleast not show them the directory index on /uploads
How is it that file sharing websites does this?
An htaccess with
deny from all

stops php from accessing the file as well

Please tell me a solution if you would know, i googled and asked on irc a few days ago about this issue, its pretty confusing to me.
Comment: put the folder outside the web root, problem solved.
Comment: Security through obscurity is never the answer. In other words, I hope downloads.php has some form of authorisation handling. Otherwise there's nothing to stop someone trying many combinations of `?id=...`
Comment: you mean outside /public_html/ ?
Comment: yes. that's how most of us do it
Comment: +1 for @Dragon. Don't mess with chmod function. I had tried all methods for restricting files from outside. The best way is putting files behind the webroot.
Answer: If you want to hide your file url from users, its better to move upload folder above of your webroot directory. So nobody can access from browser. How you make download.php
<?php

 /*
    Step 1. Authorization check
    Step 2. get name or id of file that will download $_GET
    Step 3. check if its valid (security check)
    Step 4. check if that file exist in your upload directory
    Step 5. set header using header() function put content-type, attachment etc
    Step 6. readfile and output it
 */
 ?>

Comment: +1 but worth mentioning user authentication, otherwise it has no real value over proper Web server config.
Comment: @cbuckley Thanks, For this situation yes, you're right. But when its usefull to give dynamic and temporary download link (as OP mentioned share hosting websites) and hiding real path to file.
Comment: the only way i know how to let users download file is to link them to the file, im not sure how to do step 5 which you mentioned, is there a guide you can link me?
Comment: @MarshallMathews Have a look at the documentation for [readfile](http://php.net/readfile).
Answer: Add this line in your .htaccess file
Options -Indexes

Answer: Place an index.htm file in your uploads folder or place Options -Indexes in your .htaccess file
Answer: Why not just make a place for downloadable things (mkdir publicuploads), but chmod 700 your uploads folder?
Then they can download what you allow them to download...
Comment: I mean you basically just actively choose what is in the public uploads, and what people have access to, by making a separate directory for the public.
Answer: Using a .htaccess file with deny from all will stop people accessing that folder, It wont stop php from accessing it, but you could put your files one directory lower then your htdocs/www/public_html folder and use php to grab and serve thos files.
With passing a parameter eg: ?id=1 you would access the 1 with $_GET['id'] you would need to check if the file exists, add some http headers to force the download.
Heres a simple example you can work on:
<?php
//your below webroot downloads folder
$path="/var/www/somehost.com/downloads/";

//An array created from globing the download directory or from a database source
$files=array('somefile.gif',
             'someotherFile.png');

//In my example the id is the key to the file pathe array so 0 would be somefile.gif and 1 would be the next.
if(isset($_GET['id'])){
    //Is it numeric?
    if(is_numeric($_GET['id']) && isset($files[$_GET['id']])){
        //Download the file, the download function will return error on fail, eg: not found or directory
        $status = download($path.$files[$_GET['id']]);
        //Spit out the error
        if(isset($status['error'])){
            die($status['error']);
        }
    }
}

function download($file,$chunk=1024){
    if (file_exists($file)) {
        if(is_dir($file)){return array('error'=>'Not allowed!');}
        //Set content headers to force download.
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.str_ireplace(' ','_',basename($file)).'"');
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //If download is larger the 2GB, alls not lost
        header('Content-Length: '.sprintf("%u", filesize($file)));
        //Clean the buffer
        ob_clean();
        //Open a handle to the file
        $handle = fopen($file, "rb");
        $chunksize=(sprintf("%u", filesize($file))/$chunk);

        set_time_limit(0);
        //Loop through the file
        while (!feof($handle)) {
                    //Echo a piece of the file out
            echo fgets($handle, $chunksize);
            flush();
        }
        fclose($handle);
        die;
    }else{return array('error'=>'Not found!');}
    return;
}
?>

You would also need to check user permission on the file, but thats another question.
Comment: can you comment the part where you are setting header, so i can know what im doing :)
Comment: There is an entire manual here on php/http headers: http://php.net/manual/en/function.header.php good luck.

Basic CHMOD restriction


Is there a chance for heavy violin strings to harm the instrument?

Question: Is there anything like that that heavy or other kinds of violin-strings should break down the instrument?
Answer: Thicker strings (aka higher gauge strings) do exert higher tension on the instrument.  On a violin they will do this in two primary directions: one is pulling the neck toward the tail piece, and the other is putting more pressure on the bridge.
I don't think having higher gauge strings will make much of a difference, but you should make sure of two things anyways:

The neck isn't becoming really bent over time. This is unlikely to happen, and it should have some bend, but something to keep an eye on. The main thing that stops this from happening is the ebony fingerboard (so the fingerboard shouldn't be too thin). And more importantly, that the fingerboard is not separating (becoming unglued) from the neck at all.
Your sound post is properly adjusted. If this isn't the case, the pressure from the strings can crack or dent the top piece of the violin.

You probably want to take a good violin to a luthier at least once a year.
Answer: If you have a high-quality instrument, heavy strings shouldn't damage it.
If your instrument is made out of cardboard or you're stringing it with steel power cables, things aren't so certain.  Just don't do anything ridiculous; going up a gauge or two won't exceed the parameters of a decent instrument.
Comment: What about moving from medium to gauge (all 4)? I have an old (1875) german violin, is there anything I should be worried about?
Comment: @Shimmy I'm not sure, sorry.  Hopefully someone else can answer that!


Telethon Bot - how to check if a user is subscribed to my channel by user's id

Question: Via my telegram bot I have to check if the user who texting the bot is in my telegram channel or not,
I tried:
        user_id = event.message.peer_id.user_id #user's id
        async for i in bot.iter_participants(mychannelID, filter=ChannelParticipantsRecent):
            if user_id != i.id:
                status = False
            else:
                status = True
                break

it worked only on my localhost, but on my Linux server it results an error:
Traceback (most recent call last):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/updates.py", line 467, in _dispatch_update
    await callback(event)
  File "main.py", line 226, in enter
    async for i in bot.iter_participants(MAIN_CHANNEL_ID, filter=ChannelParticipantsRecent):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/requestiter.py", line 58, in __anext__
    if await self._init(**self.kwargs):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/chats.py", line 111, in _init
    entity = await self.client.get_input_entity(entity)
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/users.py", line 466, in get_input_entity
    raise ValueError(
ValueError: Could not find the input entity for PeerUser(user_id=******8242) (PeerUser). Please read https://docs.telethon.dev/en/latest/concepts/entities.html to find out more details.

I have already read entities.html as mentioned, but nothing is working.
Also I tried:
        result = await bot(functions.channels.GetParticipantsRequest(
            channel='username',
            filter=types.ChannelParticipantsRecent(),
            offset=42,
            limit=20,
            hash=0
        ))
        if user_id not in result:
            ...

but I keep getting TypeError: argument of type 'ChannelParticipants' is not iterable
Answer: It turns out that I had to re-add my bot to the channel, because the bot lost access hash to the channel when I moved it to another device, since access hash is stored in the .session file and lost after the transfer.


How to integrate $\int{\frac{6x}{x^3+8}dx}$

Question: I'm having some trouble solving this integral using partial fraction method: $$\int{\frac{6x}{x^3+8}dx}.$$
After expanding $x^3+8$ into $(x-2)(x^2+2x+4)$ and expanding the original integral into $$\int{\frac{A}{x-2}+\frac{Bx+C}{x^2+2x+4}}dx,$$ I got $1$,$-1$, and $2$ for $A$, $B$, and $C$, respectively, yielding $$\int{\frac{1}{x-2}+\frac{-x+2}{x^2+2x+4}}dx.$$
This simplifies to $$\ln{|x-2|}-\int{\frac{x-2}{(x+1)^2+3}dx}.$$
How do I solve this resultant integral? That's where I'm stuck.
Comment: $x-2 = (x+1) - 3$. The first gives a logarithm, the second an $\arctan$.
Comment: Ahhhh how did I miss that?! Thank you! :D
Answer: Write the numerator of the last integral as $(x+1)-3,$ and break the integral up into the two parts. The first integral will be a logarithm the second an arctan but do the calculations yourself.
Comment: Okay, I got $\ln{|x-2|}-\frac{1}{2}\ln{|(x+1)^2+3|+\sqrt{3}\arctan{(x+1)}}+C$ Is this the right answer? It can be simplified down, obviously, but I want to make sure.
Comment: Looks good to me!


SBS 2003 Raid restore with fresh install

Question: I have a box running SBS 2003 with one hard drive for the os and another three in a raid 5 configuration [edit: using the build in SBS raid system]
The os hard drive seems to have died, even trying chkdsk and repairing isn't working & it just blue screens on boot.
I would like to transfer off the data from the raid drive, if I did a re-install on a spare HD with SBS 2003 would it be able to detect that there was a raid system in place on these hard drives and make it accessible or is there a way to tell it? Or is there another way to save the data?
Thanks in advance,
Stuart
Answer: As long as you can load the correct drivers for the RAID controller from the OS you use to boot your server, you will be able to access the data on your RAID-5 array.
Comment: Thanks for the answer, I probably should have mentioned I'm using SBS's built in raid functionality - does that change anything?
Comment: Do you perhaps mean that you are using Windows' dynamic disks in A RAID configuration? The answer is still yes, although you'll have to import the disk configuration. I suggest that you completely disconnect your RAID drives from the computer, build your new OS drive, *then* connect the raid drives. This approach minimizes any risk of damage to the drives while installing Windows.
Comment: Yep that sounds like what is going on, just wasn't 100% on the terminology (especially as I can't get in to see how it is described!). Will definitely do the disconnect thing - where would I import the disk configuration from?
Comment: The Disk Management console. From the Run dialog box type the command `diskmgmt.msc`
Comment: I've found that - I was just wondering where in there I would import the existing raid structure from? I can't seem to see any import, and i'm a bit paranoid about accidentally creating a fresh array on top of the existing one and loosing all my data! thanks
Comment: See if this helps: http://technet.microsoft.com/en-us/library/cc753750.aspx.  You should be able to import the array without any data loss, but of course this is something best done with a backup available in case of problems. If you don't have any backups, today is the perfect day to decide from this point forward to make regular backups of any data you value.
Comment: Actually just tried it out on a VM and saw the import when I reinstalled SBS, so many thanks for the help. It did come up with a  warning about data loss, but the test data I had on there seemed ok.
Comment: And yes - very right about the backups!


Is there any PC software that I can use to help edit Roland RD700NX sets/perform maintenance?

Question: I've just downloaded the V2 software for my RD 700NX and see the RD-NX Editor seems to only work on the iPad. I've searched and can't find anything, but does anyone know of any way to edit my keyboard's settings from a PC.
I'd love to be able to perform maintenance in this app too - backup settings etc, as my 2 year old is very very quick at hitting the write button! (I think she likes the flashing lights!)
Answer: If you've already searched the roland site and hit google with RD700NX and found nothing,
then you may need to fall back on a more "general purpose" sysex librarian software.  I've never messed with such stuff.  It will probably not let you edit parameters of the synth.  But at least it could save and restore sysex dumps that the synth is capable of.
good luck to ya.
Comment: Appreciate the reply Stephen. I'll leave the question as unanswered hoping someone is able to suggest something that can do editing of the keyboard too. So frustrating that there's that iPad app but nothing for a PC.


If $R$ has unity $1$, $R'$ has no zero divisors, and $\phi : R \to R'$ is non-zero, is $\phi(1)$ unity for $R'$?

Question: Let $R$ and $R^\prime$ be rings such that $R$ has unity $1$ and $R^\prime$ has no zero divisors; let $\phi \colon R \to R^\prime$ be a homomorphism such that $\phi [ R ] \neq \{ 0^\prime\}$, where $0^\prime$ denotes the additive identity of $R^\prime$. How to determine whether $\phi(1)$ is unity for $R^\prime$? Of course, $\phi(1)$ is unity for $\phi[R]$.
If we assume that $R^\prime$ has unity $1^\prime$, then since $$ \phi(1) \  \phi(1) = \phi(1)$$ and since $$ \phi(1) 1^\prime = \phi(1),$$ we can write $$\phi(1) \  \phi(1) - \phi(1) \ 1^\prime = \phi(1) - \phi(1) = 0^\prime,$$ which we can write as $$\phi(1) \  (\phi(1) - 1^\prime ) = 0^\prime.$$ Since $R^\prime$ is assumed to have no divisors of $0$, we conclude that either $\phi(1) = 0^\prime$ or $\phi(1) = 1^\prime.$
Now if $\phi(1)$ were to be equal to $0^\prime$, then we would have $$\phi(r) = \phi(r1) = \phi(r) \ \phi(1) = \phi(r) \ 0^\prime = 0^\prime$$ for all $r$ in $R$, contradicting our hypothesis that $\phi[R] \neq \{ 0^\prime\}$. Hence $\phi(1) = 1^\prime$.
However, in reaching this proof we have assumed the existence of unity $1^\prime$ for $R^\prime$. This assumption is of course valid for the case of $\phi$ being surjective.
What if that is not the case? I mean can we show that $R^\prime$ must have unity under the given hypotheses irrespective of whtehre or not $\phi$ is surjective?
If not, then how to establish the truth or falsity of our original assertion in the general case?
Comment: user73985, but the ring $R^\prime$ has divisors of $0$. You see, $(r,0) \ (0,s) = (0,0)$ even for non-zero $r$ in $R$ and $s$ in $S$.
Comment: Pick any unital ring $R$ and non-unital ring $S$. Then the natural map $\phi: R \rightarrow R' := R \times S$ satisfies the conditions but $\phi(1)$ is not a unit for $R'$. So it certainly isn't *always* true.
Comment: Oops. So it does.
Answer: Suppose $\phi(1)$ is not the multiplicative identity in $R'$. Then there is some $s \in R'$ such that $\phi(1)s \neq s$; set $t = \phi(1)s$. Note that $$\phi(1)t = \phi(1)\phi(1)s = \phi(1\cdot 1)s = \phi(1)s = t.$$ Therefore $\phi(1)t = t = \phi(1)s$, so $\phi(1)(t - s) = 0'$. As $t \neq s$, either $\phi(1) = 0'$ or $R'$ has zero divisors.
Therefore, if $R$ is a ring with multiplicative identity $1$, $R'$ is a ring with no zero divisors, and there is a non-zero ring homomorphism $\phi : R \to R'$, then $R'$ actually has a multiplicative identity, namely $\phi(1)$.
Comment: Hello Michael. But $\phi(1)(t-s)=0'$ and $t\neq s$ and $\phi(1)\neq 0'$ just only imply that $R'$ has "right" zero divisors. How do you solve this problem? Thanks.
Comment: @bfhaha: For me, a right zero divisor is a zero divisor. What is your definition of zero divisor?
Comment: I follow the definition from Hungerford's _Algebra_. It said that a zero divisor is an element of $R$ which is both a left and a right zero divisor (Definition III.1.3). The original question is also from this book. Let $f:R\to S$ be a homomorphism of rings such that $f(r)\neq 0$ for some nonzero $r\in R$. If $R$ has an identity and $S$ has no zero divisors, then $S$ is a ring with identity $f(1_R)$ (Exercise III.1.16).
Comment: @bfhaha: I'm not sure. What I've shown above is that if $\phi(1)$ is not a left identity, then it is a left zero divisor. The same thing is true with left replaced by right.
Answer: This is a corollary of a lemma proven elsewhere on the site that a nonzero idempotent in a ring without non-zero  zero divisors is an identity for the ring.
This follows from the equations $e(er-r)=0$ and $(re-r)e=0$ where r is any element of the ring and e is the nonzero idempotent.
The condition that the map be nonzero guarantees the image of the identity is a nonzero idempotent.
Answer: Here is my friend DinDin's solution.
In this answer, zero divisors means two-sided zero divisors.
The original question appears in Hungerford's Algebra (Exercise III.1.16).

Let $f:R\to S$ be a homomorphism of rings such that $f(r)\neq 0$ for some nonzero $r\in R$.
  If $R$ has an identity and $S$ has no zero divisors,
  then $S$ is a ring with identity $f(1_R)$.

It uses a surprising result:
A ring has a left (or right) zero-divisor if and only if it has a zero divisor.
See Is it true that a ring has no zero divisors iff the right and left cancellation laws hold?
Note that $f(1_R)=f(1_R 1_R)=f(1_R)f(1_R)$
and $f(1_R)\neq 0$.
(For if $f(1_R)=0$,
then $f(r)=f(r1_R)=f(r)f(1_R)=f(r)0=0$,
contrary to the hypothesis.)
Then
\begin{eqnarray*}
f(1_R)s=f(1_R)f(1_R)s &\Rightarrow& f(1_R)(s-f(1_R)s)=0, \\
sf(1_R)=sf(1_R)f(1_R) &\Rightarrow& (s-sf(1_R))f(1_R)=0.
\end{eqnarray*}
By the lemma and the hypothesis,
$S$ has no left zero divisor and has no right zero divisors,
it follows that $s-f(1_R)s=0=s-sf(1_R)$
and $s=f(1_R)s=sf(1_R)$.
That is,
$f(1_R)=1_S$.


Merge two array of objects together es6

Question: Currently I have two different array of objects and my end result is I am trying to have one single array of objects.
const postIds = [
  { id: 4938960132 },
  { id: 5586491011 },
  { id: 4671908225 },
  { id: 4594788047 },
  { id: 4657970305 }
]

const images = [
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]

What I am hoping to have at the end is a data structure like the following
const newData = [
    { id: 4938960132, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
    { id: 5586491011, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
    { id: 4671908225, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg'  },
    { id: 4594788047, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg'},
    { id: 4657970305, featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]

I've been trying a lot of different things here such as reduce, spread operator and other es6 functions but cannot seem to get the data structure that I am looking for.
Any help would be much appreciated
Comment: what's the logic for merge ? I don't see how id is matched with the image url in anyway
Answer: Assuming the two arrays have the same length:
const newData = [...postIds.map((postId, i) => Object.assign({}, postId, images[i]))];

Alternativelly, with ... operator:
const newData = [...postIds.map((item, i) => {
  return {
    ...item,
    ...images[i]
  };
})];

Working snippet:

const postIds = [
  { id: 4938960132 },
  { id: 5586491011 },
  { id: 4671908225 },
  { id: 4594788047 },
  { id: 4657970305 }
]

const images = [
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' },
  { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }
]

const newData = [...postIds.map((item, i) => Object.assign({}, item, images[i]))];

console.log(newData)
Answer: You creduce both array by mapping the objects at the same index and by assigning to a new object.
This works for an arbitrary count of arrays.

const
    postIds = [{ id: 4938960132 }, { id: 5586491011 }, { id: 4671908225 }, { id: 4594788047 }, { id: 4657970305 }],
    images = [{ featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/rustic20coffee20table.jpeg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Amazing-Table-For-Flamboyant-Furniture-Home-Design-Ideas-With-Rustic-Furniture-Coffee-Table.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/envoy-lookout-rooftop-11b-780x520.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/Alexanderplatz_03.jpg%3Ft=1528912781831-6.jpeg' }, { featuredImage: 'https://www.rusticfurnitureboston.com/hubfs/Blog_Media/mountain-landscape-wallpaper-29048-29765-hd-wallpapers.jpg%3Ft=1528912781831-6.jpeg' }],
    result = [images, postIds].reduce(
        (r, a) => a.map((o, i) => Object.assign({}, o, r[i])),
        []
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Merge two array of objects together es6


PHP img url with preg_match

Question: want to get only the img url
"//lh5.googleusercontent.com/-0qGW989h9DM/AAAAAAAAAAI/AAAAAAAAG3g/aXkL8mbboKY/photo.jpg"

from
    <meta itemprop="name" content="Saurabh Sharma">
<meta itemprop="description" content="Works at Google as Product Manager. Lives in San Francisco. Lived in New Delhi - Mumbai - Canonsburg - Pittsburgh - Austin - San Francisco.">
<meta itemprop="image" content="//lh5.googleusercontent.com/-0qGW989h9DM/AAAAAAAAAAI/AAAAAAAAG3g/aXkL8mbboKY/photo.jpg">
<meta itemprop="url" content="https://plus.google.com/+SaurabhSharma">

<input type="text" name="hist_state" id="hist_state" style="display:none;">

how to do it with preg_match ?
Answer: In order to get image content , use the following
$data = '<meta itemprop="name" content="Saurabh Sharma"><meta itemprop="description" content="Works at Google as Product Manager. Lives in San Francisco. Lived in New Delhi - Mumbai - Canonsburg - Pittsburgh - Austin - San Francisco."><meta itemprop="image" content="//lh5.googleusercontent.com/-0qGW989h9DM/AAAAAAAAAAI/AAAAAAAAG3g/aXkL8mbboKY/photo.jpg"><meta itemprop="url" content="https://plus.google.com/+SaurabhSharma"><input type="text" name="hist_state" id="hist_state" style="display:none;">';
preg_match('/<meta itemprop=\"image\" content=\"(.*?)\">/i', $data, $matches);

$matches will return an array
Array
(
    [0] =>
    [1] => //lh5.googleusercontent.com/-0qGW989h9DM/AAAAAAAAAAI/AAAAAAAAG3g/aXkL8mbboKY/photo.jpg
)

Comment: the content and itemprop should be flipped then it should work
Comment: print_r($matches[1]) will give you image url
Comment: is there a way to add http: before the result ?

PHP img url with preg_match


How to get GD2 generate PNG8 when resizing PNG8 images

Question: I have an image field which accepts jpg, jpeg, png. I've chosen the Image style: Medium on the display of that field. That style is configured at /admin/config/media/image-styles/manage/medium and it simply scales the image to 600px width.
On /admin/config/media/image-toolkit I can see that GD2 is being used.
My problem is that if the original image on that field is PNG8, the rendered thumbnail (by GD2) is PNG24. This results in much larger file for no reason.
Shouldn't GD2 respect the fact that the source is PNG8? Is there a way to fix this?
Comment: FWIW I switched to `Imagick image manipulation toolkit` and it also has the same problematic behavior. Thumbnails generated from PNG8 images are in PNG24 format.
Answer: GD2 indeed doesn't check what palette size is the source image. From GDToolkit.php:
// Always save PNG images with full transparency.
if ($this->getType() == IMAGETYPE_PNG) {
  imagealphablending($this->getResource(), FALSE);
  imagesavealpha($this->getResource(), TRUE);
}

The only way I could hack PNG8 in there was:
// Always save PNG images with full transparency.
if ($this->getType() == IMAGETYPE_PNG) {
  imagealphablending($this->getResource(), FALSE);
  imagesavealpha($this->getResource(), TRUE);
  imagetruecolortopalette($this->getResource(), TRUE, 256); // ← hardcoded 256 hack for PNG8
}

I couldn't find a way of determining the palette size of the source image. So by leaving that hack of mine in there the risk is that PNG24 source images will be saved in the styles/ directory as PNG8 files.


conditional statement in loop c++

Question: for (i = 1; i <= a; i++){
    for (b = 1; b <= i; b++){
        cout << "X";
    }
    cout << endl;
}

if a=4, the result would be
X

XX

XXX

XXXX

while the output of this
for (i = 1; i <= a; i++){
    for (b = 1; b <= a - i; b++){
        cout << "A";
    }
    cout << endl;
}

will be
AAA

AA

A

i recognize the different in conditional statement but i can not explain it my self why so.
Comment: Step through this code in a debugger if you can't work through what it does on paper. You also need to adopt a consistent indentation style because what you have here is pure chaos and very hard to read.
Comment: Write it out on paper. i will be 1, for 1 .. (4-1). i is 2, for 1..(4-2)...
Comment: Assume `a` is `4` like you said. The first iteration of the second loop would iterate for `a-i` times, which would be `1 < 4-0`. Sometimes just writing this out with some pen and paper can do wonders.
Comment: i wrote it down and spent 3 hours before asking here. none answer the question but i assume that the value in conditional statement of loop is the number of loops(?). for i = 1.. (4-1)would be 3,i =2 (4-2)would be 2..
but why in first loop its not work like that for i =1.. 4(?) ... this i don't understand. how conditional statement works in for loop
Answer: For your first example, the first for loop with run because 1 is less than a (4). Which then it will move on to the next for loop. So b = 1, and 1 equals to 1 which will run and print out X. Now that loop will end and the outer for loop will increment to 2, and repeat.
Answer: Take a look at your stop conditions for the inner loops:
b <= i;
b <= a - i;

Now, let's start with i being 1:
b <= 1;
b <= 3;

And, finish with i being 4:
b <= 4;
b <= 0;

Considering your b's initializations:
b = 1;
b = 1;

Combine them all => your loop ranges for bs would be [1; 4] and [3; 1].

conditional statement in loop c++


Regarding two different ordering relations.

Question: We have 3 assumptions:
1) We have two different ordering relations $ \leq_a $ and $ \leq_b $.
2) Given arbitrary sets $S_1, S_2 $, we know $ S_1 \leq_a S_2 \rightarrow S_1 \leq_b S_2 $.
3) We also know $\leq_a$ is a preorder on  $\mathbb{N} $.
?) Does this imply that $\leq_b$ is a preorder on $\mathbb{N} $?
Comment: What is the definition for an ordering relation on $A$? a subset of $A\times A$?
Answer: No it does not, let $\leq_b$ be the relation on $\mathbb N$ so that $x\leq_b y$ always except if $x=1$ and $y=0$.
Let $\leq_a$ be the usual order on $\mathbb N$. Then clearly $\leq_a$ is a preorder and clearly if $x\leq_ay$ then $x\leq_by$. But $\leq_b$ is not a preorder since $1\leq_b 2$ and $2\leq_b0$ but $1\not \leq_b 0$.
Comment: Just to clarify, don't you mean $2 \leq_b0$ instead of $2 \leq_b1$?
Comment: Yes, good eye.${}$


Exclusão de arquivo com fs não está funcionando

Question: Tenho um if para excluir um arquivo, porém ele não está sendo excluído e nem está lançando erros.
Alguém tem alguma ideia?
if (results[0].photo != `arquivos/imgpadrao.jpg`) {
  fs.unlink(`./public/${results[0].photo}`);
}

Answer: Você está usando um método assíncrono (fs.unlink), que espera um callback para quando for resolvido. Desse modo, você deve usar uma função de callback para saber se houveram erros:
if (results[0].photo !== `arquivos/imgpadrao.jpg`) {
  fs.unlink(`./public/${results[0].photo}`, (err) => {
    if (err) {
      console.log('Houve algum erro!', err);
    } else {
      console.log('Tudo certo! Arquivo removido.');
    }
  });
}

Você também pode utilizar a versão síncrona desse método, fs.unlinkSync, realizando a tratativa de erro com um try/catch:
if (results[0].photo !== `arquivos/imgpadrao.jpg`) {
  try {
    fs.unlinkSync(`./public/${results[0].photo}`);
    console.log('Tudo certo!');
  } catch (err) {
    console.log('Houve algum erro!', err);
  }
}

Answer: Utilize o unlinkSync para excluir:
fs.unlinkSync(`./public/${results[0].photo}`);

Ou utlize a Promise
fs.unlink(`./public/${results[0].photo}`).then(res => {}).catch(err => {})
Comment: Acho que vale ressaltar na resposta que a versão que utiliza as promessas não é exportada diretamente por `require('fs')`, mas sim `require('fs').promises`, e em versões posteriores do Node.