text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
dynamically created datagridview cell click event does not work
I am dynamically creating dgv and i have to make a event on its cell click, how can i do this?
Right now when i create the cellclick event, it fires nothing.
Code to make dgv:
dataGridView2 = new DataGridView();
DataGridViewColumn col1 = new DataGridViewImageColumn
{
ImageLayout = DataGridViewImageCellLayout.Stretch
};
DataGridViewColumn col2 = new DataGridViewImageColumn
{
ImageLayout = DataGridViewImageCellLayout.Stretch
};
DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
DataGridViewColumn col4 = new DataGridViewLinkColumn();
DataGridViewColumn col5 = new DataGridViewTextBoxColumn();
DataGridViewColumn col6 = new DataGridViewTextBoxColumn();
DataGridViewColumn col7 = new DataGridViewTextBoxColumn();
col1.HeaderText = "TPM Image";
col1.Name = "image_tpm";
col1.Width = 60;
col2.HeaderText = "Find Image";
col2.Name = "image_thefind";
col2.Width = 60;
col3.HeaderText = "Name";
col3.Name = "name";
col3.Width = 150;
col4.HeaderText = "URL";
col4.Name = "product_url";
col4.Width = 100;
col5.HeaderText = "Price";
col5.Name = "price";
col5.Width = 70;
col6.HeaderText = "Accuracy";
col6.Name = "image_accuracy";
col6.Width = 52;
col7.HeaderText = "History";
col7.Name = "history";
col7.Width = 200;
dataGridView2.Columns.Add(col1);
dataGridView2.Columns.Add(col2);
dataGridView2.Columns.Add(col3);
dataGridView2.Columns.Add(col4);
dataGridView2.Columns.Add(col5);
dataGridView2.Columns.Add(col6);
dataGridView2.Columns.Add(col7);
dataGridView2.Location = new System.Drawing.Point(650, 20);
dataGridView2.Size = new System.Drawing.Size(702, 413);
this.Controls.Add(dataGridView2);
My cellClickEvent
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Contains("http:"))
{
Process.Start(dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
catch
{
}
}
But nothing is happening.
A:
dataGridView2.CellClick += new DataGridViewCellEventHandler(dataGridView2_CellClick);
Got worked.>:)
| {
"pile_set_name": "StackExchange"
} |
Q:
Static member value being carried to next test
I am unit testing a class like below
public class A {
private static String aStr = null;
public void doSomething() {
if (null == aStr) {
// do something to init aStr, and this initialized val gets cached for future calls.
aStr = some_val;
} else {
// do something else using aStr value.
}
}
Now while unit testing this I am doing :
public class ATest {
private A a;
@BeforeMethod
public void setup() {
a = new A();
}
@Test
public void test1() {
a.doSomething();
// assert on some_val being fetched correctly.
}
@Test
public void test2() {
a.doSomething();
// assert again for some_val
// this is where some_val fetching is not invoked at all, while debugging I
// can see that aStr is already being initialized from previous test.
}
}
I was assuming that since i am reinitializing object 'a' in @BeforeMethod setup, i should get null value for all tests.. Isn't this assumption correct?
A:
static modifier on a field in java means that this field does not belong to a specific instance of that class, but to a class itself. In most cases you have only exemplar of the class in the running JVM. So it does not matter how many objects of this class you create - they all will share one and the same static field. And one and the same value of that field
| {
"pile_set_name": "StackExchange"
} |
Q:
How To Handle Mandrill WebHooks in .net
I'm a student trying to work with mandrill and to be quite honest, I haven't a clue what I'm at.
I'm able to send emails no problem using mandrill in .net
What I want to do now is use webhooks to catch bounce emails at the moment and maybe more once I have accomplished that.
Here is the code I have so far (from the internet)
public ActionResult HandleMandrillWebhook(FormCollection fc)
{
string json = fc["mandrill_events"];
var events = JsonConvert.DeserializeObject<IEnumerable<Mandrill.MailEvent>>(json);
foreach (var mailEvent in events)
{
var message = mailEvent.Msg;
// ... Do stuff with email message here...
}
// MUST do this or Mandrill will not accept your webhook!
return new HttpStatusCodeResult((int)HttpStatusCode.OK);
and then I have this
public class MailEvent
{
[JsonProperty(PropertyName = "ts")]
public string TimeStamp { get; set; }
[JsonProperty(PropertyName = "event")]
public string Event { get; set; }
[JsonProperty(PropertyName = "msg")]
public Message Msg { get; set; }
}
public class Message
{
[JsonProperty(PropertyName = "raw_msg")]
public string RawMessage { get; set; }
[JsonProperty(PropertyName = "headers")]
public Header Header { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "html")]
public string Html { get; set; }
[JsonProperty(PropertyName = "from_email")]
public string FromEmail { get; set; }
[JsonProperty(PropertyName = "from_name")]
public string FromName { get; set; }
// Not sure why Mandrill sends an array of arrays here...
[JsonProperty(PropertyName = "to")]
public string[][] To { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
[JsonProperty(PropertyName = "tags")]
public string[] Tags { get; set; }
[JsonProperty(PropertyName = "sender")]
public string Sender { get; set; }
[JsonProperty(PropertyName = "dkim")]
public DKIM DKIM { get; set; }
[JsonProperty(PropertyName = "spf")]
public SPF SPF { get; set; }
[JsonProperty(PropertyName = "spam_report")]
public SpamReport SpamReport { get; set; }
}
[JsonDictionary()]
public class Header : Dictionary<string, object>
{
// Need to find a nicer way of doing this... Dictionary<string, object> is kinda dumb
}
public class SpamReport
{
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "matched_rules")]
public SpamRule[] MatchedRules { get; set; }
}
public class SpamRule
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
public class DKIM
{
[JsonProperty(PropertyName = "signed")]
public bool Signed { get; set; }
[JsonProperty(PropertyName = "valid")]
public bool Valid { get; set; }
}
public class SPF
{
[JsonProperty(PropertyName = "result")]
public string Result { get; set; }
[JsonProperty(PropertyName = "detail")]
public string Detail { get; set; }
}
Could somebody please show me how to process the mandrill webhook response then.
Its in json.
I have never done anything like this before. Am I missing much code?
Is json passed in as a file or raw code?
Thanks guys.
I really appreciate it.
A:
I am running my Mandrill Webhook handling as an API project in VS and this is how I am have gotten it up and running:
[HttpPost]
public string Post()
{
/* Every Mandrill webhook uses the same general data format, regardless of the event type.
* The webhook request is a standard POST request with a single parameter (currently) - 'mandrill_events'. */
string validJson = HttpContext.Current.Request.Form["mandrill_events"].Replace("mandrill_events=", ""); //"mandrill_events=" is not valid JSON. If you take that out you should be able to parse it. //http://stackoverflow.com/questions/24521326/deserializing-mandrillapp-webhook-response
List<MandrillEvent> mandrillEventList = JsonConvert.DeserializeObject<List<MandrillEvent>>(validJson);
foreach (MandrillEvent mandrillEvent in mandrillEventList)
{
if (mandrillEvent.msg.email != null)
{
DataLayer.ReportingData.EmailSave(mandrillEvent); //Saves MandrillEvent email to database and sets a messageId for datalayer
}
}
foreach (MandrillEvent mandrillEvent in mandrillEventList)
{
DataLayer.ReportingData.MandrillEventSave(mandrillEvent); //Saves MandrillEvent object to database
}
return "DONE";
}
I then took the documented (and undocumented) JSON parameters of "mandrill_event" and used json2csharp.com to generate the C# properties. I created a class called "MandrillEvent.cs" and put these within:
public class SmtpEvent
{
public int ts { get; set; }
public DateTime SmtpTs { get; set; }
public string type { get; set; }
public string diag { get; set; }
public string source_ip { get; set; }
public string destination_ip { get; set; }
public int size { get; set; }
public int smtpId { get; set; } //added for datalayer
}
public class Msg
{
public int ts { get; set; }
public DateTime MsgTs { get; set; }
public string _id { get; set; }
public string state { get; set; }
public string subject { get; set; }
public string email { get; set; }
public List<object> tags { get; set; }
public List<object> opens { get; set; } //an array of containing an item for each time the message was opened. Each open includes the following keys: "ts", "ip", "location", "ua"
public List<object> clicks { get; set; } //an array containing an item for each click recorded for the message. Each item contains the following: "ts", "url"
public List<SmtpEvent> smtp_events { get; set; }
public List<object> resends { get; set; } //not currently documented on http://help.mandrill.com/entries/58303976-Message-Event-Webhook-format
public string _version { get; set; }
public string diag { get; set; } //for bounced and soft-bounced messages, provides the specific SMTP response code and bounce description, if any, received from the remote server
public int bgtools_code { get; set; } //Is it this? for bounced and soft-bounced messages, a short description of the bounce reason such as bad_mailbox or invalid_domain. (not currently documented but in JSON response)
public string sender { get; set; }
public object template { get; set; }
public string bounce_description { get; set; }
public Msg()
{
tags = new List<object>();
opens = new List<object>();
clicks = new List<object>();
smtp_events = new List<SmtpEvent>();
smtp_events.Add(new SmtpEvent());
resends = new List<object>();
}
}
public class MandrillEvent
{
public string @event { get; set; }
public string _id { get; set; }
public Msg msg { get; set; }
public int ts { get; set; }
public DateTime MandrillEventTs { get; set; }
public int messageId { get; set; } //added for datalayer
public List<string> SingleMandrillEventData { get; set; } //added for Reporting
public MandrillEvent()
{
SingleMandrillEventData = new List<string>();
msg = new Msg();
}
}
You now have your "mandrill_events" JSON object as a functioning C# object!! Did this help or do you need some more clarification/help?
| {
"pile_set_name": "StackExchange"
} |
Q:
BERT vs Word2VEC: Is bert disambiguating the meaning of the word vector?
Word2vec:
Word2vec provides a vector for each token/word and those vectors encode the meaning of the word. Although those vectors are not human interpretable, the meaning of the vectors are understandable/interpretable by comparing with other vectors (for example, the vector of dog will be most similar to the vector of cat), and various interesting equations (for example king-men+women=queen, which proves how well those vectors hold the semantic of words).
The problem with word2vec is that each word has only one vector but in the real world each word has different meaning depending on the context and sometimes the meaning can be totally different (for example, bank as a financial institute vs bank of the river).
Bert:
One important difference between Bert/ELMO (dynamic word embedding) and Word2vec is that these models consider the context and for each token, there is a vector.
Now the question is, do vectors from Bert hold the behaviors of word2Vec and solve the meaning disambiguation problem (as this is a contextual word embedding)?
Experiments
To get the vectors from google's pre-trained model, I used bert-embedding-1.0.1 library.
I first tried to see whether it hold the similarity property. To test, I took the first paragraphs from wikipedia page of Dog, Cat, and Bank (financial institute). The similar word for dog is:
('dog',1.0)
('wolf', 0.7254540324211121)
('domestic', 0.6261438727378845)
('cat', 0.6036421656608582)
('canis', 0.5722522139549255)
('mammal', 0.5652133226394653)
Here, the first element is token and second is the similarity.
Now for disambiguation test:
Along with Dog, Cat and Bank (financtial institute), I added a paragraph of River bank from wikipedia. This is to check that bert can differentiate between two different types of Bank. Here the hope is, the vector of token bank (of river) will be close to vector of river or water but far away from bank(financial institute), credit, financial etc. Here is the result:
The second element is the sentence to show the context.
('bank', 'in geography , the word bank generally refers to the land alongside a body of water . different structures are referred to as', 1.0)
('bank', 'a bank is a financial institution that accepts deposits from the public and creates credit .', 0.7796692848205566)
('bank', 'in limnology , a stream bank or river bank is the terrain alongside the bed of a river , creek , or', 0.7275459170341492)
('bank', 'in limnology , a stream bank or river bank is the terrain alongside the bed of a river , creek , or', 0.7121304273605347)
('bank', 'the bank consists of the sides of the channel , between which the flow is confined .', 0.6965076327323914)
('banks', 'markets to their importance in the financial stability of a country , banks are highly regulated in most countries .', 0.6590269804000854)
('banking', 'most nations have institutionalized a system known as fractional reserve banking under which banks hold liquid assets equal to only a', 0.6490173935890198)
('banks', 'most nations have institutionalized a system known as fractional reserve banking under which banks hold liquid assets equal to only a', 0.6224181652069092)
('financial', 'a bank is a financial institution that accepts deposits from the public and creates credit .', 0.614281952381134)
('banks', 'stream banks are of particular interest in fluvial geography , which studies the processes associated with rivers and streams and the deposits', 0.6096583604812622)
('structures', 'in geography , the word bank generally refers to the land alongside a body of water . different structures are referred to as', 0.5771245360374451)
('financial', 'markets to their importance in the financial stability of a country , banks are highly regulated in most countries .', 0.5701562166213989)
('reserve', 'most nations have institutionalized a system known as fractional reserve banking under which banks hold liquid assets equal to only a', 0.5462549328804016)
('institution', 'a bank is a financial institution that accepts deposits from the public and creates credit .', 0.537483811378479)
('land', 'in geography , the word bank generally refers to the land alongside a body of water . different structures are referred to as', 0.5331911444664001)
('of', 'in geography , the word bank generally refers to the land alongside a body of water . different structures are referred to as', 0.527492105960846)
('water', 'in geography , the word bank generally refers to the land alongside a body of water . different structures are referred to as', 0.5234918594360352)
('banks', 'bankfull discharge is a discharge great enough to fill the channel and overtop the banks .', 0.5213838815689087)
('lending', 'lending activities can be performed either directly or indirectly through due capital .', 0.5207482576370239)
('deposits', 'a bank is a financial institution that accepts deposits from the public and creates credit .', 0.5131596922874451)
('stream', 'in limnology , a stream bank or river bank is the terrain alongside the bed of a river , creek , or', 0.5108630061149597)
('bankfull', 'bankfull discharge is a discharge great enough to fill the channel and overtop the banks .', 0.5102289915084839)
('river', 'in limnology , a stream bank or river bank is the terrain alongside the bed of a river , creek , or', 0.5099104046821594)
Here, the result of the most similar vectors of bank (as a river bank, the token is taken from the context of the first row and that is why the similarity score is 1.0. So, the second one is the closest vector). From the result, it can be seen that the first most close token's meaning and context is very different. Even the token river, water andstream` has lower similarity.
So, it seems that the vectors do not really disambiguate the meaning.
Why is that?
Isn't the contextual token vector supposed to disambiguate the meaning of a word?
A:
BERT and ELMo are recent advances in the field. However, there is a fine but major distinction between them and the typical task of word-sense disambiguation: word2vec (and similar algorithms including GloVe and FastText) are distinguished by providing knowledge about the constituents of the language. They provide semantic knowledge, typical about word types (i.e. words in the dictionary), so they can tell you something about the meaning of words like "banana" and "apple".
However, this knowledge is at the level of the prototypes, rather than their individual instances in texts (e.g. "apple and banana republic are american brands" vs "apple and banana are popular fruits"). The same embedding will be used for all instances (and all different senses) of the same word type (string).
In past years, distributional semantics methods were used to enhance word embeddings to learn several different vectors for each sense of the word, such as Adaptive Skipgram. These methods follow the approach of word embeddings, enumerating the constituents of the language, but just at a higher resolution. You end up with a vocabulary of word-senses, and the same embedding will be applied to all instances of this word-sense.
BERT and ELMo represent a different approach. Instead of providing knowledge about the word types, they build a context-dependent, and therefore instance-specific embedding, so the word "apple" will have different embedding in the sentence "apple received negative investment recommendation" vs. "apple reported new record sale". Essentially, there is no embedding for the word "apple", and you cannot query for "the closest words to apple", because there are infinite number of embeddings for each word type.
Thus, BERT and ELMo handle the differences between word-senses but will not reveal what are the different senses of the word.
A:
The most important question to ask is : for which purpose do you need that?
You are not right when claiming that Word2Vec creates vectors for words without taking into account the context. The vectors are created in fact using a window (the size of the windo is one of the settings in W2V) in order to get the neighbouring words, so yes, it takes into account the context! That is why you can have those famous equations : king-man = queen-woman, high cosine similarity between two synonyms or words having the same part of speech, etc, etc.
If you wish to have two meanings, why not create two models, with data from two separate sectors (banking and general, let us say). In this case, each model will recognize bank with a different meaning.
Once again, what exactly is you need here ?
| {
"pile_set_name": "StackExchange"
} |
Q:
Conversion failed when converting the varchar value 'Id' to data type int
I got this error when trying run my sql query...
Conversion failed when converting the varchar value 'Id' to data type
int
SELECT *
FROM History
INNER JOIN Header
ON History.Id = Header.docId
Please help me :(
A:
In your Join condition am sure one column is of Integer type and other one is Varchar type.
ON History.Id = Header.docId
since Int has higher precedence than varchar, Varchar column will be implicitly converted to Int
So explicitly convert the Int column to varchar.
ON History.Id = cast(Header.docId as varchar(50))
I have considered Header.docId as Int type if no, then convert History.Id to varchar
| {
"pile_set_name": "StackExchange"
} |
Q:
O que é gamificação no contexto de software?
Recentemente vi alguns comentários sobre gamificação e gostaria de entender o que é e como funciona no contexto de software.
Como isso se relaciona com programação propriamente dita?
A:
"Gamificação" é um termo usado quando um sistema ou campanha quer fazer com que o usuário se sinta engajado para conquistar alguma coisa, seja status, pontuação ou prêmios, como num jogo, como uma forma mais lúdica de "prender" o usuário (o StackOverflow pode ser citado como um exemplo típico disso).
O termo deriva de "game" (jogo), quando em todo jogo, o jogador busca pontuar o mais alto possível com seu esforço e assiduidade, fazendo com que ele se sinta instigado a continuar no jogo afim de buscar mais pontos, criando uma fidelização do usuário.
Gamificação não está ligada diretamente com programação, pois isso pode ser feito de diversas formas, sem envolver programação. No caso de programação, apenas envolve como será feito o código (software) onde o programador escreve o programa que irá controlar a forma do "jogo" funcionar (back-end).
A:
Eu já dei a minha visão sobre o que é Gamificação em outra pergunta relacionada. Então, queria focar aqui na segunda parte da sua pergunta: qual é a relação com software.
Como uma ferramenta para auxiliar na motivação intrínseca das pessoas, a gamificação pode ser utilizada no contexto do desenvolvimento de software assim como em qualquer outro contexto. Porém é primeiramente necessário entender qual é o objetivo de design (observe que é diferente do objetivo do participante) intencionado. Em outras palavras, qual é o comportamento que se deseja atribuir aos participantes? Você quer que eles utilizem o software de forma mais correta, que eles programem o software de forma mais robusta, ou que eles se interessem por aprender a fazer software? Cada uma dessas perguntas é um produto/processo diferente, em que certos métodos/técnicas/ferramentas podem ser mais ou menos úteis.
Por exemplo, oferecer medalhas (badges) a usuários de um website como o Stackoverflow pode fazer com que eles se interessem pelo conteúdo muito específico ou por uma tarefa naturalmente pouco gratificante (como fazer análises de perguntas de outras pessoas) justamente pela busca por tais medalhas, mas em outros contextos em que o usuário já está motivado de forma extrínseca (porque é seu emprego e ele deve usar o sistema, por exemplo), as medalhas podem ser enxergadas meramente como um estorvo.
O colega Bruno comentou que a gamificação pode não funcionar no contexto de educação, e isso é realmente uma grande possibilidade. No exemplo citado (que não é de livre acesso, então não dá pra ter mais detalhes), uma possibilidade que eu já vi acontecer tem relação com a criação de expectativas. Ao se mencionar a alunos que a aula será "gamificada" (terá elementos de jogos), a expectativa criada é bastante grande principalmente quando a aula tradicional já é enxergada como algo chato e entediante. Se a gamificação for realizada de forma superficial (por exemplo, em que medalhas sem qualquer ligação a uma fantasia consistente e de interesse dos "jogadores" são dadas por tarefas realizadas), ela pode falhar completamente e, de fato, conduzir a experiência para o sentido oposto do intencionado (o aluno achar que a medalha é a nota da prova travestida de medalha, e assim ficar ainda mais chateado por causa da falha em cumprir uma grande expectativa criada).
Mas isso não quer dizer que tentativas assim não tenham alcançado sucesso na educação. Em São Paulo há um grupo chamado "Interpretar e Aprender" que utiliza jogos de RPG para auxiliar no ensino de História, e que tem motivado muitos alunos a se interessar pelo assunto.
Aqui há um ponto importante de discussão, a respeito de isso se tratar
de um "jogo sério" ou de uma gamificação - vide o gráfico de Deterding
et al. que eu cito na minha outra resposta já referenciada. O fato é
que elementos da História são conduzidos em meio a muitas sessões de
jogo, com diferentes pessoas e recriando contextos sociais as vezes
bastante difíceis de reconhecer fora do círculo do jogo, de forma que
isso pra mim está muito mais para um processo do que para um produto.
No ensino de computação há inúmeros exemplos, mas eu gosto de citar o jogo online chamado CodeCombat (este sim, muito mais próximo de um jogo sério do que de um processo gamificado). Mesmo sendo um jogo, ele tem motivado muitas pessoas a se interessarem mais por programação e a fazerem exercícios de forma lúdica. Utilizado num contexto acadêmico, o jogo é uma ferramenta em um processo maior, e nesse caso eu diria que se trata de uma gamificação envolvendo o aprendizado de software.
Em resumo, a relação da gamificação com o software é tangencial, assim como é a relação do desenvolvimento de jogos (sérios ou não) com sofware. Jogos digitais requerem programação envolvendo um sistema de computador, mas jogos analógicos (de tabuleiro, cartas, dados, etc) já existem há mais de 3 mil anos. O jogo desse link em particular (da família Mancala) envolve uma mecânica que simula a semeadura de sementes na terra e, principalmente, a percepção de que você não pode vencer se o seu adversário morrer de fome. Assim como o Xadrez e o Senet, esses primeiros jogos tinham uma forte relação com questões fundamentais para as civilizações humanas: respectivamente a agricultura, a guerra e a religião. O uso desses jogos, enxergado nesse contexto mais amplo, não deixa de fazer deles ferramentas em um processo gamificado, com a intenção de motivar algum comportamento ou gerar conscientização.
Em conclusão: a gamificação precede o software; mas pode se valer dele como ferramenta, ou pode ser utilizada para motivar algum comportamento relacionado ao seu uso, desenvolvimento ou aprendizado.
A:
Gamificação, do inglês gamification (de game), é a promoção do engajamento do público em certo produto ou serviço por meio de maneiras alternativas.
As comunidades do StackExchange, o StackOverflow em Português é uma delas, promovem a gamificação. Os pontos, medalhas, privilégios e a interação social cativam o usuário a perguntar e responder mais.
Um aplicativo conhecido para aprendizado de idiomas, Duolingo, também promove a ludificação através do sistema competitivo.
Esse conceito todo não se prende ao mundo virtual. Empresas estão gamificando processos para engajar seus funcionários a buscarem mais produtividade, conhecimento e etc.
A primeira referência de "gamification" foi em 2002-2003 por Nick Pelling, embora tenha sido popularizado a partir de 2010, como mostra este gráfico com a frequência de buscas:
Fonte: Google Trends (gamification)
As citações dos cases anteriores são relacionados à software. De forma simples é procurar os métodos de gamificação aplicáveis à sua solução e começar a implementação, seja o sistema de pontuação, o ranking, ou outro. O ideal é analisar resultados para ver se os mesmos surtem, aumentando o engajamento ou outro objetivo maior.
O mais legal desse campo de estudo é que não envolve somente software. Como toda área relacionada a ux, é comum ver psicologia (principalmente comportamental).
No mais, vamos ver quem ganha o “resposta aceita” nessa pergunta
Essa pergunta gerou essa, no Portuguese Language!
| {
"pile_set_name": "StackExchange"
} |
Q:
Show menu when view is long pressed
I've been looking around on the internet regarding my question but I couldn't find a straight answer. Is it possible to create a non-blocking menu similar to the overflow menu found in Android 4.0+ when a view is long pressed?
I have a number of LinearLayout instances which have an OnLongClickListener which brings up a context menu, but it's not exactly what I am looking for. I was hoping for a smoother menu which is brought up when one of these instances is clicked, and removed when the user clicks outside of the menu's region. This is very similar to the way the overflow menu behaves in the Android ActionBar.
So to sum up, is it possible to replicate the look-and-fell and the behavior of the overflow menu when using context menus?
Here's hoping I don't have to jump through hoops to get the implementation that I desire.
Thanks in advance.
EDIT: After some digging I've found the PopupMenu which is exactly what I was looking for however it works only on devices running Honeycomb and above. Does anyone know of a way with which I can replicate this menu behavior in older versions of Android without using blocking windows like dialogs?
A:
There is no compatibility library for PopupMenu that i'm aware of. So if you want it, You can use a component called ActionBarSherlock to achieve the same effect.
See here for a detailed explanation on how to do this:
https://stackoverflow.com/a/11765787/1369222
| {
"pile_set_name": "StackExchange"
} |
Q:
RecyclerView Layout Manager Manipulation
I have a recycler view that should display data as follows (1 item if position is even, 2 items beside each other if position is odd) and honestly I tried and tried but I'm failing to do so.
Here's what it should look like
And here's how it's now (ignore the width and height and see how video 3 is inflated twice)
I'm using LinearLayoutManager, and Here's my adapter:
public class MediaItemsAdapter extends RecyclerView.Adapter<MediaItemsAdapter.RecyclerViewHolder> {
private List<MediaItem> allMediaItems;
private Activity context;
private RecyclerViewOnItemClickListener itemClickListener;
public MediaItemsAdapter(Activity context, List<MediaItem> allMediaItems, RecyclerViewOnItemClickListener itemClickListener ) {
this.allMediaItems = allMediaItems;
this.context = context;
this.itemClickListener = itemClickListener;
}
@Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
MediaItem mediaItem = allMediaItems.get(position);
if(position %2 == 0){ // even
holder.tvTitle.setText(mediaItem.getTitle());
holder.tvSummary.setText(mediaItem.getDate());
try {
Picasso.with(context)
.load(mediaItem.getImageUrl())
.into(holder.ivImage, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
holder.ivImage.setAlpha((float) 1);
}
@Override
public void onError() {
Log.wtf("error", "in loading");
}
});
} catch (Exception e) {
e.printStackTrace();
}
holder.ivPlay.setVisibility(mediaItem.isVideo() ? View.VISIBLE : View.GONE);
}else{ //odd
holder.tvTitle.setText(mediaItem.getTitle());
holder.tvSummary.setText(mediaItem.getDate());
try {
Picasso.with(context)
.load(mediaItem.getImageUrl())
.into(holder.ivImage, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
holder.ivImage.setAlpha((float) 1);
}
@Override
public void onError() {
Log.wtf("error", "in loading");
}
});
} catch (Exception e) {
e.printStackTrace();
}
holder.ivPlay.setVisibility(mediaItem.isVideo() ? View.VISIBLE : View.GONE);
try{
MediaItem secondMediaItem = allMediaItems.get(position + 1);
holder.tvSecondTitle.setText(secondMediaItem.getTitle());
holder.tvSecondSummary.setText(secondMediaItem.getDate());
try {
Picasso.with(context)
.load(secondMediaItem.getImageUrl())
.into(holder.ivSecondImage, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
holder.ivSecondImage.setAlpha((float) 1);
}
@Override
public void onError() {
Log.wtf("error", "in loading");
}
});
} catch (Exception e) {
e.printStackTrace();
}
holder.ivSecondPlay.setVisibility(secondMediaItem.isVideo() ? View.VISIBLE : View.GONE);
}catch (Exception e){
e.printStackTrace();
}
}
}
@Override
public int getItemViewType(int position) {
return position %2 == 0 ? 0 : 1;
}
@Override
public int getItemCount() {
return this.allMediaItems.size();
}
public interface RecyclerViewOnItemClickListener {
void onItemClicked(View v, int position);
}
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView;
if (viewType == 0 ){
layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.even_media_layout, parent, false);
RecyclerViewHolder rcv = new RecyclerViewHolder(layoutView);
return (rcv);
}else{
layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.odd_media_layout, parent, false);
RecyclerViewHolder rcv = new RecyclerViewHolder(layoutView);
return (rcv);
}
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTitle, tvSecondTitle, tvSummary, tvSecondSummary;
private ImageView ivImage, ivSecondImage;
private ImageButton ivPlay, ivSecondPlay;
protected View itemView;
public RecyclerViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
this.itemView.setOnClickListener(this);
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
tvSecondTitle = (TextView) itemView.findViewById(R.id.tvSecondTitle);
tvSummary = (TextView) itemView.findViewById(R.id.tvSummary);
tvSecondSummary = (TextView) itemView.findViewById(R.id.tvSecondSummary);
ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
ivSecondImage = (ImageView) itemView.findViewById(R.id.ivSecondImage);
ivPlay = (ImageButton) itemView.findViewById(R.id.ivPlay);
ivSecondPlay = (ImageButton) itemView.findViewById(R.id.ivSecondPlay);
}
@Override
public void onClick(View view) {
itemClickListener.onItemClicked(view, getLayoutPosition());
}
}
}
How to prevent the data replication, how to tell the array list that object 3 has already been inflated? is there a better way than the LinearLayoutManager
Regards.
A:
User GridLayoutManage to your RecyclerView and set span size lookup like this.
GridLayoutManager glm = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup(){
@Override
public int getSpanSize(int position) {
return position % 3 == 0 ? 2 : 1;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
unresolved external symbol, but dumpbin says it's ok
I downloaded Crypto++ 5.62 and built it with default project settings. In my project I set up the path to cryptopp.lib and defined its name in "Additional Dependencies". Both Crypto++ and my project - VS 2008.
During building of my project I get:
main.obj : error LNK2001: unresolved external symbol
"class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const CryptoPP::DEFAULT_CHANNEL" (?DEFAULT_CHANNEL@CryptoPP@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@B)
main.obj : error LNK2001: unresolved external symbol
"bool (__cdecl* CryptoPP::g_pAssignIntToInteger)(class type_info const &,void *,void const *)" (?g_pAssignIntToInteger@CryptoPP@@3P6A_NABVtype_info@@PAXPBX@ZA)
dumpbin /all cryptopp.lib shows me in the public symbols section
19471C _imp_?DEFAULT_CHANNEL@CryptoPP@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@B
1D6F30 __imp_?g_pAssignIntToInteger@CryptoPP@@3P6A_NABVtype_info@@PAXPBX@ZA
What's wrong then? Why the linker can't find the symbols?
upd:
linker command line from my project settings
/OUT:"C:\Projects\crypto_hash\Debug\crypto_hash.exe" /NOLOGO /LIBPATH:"e:\libs\cryptopp\cryptopp562\cryptopp\Win32\DLL_Output\Debug" /MANIFEST /MANIFESTFILE:"Debug\crypto_hash.exe.intermediate.manifest" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"C:\Projects\crypto_hash\Debug\crypto_hash.pdb" /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:PROMPT cryptopp.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
A:
Try adding CRYPTOPP_IMPORTS to your project defines.
From config.h:
#ifdef CRYPTOPP_EXPORTS
# define CRYPTOPP_IS_DLL
# define CRYPTOPP_DLL __declspec(dllexport)
#elif defined(CRYPTOPP_IMPORTS)
# define CRYPTOPP_IS_DLL
# define CRYPTOPP_DLL __declspec(dllimport)
#else
# define CRYPTOPP_DLL
#endif
Or include Crypto++'s dll.h. It sets CRYPTOPP_IMPORTS:
#if !defined(CRYPTOPP_IMPORTS) && !defined(CRYPTOPP_EXPORTS) && !defined(CRYPTOPP_DEFAULT_NO_DLL)
# ifdef CRYPTOPP_CONFIG_H
# error To use the DLL version of Crypto++, this file must be included before any other Crypto++ header files.
# endif
# define CRYPTOPP_IMPORTS
#endif
If that does not work...
g_pAssignIntToInteger is from algparams.cpp:
$ grep -R g_pAssignIntToInteger *
algparam.cpp:PAssignIntToInteger g_pAssignIntToInteger = NULL;
algparam.h:CRYPTOPP_DLL extern PAssignIntToInteger g_pAssignIntToInteger;
algparam.h: if (!(g_pAssignIntToInteger != NULL && typeid(T) == typeid(int) && g_pAssignIntToInteger(valueType, pValue, &m_value)))
integer.cpp: if (!g_pAssignIntToInteger)
integer.cpp: g_pAssignIntToInteger = AssignIntToInteger;
Looking at the declaration in algparam.h:
// to allow the linker to discard Integer code if not needed.
typedef bool (CRYPTOPP_API * PAssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt);
CRYPTOPP_DLL extern PAssignIntToInteger g_pAssignIntToInteger;
And the implementation in algparam.cpp:
#ifndef CRYPTOPP_IMPORTS
...
NAMESPACE_BEGIN(CryptoPP)
PAssignIntToInteger g_pAssignIntToInteger = NULL;
...
So you might need to change the implementation to ensure the code uses g_pAssignIntToInteger (to keep it from being discarded). Unfortunately, nothing comes to mind at the moment.
DEFAULT_CHANNEL is declared in cryptlib.h and has storage allocated in cryptolib.cpp:
$ grep -R DEFAULT_CHANNEL *
...
cryptlib.cpp:const std::string DEFAULT_CHANNEL;
...
cryptlib.h:extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
...
This might be a different problem since I'm not used to seeing issues with DEFAULT_CHANNEL. See how CRYPTOPP_IMPORTS works for you, and then ask a different question since this might be a different problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Boolean String Normalizer
How can the normalize() method below be improved? I've extracted the functionality from a project I'm working on into a simple class for the purposes of this question.
The method takes a string input and compares it to a set of 'truthy' and 'falsey' strings, returning true or false respectively if a case insensitive match is found. The truthy and falsey strings are mutable so cannot be hard coded into the method.
If the $nullable property is set to true and no match is found, null is returned. Otherwise false is returned.
I feel as though I may be missing a trick by looping through the array and calling strcasecmp twice for each iteration.
<?php
class BooleanNormalizer
{
/** @var array */
public $binaries = [
'yes' => 'no',
'1' => '0',
'on' => 'off',
'enabled' => 'disabled',
];
/** @var bool */
public $nullable = false;
/**
* @param string $value
*
* @return bool|null
*/
public function normalize($value)
{
foreach ($this->binaries as $truthy => $falsey) {
if (strcasecmp($value, $truthy) === 0) {
return true;
}
if (strcasecmp($value, $falsey) === 0) {
return false;
}
}
return ($this->nullable) ? null : false;
}
}
Usage:
$normalizer = new BooleanNormalizer();
$normalizer->nullable = true;
$normalizer->binaries = ['enabled' => 'disabled'];
$normalizer->normalize('enabled'); // returns true
$normalizer->normalize('disabled'); // returns false
$normalizer->normalize('blah'); // returns null
A:
I guess foremost, I question the mutability of this class. Should one really be able to change the value of $binaries?
I very much question the optional "nullable" thing here. First of all, name-wise this doesn't seem to make sense as typically when you think of something as "nullable" it means it is a variable, property, field, etc. that is allowed to be set to null. You are not setting anything here, so the terminology seems weird. Perhaps it should be called $returnFalseOnMissingValue or something that more directly ties it to the return behavior of the normalize() method.
I would however get rid of it, as it will become a source of fragility to calling code, as in some cases (including default case) your calling code would not be able to distinguish a false "hit" result from a false "miss" result. Let the calling code deal with converting null to false if it needs to send false up the call stack. Don't obfuscate the result right here in this class which is designed to own this determination.
Why use strcasecmp()? This seems an odd choice vs. just casting $value to lowercase for direct comparison.
i.e.
$value = strtolower($value);
if ($value === $truthy) return true;
if ($value === $falsey) return false;
return null;
I also don't understand the lookup mechanism and comparison mechanisms here. It seems obscure upon first read to have key/value positioning determine how the string is mapped to true/false. I think I would be more explicit like:
protected $mappings = [
'yes' => true,
'no' => false,
'1' => true,
'0' => false,
'on' => true,
'off' => false;
'enabled' => true,
'disabled' => false
];
And have your comparison method simply do something like:
public function normalize($value) {
$value = strtolower($value);
if(!array_key_exists($value, $this->mappings) return null;
return $this->mappings[$value];
}
If you truly need to keep the concept of true/value pairs for some reason not shown in this code, then perhaps a structure like:
protected $mappings = [
'yes' => ['boolean' => true, 'inverse' => 'false'],
'no' => ['boolean' => false, 'inverse' => 'true'],
...
];
This prevents you from having to iterate through the $binaries values every time you want to do a lookup like you are currently doing. The name $binaries also seems odd here as that typically has a much different meaning when talking about writing code.
I would suggest that 'true' and 'false' should be strings in your default mapping of boolean values.
Does this class really need a concrete instantiation?
Consider adding some parameter validation anytime you have public methods. Ideally this could be a combination of type hinting and/or variable inspection to make sure you are being passed a valid parameter. What happens now you if your method is passed an integer, array, object, empty string, etc.?
| {
"pile_set_name": "StackExchange"
} |
Q:
Do Scala objects survive activity restarts on Android?
I'm writing an Android app in Scala, and I haven't been able to find a clear answer to this question.
My application contains an object with a bunch of static data defined in vals. The data includes instances of classes.
My question is, what happens to my object when Android decides to kill the activity and later restarts it? I understand that objects in Scala can be used to achieve a similar purpose to static values in Java, but are not actually implemented that way in the generated bytecode. So does Android know to re-initialize my object when it restarts the activity? Are there circumstances where it would not do so, or where I have to be careful?
If the answer to the above is "all is fine", I gather that an object composed of mutable data would be quite different. In that case I'm pretty sure that I would need to explicitly save/restore such objects to retain the state. But it seems silly to have to save/restore data that is always the same and is hard-wired into the APK itself.
A:
In short, objects are translated to singletons, and the single instance is held in a static final field. Therefore objects will be reinitialized, and you'll need serialization to restore the same data for mutable objects.
Programming in Scala (from Odersky et al.), chapter 31, explains how to use the decompiler to get the answer you need - it's very easy.
Basically, given an object like this:
object App {
def main(args: Array[String]) {
println("Hello, world!")
}
}
It will be translated to a class named App$ implementing the singleton pattern. In particular, the singleton instance is contained within a field defined as public static final App$ MODULE$ = new App$(); , and the methods are defined as instance methods. javap App$ can be used to confirm the declaration of the field - probably jad can decompile also the source code. If no companion class is defined, Scala will also define a class named App containing corresponding static final methods to call from Java. This way, you get an App.main method with the right signature and can invoke scala App, which in turn invokes java App with the right additional libraries.
| {
"pile_set_name": "StackExchange"
} |
Q:
I want to add an image to the specific section used in the html code whenever the screen size is resized to mobile view using media query
How to add an image as a background using media queries to the section id= "vid" and hide the background video running on it.
My code HTML code is shown below
<section id="vid" class="vidd">
<video playsinline autoplay muted loop poster="css\img_forest1.jpg" id="bgvd">
<source src="video\Love-Coding.webm" type="video/webm">
</video>
</section>
and CSS code is shown below
@media screen and (max-width: 480px)
{
video { display: none; }
}
@media screen and (max-width: 480px)
{
#vid {
background: url(img_forest.jpg) no-repeat center center scroll;
}
}
A:
Add your background image into <section> separately.
HTML
<section id="vid" class="vidd">
<img src="css\img_forest1.jpg" class="image1"/>
<video playsinline autoplay muted loop poster="css\img_forest1.jpg" id="bgvd">
<source src="video\Love-Coding.webm" type="video/webm">
</video>
</section>
CSS
.image1{ display: none; }
@media screen and (max-width: 480px)
{
video { display: none; }
.image1 { display: block; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript In Protractor
SnapshotI have to automate click on dropdown inside an iframe using protractor.
Iframe:
<iframe src="swagger-ui/index.html" frameborder="0" marginheight="0" marginwidth="0"
width="100%" height="900" scrolling="auto" target="_top" class="ng-scope">
</iframe>
Dropdown:
<select id="select_baseUrl" name="select_baseUrl">
<option value="1">default (1)</option>
<option value="2">eventui (2)</option>
<option value="3">eventservice (3)</option>
</select>
I tried
var eeel = browser.executeScript("document.getElementByTagName('iframe')
.contentWindow.document.getElementById('select_baseUrl').click();");
browser.wait(eeel,200000);
console.log("Lv2");
But not working.
A:
You are abusing the executeScript() function which is not needed in this case at all. Protractor (and the underlying Webdriver.js) allows you to switch Iframes using:
browser.driver.switchTo().frame(0);
in most cases using 0 should return the first iframe visible on the page, but if there are more you have to find the appropriate index number.
Once you have switched you can find elements as you normally would. But once you are done you must switch back to the default window using browser.driver.switchTo().defaultContent();
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatic nested list
I'm trying to create a nested list in Asp.Net/C# using a ListView control. I looked at lots of examples but I can't seem to make any sense of them.
Here's the pattern:
<ul>
<li>Item 1 - level 1</li>
<li>Item 2 - level 1</li>
<li>Item 3 - level 1
<ul>
<li>Item 1 - level 2</li>
<li>Item 2 - level 2</li>
<li>Item 3 - level 2</li>
</ul>
</li>
</ul>
I've created a list, which uses a single level, so it's not properly nested with regards to html - just a flat list of <li> tags.
However, I'd like to make changes.
Only one level will have a sub-menu - and it's possible that some level-1 items will not have any child items - so I'm looking for a pattern that could render 0 or 1 sub-menu.
Anyone know what I need to do with the following code to achieve what I want?
<asp:ListView ID="lv" runat="server"
OnItemDataBound="LV_ItemDataBound">
<LayoutTemplate>
<nav>
<ul class="content-nav">
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</nav>
</LayoutTemplate>
<ItemTemplate>
<li id="liMenuItem" runat="server">
<asp:HyperLink ID="lnkMenuItem" runat="server"
CssClass="content-nav_link"></asp:HyperLink>
</li>
</ItemTemplate>
</asp:ListView>
protected void LV_ItemDataBound(object source, ListViewItemEventArgs e)
{
var item = e.Item;
if (item.ItemType == ListViewItemType.DataItem)
{
var data = (ContentNavItem)item.DataItem;
var liMenuItem = item.GetControl<HtmlGenericControl>("liMenuItem");
// Do something with the item here
}
}
void Build()
{
var currentId = MenuItems.First(x => x.Route == CurrentUrl).Id;
var currentItems = MenuItems
.Where(x => x.IsTopLevel || x.ParentId == currentId)
.OrderBy(x => x.GroupId).ThenBy(x => x.Anchor);
lv.DataSource = currentItems;
lv.DataBind();
}
A:
It would be much easier to create the menu as a string with a StringBuilder. But if you really want recursive controls you can clone the control and re-use it for every menu level. I use a Repeater for this demo because it's better suited for repeating items. So first we create a class and some demo data
public class MenuItem
{
public string name { get; set; }
public List<MenuItem> menuitems { get; set; }
}
Fill it with dummy data
protected void Page_Load(object sender, EventArgs e)
{
List<MenuItem> MenuItems = new List<MenuItem>();
for (int i = 0; i < 10; i++)
{
MenuItems.Add(new MenuItem() { name = "Name " + i });
if (i == 2 || i == 5 || i == 8)
{
MenuItems[i].menuitems = new List<MenuItem>();
MenuItems[i].menuitems.Add(new MenuItem() { name = "SubName 1" });
MenuItems[i].menuitems.Add(new MenuItem() { name = "SubName 2" });
MenuItems[i].menuitems.Add(new MenuItem() { name = "SubName 3" });
if (i == 8)
{
MenuItems[i].menuitems[0].menuitems = new List<MenuItem>();
MenuItems[i].menuitems[0].menuitems.Add(new MenuItem() { name = "SubName 1" });
MenuItems[i].menuitems[0].menuitems.Add(new MenuItem() { name = "SubName 2" });
MenuItems[i].menuitems[0].menuitems.Add(new MenuItem() { name = "SubName 3" });
}
}
}
Repeater1.DataSource = MenuItems;
Repeater1.DataBind();
}
Add the Repeater control to the page. Also with a PlaceHolder so it can hold a copy of itself.
<nav>
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<ul class="content-nav">
</HeaderTemplate>
<ItemTemplate>
<li id="liMenuItem" runat="server">
<%# Eval("name") %>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</nav>
Now in the ItemDataBound event we make a clone of Repeater1, fill it with the submenu, add it to the PlaceHolder of the parent Repeater and attach a ItemDataBound programaticallty so that Repeater then can generate it's own children.
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
MenuItem item = e.Item.DataItem as MenuItem;
//check if the item exists and if it has subitems
if (item != null && item.menuitems != null)
{
//determine type and get the properties
Type type = sender.GetType();
PropertyInfo[] properties = type.GetProperties();
Object obj = type.InvokeMember("", BindingFlags.CreateInstance, null, sender, null);
//copy the properties
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.CanWrite)
{
propertyInfo.SetValue(obj, propertyInfo.GetValue(sender, null), null);
}
}
//cast the created object back to a repeater
Repeater nestedRepeater = obj as Repeater;
//fill the child repeater with the sub menu items
nestedRepeater.DataSource = item.menuitems;
//attach the itemdatabound event
nestedRepeater.ItemDataBound += Repeater1_ItemDataBound;
//bind the data
nestedRepeater.DataBind();
//find the placeholder and add the created Repeater
PlaceHolder ph = e.Item.FindControl("PlaceHolder1") as PlaceHolder;
ph.Controls.Add(nestedRepeater);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Phpmyadmin-error on nginx VPS with Ubuntu 12.04.3 x32
I am trying to install phpmyadmin on a VPS LEMP-stack.
I created an info.php, which is perfectly reachable when I call my server's IP in my browser, revealing all relevant php-info, i.e. nginx is running.
However, after installing phpmyadmin, which I try to access via http://192.xxx.xxx.x/phpmyadmin/, I get the following error message:
The mysqli extension is missing. Please check your PHP configuration.
I already installed php5-mysql via sudo apt-get install php5-mysql, restarted nginx and cleared my browser-cache, but the situation remains.
Could you please advice me what goes wrong?
A:
mysql and mysqli are two different things.
You have to install the mysqli library:
sudo apt-get install php5-mysqli
Don't forget to also restart the php fpm workers, because that's where the mods get loaded, not in nginx.
/etc/init.d/php5-fpm restart
Update:
I was wrong, the php5-mysql package contains the mysql AND the mysqli library.
It must be enough for you to restart the php workers :-)
| {
"pile_set_name": "StackExchange"
} |
Q:
If you have a conserved quantity, why can't you use it to eliminate a variable in the Lagrangian?
Suppose, for example, we take a particle in polar coordinates $(r, \theta)$ with a central force, so $U = U(r).$ The Lagrangian is $$\mathcal{L} = \dfrac12 m (\dot{r}^2 + (r\dot{\theta})^2) - U(r).$$
The corresponding equation of motion for $r$ is $$m\ddot{r} = m\dot{\theta}^2r - \dfrac{\mathrm{d}U}{\mathrm{d}r}.$$
Using angular momentum conservation, $L = mr^2 \dot{\theta}$ is constant, so we can use it to eliminate $\dot{\theta}$ and obtain $$m\ddot{r} = \dfrac{L^2}{mr^3} - \dfrac{\mathrm{d}U}{\mathrm{d}r}.$$
However, suppose we return to the original statement of the Lagrangian and eliminate $\dot{\theta}$ there. Then we'd have $$\mathcal{L} = \dfrac12 m\left(\dot{r}^2 + \dfrac{L^2}{m^2r^2}\right) - \dfrac{\mathrm{d}U}{\mathrm{d}r}.$$
Applying the Euler-Lagrange equation $\dfrac{\mathrm{d}}{\mathrm{d}t}\dfrac{\partial \mathcal{L}}{\partial \dot{r}} = \dfrac{\partial \mathcal{L}}{\partial r}$ to the above, $$m\ddot{r} = -\dfrac{L^2}{mr^3}-\dfrac{\mathrm{d}U}{\mathrm{d}r}.$$
This is wrong; we can't eliminate $\dot{\theta}$ in the Lagrangian this way before applying the Euler-Lagrange equations, but why not?
A:
You can eliminate coordinates. You are just not allowed to eliminate velocities. If you want to eliminate a velocity, you have to go over to the Routhian. Landau Lifshitz has a discussion in paragraph 41.
The idea is that you want to replace the velocity $\dot \theta$ by the conserved quantity which is the associated generalized momentum $L$. In order to do that you have to perform a (partial) Legendre transform (essentially going over to the Hamiltonian with respect to $\dot \theta$). So for fixed anuglar momentum $L$, we have the Routhian (note that LL use a different sign convention)
$$\mathcal{R}= \mathcal{L}- \dot\theta L =\frac{m}{2} \dot r^2 -\frac{L^2}{2m r^2} - U(r) =\frac{m}{2} \dot r^2 - U_\text{eff}(r) \,.$$
So the correct Lagrangian is given by $\mathcal{R}$ the effect of the angular coordinate is the centrifugal potential $L^2/2mr^2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
MYSQL Help - 2 Databases, 1 Featured Image
I currently have 2 MYSQL databases.
DatabaseOne is the full database with all cars, and the DatabaseTwo is focused on specific details of the car manufacturer. For example:
DatabaseOne has the car Manufacturer, model, year, color, and a link to the picture of the car.
DatabaseTwo has the Manufacturer, details on the manufacturer, the phone number, website, etc, along with a featured_image_id, which I can set to highlight a specific car from DatabaseOne, joining on matching ID.
Table data DatabaseOne:
ID | Manufacturer | Model | Year | Color | ImageLink
1 | Toyota | Camry | 2002 | Black | 88.jpg
2 | Toyota | Venza | 2010 | Black | 91.jpg
3 | Mazda | Miata | 2001 | Red | 77.jpg
4 | Mercedes | Benz | 2012 | Green | 46.jpg
5 | Mercedes | Benz | 2000 | Blue | 12.jpg
Table data DatabaseTwo:
ID | Manufacturer | PhNumber | Website | FeaturedImage
1 | Toyota | 555-5555 | .com | 2
2 | Mazda | 555-5555 | .com | 3
3 | Mercedes | 555-5555 | .com |
The databases join when the FeaturedImage from DatabaseTwo matches the ID of DatabaseOne.
In this case, Toyota would show the ImageLink (.jpg) for DatabaseOne ID 2 (Venza), Mazda would show the image of Mazda with DatabaseOne ID 3, and since the Mercedes FeaturedImage is not set, I want it to show the most recent Mercedes, which would be DatabaseOne ID 5.
What I am trying to do is display the results, categorized by the Manufacturers in DatabaseTwo, and if a featured_image_ID is set in DatabaseTwo, I want to show image_link from the matching ID in DatabaseOne, and if featured_image_id is not set, I just want to show the image_link of the most recent car by that manufacturer.
When displaying the results, when the second CASE in the below statement is preceded by "OR", all recent images of the cars show, however the Manufacturers with featured_image_id set will just show the recent associated image_link as well.
When the second CASE is preceded by "AND", ONLY the Manufacturer with the featured_image_id set will show up, and none of the other Manufacturers without featured_image_id show up.
I am trying to make sure all manufacturers show up with images, whether it is specifically set in DatabaseTwo.featured_image_id, or if not set, then falling back to the most recent image id by the matching manufacturer.
Here is my current MYSQL code:
SELECT DatabaseOne.id, DatabaseOne.manufacturer,
DatabaseOne.model,DatabaseOne.year, DatabaseOne.picture,
DatabaseOne.image_link, DatabaseTwo.featured_image_id,
DatabaseTwo.title, DatabaseTwo.id,
IF(DatabaseTwo.id != 0, DatabaseTwo.id, 'N/A') AS card_id
FROM DatabaseOne
LEFT JOIN DatabaseTwo
ON (CASE
WHEN (DatabaseTwo.featured_image_id != 0 AND DatabaseTwo.category = 'Manufacturer'
AND DatabaseTwo.Manufacturer = DatabaseOne.Manufacturer)
THEN (DatabaseTwo.featured_image_id = DatabaseOne.id)
END )
WHERE DatabaseOne.Manufacturer != ''
AND DatabaseOne.id != 0
OR ((CASE
WHEN (DatabaseTwo.featured_image_id IS NOT NULL)
THEN (DatabaseTwo.featured_image_id != 0 ) END) )
GROUP BY DatabaseOne.Manufacturer
ORDER BY DatabaseOne.Manufacturer ASC, DatabaseOne.id DESC
A:
Please try the following query:
SELECT t1.ID, t1.Manufacturer, t1.Model, t1.Year, t1.Color,
t3.ImageLink
FROM DatabaseOne t1 LEFT JOIN
(
SELECT db2.Manufacturer,
COALESCE(db2.FeaturedImage, t.DefaultFeaturedImage) AS FeaturedImage
FROM DatabaseTwo db2
INNER JOIN
(
SELECT MAX(ID) AS DefaultFeaturedImage, Manufacturer
FROM DatabaseOne
GROUP BY Manufacturer
) t
ON db2.Manufacturer = t.Manufacturer
) t2
ON t1.Manufacturer = t2.Manufacturer
INNER JOIN DatabaseOne t3
ON t2.FeaturedImage = t3.ID
Follow the link below for a running demo:
SQLFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove columns the tidyeval way
I would like to remove a vector of columns using dplyr >= 0.7
library(dplyr)
data(mtcars)
rem_cols <- c("wt", "qsec", "vs", "am", "gear", "carb")
head(select(mtcars, !!paste0("-", rem_cols)))
Error: Strings must match column names. Unknown columns: -wt, -qsec, -vs, -am, -gear, -carb
dplyr < 0.7 worked as follows:
head(select_(mtcars, .dots = paste0("-", rem_cols)))
# mpg cyl disp hp drat
# Mazda RX4 21.0 6 160 110 3.90
# Mazda RX4 Wag 21.0 6 160 110 3.90
# Datsun 710 22.8 4 108 93 3.85
# Hornet 4 Drive 21.4 6 258 110 3.08
# Hornet Sportabout 18.7 8 360 175 3.15
# Valiant 18.1 6 225 105 2.76
I've tried about all combinations of rlang:syms(), !!, !!!, quo and enquo that I can think of... help!?
A:
We can use one_of
mtcars %>%
select(-one_of(rem_cols))
A:
I would also use one_of() in this case but more generally you have to create calls to - with the symbols as argument.
# This creates a single call:
call("-", quote(a))
# This creates a list of calls:
syms(letters) %>% map(function(sym) call("-", sym))
You can then splice the list of calls with !!!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to load a graph with tensorflow.so and c_api.h in c++ language?
I am not able to find any examples about how to load a graph with tensorflow.so and c_api.h in C++. I read the c_api.h, however the ReadBinaryProto function was not in it. How can I load a graph without the ReadBinaryProto function?
A:
If you're using C++, you might want to use the C++ API instead. The label image example would probably be a good sample to help you start.
If you really want to use just the C API, use TF_GraphImportGraphDef to load a graph. Note that the C API isn't particularly convenient to use (it is intended to build bindings in other languages such as Go, Java, Rust, Haskell etc.) For example:
#include <stdio.h>
#include <stdlib.h>
#include <tensorflow/c/c_api.h>
TF_Buffer* read_file(const char* file);
void free_buffer(void* data, size_t length) {
free(data);
}
int main() {
// Graph definition from unzipped https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
// which is used in the Go, Java and Android examples
TF_Buffer* graph_def = read_file("tensorflow_inception_graph.pb");
TF_Graph* graph = TF_NewGraph();
// Import graph_def into graph
TF_Status* status = TF_NewStatus();
TF_ImportGraphDefOptions* opts = TF_NewImportGraphDefOptions();
TF_GraphImportGraphDef(graph, graph_def, opts, status);
TF_DeleteImportGraphDefOptions(opts);
if (TF_GetCode(status) != TF_OK) {
fprintf(stderr, "ERROR: Unable to import graph %s", TF_Message(status));
return 1;
}
fprintf(stdout, "Successfully imported graph");
TF_DeleteStatus(status);
TF_DeleteBuffer(graph_def);
// Use the graph
TF_DeleteGraph(graph);
return 0;
}
TF_Buffer* read_file(const char* file) {
FILE *f = fopen(file, "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); //same as rewind(f);
void* data = malloc(fsize);
fread(data, fsize, 1, f);
fclose(f);
TF_Buffer* buf = TF_NewBuffer();
buf->data = data;
buf->length = fsize;
buf->data_deallocator = free_buffer;
return buf;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Error code: 1451 with 2 primary keys
I cannot run the following statement:
delete from UT_Session where my_id='5146' and upgrade_time='2016-01-03 17:25:18'
Since I get:
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`Upgrade_tool`.`pre_tasks`, CONSTRAINT `pre_tasks_ibfk_1` FOREIGN KEY (`my_id`) REFERENCES `UT_Session` (`my_id`))
There are the tables:
create table UT_Session
(
my_id int not null,
upgrade_time DATETIME not null,
ownerName varchar(20),
source varchar(20) not null,
target varchar(20) not null,
isClosed boolean,
primary key (my_id,upgrade_time)
)ENGINE=INNODB;
CREATE INDEX upgrate_time_index
ON UT_Session (upgrade_time);
create table pre_tasks
(
my_id int,
foreign key (my_id) references UT_Session(my_id),
upgrade_time DATETIME not null,
foreign key (upgrade_time) references UT_Session(upgrade_time),
pre_task_type varchar (100),
reason varchar(500),
primary key (my_id,pre_task_type,upgrade_time)
)ENGINE=INNODB;
create table post_tasks
(
my_id int,
foreign key (my_id) references UT_Session(my_id),
upgrade_time DATETIME not null,
foreign key (upgrade_time) references UT_Session(upgrade_time),
post_task_type varchar (100),
reason varchar(500),
primary key (my_id,post_task_type,upgrade_time)
)ENGINE=INNODB;
Now when I run this querys to show the content of the tables, I get this:
mysql> select * from UT_Session where my_id='5146';
+------+---------------------+-----------+----------+----------+----------+
| my_id | upgrade_time | ownerName | source | target | isClosed |
+------+---------------------+-----------+----------+----------+----------+
| 5146 | 2016-01-03 17:25:18 | Ronen | 5.1.2.12 | 5.2.2.26 | 0 |
| 5146 | 2016-01-03 17:35:10 | Ronen | 5.1.2.12 | 5.2.2.26 | 0 |
| 5146 | 2016-01-03 17:36:57 | Ronen | 5.1.2.12 | 5.2.2.26 | 1 |
+------+---------------------+-----------+----------+----------+----------+
mysql> select * from pre_tasks where my_id='5146';
+------+---------------------+--------------------------------------------------------+--------+
| my_id | upgrade_time | pre_task_type | reason |
+------+---------------------+--------------------------------------------------------+--------+
| 5146 | 2016-01-03 17:36:57 | Type 87954r0f | |
| 5146 | 2016-01-03 17:36:57 | Type 1a79F4rf | |
+------+---------------------+--------------------------------------------------------+--------+
mysql> select * from post_tasks where my_id='5146';
+------+---------------------+--------------------------------------------------------+--------+
| my_id | upgrade_time | post_task_type | reason |
+------+---------------------+--------------------------------------------------------+--------+
| 5146 | 2016-01-03 17:36:57 | Type v7d54r8f | |
+------+---------------------+--------------------------------------------------------+--------+
As you can see both the "my_id" and the "upgrade_time" are keys, and the row I want to delete is not present on the child tables, because it's a different time.
What's wrong here?
Thanks!
A:
Yes but you do have records in child or referencing table with my_id='5146' and so it's throwing that error correctly. If you really want to delete that record then delete them first from child tables and then from parent.
You could have created your FOREIGN KEY constraint with ON DELETE CASCADE cascading option saying below in which the delete would have been cascaded to the child tables as well
foreign key (my_id) references UT_Session(my_id) on delete cascade
What you are actually trying to do is create a composite foreign key like below; in which case uniqueness of the records will depend on both the key.
FOREIGN KEY (my_id, upgrade_time)
REFERENCES UT_Session (my_id, upgrade_time) ON DELETE CASCADE
| {
"pile_set_name": "StackExchange"
} |
Q:
Php checked checkbox from loop
I have information from the database that i list using foreach loop:
<table class="price_table">
<caption>Prices</caption>
<?php if($price= getCarPricePeriod($car->ID)):?>
<?php foreach ($prices as $price): ?>
<tr>
<td><input type="radio" name="price" value="<?= $price['Price'];?>"> </td>
<td><?= $price['Price'];?>$</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>
So with this loop i get prices with radio button. How to make first item from loop be checked. Just first need to be checked
If i add checked in loop all items will be checked or randomly.
A:
You will have to use a variable flagging your element is first:
<table class="price_table">
<caption>Prices</caption>
<?php if($price= getCarPricePeriod($car->ID)):
$first = true;
foreach ($prices as $price): ?>
<tr>
<td><input type="radio" name="price" value="<?= $price['Price'];?> <?= $first ? 'checked' : '' ?>"> </td>
<td><?= $price['Price'];?>$</td>
</tr>
<?php $first = false;
endforeach; ?>
<?php endif; ?>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server - Group Records Like Archives By Month
I have a table Fixture with three fields.
ID | Fixture | Date
-------------------------
1 | 123456 | 20110515
2 | 123446 | 20110512
3 | 123476 | 20110411
4 | 123486 | 20110310
...and so on.
I need to group the records by date and want to get fixture counts.
Results would display like the following example. How can I achieve the results from SQL Query?
Archives
February 2011 (3)
January 2011 (6)
December 2010 (10)
November 2010 (7)
October 2010 (5)
I need community help to solve this issue, kindly help me out.
A:
How about something like
DECLARE @Table TABLE(
ID INT,
Fixture INT,
Date DATETIME
)
INSERT INTO @Table SELECT 1,123456,'20110515'
INSERT INTO @Table SELECT 2,123446,'20110512'
INSERT INTO @Table SELECT 3,123476,'20110411'
INSERT INTO @Table SELECT 4,123486,'20110310'
;WITH Vals AS (
SELECT DATENAME(month,Date) + ' ' + CAST(DATEPART(year,Date) AS VARCHAR(4)) DateValue,
ID,
CONVERT(VARCHAR(6), Date, 112) OrderValue
FROM @Table
)
SELECT DateValue,
COUNT(ID) Cnt
FROM Vals
GROUP BY DateValue,
OrderValue
ORDER BY OrderValue
A:
I believe this code will do what you require:
SELECT
DATENAME(m, [Date]) + ' ' + CAST(YEAR([Date]) AS VARCHAR(4)) AS ArchiveMonth
,COUNT(ID) AS Items
FROM
Fixture
GROUP BY
DATENAME(m, [Date]) + ' ' + CAST(YEAR([Date]) AS VARCHAR(4))
(dang it... already beaten)
A:
Try it, it has month numbers, you can update it in your code or in sql
select COUNT(id), DATEPART(year, dtCreated) as y, DATEPART(MONTH,dtCreated) as mo
from TaxesSteps group by DATEPART(year, dtCreated), DATEPART(MONTH,dtCreated)
order by 2 desc, 3 desc
| {
"pile_set_name": "StackExchange"
} |
Q:
If $A^T A v = A A^T v = v$ with $A$ *not* orthogonal. Must $v$ be an eigenvector?
Consider a square matrix $A$ over the real numbers that is not orthogonal. Let $v \neq 0$ be a non-zero vector such that $A^T A v = A A^T v = v$. Is it true that $v$ must be an eigenvector of $A$?
It's not hard to see that if $v$ is an eigenvector, then its eigenvalue must be on the unit circle. But I can't determine whether or not $v$ is necessarily an eigenvector.
Somehow this looks like it would be a consequence of the spectral theorem, but I can't see a crisp proof. Thanks!
A:
No. Let $Q\ne\pm I$ be any $n\times n$ orthogonal matrix, $u\in\mathbb R^n$ be any vector that is not an eigenvector of $Q$, and $a\ne\pm1$. Let
$$
A=\pmatrix{Q&0\\ 0&a},\ v=\pmatrix{u\\ 0}.
$$
Then $A$ is not orthogonal and $AA^Tv=A^TAv=v$, but $v$ is not an eigenvector of $A$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two Segmented control (IOS)
I have two (Segmented control)
As I can do that for example when you select (1 Segment control) 1 and (2 Segment control) 2 then the action would be executed.
A:
I think it is very easy if you give same action to both segmented controls like this:
@IBOutlet weak var sg1: UISegmentedControl!
@IBOutlet weak var sg2: UISegmentedControl!
//MARK: CLick event of segment control
@IBAction func onClickSegment(_ sender: UISegmentedControl)
{
print(sender.selectedSegmentIndex)
if sg1.selectedSegmentIndex == 0 && sg2.selectedSegmentIndex == 1
{
//Code to Execute
}
else
{
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How many simultaneous calls are available over Twillio Elastic SIP Trunking with a single number?
Trialing elastic sip trunking from Twillio with one number attached. My PBX wants me to input number of simultaneous calls and I do not find references to that in Twillio docs
3CX pbx
A:
Twilio developer evangelist here.
Elastic SIP Trunking is built to allow for unlimited concurrent calls. I think your PBX likely wants this information because older suppliers of SIP trunks would sell you connection with that sort of limit and the PBX would need to handle the limits for you.
My colleague Devin dropped a link into comments that shows the limits of Twilio's Elastic SIP Trunking. The limit applicable to your question is:
Unlimited concurrent calls
If your PBX really won't let you move on without a number then I recommend you estimate the maximum number of simultaneous calls that you will need and enter that. Or just any really big number. Twilio will handle it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make an intricate multi-buffer search?
In Python's regex dialect (correct terminology?) we have (?<=...) which can be used to narrow down searches with respect to what precedes a given pattern.
Trying this on Emacs to perform some intricate multi-buffer searching e.g. search only those buffers whose content contain "x" and/or "y" and then search the content of the matching buffers for "foo" and list the results, wasn't fruitful since:
(multi-occur-in-matching-buffers "." "\\(?<=:x\\|y\\)foo")
didn't match anything.
The Regexp Syntax Summary states that it is not available GNU Emacs/Elisp.
How can I solve this problem?
A:
This is easy using Icicles.
C-x b, which chooses buffers, lets you also choose by their contents matching your input pattern (which can be a regexp). And it is a multi-command, which means that you can choose any number of buffers with a single use of C-x b.
Progressive completion lets you use any number of patterns (e.g. regexps), combining them to get their intersection (anding). And you can subtract matches of other patterns (complementing).
You can "mark" or "save" chosen buffers, as a set of saved completion candidates. (You can even save such a set persistently.)
This means you can easily select all buffers that match both x and y. Or if you want all that match x or y, just add those that match y to the buffers you marked for matching x.
Given that marked or "saved" set of buffers, you can then search for foo in them, using Icicles search or vanilla Isearch.
On the other hand, if all you want to do is find buffers that match foo as well as x or y, then just use C-x b. Note too that the last content-matching pattern (e.g., foo) you use for finding buffers is automatically saved as the last Isearch regexp. So when you then visit the buffers you can immediately use C-M-s to search for individual occurrences.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I reload a page form Service Worker (or Secondary Thread)?
I have a functional progressive web app. In it to upload data I'm first caching it in IndexDB and then uploading it and if the upload is successful delete the data from IndexDB. Now, I want to reload the page once the data is deleted. Is there any way to achieve this outside the main thread(ie. form service worker)?
NOTE:window object is not accessible in service worker.
A:
You have to communicate first with your page over the postMessage function, then you can access window and reload the page. Here you can find a good description:
http://craig-russell.co.uk/2016/01/29/service-worker-messaging.html#.WgxuSmjWzIU
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - Get sales figure in 2 period
I have two tables: one contains employees information and another is transactions (sales) information including sales man (employeee ID)
Table 1: employees,code name ...
Table 2: sales, employee_code, product, Date, Price, Amount
I would like to calculate how much each employees can generate revenue (total amount) for each of 2 periods (1 Jan to 30 Jun and 1 Jul to 31 Dec) or maybe any period of time - like this:
Name _________Period1_1_30_6______Period 1_7_31_12
Adam__________________50b$______________70b$
David_________________90b$______________1000b$ ....
A:
You can try something like this
DECLARE @Employees TABLE(
EmpCode INT,
EmpName VARCHAR(50)
)
INSERT INTO @Employees (EmpCode,EmpName) SELECT 1, 'Adam'
INSERT INTO @Employees (EmpCode,EmpName) SELECT 2, 'David'
DECLARE @sales TABLE(
EmpCode INT,
product VARCHAR(50),
Date DATETIME,
Price FLOAT,
Amount FLOAT
)
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 1, 'A', '01 Jan 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 1, 'A', '01 Mar 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 1, 'A', '01 May 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 1, 'A', '01 Jul 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 1, 'A', '01 Sep 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 2, 'A', '01 Jan 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 2, 'A', '01 May 2009', 5, 10
INSERT INTO @sales (EmpCode,product,Date,Price,Amount) SELECT 2, 'A', '01 Sep 2009', 5, 10
DECLARE @Period1Start DATETIME,
@Period1End DATETIME,
@Period2Start DATETIME,
@Period2End DATETIME
SELECT @Period1Start = '01 Jan 2009',
@Period1End = '30 Jun 2009',
@Period2Start = '01 Jul 2009',
@Period2End = '31 Dec 2009'
SELECT e.EmpName,
Totals.Period1,
Totals.Period2
FROM @Employees e INNER JOIN
(
SELECT EmpCode,
SUM(CASE WHEN Date BETWEEN @Period1Start AND @Period1End THEN Price * Amount ELSE 0 END) Period1,
SUM(CASE WHEN Date BETWEEN @Period2Start AND @Period2End THEN Price * Amount ELSE 0 END) Period2
FROM @sales
GROUP BY EmpCode
) Totals ON e.EmpCode = Totals.EmpCode
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Add Text plus Value in Python Seaborn Heatmap
I am trying the python Seaborn package to create a heatmap.
So far I been able to create the heatmap with the values in it.
My final line in the code for creating the heatmap is:
sns.heatmap(result, annot=True, fmt='.2f', cmap='RdYlGn', ax=ax)
The resulting image is shown below:
However, I want to also have a string next to the values.
For example: AAPL -1.25 instead of -1.25 in the second field of the second row. Is there a way to add the text to the values in the heatmap?
A:
You can add custom annotations to your heatmap using seaborn. In principle, this is only a special case of this answer. The idea now is to add the string and numbers together to get the proper custom labels. If you have an array strings of the same shape as result that contains the respective labels you can add them together using:
labels = (np.asarray(["{0} {1:.3f}".format(string, value)
for string, value in zip(strings.flatten(),
results.flatten())])
).reshape(3, 4)
Now you can use this label array as custom labels for your heatmap:
sns.heatmap(result, annot=labels, fmt="", cmap='RdYlGn', ax=ax)
If you put this together using some random input data the code will look like this:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
results = np.random.rand(4, 3)
strings = strings = np.asarray([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l']])
labels = (np.asarray(["{0} {1:.3f}".format(string, value)
for string, value in zip(strings.flatten(),
results.flatten())])
).reshape(4, 3)
fig, ax = plt.subplots()
sns.heatmap(results, annot=labels, fmt="", cmap='RdYlGn', ax=ax)
plt.show()
The result will look like this:
As you can see, the strings are now correctly added to the values in the annotations.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select marker by coordinates or title?
I have map with dynamically generated markers using gmaps.js
And it works.
But I would like to select marker by coordinates and trigger click on it.
I know how to trigger it but I can't figure out how to proper select marker in jQuery or find it in map.markers array?
This is my code:
# = require lib/gmaps
$(document).on 'ready', ->
if $('#map').length > 0
map = new GMaps(
div: "#map"
lat: 53.5500000
lng: 10.0000000
zoom: 12
)
url = "nearby_cardiologists.json" + window.location.search
$.getJSON url, (data) ->
if data and data.length > 0
firstMarker = data[0]
map.setCenter firstMarker.latitude, firstMarker.longitude
$.each data, (index, cardiologist) ->
cardiologist_info = '<p>' + '<b>' + cardiologist.title + ' ' + cardiologist.first_name + ' ' + cardiologist.last_name + '</b><br>' + cardiologist.street + ', ' + cardiologist.city
infowindow = new google.maps.InfoWindow(content: cardiologist_info)
marker = map.addMarker
lat: cardiologist.latitude
lng: cardiologist.longitude
google.maps.event.addListener marker, "click", ->
infowindow.open map, this
$("#nearby_cardiologists").on 'click', 'a', (event) ->
event.preventDefault()
cardiologist = $(this)
i = cardiologist.data('id')
marker = map.markers[0]
map.setCenter cardiologist.data('coordinates').latitude, cardiologist.data('coordinates').longitude
map.setZoom 16
else
$('#map').hide()
My goal is to click on link and zoom + show info window by opening it or triggering click on marker
A:
I think this answer should help you with this case: https://stackoverflow.com/a/14524925/1856970
You need to be able to tie the marker to the a link in some way (this example uses an id attribute appended to both to determine the correct marker click event to trigger), in order to be able to find it at runtime. It is not possible to slect the marker solely by it's long/lat coords.
An alternative method would be to create the a link click events within the foreach loop in which you instantiate markers. This simplifies things by allowing you to have each marker in scope as you progress and eliminates the need for you to select the markers at a later execution point.
Once you have the appropriate marker, getting the long lat is trivial and can be done using getPosition (presumably to center the map etc).
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP openssl_decrypt: Partial decryption works even with different IV?
Given the following to-be-encrypted email, and this (weak) encryption key:
$source="[email protected]";
$pass="Somepassword...";
I want to generate a somewhat good encrypted string:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$method="AES-128-CBC";
$encrypted=openssl_encrypt($source, $method, $pass, true, $iv);
If I try to decrypt it works fine:
$decrypted=openssl_decrypt ($encrypted, $method, $pass, true, $iv);
echo $decrypted;
// [email protected]
But when I tried to decrypt with a different $iv (!), I expected to get a non-sense result, but instead I got:
$iv2 = "tralala1tralala2";
$decrypted=openssl_decrypt ($encrypted, $method, $pass, true, $iv2);
echo $decrypted;
// m~Œ=¢ì •wêàdÏŠ[email protected]
So basically the last 26 characters are decrypted even with a different $iv ("[email protected]"). Can someone explain why this happens? (The same 26 chars are decrypted even when I change the $iv again)
I've got this encription method from the best answer here
A:
To understand this, you will need to look into how block cyphers work.
https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
Commonly (and this includes AES/Rijndael), each block is used to influence the decryption of the next block. The IV merely acts to influence the decryption of the first block (where no previous block exists). So yes, a separate IV will - depending on the exact algorithm used - only impact the decryption of the first block of the cypher text. This is what you are seeing.
| {
"pile_set_name": "StackExchange"
} |
Q:
CALayer overlaps top layer after transformation
I have two CALayers each showing an image. The first (left) layer in the view hierarchy is on top of the second one. The problem is that after I apply a rotation around the y-axis, the right layer is all of a sudden drawn above the layer that's supposed to be on top.
I tried using different zPosition values. Nothing. My other guess was that maybe the animation of the right layer finishes after the animation for the left layer and hence it is drawn on top. To test this, I applied the transformation for the right layer first, but still the same result. Oh, I also tried CA transactions without any luck.
Here a screenshot:
What is the correct way to animate a number of CALayers while keeping their order?
Thanks, Mark.
EDIT:
Here is the code for the transformation. I tried disabling the animation, but got the same result.
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / 400;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, DegreesToRadians(70), 0, 1, 0);
for(CALayer *layer in [self.layer sublayers]) {
// transform the two layers
layer.transform = rotationAndPerspectiveTransform;
}
[CATransaction commit];
A:
Have you tried translating on the z axis? Either make your top layer have a larger number or your lower layer have a lower or negative number. Try something really large to start with and see if it addresses the issue. Then narrow the margin until you get the layer as close as possible without causing the shift you're seeing. Something like this:
CATransform3D trans = CATransform3DIdentity;
trans.m34 = 1 / -900;
trans = CATransform3DTranslate(trans, 0.0f, 0.0f, -500.0f);
[lowerLayer setTransform:trans];
The down side is if you're planning to stack up a bunch of layers, you would probably have to use this minimum margin and multiply that by the number of layers you're planning to display causing the stack to fade into the distance. Of course, if that's the effect you're going for, this would be a good thing.
| {
"pile_set_name": "StackExchange"
} |
Q:
COUNT select and local variable storage
I need to find the id of the person with the least number of clients associated to them, inorder that the current new client is allocated to this staff member.
I've used the following to establish the id of this staff member as follows;
SELECT TOP(1) JA.judgeID, COUNT(JA.judgeId) AS COUNT
FROM recJudgeAssignment AS JA
LEFT JOIN recEntrantStatus AS ES
ON JA.bandId = ES.entrantId
GROUP BY JA.judgeId, ES.roundId
HAVING ES.roundId = @round
ORDER BY COUNT
But I need to catch this as a local variable to use in the next statement;
UPDATE recJudgeAssignment
SET judgeId = @judge
WHERE roundId = @round
AND bandId = @entrantId
How do I catch the judgeId in the 1st select? Normally I would do something like;
SELECT @judge =(SELECT TOP(1) JA.judgeID, COUNT(JA.judgeId) AS COUNT
FROM recJudgeAssignment AS JA
LEFT JOIN recEntrantStatus AS ES
ON JA.bandId = ES.entrantId
GROUP BY JA.judgeId, ES.roundId
HAVING ES.roundId = @round
ORDER BY COUNT)
This doesn't work of course because the select is returning the judgeId and the COUNT. I would prefer to not have to send the result of the 1st select back to the webpage and then do the subsequent update statement in a seperate web>db transaction.
So... Any help or even remedies anyone can offer, would be greatly appreciated.
Thanks in advance!
A:
-- Query the DB for your variables
-- (I have also moved the HAVING clause to a WHERE clause.)
------------------------------------------------------------
SELECT TOP(1)
@judgeID = JA.judgeID,
@count = COUNT(JA.judgeId)
FROM
recJudgeAssignment AS JA
LEFT JOIN
recEntrantStatus AS ES
ON JA.bandId = ES.entrantId
WHERE
ES.roundId = @round
GROUP BY
JA.judgeId, ES.roundId
ORDER BY
COUNT
-- Update the DB
------------------------------------------------------------
UPDATE
recJudgeAssignment
SET
judgeId = @judgeID
WHERE
roundId = @round
AND bandId = @entrantId
-- Return the variables to the client
------------------------------------------------------------
SELECT
@judgeID AS judgeID,
@count AS count
| {
"pile_set_name": "StackExchange"
} |
Q:
google V8 build error LNK1104: cannot open file 'ws2_32.lib'
I'm trying to build google's V8 JavaScript Engine with MS Visual Studio 2012 on a 64bit system, but it always outputs the error
LINK : fatal error LNK1104: cannot open file 'ws2_32.lib'
I have done everything according to https://code.google.com/p/v8/wiki/BuildingWithGYP. I have used the python way instead of cygwin to generate the project files.
How do i set up my linker that it finds the ws2_32.lib?
//EDIT For some reason GYP made project files for vs2010 and not vs2012 so I had to update them. Now it works. (weird, I tried this before and it didn't work)
A:
GYP created VS2010 project files so I had to update them to VS2012.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between these whitespaces?
I have 2 queries as below. But only the second one return the results.
The white space in query 1 I typed from my computer and in query 2 I copy from the data. What is the differences between them?
SELECT * FROM table1 WHERE col1 like ' %';
SELECT * FROM table1 WHERE col1 like ' %';
Thanks GreenLake4964. I attached the inspected code in Chrome for 2 queries above.
A:
Try to use a tool such as UltraEditor or Notepad++,
paste your sql statement there and convert from "ASCII to Hex",
then you should be able to see the differences.
Alternatively, the DB you are using might have a ASCII to hex conversion feature (or similar) that you can find out the exact character you are using.
| {
"pile_set_name": "StackExchange"
} |
Q:
R system() not working with MODIS Reprojection Tool
I have a command that works when typed into the Terminal on a Mac (OSX El Cap), but the same command fails when called from R using system().
I am trying to batch-process MODIS satellite files using the MODIS Reprojection Tool. My software is all up to date.
This is a simple example in which I mosaic two files. The names of the two files are in a text input file called input.list. The command just tells the mrtmosaic routine where to find the input list and where to put the output.
This command works correctly in the Terminal:
/Applications/Modis_Reprojection_Tool/bin/mrtmosaic -i ~/temp/input.list -o ~/temp/output.hdf
However, if I put exactly the same string into a variable and run it from R (using RStudio), it fails:
comstring<-"/Applications/Modis_Reprojection_Tool/bin/mrtmosaic -i ~/temp/input.list -o ~/temp/output.hdf"
system(comstring)
Warning: gctp_call : Environmental Variable Not Found:
MRT_DATA_DIR nor MRTDATADIR not defined
Error: GetInputGeoCornerMosaic : General Processing Error converting lat/long coordinates to input projection coordinates.
Fatal Error, Terminating...
The strange thing is that the system knows what the environment variables are. In the terminal, the command
echo $MRT_DATA_DIR
shows the correct directory: /Applications/Modis_Reprojection_Tool/data
I don't see why it would have trouble finding the variables from an R system() call when it has no trouble in the Terminal. I'm very stumped!
A:
I posted this question to the R help list, and two people there helped me solve the problem. They suggested (if I understood right) that the problem was that OSX El Capitan was not successfully passing environment variables to R. In any case:
These do not work:
Setting the environment variable in my .bash_profile (for example by adding and exporting MTR_DATA_DIR="/Applications/MRT/data"); or
Setting the environment variable by adding the same line to the .Rprofile file in my home directory.
These do work:
Setting the environment variable at the R command line by typing Sys.setenv(MRT_DATA_DIR="/Applications/MRT/data"); or
Setting the environment variable in the .Renviron file (which is in my home directory) by adding MRT_DATA_DIR="/Applications/MRT/data" to it; or
Typing MRT_DATA_DIR="/Applications/MRT/data" open -a Rstudio in the Terminal. This last method is an effective workaround and a useful tool in a bag of tricks, but is slightly clumsier since one has to remember to open RStudio this way each time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Merging tables by row/ rbind tables with different column lengths/names by row
I've many tables containing different ARIMA-Orders from a time series analysis. A short example would be something like this:
The two tables are Order1 and Order2 containing a) different orders b) different frequencies of combinations.
Order1
(1,0,1) (1,1,1) (2,1,4)
4 5 9
Order2
(1,0,1) (3,0,4) (0,1,1) (2,1,2)
1 2 7 10
In the previous step the two tables are sorted by sort(Order1) and sort(Order2)
I want to merge both tables, by row to get one "big" table with two rows.
My expected Output should be something like this:
(1,0,1) (1,1,1) (2,1,4) (3,0,4) (0,1,1) (2,1,2)
Order 1 4 5 9 0 0 0
Order 2 1 0 0 2 7 10
or if its possible just the two input tables in one big table with "different column names and lentghs"
(1,0,1) (1,1,1) (2,1,4)
Order 1 4 5 9
(1,0,1) (3,0,4) (0,1,1) (2,1,2)
Order 2 1 2 7 10
I tried something like merge or rbind, but it doesn't work.
A:
dd1 <- as.data.table(t1)
dd2 <- as.data.table(t2)
merge(dd1, dd2, by="Var1", incomparables=NA, all=TRUE)
Is it OK ?
> merge(dd1,dd2, by="Var1", incomparables = NA, all=TRUE)
Var1 Freq.x Freq.y
1 ( 2 1 1 ) ( 1 1 1 ) 1 NA
2 ( 1 1 0 ) ( 1 1 1 ) 3 NA
3 ( 0 1 1 ) ( 0 1 1 ) 29 93
4 ( 2 1 1 ) ( 0 1 1 ) 54 2
5 ( 1 1 0 ) ( 0 1 1 ) 58 NA
6 ( 2 1 0 ) ( 0 1 1 ) NA 54
To have the frequencies in rows:
> ddd <- merge(dd1, dd2, ...) # as above
> ddd <- dd[,-1]
> rownames(ddd) <- dd$Var1
> t(ddd)
( 2 1 1 ) ( 1 1 1 ) ( 1 1 0 ) ( 1 1 1 ) ( 0 1 1 ) ( 0 1 1 )
Freq.x 1 3 29
Freq.y NA NA 93
( 2 1 1 ) ( 0 1 1 ) ( 1 1 0 ) ( 0 1 1 ) ( 2 1 0 ) ( 0 1 1 )
Freq.x 54 58 NA
Freq.y 2 NA 54
| {
"pile_set_name": "StackExchange"
} |
Q:
HEX decoding in Python 3.2
In Python 2.x I'm able to do this:
>>> '4f6c6567'.decode('hex_codec')
'Oleg'
But in Python 3.2 I encounter this error:
>>> b'4f6c6567'.decode('hex_codec')
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
b'4f6c6567'.decode('hex_codec')
TypeError: decoder did not return a str object (type=bytes)
According to the docs hex_codec should provide "bytes-to-bytes mappings". So the object of byte-string is correctly used here.
How can I get rid of this error to be able to avoid unwieldy workarounds to convert from hex-encoded text?
A:
In Python 3, the bytes.decode() method is used to decode raw bytes to Unicode, so you have to get the decoder from the codecs module using codecs.getdecoder() or codecs.decode() for bytes-to-bytes encodings:
>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)
The latter function seems to be missing from the documentation, but has a useful docstring.
You might also want to have a look at binascii.unhexlify().
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple steps form. All-in-one or multiple web pages
Is it preferable to develop multiple steps form (80+ fields grouped into 5 steps) as single web page (tabbed) compared to page-per-step approach if users tend to complete form when started to populate?
What are draw-backs big tabbed single page and page-per-step forms usually have?
Thank you in advance!
A:
IMHO the division must be done by relevance on inputs like an
Address section can group all fields like:
address 1, ddress 2, zip, country, city, state / province / region
while the Contact section can group
phone number, cell number, work number, e-mail, myspace, linkedin
Then depend, if all the fields are required or not!!! you can plan to write it different way!!! for example using tabs!!!
USEFUL TOOLS:
BTW you can found this links useful
If i could remember right: there are some jQuery Plugin that doing all the job for you by transforming your huge form into step-by-step form!
http://www.jankoatwarpspeed.com/post/2009/09/28/webform-wizard-jquery.aspx
http://plugins.jquery.com/project/babysteps
a must see / try is also this web service
http://wufoo.com/
USEFUL READS:
http://www.deyalexander.com.au/resources/uxd/form-design.html
http://www.usability.gov/government/lssnslearned/form.html
| {
"pile_set_name": "StackExchange"
} |
Q:
ECDH (256 bit key), Create Private Key from X component
I am trying to implement BitMessage Crypto with Windows CNG functions
I am trying to create a key pair from a single 32 byte value.
In order to encrypt the pubkey data, a double SHA-512 hash is calculated from the address version number, stream number, and ripe hash of the Bitmessage address that the pubkey corresponds to. The first 32 bytes of this hash are used to create a public and private key pair with which to encrypt and decrypt the pubkey data, using the same algorithm as message encryption (see Encryption).
Bitmessage Protocol regarding this
This can be done by using the 32 byte integer as the private key component.
But how can i do this using Windows CNG functions.
or maybe i can do the calculation manually?
Thanks for any input.
A:
BCryptImportKeyPiar using a blank public key(X,Y), and use the random 32 byte number as the private part of the BCRYPT_ECCKEY_BLOB.
duh..
| {
"pile_set_name": "StackExchange"
} |
Q:
TextView size issue android
I set texview size from dimens.xml . but it's behave different in different mobile screen like , In honor 6x device looks big font and intex mobile look like small but i apply same textsize.
Here my code :-
private fun changeStandardDialog(standardList: ArrayList<Category>) {
val factory = LayoutInflater.from(this)
val standardDialog = factory.inflate(R.layout.select_standard_diolog, null)
selectedStandardId = SettingsHandler(this).getSettings("default_standard")
for (item in standardList) {
val rdbtn = RadioButton(this)
rdbtn.id = item.id
rdbtn.text = item.title
if (selectedStandardId.toInt() == item.id) {
rdbtn.isChecked = true
}
rdbtn.textSize = resources.getDimension(R.dimen.radio_text_size)
val textColor = Color.parseColor("#323642")
rdbtn.setButtonTintList(ColorStateList.valueOf(textColor));
rdbtn.setPadding(20, 30, 30, 30)
standardDialog.selectSubjectList.addView(rdbtn)
}
AlertDialog.Builder(this, R.style.MyDialogTheme)
.setTitle(R.string.selectStd)
.setPositiveButton("Ok") { dialog, whichButton ->
if (standardDialog.selectSubjectList.checkedRadioButtonId > 0) {
changeSelectedStandardTitle(standardDialog.selectSubjectList.checkedRadioButtonId)
settingHandler.updateSettingsViaKey("default_standard", standardDialog.selectSubjectList.checkedRadioButtonId.toString())
}
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, whichButton ->
dialog.dismiss()
}
.setView(standardDialog)
.create()
.show()
}
My dimens.xml for R.dimen.radio_text_size :-
<dimen name="radio_text_size">6sp</dimen>
Here i use 6 sp for Radio button Textview show differnt screen textsize Left side Honor 6x ScreenShot and Right side Intex
A:
If you look at the implementation of TextView#setTextSize(float) you'll see that it treats the value you give it as a sp value. When you're using getDimension that's converting the sp value from dimens.xml into a pixel value, when you then set that value onto the TextView it's converting that pixel value as if it was a sp value into another (different) pixel value.
You'll either just want to use your sp value in code like
rbbtn.textSize = 6f
or you'll want to specify that you're using pixels and use the value you've retrieved from dimens
rdbtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.radio_text_size))
| {
"pile_set_name": "StackExchange"
} |
Q:
Notify the recyclerview item when it is onMoving without interruption
I've expandable row layouts in RecyclerView, normally they're expanded.
Atteched ItemTouchHelper.SimpleCallback to the RecyclerView for moving the rows with onMove(). Everythings is right and moving the rows correctly.
ItemTouchHelper.SimpleCallback:
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
Collections.swap(adapter.getShelves(), fromPosition, toPosition);
adapter.notifyItemMoved(fromPosition, toPosition);
return true;
}
// Minifying the rows before the onMove is started:
@Override
public boolean isLongPressDragEnabled() {
adapter.minifyRow(position);
return true;
}
It should minify the rows when long pressing, before onMoving() is started. Then should start the moving without any interrupting. The problem is starting dragging and minifiying the row when long press but interrupting the dragging at the moment. So it doesn't dragging or moving the row. How to simulate onMove with notify?
In adapter class:
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
boolean rowIsExpanded = rows.get(position).isExpanded();
if(rowIsExpanded){
holder.rowLayout.setVisibility(View.VISIBLE);
} else {
holder.rowLayout.setVisibility(View.GONE);
}
}
public void minifyRow(boolean situation, int adapterPos){
RowModel row = rows.get(adapterPos);
row.setExpanded(situation);
notifyItemChanged(adapterPos);
}
A:
You shouldn't call adapter.minifyRow(position); inside isLongPressDragEnabled it only flags to check your adapter enable long-press or not. You should override onSelectedChanged. Remove method in isLongPressDragEnabled and Try this
@Override
public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
if (viewHolder != null && actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
((YourViewHolder)viewHolder).rowLayout.setVisibility(View.GONE);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find if Item language is falling back to another language?
We have a multilingual website and using language fallback(Item Level). I am finding hard to get the fallback language of an item.
We have fr-FR which is falling back to en-FR. But when I get the item in fr-FR and check for
LangugaeFallbackEnabled field is false
I could not find any other fields specifying this information.
I have double checked in Sitecore it's falling back to en-FR.
What's the best way to check for the fallback language of an item?
Sitecore Version - 8.1 update 3
A:
To check if an item you are accessing is a fallback use the IsFallback property:
Sitecore.Data.Items.Item.IsFallback. To get the actual language being used you could use the method Sitecore.Data.Items.Item.GetFallbackItem() and check the language on that.
It's possible that you could do this more efficiently while looking at that method by using the language fallback manager:
Sitecore.Data.Managers.LanguageFallbackManager.GetFallbackLanguage(Language language, Database database, ID relatedItemId).
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling function without parenthesis
Hi i'm trying to use viser-ng and I need to call a function onClick event.
But when I try to use this inside my calling function I am getting an error this is undefined.
<v-chart [forceFit]="forceFit" [height]="height" [data]="data" [onClick]="clickbar"></-chart>
In my component
clickbar(e: any) {
console.log('clickbar', e.target); // return clicked data
console.log("this", this); // return undefined
this.openDialog(e.data._origin) // error
}
openDialog(data): void {
console.log(data) // error
}
Can you explain me how can I call my openDialog function ?
Trying (click)="clickbar($event)" but $event return mouseevent not clickedData
A:
In your component, try to define a variabile containing this.
For example
public thisRef;
constructor(){
this.thisRef = this;
}
And in the HTML you should be able to do
<v-chart [onClick]="clickbar.bind(thisRef)">...
This way you're binding the thisRef(which is indeed this) to this inside of your function.
| {
"pile_set_name": "StackExchange"
} |
Q:
What causes sandy, flecked, or speckled leaves like this?
There are several different species of plants in my yard that have developed some kind of condition where the leaves get pale, tiny specks all over them (such that they look kind of sandy). Many of them have webs that seem indicative of spider mites. Are the webs from spider mites? However, I'm not sure if the speckling is caused by spider mites or something else, like maybe manganese deficiency caused by too much calcium in the soil (I did add probably too much basalt rockdust for all of these except the apple tree at the end, which has had the problem for 1-3 years now). What could be causing this (the speckling)?
It began with the apple trees and rose bushes about a year or two ago, but it seems to be on lots of stuff in the yard, now. It seems to be leaving alone the tomatoes, peppers, and muskmelons, however. It was all over the watermelons, except the Citron watermelon (which was only lightly afflicted, but it wasn't with the other watermelons). On the other watermelons, it started on the shaded parts of the plants, and slowly progressed to the parts in full sun. Eventually, it totally enveloped them, and pretty much killed them (although the pictures I uploaded only show the early stages of the condition). Thankfully, the fruits ripened at about the same time they were completely overcome. Strangely, however, Aunt Molly's ground cherry showed symptoms in stronger sun first, and then on the shaded plants. These plants also gave their fruit and eventually died.
The issue was virtually absent until about mid-summer (although it affected apple trees, rose bushes, and maybe grape vines on at least one previous year).
The pictures that follow show the issue on several different kinds of plants in several different locations. It should be noted that it also affects the fruit, however, but that's not pictured here (it speckled the outer rind of a Ledmon watermelon quite heavily).
Around the time I first asked this question, I gave some of the plants some manganese sulfate and monopotassium phosphate. The pepino melons improved quite a bit (and seem fully recovered from the problem), whether or not manganese deficiency is the visible problem. Many of the other plants improved after the weather cooled down, and perhaps with a little rain, too.
The soil here is clay loam. We have a couple large pine trees that possibly could be eating up the manganese in the yard. I understand they prefer acidic soil (and because of that they are probably used to a lot more manganese than is available to them in our yard). The soil possibly also has a higher PH, which could also cause manganese deficiency symptoms in plants.
I should note that our nieghbors fruther away from the aforementioned tree also have speckles like this on their apple tree.
The black stringy things you see on some of the plants are not related to the problem. They're just ashes from the fires that have been going on in southwestern Idaho. The speckles, however, are definitely not ashes, even where they may look kind of like them.
Pepino Melon
Aunt Molly's Ground Cherry
Aunt Molly's Ground Cherry
Diamond Eggplant
Garden Huckleberry
Shark Fin Melon
Watermelon
McIntosh Apple Tree
A:
All of this damage looks like spider mites. It is odd to see so extensive an infestation outside where natural predators like ladybugs usually move in for a feast.
Spider mites like it when it is hot and dry. Plants that are stressed are favourite targets.
Indicators are:
webbing
tiny pale spots on the leaves where the mites have sucked out the plant juices
they normally live on the underside of the leave and can usually be seen with the naked eye. They resemble grains of salt in size and colour.
Examination with a magnifying glass is usually conclusive.
Control is by soap and water as has been discussed here. This gets much harder for trees and shrubs but persistence with multiple sprays at five to six intervals. For your purposes any of these plants that are annual should be removed and composted.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSDictionary key comparison fails
I am dealing a very basic problem, I have two dictionary keys I need to compare but when I do it doesn't give me correct answer, somehow I am failing to create the logic.
So I have this in a plist array of dictionaries and json array comming from server
I want to compare them if event exist in plist do certain thing if not do another thing;
PROBLEM:
According to my logic if two events in plist are equal to other two events comming from server if logic should be printed per for each dictionary coming from server , so in this case 2 times total , but in my code it is printed 4 times. basically it is satisfying the condition every single time.
NSLOG:
evreka find the id
evreka find the id
evreka find the id
evreka find the id
SOURCE:
in a plist;
createList (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "[email protected]";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "[email protected]";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
This comming from server
responseobj (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "[email protected]";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "[email protected]";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
CODE:
Comparison code;
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
createList= [NSMutableArray arrayWithContentsOfFile:dataPath];
NSLog(@"createList %@",createList);
NSLog(@"responseobj %@",responseObj);
//compare plist and response object
for (int i=0; i<[responseObj count]; i++) {
NSDictionary *dataDict = [responseObj objectAtIndex:i];
NSString *event_name =[dataDict objectForKey:@"event_name"];
//NSString *event_id =[dataDict objectForKey:@"event_id"];
BOOL eventExistInPlist=NO;
for (int j=0; j<[createList count]; j++) {
NSDictionary *createDict = [createList objectAtIndex:i];
//NSString *create_id =[createDict objectForKey:@"event_id"];
NSNumber *create_id =[createDict objectForKey:@"event_id"];
if ([[dataDict objectForKey:@"event_id"] isEqual:[createDict objectForKey:@"event_id"]]) {
// if (create_id==event_id) {
NSLog(@"evreka find the id");
What I have tried:
I have tried to compare them as strings(isEqualtoString), numbers(==) and isEqual: method , they have all failed.
What am I doing wrong?
A:
In
NSDictionary *createDict = [createList objectAtIndex:i];
^----- HERE
you are using the wrong index, it should be j instead of i for the inner loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
igraph: Specify weights in a layout algorithm
I found multiple postings (e.g. here and here) that illustrate how to modify a layout by adding an edge weight.
Still when I do
require(igraph)
g <- graph.ring(10)
plot(g)
set.seed(28100)
E(g)$weight <- sample(1:10, 10, replace = TRUE)
E(g)$weight
# [1] 4 3 4 6 2 9 5 2 9 7
l <- layout_with_fr(g, weights=E(g)$weight)
plot(g, layout=l)
with R version 3.2.2 and igraph version 1.0.1 I got the exact same layout. What instead I would expect to obtain is a layout where edges with a higher (lower) weight are shorter (longer). In other words, nodes connected by an edge with a higher weight are relative closer to each other than nodes connected by a low-weight edge.
Am I doing something wrong?
A:
There is/was a bug in the new Fruchterman-Reingold layout implementation (starting from igraph 1.0.0) which made it ignore the weights. This has already been fixed in the development version, but it seems like this version was not released yet. You can install the development version from Github with the devtools package:
devtools::install_github("gaborcsardi/pkgconfig")
devtools::install_github("igraph/rigraph")
| {
"pile_set_name": "StackExchange"
} |
Q:
Confusion about Surfaces, Normal Vectors in $R^n$
I think I'm having some confusions about some elementary concepts.
I'm studying the book "Calculus of Several Variables" by Lang. I realize the book is not completely rigorous but the following left me questioning some things, while I was trying to understand the author's argument about Lagrange multipliers.
See the screenshots below. The author argues that the gradient vector is the unique normal/orthogonal vector at a surface because it's normal to every differentiable curve passing through that surface.
But what if your "surface" was a line in $R^3$ - say the x axis? Then you could have two different orthogonal vectors that are normal to the surface (i.e. y and z axes). But I realize the x-axis can not be put in the form $g(x, y, z) = c$.
So what's going on here? Do points satisfying a constraint such as $g(x, y, z) = c$ always have one unique orthogonal vector at every point unlike a line in $R^3$ (in the sense the vector is orthogonal to any curve containing those points)? Can this be proven?
Is a line not a "surface" in $R^3$?
I hope what I'm saying makes sense.
A:
The word "surface" in this context is defined in the first sentence of your screenshot. It is a result of differential geometry that such a set of points has exactly the $2$-dimensional shape that you have in mind when you hear the word "surface". It cannot be a line.
See this question: in your case, since the target space is $\mathbb{R}$, $\text{grad}\ f(X)$ being non-zero is equivalent to d$_Xf$ being surjective, hence the preimage is locally a $3-1=2$-manifold.
Note also the gradient cannot be uniquely defined by the property you mention. There are infinitely many normal vectors to a surface at a given point (namely all multiples of the gradient).
I am quite surprised by your sentence "I realize the book is not completely rigorous". What do you mean? What is not rigorous?
Edit: A linear form is what you call a linear transformation in the special case where the codomain has dimension $1$. Say that the domain has dimension $n$. By the rank-nullity theorem, the kernel has to have dimension either $n$ (if the map is trivial) or $n-1$. Note that there is only one direction that is orthogonal to an $n-1$-dimensional subspace - and there is one unique orthogonal vector $v_0$ such that your linear form is the inner product $v\mapsto \left< v, v_0\right>$. That vector is nothing but the $1\times n$ matrix that represents the linear map.
In your case, when the linear form is the differential of a smooth function at a given point $p$, and provided that $\operatorname{d}_pf$ is surjective (hence has $n-1$-dimensional kernel), this one unique vector is what you call $\operatorname{grad} f$.
By smoothness, $\operatorname{d}f$ will stay surjective in a neighbourhood of $p$ and the gradient will therefore exist. In such a neighbourhood, $f$ is close to a linear map and its level sets $f^{-1}(c)$ look like $n-1$ dimensional affine subspaces, in the sense that they are affine subspaces up to a smooth change of variables.
This is known as the submersion theorem - see for instance these lecture notes, Theorem 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
WPFにおける階層構造を持ったViewModelに対するデータバインディングの仕組み
WPFのデータバインディングについて、特に階層構造を持つViewModelをバインドする場合の仕組みについて教えて下さい。
ViewModel定義
public class Outer : INotifyPropertyChanged {
public Inner Inner { /* get,setのコードは省略 */ }
}
public class Inner : INotifyPropertyChanged {
public string Hoge { /* get,setのコードは省略 */ }
}
XAML
<Window.DataContext>
<vm:Outer/>
</Window.DataContext>
<Grid>
<TextBox Text="{Binding Inner.Hoge}"/>
</Grid>
上記のようなコードであるとき、TextBoxはInnerインスタンスのPropertyChangedイベントを直接的に監視しているのでしょうか?
それともDataContextで指定されているOuterインスタンスのPropertyChangedイベントを監視しているのでしょうか?
A:
実際にOuterとInnerのPropertyChangedへイベントハンドラを追加して検証しました。
public class Outer : INotifyPropertyChanged
{
public Outer()
{
// _innerはInnerプロパティ内で参照するprivateメンバ
_inner = new Inner();
_inner.PropertyChanged +=new PropertyChangedEventHandler(_inner_PropertyChanged);
this.PropertyChanged += new PropertyChangedEventHandler(Outer_PropertyChanged);
}
private void _inner_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("Inner: " + e.PropertyName);
}
private void Outer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("Outer: " + e.PropertyName);
}
//...
}
ここでInner.Hogeの値を変更してみますとInner側しか発火していませんでした。TextBoxの表示は正しく更新されました。(素直に実装すればOuterのPropertyChangedはInner自体を変更しないと発火しないようになると考えます。)
よって、TextBoxの更新に関係しているのはInner側のPropertyChangedだと考えました。
| {
"pile_set_name": "StackExchange"
} |
Q:
Punctuation in what I believe is a subordinate conjugation
I have the following sentence (it's from a comment in computer code, just ignore the weird bits):
By strong convention when opening a typeOfObject in the view, send in
an object like this {blah blah}.
I think there's a comma missing after "convention", but I'm not sure what the English rules for punctuation is in this case. In Swedish, there would have most definitely been a comma there, so maybe I'm just letting that influence me too much?
EDIT: I guess there should maybe also be a colon after "this", or can that be left out?
A:
Your sentence has two elements in question: a relative clause and a prepositional phrase.
The words
when opening a typeOfObject in this view
form a relative clause. It is introduced by the relative adverb "when" and contains the verb "opening."
An introductory relative clause should be separated from the main clause by a comma when it is not essential to the meaning of the sentence. In this case,
Send in an object like this
can be understood completely; the introductory relative clause just adds additional background information. (Grammar Bytes!)
In contrast, the words
By strong convention
form a prepositional phrase. It is introduced by the preposition "by" and contains the object of the preposition "convention."
Purdue OWL suggests that introductory prepositional phrases should only be followed by a comma if they are long (more than five words) or part of a series of prepositional phrases (e.g. "On the windowsill in my bedroom, I placed a terrarium.").
Therefore, you should retain the comma after "view" but do not need another comma after "convention."
Since this answer is long enough as-is, I will leave it to another user to advise you on the "like this" and colon question.
| {
"pile_set_name": "StackExchange"
} |
Q:
再帰を用いたプログラムの計算複雑度について
ある面で、最も広い面積の正方形の辺の長さを求めるプログラムを書いています。
入力された配列の要素が0なら黒、1なら白とし、白の面積が最大となる場合の1辺の長さを出力します。
困っていること
動的計画法で書いた再帰表現を含むプログラムを実行しているのですが、計算複雑度のオーダを考える時に、最悪の場合「square(M, i+1, j+1) + 1 」が何回繰り返されるかに依存すると考えられます。
行列Mの縦横i,jの内、長い方ということになるでしょうか。
3x4行列であれば、O(4)で、一般化するとCが定数でO(C)という理解で合っていますか。
もし間違っていたらご指摘いただきたいです。
プログラム
def square(S, i, j):
max = 0
if S[i][j]== 0:
return 0
elif S[i][j]==1 and S[i+1][j]==1 and S[i][j+1]==1 and S[i+1][j+1]==1:
return square(S, i+1, j+1) + 1
return 1
i = 2
j = 1
S= [[0, 1, 1, 0, 1],
[1, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
print(square(S, i, j)) #2
A:
計算量に関する考え方が根本的に間違っています。
問題に対して変化する数量、この問題の場合はiやjに対して計算量がどれぐらいのオーダーで変化するかどうかです。たとえば、もし、1x1行列でも3x4行列でも10000x10000行列でも計算回数(時間計算量)もメモリ使用量(空間計算量)も変わらないようなアルゴリズムであればO(1)です。しかし、もし、1x1行列の計算量にたいして、3x4行列では最大で4倍、10000x10000行列では最大で10000倍、ほとんどの場合で最大でmax(i, j)倍になるようであれば、O(max(i,j))であろうとなります。つまり、3x4行列だけを考えてもダメで、色々変化していくときにどうなるかを考える必要があります。
このように、変化して行くであろう数量に対して、計算回数やメモリ使用量がどれくらいのオーダー(n倍なのか、n^2倍なのか、n!倍なのか、それとも変わらないのか)で必要になっていくのかを見ていきます。NPPさんが、10000x10000行列も3x4行列も1x1行列も最悪の場合の計算回数が変わらないと思うのであれば、それはきっと時間計算量は定数時間O(1)なのでしょう。はたして、本当にそう思いますか?もし、そうではないと思うのなら、どの値にどのように依存しているのかを考え直してください。
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move the Green Button to he center with the arrow still next to it?
Hi,
So I want to move the button to the center, but still have the arrow and click here next to it. Currently the image (arrow and click here) is pushing it to the center. Can't seem to get it to work without the arrow coming up on the next line. Here is my code (look for GET STARTED NOW image http://www.clevercontracts.co.za/wp-content/uploads/2015/03/hand_arrow.png - any thoughts?
/**
* Header 17 stylesheet
* */
.header-17-startup-antiflicker {
background:white!important
}
.header-17 {
z-index:100;
width:100%;
height:100px;
padding-top:0;
padding-bottom:0
}
.header-17 .header-background {
background:#fff
}
.header-17 .navbar {
position:absolute;
z-index:2;
top:0;
margin:0
}
.header-17 .navbar.navbar-fixed-top {
top:0!important
}
.header-17 .navbar .navbar-form {
padding:30px 0 19px 60px
}
.header-17 .navbar .btn {
padding-left:26px;
padding-right:26px;
font-size:14px;
font-weight:normal;
color:#ffffff;
font-weight:800
}
.header-17 .navbar .btn.btn-primary {
background-color:#16a085
}
.header-17 .navbar .btn.btn-primary:hover,.header-17 .navbar .btn.btn-primary:focus {
background-color:#16a085
}
.header-17 .navbar .btn.btn-primary:active,.header-17 .navbar .btn.btn-primary.active {
background-color:#16a085
}
.header-17 .navbar .brand {
padding-top:33px!important;
font-size:25px;
font-weight:normal;
font-weight:800;
letter-spacing:0;
color:#1f2225;
position:relative;
overflow:hidden
}
.header-17 .navbar .brand img:first-child {
float:left;
margin:0 15px 0 2px;
position:relative;
z-index:2
}
.header-17 .navbar .nav > li {
margin-left:24px
}
.header-17 .navbar .nav > li:first-child {
margin-left:0
}
.header-17 .navbar .nav > li > a {
text-transform:uppercase;
padding:42px 0 24px;
font-size:14px;
font-weight:normal;
color:#1f2225;
font-weight:800;
color:#95a5a6
}
.header-17 .navbar .nav > li > a:hover,.header-17 .navbar .nav > li > a:focus,.header-17 .navbar .nav > li > a.active {
color:#1f2225
}
.header-17 .navbar .nav > li.active > a {
color:#1f2225
}
.header-17 .navbar .nav > li.active > a:hover,.header-17 .navbar .nav > li.active > a:focus,.header-17 .navbar .nav > li.active > a.active {
color:#1f2225
}
.header-17 .navbar .navbar-toggle {
background-image:url(http://www.clevercontracts.co.za/wp-content/themes/startup/templates/startup-framework/build-wp/common-files/icons/[email protected]);
-webkit-background-size:17px 12px;
-moz-background-size:17px 12px;
-o-background-size:17px 12px;
background-size:17px 12px;
margin-top:34px
}
.header-17-sub {
position:relative!important;
background-color:#1F2225;
padding-top:105px;
padding-bottom:105px;
color:#7f8c8d
}
.header-17-sub .dm-carousel {
height:48px
}
.header-17-sub.v-center,.header-17-sub .v-center {
display:table;
width:100%
}
.header-17-sub.v-center > div,.header-17-sub .v-center > div {
display:table-cell;
vertical-align:middle;
margin-top:0;
margin-bottom:0;
float:none
}
@media (min-width: 768px) {
.header-17-sub .v-center.row:before,.header-17-sub .v-center.row:after {
display:none
}
}
@media (max-width: 767px) {
.header-17-sub .v-center {
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
padding-left:5px;
padding-right:5px
}
.header-17-sub .v-center.row {
display:block;
width:auto
}
.header-17-sub .v-center.row:before,.header-17-sub .v-center.row:after {
display:none
}
.header-17-sub .v-center.row > * {
display:block;
vertical-align:baseline
}
}
.header-17-sub .row.v-center {
width:auto
}
.header-17-sub .btn.btn-clear {
font-size:20px;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
padding:20px 25px 21px;
background:#16a085;
border:2px solid #16a085
}
.header-17-sub .btn.btn-clear:hover,.header-17-sub .btn.btn-clear:focus {
border-color:#fff;
background:#16a085
}
.header-17-sub .btn.btn-clear:active,.header-17-sub .btn.btn-clear.active {
border-color:#fff;
background:#16a085;
color:rgba(255,255,255,0.75)
}
.header-17-sub .btn.btn-clear {
font-size:30px;
font-weight:normal;
color:#fff;
margin:-2px 15px 0 0
}
@media (max-width: 480px) {
.header-17-sub .btn.btn-clear {
font-size:18px;
font-weight:normal;
color:#fff;
display:block;
min-width:260px
}
.header-17-sub .btn.btn-clear [class*="fui-"] {
float:left
}
}
.header-17-sub h3 {
margin:0 0 10px
}
.header-17-sub .hero-unit {
margin:40px 0 60px;
padding:0;
background:transparent
}
.header-17-sub .hero-unit h1 {
margin:0;
font-size:39px;
font-weight:normal;
color:#ffffff;
line-height:49px;
font-weight:500;
letter-spacing:0
}
.header-17-sub .hero-unit p {
padding:20px 0 0;
font-size:28px;
font-weight:normal;
color:#ffffff;
font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight:300
}
@media (max-width: 480px) {
.header-17-sub .hero-unit {
text-align:left;
margin:0 0 33px
}
.header-17-sub .hero-unit h1 {
margin:0 0 23px;
font-size:25px;
font-weight:normal;
color:#ffffff;
line-height:32px
}
.header-17-sub .hero-unit p {
font-size:17px;
font-weight:normal;
color:#7f8c8d;
line-height:23px
}
}
.header-17-sub .hero-unit,.header-17-sub big,.header-17-sub h1,.header-17-sub .h1,.header-17-sub h2,.header-17-sub .h2,.header-17-sub h3,.header-17-sub .h3,.header-17-sub h4,.header-17-sub .h4,.header-17-sub h5,.header-17-sub .h5,.header-17-sub h6,.header-17-sub .h6 {
color:white
}
.header-17-sub .btn.btn-clear {
color:#fff
}
.header-17-sub .btn.btn-clear:hover,.header-17-sub .btn.btn-clear:focus {
color:white
}
.header-17-sub .btn.btn-clear:active,.header-17-sub .btn.btn-clear.active {
color:rgba(255,255,255,0.75)
}
.header-17-sub big {
font-size:22px;
font-weight:normal;
color:#ffffff;
font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;
line-height:32px
}
.header-17-sub h6 {
font-size:18px;
font-weight:normal;
color:#ffffff;
font-weight:500;
text-transform:none
}
.header-17-sub .pt-perspective {
position:relative;
height:100%;
-webkit-perspective:1200px;
-moz-perspective:1200px;
perspective:1200px
}
.header-17-sub .pt-page {
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
visibility:hidden;
overflow:hidden;
-webkit-backface-visibility:hidden;
-moz-backface-visibility:hidden;
backface-visibility:hidden;
-webkit-transform:translate3d(0,0,0);
-moz-transform:translate3d(0,0,0);
transform:translate3d(0,0,0);
-webkit-transform-style:preserve-3d;
-moz-transform-style:preserve-3d;
transform-style:preserve-3d
}
.header-17-sub .pt-page.pt-page-current {
position:relative
}
.header-17-sub .calculated .pt-page.pt-page-current {
position:absolute
}
.header-17-sub .pt-page-current,.header-17-sub .no-js .pt-page {
visibility:visible;
z-index:1
}
.header-17-sub .pt-page-ontop {
z-index:999
}
.header-17-sub .page-transitions {
margin:85px 0 100px
}
.header-17-sub .page-transitions .col-sm-3 {
text-align:left
}
.header-17-sub .img-holder {
text-align:center
}
.header-17-sub .img-wrapper {
display:inline-block
}
.header-17-sub .pt-controls {
position:absolute;
bottom:-100px;
left:0;
right:0;
text-align:center
}
.header-17-sub .pt-controls .pt-indicators {
list-style:none;
margin:0;
padding:0
}
.header-17-sub .pt-controls .pt-indicators li {
line-height:18px;
display:inline-block;
width:9px;
height:9px;
text-indent:-999px;
background-color:rgba(127,140,141,0.3);
border-radius:50%;
cursor:pointer
}
.header-17-sub .pt-controls .pt-indicators li + li {
margin-left:10px
}
.header-17-sub .pt-controls .pt-indicators li.active {
background-color:#1abc9c
}
@media (max-width: 767px) {
.header-17-sub .page-transitions .col-sm-3 {
text-align:center
}
.header-17-sub .page-transitions .col-sm-6 {
margin:40px 0
}
}
@media (max-width: 480px) {
.header-17-sub {
padding-top:65px;
padding-bottom:65px
}
}
.header-17-sub .btn.btn-huge.fui-facebook {
font-family:"Helvetica Neue",Helvetica,Arial,sans-serif
}
.header-17-sub .btn.btn-huge.fui-facebook:before {
margin-right:15px;
display:inline-block;
vertical-align:top;
font-size:30px;
font-family:'Flat-UI-Pro-Icons'
}
.header-17-sub .btn.btn-huge.fui-facebook:hover:before {
color:#fff
}
<header class="header-17">
<div class="container">
<div class="row">
<div class="navbar col-sm-12" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle">
</button> <a href="/" class="brand custom-img"><img alt="" src="http://www.clevercontracts.co.za/wp-content/uploads/2015/03/Screen-Shot-2015-03-01-at-1.04.39-PM-e1425234548831.png"> </a>
</div>
<div class="collapse navbar-collapse pull-right">
<div class="pull-left">
<ul class="nav">
<li><a href="#">Home</a> </li>
<li><a href="http://www.clevercontracts.co.za/?p=67">Contracts</a> </li>
<li><a href="#">Blog</a> </li>
<li><a href="#">Contact</a> </li>
</ul>
</div>
<form class="navbar-form pull-left" action="action">
<a href="/" class="btn btn-primary">GET STARTED </a>
</form>
</div>
</div>
</div>
</div>
<div class="header-background">
</div>
</header>
<section class="header-17-sub text-center dm-controlsView-holder" style="background-color: #1f2225">
<div class="background" style="background-image: url(http://www.clevercontracts.co.za/wp-content/themes/startup/templates/startup-framework/build-../../../../../../uploads/2015/02/homepage_background-1400x948-53520.jpg); opacity: 0.54">
</div>
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="hero-unit">
<h1>Easily create the perfect contract</h1>
<p>Clever contracts makes it super easy & simple for anyone to create a legally tight contact ready to be signed. We'll guide you through each step.</p>
</div>
<a href="/" class="btn btn-huge btn-clear">GET STARTED NOW</a> <img src="http://www.clevercontracts.co.za/wp-content/uploads/2015/03/hand_arrow.png" alt="image">
<div id="h-17-pt-1-61" class="page-transitions pt-perspective">
<div class="pt-page">
<div class="row v-center">
<div class="col-sm-3 ani-processed">
<big>Protect yourself from lawsuits and a possible court summons.</big>
</div>
<div class="col-sm-6 ani-processed">
<img width="384" height="191" alt="" src="http://www.clevercontracts.co.za/wp-content/themes/startup/templates/startup-framework/build-wp/common-files/img/header/[email protected]">
</div>
<div class="col-sm-3 ani-processed">
<h6>Live Easy</h6>
<span>Creating a contract has never been this easy.Only R89 per contract.</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
A:
wrap the a tag and img tag with a div, center it.. and use positioning on the img tag.
section {
text-align:center;
background-color:brown;
}
div.btnwrapper, a.btn
{
width:10em;
height:2em;
display:block;
overflow:visible;
margin:auto;
padding:0;
}
div.btnwrapper
{
position:relative;
background-color:gray;
line-height:2em;
}
a.btn {background-color:skyblue;text-decoration:none;}
div.img {
width:8em;background-color:white;border:0e;display:block;padding:0 1em;
position:absolute;left:100%;top:0;
}
<section>
<p> This is text </p>
<div class="btnwrapper">
<a href="#" class="btn">CLICK ME</a>
<div class="img">An Image</div>
</div>
<p>Other text</p>
</section>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass the variable value which is a function to the calling
I am iterating the array which will setup my React input component. The problem that I am facing is I don't know how to pass the onEmailFilled as a function to the handle_changes.
const inputComponentArray= [{id_name : "signin_email", input_label : "Email", input_type : "email", handle_changes: "{onEmailFilled}"}, {id_name : "signin_password", input_label : "Password", input_type : "password", handle_changes: "{onPasswordFilled}"}]
class Test extends Component{
render()
{
{
inputComponentArray.map((object => {
return
<VerticalInputComponent
id_name={object.id_name}
input_label={object.input_label}
input_type={object.input_type}
handle_changes={object.handle_changes} //this is not working because it received a string instead of a function
/>
}
))
}
}
}
How do I this or is there a better way of doing this? I am using map is because I want to make a dynamic form page.
This is in the VerticalInputComponent.js which is a different page.
<input
id={this.props.id_name}
name={this.props.id_name}
className="input-reset ba b--black-20 pa2 mb2 db w-100 lh-copy lh-copy-l lh-copy-m lh-copy-ns"
type={this.props.input_type}
autoComplete="on"
onChange={this.props.handle_changes}
/>
A:
Assign the function reference directly to the object property, without executing it. For example:
const onEmailFilled = () => {
console.log("onEmailFilled called");
};
const inputComponentArray = [
{
id_name: "signin_email",
/*...*/
handle_changes: onEmailFilled
}
];
/*...*/
inputComponentArray.map(object => (
<VerticalInputComponent
id_name={object.id_name}
input_label={object.input_label}
input_type={object.input_type}
handle_changes={object.handle_changes}
/>
));
Depending on where the function is coming from you have to add the reference to it, but without executing it (without adding ())
From props: handle_changes: this.props.onEmailFilled
From class method: handle_changes: this.onEmailFilled
From constant: handle_changes: onEmailFilled
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent IIS from reusing worker processes for separate ASP.Net AppDomains
When IIS restarts an ASP.Net (2.0) web application, it can either:
Recycle the AppDomain: Unload the AppDomain and load a new AppDomain on the same process (e.g. when HttpRuntime.UnloadAppDomain() is called, when web.config is changed).
Recycle the process: unload the AppDomain and load a new one on a new process (e.g. when invoking Recycle command on an AppPool via inetmgr, or when memory limit is reached).
Due to some internal reasons (trouble with legacy native code we depend upon), we cannot allow the first option. We just can't load the application twice on the same process.
Can IIS be somehow told to never allow worker process reuse?
I've tried preventing it myself by tracking whether an application has already started on a process once using a Mutex, and if so - throwing an exception during Application_Start()); I've also tried terminating the process by calling Environment.Exit() during Application_End(). The problem with both methods is that it causes any requests that arrive during Application_End or Application_Start to fail (unlike a manual process recycle, which fails absolutely no requests because they are redirected to the new process right away).
A:
Couldn't find a way to tell IIS that worker processes are not to be reused. Can't afford fixing the underlying problem that forbids process reuse. Therefore, ended up calling Environment.Exit(0) in Application_End, although it may cause a small number of requests to fail with a connection reset.
| {
"pile_set_name": "StackExchange"
} |
Q:
Accidentally edited a low-quality answer, what should I do?
I recently reviewed some posts from the Low-Quality Queue and got this self-answer for review:
yeah I added the "stopClk <= true;" line and it seems to be working now! thanks for all the help !
It looked like an answer to me, where I just had to strip of the noise. So, I edited the post to:
I added the
stopClk <= true;
line and it seems to be working now.
Later on, I stumbled over the answer again and saw, that the answer was just a reply to another accepted answer. So, I down-voted the answer and left a comment explaining the situation:
I improved this answer during the review process because I thought it was an answer. But, now I see, that it was just a reply to another post. Please delete your answer, it is not even helpful. StackOverflow is not a discussion forum. Just accept an answer as you have already done. Once you have enough reputation, you can also vote on answers.
Should I have recommend the answer for deletion in the first place?
Should I take any additional action?
According, to this meta post, I should not flag it again.
A:
After your mistake in the queue, your actions were fine and totally appropriate. And, yes, you should flag again.
The Meta post you linked to is dealing with the potential abuse reviewers can make, that is, flagging the answer and then recommending deletion so that their helpful flags count increases. This is not the case here: in fact, when you edited the answer, it was pulled out of the "Low Quality Posts" queue so there can be no abuse.
You shouldn't have edited the post in the queue, and, instead, chose "Recommend Deletion":
yeah I added the "stopClk <= true;" line and it seems to be working now! thanks for all the help !
The end of the post implies that this is a "Thank you" answer directed at another post of the question. In this case, best to investigate further by actually looking at the question and all of its answers to see if it is actually the case or not.
It can happen that, sometimes, there are no other answers and the OP is refering to comments that were left. Sometimes there aren't even comments, and the "thanks" is just there as fluff. In such a scenario, you should edit and remove the fluff, exactly like you did. (Also, the answer shouldn't have been flagged to begin with, but, unfortunately, it happens...)
But when there are another answer and it is clear that it is directed at another answer, don't edit and recommend deletion. It would be "Not An Answer" and the appropiate comment to leave would be:
“Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful.”
| {
"pile_set_name": "StackExchange"
} |
Q:
Fibonacci function list
I am currently doing a part of my assignment i have to make it so if the user enters 10 in function
the answer should be
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
but my program results in
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
This is my program
def fib(n):
fibonacci = []
a = 0
b = 1
for i in range(n):
fibonacci.append(b)
a, b = b, a+b
return fibonacci
A:
You just need to append a instead of b.
def fib(n):
fibonacci = []
a = 0
b = 1
for i in range(n):
fibonacci.append(a)
a, b = b, a+b
return fibonacci
Results for print(fib(10))
> python fib.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| {
"pile_set_name": "StackExchange"
} |
Q:
c# console application to repeat keyboard presses?
I am trying to make a simple macro program to repeat keyboard key presses and I am having trouble finding out how to fire a keyboard event, anyone have any hints?
A:
As tommieb75 mentioned, don't reinvent the wheel. Just take AutoIt3.
| {
"pile_set_name": "StackExchange"
} |
Q:
Double click on row in NSTableView doesn't display the new view
I have an os x app that uses core data.
I have 3 .xib files in my app, those are:
1. MainMenu.xib
2. MasterTableViewController.xib
3. DetailViewController.xib
When started , app displays a view that has NSTableView with couple of records in it.
I name that view MasterTableViewController
I want when user double click on the row, to hide the "master" view and to display my "detail" view. I named that view DetailViewController.
When double clicked on the row in the NSTableView in the "master" view,nothing happen, "master" view remains visible. What I want is "master" view to dissapear, and "detail" view to appear.
Here is the code that I have right now, and more explanations follows:
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (nonatomic,strong) NSViewController *mainAppViewController;
@property (weak) IBOutlet NSView *mainAppView;
- (void)changeViewController:(NSInteger)tag;
@property (weak) IBOutlet NSTableView *websitesTableView;
- (void)tableViewDoubleClick:(id)nid;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "MasterTableViewController.h"
#import "DetailViewController.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
- (IBAction)saveAction:(id)sender;
@end
@implementation AppDelegate
NSString *const masterTable = @"MasterTableViewController";
NSString *const detail = @"DetailViewController";
-(void)awakeFromNib {
[_websitesTableView setTarget:self];
[_websitesTableView setDoubleAction:@selector(tableViewDoubleClick:)];
}
- (void)tableViewDoubleClick:(id)nid {
NSInteger rowNumber = [_websitesTableView clickedRow];
NSTableColumn *column = [_websitesTableView tableColumnWithIdentifier:@"websiteUrl"];
NSCell *cell = [column dataCellForRow:rowNumber];
NSInteger tag = 2;
[self changeViewController:tag];
}
- (void)changeViewController:(NSInteger)tag {
[[_mainAppViewController view]removeFromSuperview];
switch (tag) {
case 1:
self.mainAppViewController = [[MasterTableViewController alloc]initWithNibName:masterTable bundle:nil];
break;
case 2:
self.mainAppViewController = [[DetailViewController alloc]initWithNibName:detail bundle:nil];
break;
}
[_mainAppView addSubview:[_mainAppViewController view]];
[[_mainAppViewController view] setFrame:[_mainAppView bounds]];
[[_mainAppViewController view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// automatically run the master table view controller
NSInteger tag = 1;
[self changeViewController:tag];
}
Now, some of you may wondering, where is the rest of the code. I have ommited the boiler plate code for the core data below in the AppDelegage.m, since it is unchanged. I used binding to make my NSTableView to work and to display my records, so MasterTableViewController.h and .m files are empty, and same is true for the DetailViewController.h and .m file.
Important note - What i can't understand here: If I change the tag in 2 in the applicationDidFinishLaunching method, detail view is displayed normally, but if i switch it back on 1, and then double click on the row, "master" view (with the NSTableView) remains visible, and nothing happen (views are not swapped)
Anyone can help me to find out what is wrong with my code?
Regards, John
A:
You apparently had a second instance of your AppDelegate class instantiated in the MasterTableViewController.xib file. There should be only one AppDelegate instance and that's the one in MainMenu.xib. So, it shouldn't be in MasterTableViewController.xib.
One of the instances was receiving the double-click action method from the table, but the other one was the one with the outlet to the main window.
You need(ed) to get rid of the second instance and find another way to access the app delegate from the MasterTableViewController.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Batch, JdbcExecutionContextDao java.util.Map$Entry deserializer issue, xstream 1.4.1
I have a problem using Spring Batch 2.1.9:
when i use jobExplorer.getJobExecution(jobExecutionId), i find a problem when DAO has to deserialize a string like:
{"map":[{"entry":{"string":"parsedComparingDate","date":"2014-03-08 23:00:00.0 UTC"}}]}
from the BATCH_JOB_EXECUTION_CONTEXT table, using method JdbcJobExecutionDao.getJobExecution().
I know that spring batch uses xstream 1.3, but in my Pom, i have:
spring-batch 2.1.9;
xstream 1.4.1 (inherited from smooks);
jettison 1.3.3 (inherited from cxf);
Also, i read that xstream 1.3 does not work fine with jettison 1.3.3, but using xstream 1.3 (excluding xstream 1.4.1 from pom) the job works correctly, while, using xstream 1.4.1 or major, i find the following exception:
Caused by: java.lang.InstantiationError: java.util.Map$Entry
at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source) [:1.6.0_23]
at java.lang.reflect.Constructor.newInstance(Constructor.java:513) [rt.jar:1.6.0_23]
at com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider.newInstance(Sun14ReflectionProvider.java:75) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.instantiateNewInstance(AbstractReflectionConverter.java:424) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:229) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.collections.MapConverter.putCurrentEntryIntoMap(MapConverter.java:85) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.collections.MapConverter.populateMap(MapConverter.java:77) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.collections.MapConverter.populateMap(MapConverter.java:71) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.converters.collections.MapConverter.unmarshal(MapConverter.java:66) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1035) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1019) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:895) [xstream-1.4.1.jar:]
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:886) [xstream-1.4.1.jar:]
at org.springframework.batch.core.repository.dao.XStreamExecutionContextStringSerializer.deserialize(XStreamExecutionContextStringSerializer.java:48) [spring-batch-core-2.1.9.RELEASE.jar:]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:222) [spring-batch-core-2.1.9.RELEASE.jar:]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:215) [spring-batch-core-2.1.9.RELEASE.jar:]
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:92) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:649) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:587) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:637) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:666) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:674) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:714) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.simple.SimpleJdbcTemplate.query(SimpleJdbcTemplate.java:202) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.jdbc.core.simple.SimpleJdbcTemplate.query(SimpleJdbcTemplate.java:209) [org.springframework.jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:106) [spring-batch-core-2.1.9.RELEASE.jar:]
1) i have seen the code, can i configure the XStreamExecutionContextStringSerializer in order to set reflectionProvider = null (in this way, it will not uses the Provider) ?
2) there are other solutions to fix my problem ?
thanks
A:
It's impossible for me to change xstream version and jettison version because they imported by other components (like smooks).
A possible solution could be to create two different JBoss modules and to use them togheter.
So, i find another solution: use spring-batch 2.2.0.RELEASE, and use org.springframework.batch.core.repository.dao.DefaultExecutionContextSerializer as serializer instead of XStream.
Below the configuration:
<bean id="batchDefaultSerializer" class="org.springframework.batch.core.repository.dao.DefaultExecutionContextSerializer" />
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="batchTransactionManager" />
<property name="lobHandler" ref="defaultLobHandler" />
<property name="serializer" ref="batchDefaultSerializer" />
</bean>
<bean id="jobExplorer"
class="org.springframework.batch.core.explore.support.JobExplorerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="serializer" ref="batchDefaultSerializer" />
</bean>
I tested it and it works fine, so, i think it's the best solution.
A:
Due to the incompatibility of Jettison 1.2+ with XStream, upgrading XStream will cause Spring Batch to break. This is something that was recently identified but has not been addressed yet. The solution for your issue is to use Jettison 1.2 and XStream 1.4.7
A:
I'm using Spring Boot 1.4.0 with Spring Batch 3.0.7 and ran into this problem with a microservice that is using the Netflix OSS components b/c they use XStreams 1.4.2.
I'm also using Java configuration instead of XML. Here's what I came up with to solve the issue:
In a @Configuration class:
@Bean
public ExecutionContextSerializer serializer()
{
return new Jackson2ExecutionContextStringSerializer();
}
@Bean
@Autowired
public JobRepository jobRepository( DataSource dataSource,
PlatformTransactionManager txManager ) throws Exception
{
JobRepositoryFactoryBean fac = new JobRepositoryFactoryBean();
fac.setDataSource( dataSource );
fac.setTransactionManager( txManager );
fac.setSerializer( serializer() );
fac.afterPropertiesSet();
return fac.getObject();
}
@Bean
@Autowired
public JobExplorer jobExplorer( DataSource dataSource ) throws Exception
{
JobExplorerFactoryBean fac = new JobExplorerFactoryBean();
fac.setDataSource( dataSource );
fac.setSerializer( serializer() );
fac.afterPropertiesSet();
return fac.getObject();
}
I'm using Postgres as a backing store, so the DefaultExecutionContextSerializer didn't work as it tried to serialize binary instead of UTF-8 (JSON).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to comment out a part of a string in c#?
I got this code part here:
label1.Text = $"Score: {score} | Speed: {speed}";
This shows a score and speed of a breakout game I made. Now I don't need the speed and I wondered if there is a way of commenting out a part of a string.
Of course I could do
label1.Text = $"Score: {score}";// | Speed: {speed};
but maybe there is another way, so the comment can be removed easier. Something like
label1.Text = $"Score: {score} #comment | Speed: {speed} #endcomment";
or
label1.Text = $"Score: {score} #/*| Speed: {speed} #*/";
so it's easier to read and change
A:
Instead of commenting out, you can make use of preprocessor directives:
#if DEBUG
label1.Text = $"Score: {score} | Speed: {speed}";
#else
label1.Text = $"Score: {score}";
#endif
DEBUG should be defined when in Debug Mode. That is default in Visual Studio. So you don't need to always comment in and out and keep it in mind to not let it slip into Release output.
Mind that you shouldn't use this excessively. Having many of those will clutter your code and make it unreadable (and a maintainance hell) in the long run. For a specific and small usage like here, it should be fine, though.
A:
You can have your string define on two line like this:
label1.Text = $"Score: {score}";
label1.Text += $" | Speed: {speed}";
So you can comment it like that:
label1.Text = $"Score: {score}";
//label1.Text += $" | Speed: {speed}";
A:
Create a method that filters and returns only the ones you need:
public static string Filter(string input, params string[] items)
{
return string.Join("|",input.Split('|').Where(x => items.Contains(x.Split(':')[0].Trim())));
}
Now You can get it like:
string text = $"Score: {score} | Speed: {speed}";
Label1.Text = Filter(text, "Score");
Or
Label1.Text = Filter(text, "Speed");
Or
Label1.Text = Filter(text, "Score", "Speed");
DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
What is H18 (Canada)?
I'm currently doing university level continuing education in Quebec, Canada. As part of my degree, I want to do some courses from another university online. I've talked to my chairperson, and he validated certain courses. So I made an application this January, and recently received a conditional offer of admission.
One of the conditions was receiving the official transcript from my current university. No problem, right? Simply ask my home university to send them the document: they have an online form for it, which I filled out, and off it went.
What I'm concerned about is that under the Documents to send is listed "Official transcript" and under details, "with H18." What is H18? Does it refer to something that must be on the document, or something about the university?
A:
H18 stands for Hiver 2018 (Winter 2018), that is, the current semester.
Similarly, E18 is Été 2018 (Summer 2018) and A18 is Automne 2018 (Fall 2018).
Source: I'm from Québec, and I recognize my former University software in this screen capture.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chrome is not maximizing
I am using this code to maximize but it is not working:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
A:
Not to worry, try the following code
driver().manage().window().maximize();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dolphin dive in Battlefield1?
First of all, a dolphin dive is a term from COD Black Ops,
here's a video of what it looks like.
I think the BF1 version is a bit different but I've seen people flying and then landing on the ground, how is it done?
A:
You can do that, more or less, the same way you charge.
Start sprinting
After some steps, stop pressing Shift (you'll keep sprinting
for a short distance) and press Ctrl (you may have to press it
for a short period of time, not just "one click")
This same thing can also be done when Toggle Crouching replacing Ctrl for X
| {
"pile_set_name": "StackExchange"
} |
Q:
WSServletContainerInitializer and SpringBeanAutowiringSupport
I have some integration issues regarding the mentioned classes but only with "too new" tomcat versions.
The base setup:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="FooService" version="2.5" metadata-complete="true">
<display-name>FooService</display-name>
<servlet>
<servlet-name>jax-ws</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
</web-app>
FooServiceImpl:
@WebService(serviceName = ServiceInfo.SERVICENAME, targetNamespace = ServiceInfo.TARGETNAMESPACE, endpointInterface = "bar.FooService")
@HandlerChain(file = "/handler-chain.xml")
public class FooServiceImpl extends SpringBeanAutowiringSupport implements FooService {
@Autowired
private Bar bar;
<< some methods using the injected bar singleton >>
JAX-WS dependency: compile 'com.sun.xml.ws:jaxws-rt:2.2.7'
Spring version: 3.1.2.RELEASE
With Tomcat 7.0.22 I don't have the problem. The declared webapp version in the web.xml is 2.5. Tomcat 7.0.22 doesn't process the WSServletContainerInitializer. So as declared in web.xml, ContextLoaderListener is initialized first, so an instance of Bar will be available in the WebApplicationContext. Then WSServletContextListener instantiates FooServiceImpl, aoutowiring works and everybody is happy.
But... My colleague tried it with Tomcat 7.0.30 and the autowiring didn't work (7.0.32 gives the same problem, currently this is the newest). It really couldn't work, because the new Tomcat version has processed WSServletContainerInitializer, not taking into account the 2.5 webapp version (and metadata-complete="true").
I've found a possible solution. I commented out the body of the web.xml, changed webapp version to 3.0 and created a WebapplicationInitializer:
public class MyInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ContextLoader loader = new ContextLoader();
loader.initWebApplicationContext(servletContext);
}
}
This worked perfectly for me. But not for my colleague... If he tried to run the app, WSServletContainerInitializer fired first which created exactly the same wiring problem as above.
Obviously we can "hack" the problem getting rid of SpringBeanAutowiringSupport and inject Bar manually from a getter or a web method, or any similar way. But SpringBeanAutowiringSupport would be much clearer, so we would like to use it if there's a good solution for the above problems.
UPDATE: this causes the problems: https://issues.apache.org/bugzilla/show_bug.cgi?id=53619
A:
for me the solution was to invoke the following when the autowired reference is null
processInjectionBasedOnCurrentContext(this);
I hope it helps for all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot copy mirror some bones between keyframes
I'm working on an 8 frame walk cycle, and I'd like to copy and mirror the poses of the first 4 frames to the last 4 frames. However, for some reason my arms won't copy mirror properly.
Can someone spot what I'm doing wrong?
Here's a link to my blender file:
http://pasteall.org/blend/index.php?id=50223
A:
It looks like your arm bones are not well oriented:
In Edit mode, select the right upper and lower arm.
ctrl R 180 to make a 180° rotation
now it works
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML table coded before img src but browser showing image before table. Help fix?
this is my first posted question. My html index file is written out with table tags first and img src last in the body. However, my browser shows the image first and then the table. How do I fix this? Here's the code:
<DOCTYPE html>
<html lang ="en">
<head>
<meta charset ="utf-8">
<title>Levi's Biography</title>
<!-- lines 6 through 11 are simply added for developing the page to a future standard -->
<link rel="stylesheet" type="text/css" href="mybio.css">
<script src="/jquery.js"></script>
<script type="text/javascript" src="/js/jquery-1.3.1.js"></script>
</head>
<body>
<table border="4px">
<thead>
<tr border="3px">
<th colspan="4"><h2>Levi Donaldson</h2></th>
</thead>
<tbody>
<tr>
<td>Born</td>
<td>Grew up</td>
<td>Hobbies</td>
<td>Foods</td>
</tr>
<tr>
<td>Moenci, AZ</td>
<td>Mesa, AZ
<br>
Wasilla, AK
<br>
Eagar, AZ
<br>
Cliff, NM
</td>
<td>Quality family time
<br>
Traveling
<br>
Fishing
<br>
Cooking
<br>
Passive income streams
<br>
Creating things or improving their designs
</td>
<td>A great steak
<br>
Sushi (with scallops if possible)
<br>
Brazilian rice and beans
<br>
Home grown fruit
<br>
Fresh garden veggies and herbs
<br> Cheesecake (but for heavens sake, NO New York style)
</td>
</tr>
</tbody>
<img src="http://1.bp.blogspot.com/_b3dSgzaqFKs/SRfDqJxbSOI/AAAAAAAAADc/iNvyqMQqzKs/S220/katie%26levi2+001.jpg"/>
</body>
</html>
A:
You forgot to close your table with a </table> tag. So the img is being moved. Just put a </table> tag after </tbody> but before img tag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display results of multiple count in a sql query
There are two table:
Table persons:
P_id Name BirthDate
1 N1 2016-08-02
2 N2 2015-05-02
3 N3 2013-06-01
4 N4 2014-01-09
Table visited:(p_id is foreign key to table persons)
Id. Visitor_id. P_id. Visit_date
1 10 1 2017-03-05
2 11 2 2017-01-01
3 10 2 2017-02-03
4 12 3 2016-05-07
5 11 4 2016-04-09
6 10 1 2017-04-09
We are going to get the count of visited persons who their old are under 1, between 1 and 2, between 2 and 3 at date of visit_date by each visitor_id.
The results like :
Visitor_id Under_one Bet_one_two Bet_two_three
10 2 1 0
11 0 1 1
12 0 0 1
Could anyone help me how write a query in sql server for getting the results?
In above results, 0,1,2 means that we subtract of two date(visited_date - birthdate), for example : the result of 2013/03/05 - 2011/06/07 is between 1 and 2
A:
you can try a pivot query like below
select
visitor_id,
Under_one=ISNULL([0],0),
Bet_one_two=ISNULL([1],0),
Bet_two_three=ISNULL([2],0)
from
(
select visitor_id, datediff(m,BirthDate,visit_date)/12 age_in_years,count(1) count from persons p join
visited v on p.p_id=v.p_id
group by visitor_id,datediff(m,BirthDate,visit_date)/12
) src
pivot
(
max(count) for age_in_years in ([0],[1],[2])
)p
see live demo
| {
"pile_set_name": "StackExchange"
} |
Q:
php - search for specific substring
I am trying to figure out how to search in php for substring. When I tried using this:
while ($row = db_fetch_array($results)) {
if(strpos($row['field_rep_contact_name_value'], $get)) {
$names['suggestions'][] = $row['field_rep_contact_name_value'];
}
}
I found that when the $get value was 'arm', it returned true for strings which had 'ar', I only want it to return true if it contains 'arm', the full value of the $get variable. I think this can be done with regex but not exactly sure how.
A:
Add a !== false to your statement
$stringone = 'lucas vieira';
$stringtwo = 'luca';
strpos($stringone, 'lucas') !== false // returns true
strpos($stringtwo, 'lucas') !== false // returns false
| {
"pile_set_name": "StackExchange"
} |
Q:
How to join 2 tables using SQL
I created two temporary tables, #tableA (1872 entries) and #tableB (1146 entries). I have populated both with mailing info. I want to filter out the entries from #tableA that also show up in #tableB (437 shared entries). I want to do this by looking at the FullName field found in both temp tables. After we filter these shared names out I need to return the data from #tableA (which now has 1435 entries).
select * from #TableA
--inner join #TableB ON #TableA.FullName = #TableB.FullName --shows 437 shared names
where
--#TableA.FullName <> #TableB.FullName --this is obviusly not going to work
Could you guys please point me in the right direction?
thank you
A:
select a.*
from #TableA a
left join #TableB b ON a.FullName = b.FullName
where b.FullName IS NULL
A:
I rather advise you to learn joins. If you don't know it- you need to! Otherwise you will be asking others to do it for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
PG::ConnectionBad: connection is closed after upgrading rails from 4.2 to 5.2
I have upgraded my rails version of a project from 4.2 to 5.2.1 some of my tests are failed because of pg connection closed error on the full trace is is as following.
Failure/Error: DatabaseCleaner[:active_record].clean_with(:truncation)
ActiveRecord::StatementInvalid:
PG::ConnectionBad: connection is closed: TRUNCATE TABLE "public"."alerts", "public"."article_attachments", "public"."article_check_specification_tolerances", "public"."article_machine_part_settings", "public"."articles", "public"."attachments", "public"."check_batches", "public"."check_groups", "public"."check_specification_machine_types", "public"."check_specification_priorities", "public"."check_specification_responsibility_areas", "public"."check_specifications", "public"."checks", "public"."comments", "public"."counters", "public"."customers", "public"."defect_groups", "public"."defect_translations", "public"."defects", "public"."delayed_jobs", "public"."furnaces", "public"."gv_area_equipments", "public"."gv_areas", "public"."gv_components", "public"."gv_entries", "public"."gv_equipment_families", "public"."gv_equipments", "public"."gv_squads", "public"."gv_stop_reasons", "public"."gv_sub_equipment_components", "public"."gv_sub_equipments", "public"."job_specifications", "public"."jobs", "public"."lab_recipe_versions", "public"."lab_recipes", "public"."lines", "public"."machine_downtimes", "public"."machine_groups", "public"."machine_part_change_reasons", "public"."machine_part_changes", "public"."machine_part_translations", "public"."machine_parts", "public"."machine_type_group_machine_types", "public"."machine_type_groups", "public"."machine_types", "public"."messages", "public"."mold_sets", "public"."packing_schemes", "public"."rails_admin_settings", "public"."reasons", "public"."rejects", "public"."responsibility_areas", "public"."roles", "public"."settings", "public"."shift_definitions", "public"."shifts", "public"."system_log_entries", "public"."task_status_changes", "public"."tasks", "public"."tresholds", "public"."user_responsibility_areas", "public"."users", "public"."users_roles", "public"."workstations", "public"."machines", "public"."systematic_rejects", "public"."systematic_reject_machines" RESTART IDENTITY CASCADE;
and my rspec configurations are
RSpec.configure do |config|
config.around(:each) do |example|
DatabaseCleaner[:active_record].clean_with(:truncation)
# DatabaseCleaner.clean_with(:truncation)
DatabaseCleaner.cleaning do
example.run
end
end
end
strange thing is I can run tests one by one directory like
rspec spec/controllers/
rspec spec/contexts/
rspec spec/models
but it does not work when I try to run all in one with just
rspec spec/featues/
my feature_helper.rb is
require 'spec_helper'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'capybara/rails'
require 'rack/handler/puma'
require 'support/shared_activerecord_connection'
require 'support/feature_macros'
Capybara.register_server :puma do |app, port, host|
require 'rack/handler/puma'
Capybara.asset_host = "http://#{host}:#{port}"
Rack::Handler::Puma.run(app, Host: host, Port: port, Threads: '0:4', Silent: true, config_files: ['-'])
end
Capybara.configure do |config|
config.server = :puma
end
RSpec.configure do |config|
config.before(:suite) do
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
end
end
require 'spec_helper'
require 'counter_column_fix'
RedisStore.class_eval do
def self.new_instance
$redis = Redis.new(Rails.configuration.redis_config)
end
end
what should I do to remove this error?
A:
DatabaseCleaner isn’t generally needed with Rails 5.1+ . Remove all references to it from your project and enable transactional testing in your RSpec config
| {
"pile_set_name": "StackExchange"
} |
Q:
collect_list keeping order (sql/spark scala)
I have a table like this :
Clients City Timestamp
1 NY 0
1 WDC 10
1 NY 11
2 NY 20
2 WDC 15
What I want as an output is to collect all the cities based on the timestamp (each timestamp has a unique city per user). But without displaying the timestamp. The final list must only contains the cities in order. So, for that example, it gives something like this :
Clients my_list Timestamp
1 NY - WDC - NY
2 WDC - NY
Maybe, I should generate a list using timestamp. Then remove the timestamp in this list. I don't know...
I am using spark sql with scala. So,I tried to use collect_list in both sql or in scala but it seems that we lose the ordering after using it.
Can you help me to fix this issue ?
A:
# below can be helpful for you to achieve your target
val input_rdd = spark.sparkContext.parallelize(List(("1","NY","0"),("1","WDC","10"),("1","NY","11"),("2","NY","20"),("2","WDC","15")))
val input_df = input_rdd.toDF("clients","city","Timestamp")
val winspec1 = Window.partitionBy($"clients").orderBy($"Timestamp")
val input_df1 = input_df.withColumn("collect", collect_list($"city").over(winspec1))
input_df1.show
Output:
+-------+----+---------+-------------+
|clients|city|Timestamp| collect|
+-------+----+---------+-------------+
| 1| NY| 0| [NY]|
| 1| WDC| 10| [NY, WDC]|
| 1| NY| 11|[NY, WDC, NY]|
| 2| WDC| 15| [WDC]|
| 2| NY| 20| [WDC, NY]|
+-------+----+---------+-------------+
val winspec2 = Window.partitionBy($"clients").orderBy($"Timestamp".desc)
input_df1.withColumn("number", row_number().over(winspec2)).filter($"number" === 1).drop($"number").drop($"Timestamp").drop($"city").show
Output:
+-------+-------------+
|clients| collect|
+-------+-------------+
| 1|[NY, WDC, NY]|
| 2| [WDC, NY]|
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the version of Java that CDH uses
I currently have CDH 5 installed on CentOS 6.5 with java jdk1.7 and I am trying to get CDH to use jdk1.8.
I do know that Java 1.8 is not a recommended version of CDH, but it is only a test cluster, so it isn't a big deal.
I have installed both Java 1.7 and Java 1.8 from Oracle's website using the RPM installation, so both versions of Java are currently under /usr/java. Using ls -ld my Java directory looks like:
/usr/java/default -> /usr/java/latest
/usr/java/jdk1.7.0_75
/usr/java/jdk1.8.0_31
/usr/java/latest -> /usr/java/jdk1.8.0_31
I also have script set up in /etc/profile.d to set $JAVA_HOME to /usr/java/default. The contents of my profile.d script:
export JAVA_HOME=/usr/java/default
export PATH=${JAVA_HOME}/bin:${PATH}
So when felt that I have this right, I run:
$ which java
/usr/java/default/bin/java
Telling me that it is pointing to the version of Java symlinked in default. And to determine which version of java is running, I run:
$ java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
And I can see that I have Java 1.8 currently running.
Everything seems great, except when I try to start a Hadoop service. The easiest to start is ZooKeeper, because it only has one service. HDFS has multiple servers so it is more work that to just start and stop ZooKeeper.
Starting ZooKeeper is done with the following command:
$ sudo service zookeeper-server start
Then to check which version of java it is running, I search the running processes list for java:
$ ps -ef | grep java
495 7170 1 7 12:27 ? 00:00:00 /usr/java/jdk1.7.0_75/bin/java -Dzookeeper.datadir.autocreate=false -Dzookeeper.log.dir=/var/log/zookeeper -Dzookeeper.root.logger=INFO,ROLLINGFILE -cp /usr/lib/zookeeper/bin/../build/classes:/usr/lib/zookeeper/bin/../build/lib/*.jar:/usr/lib/zookeeper/bin/../lib/slf4j-log4j12.jar:/usr/lib/zookeeper/bin/../lib/slf4j-log4j12-1.7.5.jar:/usr/lib/zookeeper/bin/../lib/slf4j-api-1.7.5.jar:/usr/lib/zookeeper/bin/../lib/netty-3.2.2.Final.jar:/usr/lib/zookeeper/bin/../lib/log4j-1.2.16.jar:/usr/lib/zookeeper/bin/../lib/jline-0.9.94.jar:/usr/lib/zookeeper/bin/../zookeeper-3.4.5-cdh5.3.0.jar:/usr/lib/zookeeper/bin/../src/java/lib/*.jar:/etc/zookeeper/conf::/etc/zookeeper/conf:/usr/lib/zookeeper/*:/usr/lib/zookeeper/lib/* -Dzookeeper.log.threshold=INFO -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /etc/zookeeper/conf/zoo.cfg
I know that runs off the screen, bu the important part is that Zookeeper is being started by /usr/java/jdk1.7.0_75/bin/java.
To fix this, I have tried a few things:
Looking at the conf files for Hadoop and ZooKeeper under /etc/hadoop/conf and /etc/zookeeper/conf, respectively.
I found nothing setting JAVA_HOME.
Looking at the /usr/bin/zookeeper script to see if JAVA_HOME was set elsewhere,
I did find the script /usr/lib/bigtop-utils/bigtop-detect-javahome has the ability to set JAVA_HOME, but my profile.d script overrides that.
Manually moving /usr/java/jdk1.7 to /tmp.
Sadly, this is the only thing that works. When I move the jdk1.7 dir to another directory, and start ZooKeeper, it will use Java 1.8. Moving the jdk1.7 dir back, reverts to ZooKeeper using Java 1.7.
Has anyone dealt with this problem and does anyone know how to deal with this? I feel that I have Java set up correctly, but something is telling ZooKeeper/Hadoop to use an old version of Java?
A:
I hate to answer my own questions, but here is the answer:
The wrong version of $JAVA_HOME is getting set for 2 reasons:
Using the command service removes most environmental variables. From man service:
service runs a System V init script in as predictable environment as
possible, removing most environment variables and with current work-
ing directory set to /.
The /usr/lib/bigtop-utils/bigtop-detect-javahome script has the ability to be configured with the environment variable BIGTOP_JAVA_MAJOR to manually set which version of Java to use. I tried setting this as an environment variable, but service removes it :(. It is also important to note that this script will find all versions of java installed, but the order of preference is Java 6, Java 7, Java 8, Open Java. So if you have Java 6, and 8 installed, it will prefer 6 over 8.
In short, to fix my problem, I added the following to the top of /usr/lib/bigtop-utils/bigtop-detect-javahome:
BIGTOP_JAVA_MAJOR=8
You can also set JAVA_HOME in this file to specify a specific version or path.
A:
I came here because I was looking for ways to upgrade JDK from 1.7 to 1.8 on the latest Coudera QuickStart VM 5.8 (can't believe they still ship it with JDK1.7 by default!). The hints and suggestions in the above answers helped tremendously - but since they were not listing complete steps to achieve the upgrade - I thought I would add that to help others like me.
So, here is a complete set of steps to upgrade Cloudera QuickStart VM from JDK1.7 to 1.8:
check your current JDK version - out-of-the-box it is:
[cloudera@quickstart ~]$ java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)
download desired version of JDK1.8.xx - in my case: jdk-8u111-linux-x64.tar.gz
as user 'cloudera':
untar and move the resulting jdk1.8.0_111 dir to the /usr/java dir:
tar xzf jdk-8u111-linux-x64.tar.gz
sudo mv -f jdk1.8.0_111 /usr/java
shutdown all Hadoop services:
$ for x in `cd /etc/init.d ; ls hadoop-*` ; do sudo service $x stop ; done
update bigtop-utils file - set JAVA_HOME to your new JDK:
sudo vi /etc/default/bigtop-utils
updated lines:
# Override JAVA_HOME detection for all bigtop packages
export JAVA_HOME=/usr/java/jdk1.8.0_111
update 'cloudera' user's .bash_profile - export JAVA_HOME and add update PATH:
export JAVA_HOME=/usr/java/jdk1.8.0_111
PATH=$JAVA_HOME/bin:$PATH:$HOME/bin
export PATH
restart your VM
check Java version - should be the 1.8 one now:
[cloudera@quickstart ~]$ java -version
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
By the way, I did not setup the /usr/java/default with the 'latest' sym link as @milk3422 did, for the sake of simplicity, but it would have worked just as well.
thanks!
| {
"pile_set_name": "StackExchange"
} |
Q:
Update #f="ngForm" variable after editing profile
I`m using Angular 7 and reactive forms to create Edit Profile page.
I have all my input values filled in from database. If I want to change first name and last name for example, clicking the update button, everything is looking fine, all fields are updated.
The problem is that if I want to update again only the first name, after clicking the update button, last name has intial value.
So, the problem is that my variable #f="ngForm" is keeping old values (first values) and somehow after update process, #f variable has again first values.
<form [formGroup]="patientEditForm" #f="ngForm" (ngSubmit)="editPatientProfile(f)">
editPatientProfile(f: NgForm ) {
this.submitted = true;
this.isRequesting = true;
this.errors = '';
if (f.valid) {
this.userService.editPatientProfile(this.patientId,
this.patient.nin,
f.value.firstName,
f.value.lastName,
this.email,
f.value.password,
f.value.city,
f.value.country,
f.value.birthdate,
f.value.phoneNumber)
.finally(() => this.isRequesting = false)
.subscribe(
result => {
if (result) {
this.router.navigate(['/patient/account']);
localStorage.setItem('displayMessage1', "true");
window.location.reload();
}
},
errors => this.errors = errors);
}
}
<input type="email" value="{{patient.email}}" disabled class="form-control mb-2 mr-sm-2 mb-sm-0">
this.patientEditForm = this.formBuilder.group({
lastName: ['Test', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
firstName: ['Test', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
phoneNumber: ['0745119974', [Validators.required, Validators.pattern("[0-9]+")]],
birthdate: ['1996-02-10', [Validators.required,this.validateDOB.bind(this)]],
city: ['Iasi', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(35), this.validatePasswordConfirmation.bind(this)]],
country: ['Romania', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]]
});
A:
Finally, I solved the problem by setting the new proprieties in subscrive event:
private getPatient() {
this.userService.getPatient(this.patientId)
.subscribe((patient: PatientProfile) => {
this.patient = patient;
this.patientEditForm.controls['lastName'].setValue(patient.lastName);
this.patientEditForm.controls['firstName'].setValue(patient.firstName);
this.patientEditForm.controls['phoneNumber'].setValue(patient.phoneNumber);
this.patientEditForm.controls['birthdate'].setValue(patient.birthdate);
this.patientEditForm.controls['city'].setValue(patient.city);
this.patientEditForm.controls['country'].setValue(patient.country);
},
errors => this.errors = errors
);
| {
"pile_set_name": "StackExchange"
} |
Q:
Return Text From Lookup Field in Javascript
I have a Javascript button that creates an Opportunity from a Case. One of the fields in the new Opportunity is a Contact lookup field that needs to be pre-populated with the Contact field on the Case. All works fine unless the Contact name contains an apostrophe, then the Javascript throws an error that I'm missing a ). Does anyone know how to get the text of the Contact field from the Case? I tried using JSENCODE, but that end us returning the Contact ID.
{!REQUIRESCRIPT("/soap/ajax/36.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/36.0/apex.js")}
var query = "SELECT FirstName,LastName FROM Contact WHERE Id = '{!Case.ContactId}' limit 1";
var CName = sforce.connection.query(query);
ConName = CName.getArray("ConName");
console.log('###'+ConName);
var myCon1 = ConName[0].FirstName;
window.open('/006/e?retURL={!Case.Id}&accid={!Account.Id}&RecordType=012a0000001Fsxa&opp11=Quote&00Na000000BODU0=Small Quote&opp3={!Case.Account} - Quote&opp9={!TODAY()+30}&CF00Na000000BAz6W='+myCon1+' '+myCon.LastName+'&ent=Opportunity');
A:
This is where the issue is with your code
ConName = CName.getArray("ConName");
console.log('###'+ConName);
You are asking the system to getArray by name "ConName". when you query using sforce.connection you get the result bask in the following format
$$$$${done:'true', queryLocator:null, records:{type:'Contact',
Id:null, FirstName:'test', LastName:'dasfsdfsd', }, size:'1', }
In the above response the only array you see is "records" so your CName,getArray("ConName") is coming back undefined because there is no array by name ConName.
Solution:
Change this to
var ConName = CName.getArray("records");
| {
"pile_set_name": "StackExchange"
} |
Q:
function in javascript is not defined
i have this js and qunit test below. why the browser gave me the listClasses is not defined? How to solve it. I saw mostly did
function ajax() {
$.ajax({
});}
but if i did like below how to do the test?
$('#MregisteredClasses').on('pageinit', function listClasses(){
var rowInput = "1";
var pageInput = "1";
$.ajax({
url: 'http://137.57.102.146:8080/Training/getRegisteredClassesData.html',
data: ( {rows : rowInput , page : pageInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = "<li data-mini='true' id='icon'><a href='http://137.57.102.146:8080/Training/MRegisteredClassesDetail.phone?courseId="
+ [json_results.rows[key].courseId] + "®No=" + [json_results.rows[key].regNo] +
"' rel='external'>" + json_results.rows[key].courseName+ "</a>"
+ "<a href='http://137.57.102.146:8080/Training/MRateCourse.phone?courseId="
+ [json_results.rows[key].courseId] + "®No=" + [json_results.rows[key].regNo] +
"' rel='external'>RATE THIS COURSE</a></li>" ;
listItems.append(html);
});
$('#list ul').listview();
},
});
});
and this is qunit test
test('asynchronous test', function() {
// Pause the test, and fail it if start() isn't called after one second
stop();
listClasses(function() {
// ...asynchronous assertions
ok(true, "Success");
});
setTimeout(function() {
start();
}, 2000);
});
A:
$('#MregisteredClasses').on('pageinit', function listClasses(){ ... is incorrect usage.
The function either needs to be anonymous (i.e. drop the listClasses bit) in which case running listClasses() will fail.
What you need to do is externalise the function declaration.
i.e.:
function listClasses(){
var rowInput = "1";
var pageInput = "1";
$.ajax({
url: 'http://137.57.102.146:8080/Training/getRegisteredClassesData.html',
data: ( {rows : rowInput , page : pageInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = "<li data-mini='true' id='icon'><a href='http://137.57.102.146:8080/Training/MRegisteredClassesDetail.phone?courseId="
+ [json_results.rows[key].courseId] + "®No=" + [json_results.rows[key].regNo] +
"' rel='external'>" + json_results.rows[key].courseName+ "</a>"
+ "<a href='http://137.57.102.146:8080/Training/MRateCourse.phone?courseId="
+ [json_results.rows[key].courseId] + "®No=" + [json_results.rows[key].regNo] +
"' rel='external'>RATE THIS COURSE</a></li>" ;
listItems.append(html);
});
$('#list ul').listview();
}
});
}
Then call the function from the on command:
$('#MregisteredClasses').on('pageinit', listClasses)
Assuming your script only failed on listClasses(), then I would assume that the listClasses name is just dropped silently.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to have Code Analysis warnings formatted like normal ones?
I like the code analysis included in VS2012. But it's a bit annoying that the warnings are only processable in the Code Analysis window, and not by stepping through the build output with F4.
Is there a way to overcome this limitation? How could I format the output of the static code analysis like normal compiler output (i.e. don't only print the filename but the correct path to the file being inspected)?
I'm not using FxCop since I'm working with unmanaged code.
A:
For unmanaged code analysis, the MSBuild scripts use /analyze:quiet instead of /analyze in order to prevent writing results to the error list. The simplest way to change the behavior would be to modify your Microsoft.CodeAnalysis.Targets file (typically located at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\CodeAnalysis\Microsoft.CodeAnalysis.Targets) to avoid specifying quiet mode. i.e.: Change the line
<AdditionalOptions Condition="'$(PlatformToolsetVersion)'>='110'">%(ClCompile.AdditionalOptions) /analyze:quiet</AdditionalOptions>
to
<AdditionalOptions Condition="'$(PlatformToolsetVersion)'>='110'">%(ClCompile.AdditionalOptions) /analyze</AdditionalOptions>
| {
"pile_set_name": "StackExchange"
} |
Q:
Possibility of determining a certain length in a triangle.
The figure is on the bottom of the question.
Suppose I have a triangle $ABC$ with an additional point $M$ on the middle of $AB$. Suppose that I know the following three quantitites, where $\ell(\cdot)$ represents the lenth of the line.
$y:=\ell(AM)$
$k:=\ell(AC) - \ell(CM)$
$l:=\ell(BC) - \ell(CM)$
Is it possible to determine $x:=\ell(CM)$? And if so, is this value unique?
Thank you in advance.
EDIT:
A:
The 2nd and 3rd values determine two hyperbolas (with foci respectively $M,A$ and $M,B$).
The point C is the intersection of these two hyperbolas.
So yes, it's possible.
We first draw $A,B,M$, this we can obviously do. Then we draw the two hyperbolas, we see where they intersect, and that determines $C$ (I do not say it's a unique $C$, maybe there are more than $1$ or maybe $0$ solutions for $C$, I didn't investigate that).
See also: Hyperbola
| {
"pile_set_name": "StackExchange"
} |
Q:
Debugging dynamic sql + dynamic tables in MS SQL Server 2008
I have a messy stored procedure which uses dynamic sql.
I can debug it in runtime by adding print @sql; where @sql; is the string containing the dynamic SQL, right before I call execute (@sql);.
Now, the multi-page stored procedure also creates dynamic tables and uses them in a query. I want to print those tables to the console right before I do an execute, so that I know exactly what the query is trying to do.
However, the SQL Server 08 does not like that. When I try:
print #temp_table; and try to compile the S.P. I get this error:
The name "#temp_table" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Please help.
EDIT:
I am a noob when it comes to SQL. However, the following statement: select * from #tbl; does not print anything to the console when it is run non-interactively; the print statement works though.
The following statement has incorrect syntax: print select * from #tbl;. Is there a way for me to redirect the output of select to a file, if stdout is not an option?
Thanks.
A:
When we use dynamic SQl we start by having a debug input variable in the sp (make it the last one and give it a default value of 0 (to indicate not in debug mode that way it won't break existing code calling the proc).
Now when you run it in debug mode, you print instead of execute or you print and execute but you always rollback at the end. If you need to see the data at various stages, the best thing to do is the second. Then before you rollback you put the data you want to see into a a table varaiable (This is important it can't be a temp table). after the rollback, select from the table variable (which did not go out of scope with the rollback) and run your print tstatments to see the queries which were run.
| {
"pile_set_name": "StackExchange"
} |
Q:
Who chooses test questions in the review queue?
Some questions in the review queue are there only to test the reviewer. Who chooses those?
A:
From the capital-M Meta FAQ on review audits,
Review audits are chosen automatically. The system isn't perfect, meaning that every so often a post slips through normal community detection, causing the system to expect the wrong type of action against a post.
The answer goes into a little bit more detail about the criteria, for some of these. For example, questions that are "highly-voted with no close votes" can be chosen as tests where the reviewer is expected to keep vote to leave open.
| {
"pile_set_name": "StackExchange"
} |
Q:
Method Calls without using flags
I have a method that I want to call from two different places on the same class where in one it calls a dialog normally and on the other it calls the dialog with one disabled field on it.
I know that passing a flag on the call and making the test inside the method works but is there a more optmized way of doing it?
Is there any way to inside the method knowing where the call happened?
edit:
// The part where you call the method passing a flag.
showItemCustomDialog(true);
showItemCustomDialog(false);
// The dialog
public void showItemCustomDialog(boolean flag) {
customDialog = new Dialog(this));
field.setEnabled(flag);
}
Is that a good example?
A:
Ultimately you're going to need to do some kind of test to know whether or not you need to disable the field, and you test on boolean values, so the easiest way to get that boolean is to simply pass it. Parameter passing of any kind, primitives, objects, etc., is relatively cheap, so performance wise, there isn't really any issue with this.
In terms of design, it makes sense to use the parameter since this is indeed the purpose of a boolean value, to indicate to do one thing or another whether it's true or false.
Any other solution you come up with is going to be either nasty or slow (I'm looking at you, Thread.currentThread().getStackTrace() people) and is going to require you to test some value, but you'll have to calculate that value first, which takes time.
If you really don't want to pass the parameter, then maybe you can use some kind of state within the object to decide this, but ultimately that will just be a boolean field instead of a boolean parameter, so really, you're just doing the same thing. Plus, if you run that code in any kind of concurrent system, then you'll have to add synchronization, which just further increases code complexity you could have avoided by passing it as a parameter.
I guess, long story short, just use a parameter. It's sensible, readable, and anyone who reads your code will immediately understand what you did. Don't do things in your code that are vague, that will hinder readability, etc. just because it will "do something cool" like make it so you don't have to pass a parameter. Think of it like this: if someone wanted to call that method from some other method besides the ones you added, how long would it take them to figure out how to call it?
Edit: One other option would be overloading. You could provide some common default-valued method and a method with the parameter. If you find that you enable the field more often than you disable it:
public void showDialog() {
showDialog(true);
}
public void showDialog(boolean fieldEnabled) {
// Show the dialog
}
Then everywhere that opens the dialog with it enabled will call the first method (or the second with true), and the ones that want it to be disabled call the second one and have to pass false.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem of to less space in table of contents
I have the problem that the space between the part number and the part name in my table of contents is too small. I tried a lot of solutions which I found on the internet but nothing happened.
Could you help me with the space between part number and part name of the table of contents?
Here is a small example of my problem with the settings used by me. I prefer not to change the document class.
Thanks a lot Latex community :)
Here the example with part "Audi" making the problem:
\documentclass[a5paper,pagesize,14pt,bibtotoc,pointlessnumbers,
normalheadings,DIV=9,twoside=true]{scrbook}
\KOMAoptions{DIV=last}
\setlength{\parindent}{0pt}
\usepackage{trajan}
\usepackage{graphicx}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[babel,german=guillemets]{csquotes}
\usepackage[sc]{mathpazo}
\linespread{1.05}
\usepackage{verbatim} % for comments
\usepackage{listings} % for comments
\usepackage[justification=centering]{subfig}
\usepackage{blindtext}
\setlength{\parindent}{0pt} %Wenn Absatzabstand, dann Einzug unnötig
\usepackage{vmargin}
\usepackage{here}
\usepackage{chngcntr}
\begin{document}
%=========================================
\setcounter{tocdepth}{0} % Show sections
\tableofcontents
\thispagestyle {empty}
%=========================================
\part{Porsche}
\part{Mercedes}
\part{Volkswagen}
\part{BMW}
\part{Toyota}
\part{Fiat}
\part{McLaren}
\part{Audi}
\part{Opel}
\end{document}
A:
To change with KOMA-Script the distance between number and text you can use
\RedeclareSectionCommand[tocnumwidth=2.5em]{part}
Your used options for KOMA-Script are old ones. With an current version of KOMA-Script you should use the following options (check your log file for warnings!):
\documentclass[%
paper=a5,
pagesize,
fontsize=14pt,
bibliography=totoc,
numbers=noenddot,
headings=normal,
DIV=9,
twoside=true
]{scrbook}
Some of the packages you use are obsolete and schould not be used any longer.
Please have a look to the following MWE
\documentclass[%
paper=a5,
pagesize,
fontsize=14pt,
bibliography=totoc,
numbers=noenddot,
headings=normal,
DIV=9,
twoside=true
]{scrbook}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{trajan} % <============================================= ???
\usepackage[sc]{mathpazo}
\usepackage{graphicx}
\usepackage[babel,german=guillemets]{csquotes}
\usepackage{verbatim} % for comments
\usepackage{listings} % for comments
\usepackage[justification=centering]{subfig} % caption/subcaption ??
\usepackage{blindtext}
%\usepackage{vmargin} % <===== obsolete, use geometry or KOMA-Script
%\usepackage{here} % <===== obsolet, use float
%\usepackage{chngcntr}
%\setlength{\parindent}{0pt} %Wenn Absatzabstand, dann Einzug unnötig
\linespread{1.05}
\RedeclareSectionCommand[tocnumwidth=2.5em]{part} % <===================
\begin{document}
\setcounter{tocdepth}{0} % Show sections
\tableofcontents
\thispagestyle {empty}
%=========================================
\part{Porsche}
\part{Mercedes}
\part{Volkswagen}
\part{BMW}
\part{Toyota}
\part{Fiat}
\part{McLaren}
\part{Audi}
\part{Opel}
\end{document}
with the resulting toc:
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get req and res in a Sailsjs service?
I've recently started using services in sailsjs to cut down on code in my controllers. Heres's an example of how I call a function in my service:
ValidationService.addError(req,res,'Password is too short.');
Notice I pass req and res to my service. Why arent these already available? How can I add them to the service so I dont always have to explicitly pass them?
As requested, here is the code in my service:
var errorCss = 'alert-danger';
var successCss = 'alert-success';
module.exports = {
init : function(req,res){
req.session.flash = {};
req.session.flash.alert = {};
req.session.flash.alert.data = [];
req.session.flash.alert.result = 'pass';
},
addError : function(req,res,error){
req.session.flash.alert.data.push(error);
req.session.flash.alert.css = errorCss;
req.session.flash.alert.result = 'fail';
},
addSuccess: function(req,res,success){
req.session.flash.alert.data.push(success);
req.session.flash.alert.css = successCss;
},
isValid : function(req,res){
if ((req.session.flash.alert.result == 'pass')){
return true;
}
return false;
},
clear : function(req,res){
delete req.session.flash;
}
}
A:
I'm sure you read this already, but take another look at the definition of the Sails services. This, basically, means that you can have in your services any common code, not necessarily something dealing with request and response. For example, there can be a part of your application that you are running from the command line: there will be no request or response in this case, but you still want to be able to use your services.
Bottom line, you are doing it right already by passing req/res. (Just don't overdo it: you should only create services for the code you are using in multiple places, doing it for every controller doesn't make sense).
| {
"pile_set_name": "StackExchange"
} |
Q:
Хранение дополнительных данных в Laravel
Подскажите, пожалуйста, как в Laravel хранить данные о пользователе после его авторизации?
К примеру, есть таблица users и в ней только базовая информация о пользователе (использовать данные после авторизации из таблицы я могу - $user = Auth::user();), так же есть таблица к примеру options, которая хранит данные о настроенном пользователем интерфейсе веб приложения.
Так вот, после авторизации (реализована через middleware) как единожды подгрузить дополнительные данные о пользователе и каким образом после их передавать по мере действий клиента и перезагрузки страницы (соответственно переходы между контроллерами). Есть ли какой-то специальный механизм в Laravel или использовать обычные session ?
A:
Сделайте модель для опций, например UserOptions
Добавьте в модель User связь с опциями:
class User extends Authenticatable {
//...
public function options () {
return $this->hasOne('App\UserOptions');
}
//...
}
В шаблонах после $user = Auth::user(); можете теперь использовать $user->options
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable HDMI Interface to achieve a lower power footprint
Is it possible, to turn off the HDMI video component? My Pi operates headless so there ist no need for me to have a video out component.
If yes, how much power will be saved?
A:
I think you can just switch it off, but I do not know how much power is saved.
Switch off
/opt/vc/bin/tvservice -o
Switch on
/opt/vc/bin/tvservice -p
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Object API name of any Lookup field
I have requirement where I need the object name of any lookup field on any object.
for fetching lookup field I am using Schema class
Schema.DescribeFieldResult f = Schema.sObjectType.CustomOpportunity__c.fields.CustomTask__c;
for(Schema.SObjectType reference : f.getReferenceTo()) {
System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}
This gives me the name and API name of the lookup object but I want to make it for any object so I changed above code to below
String objectName = 'CustomOpportunity__c';
String fieldName = 'CustomTask__c';
Schema.DescribeFieldResult f =
Schema.sObjectType.objectName.fields.fieldName;
for(Schema.SObjectType reference : f.getReferenceTo()) {
System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}
I know that It will throw an error saying Schema.SObjectType.objectName.fields does not exist or something.
I want to make this function generic function where I can pass the objectName and lookup fieldName and it returns me the Lookup object API name and Label Name.
A:
Use Schema.getGlobalDescribe() method that accepts String as API name of object and then use getMap() method to get map of SObjectFields
String objectName = 'Opportunity';
String fieldName = 'AccountId';
Schema.DescribeFieldResult f = Schema.getGlobalDescribe()
.get(objectName)
.getDescribe()
.fields
.getMap()
.get(fieldName)
.getDescribe();
for(Schema.SObjectType reference : f.getReferenceTo()) {
System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Lay or Lie in "what powers lies between their hands"?
This is for sure a duplicate question, but I'm sorry I'm just getting confused no matter how many articles I read. In the sentence,
And still they are not aware what powers lies between their hands!
Should this be lays, lies? And what should it be if the tense were changed to "were not aware"?
A:
And still they are not aware what powers lie between their hands!
And still they were not aware what powers lay between their hands!
B1 [ I + adv/prep, L ]
present participle lying
past tense lay
past participle lain
If something lies in a particular place, position, or direction, it is
in that place, position, or direction
Lie (Cambridge)
Lie (Collins)
English verb: to lie
Present tense:
Singular: I lie, you lie, he/she/it lies.
Plural: we lie, you lie, they lie.
Past tense:
Singular: I lay, you lay, he/she/it lay.
Plural: we lay, you lay, they lay.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is $C$ weakly closed?
following question jumped into my mind.
Let $X$ be a Banach space. Let $C$ be a nonempty subset of $X$. Set
$$A : = \{ x \in X \;|\; \exists \text{ a norm-bounded net } x_{i} \to x \text{ (weakly) } \, \forall i: x_i \in C \}$$
Question 1 : Is $A$ actually the entire weak-closure of C?
Question 2 : Is $A$ weakly closed set?
I'm positive that the answer of 1 is NO, but dont have explicit example. This is because in any infinite dimension space one can construct a net $x_i$ such that $\| x_i \| \to \infty$ but $x_i \to 0~(weakly)$.
Question 2 is harder, I tried to prove it, I had to go through some diagonal process regarding for index sets, which was kinda impossible !! Now I changed my mind, and start to find a counter example instead of proving it.
Any help would be greatly appreciated.
A:
The answer to both questions is negative. Here are some counterexamples in $\ell^2$.
For
$$C := \{ e_n + n \, e_m \mathrel\mid n,m \in \mathbb N,\; n < m \}$$
one hase
$$A = C \cup \{ e_n \mathrel\mid n \in \mathbb N \}$$
but the weak closure of $C$ contains $0$. The set $A$ is also not weakly closed.
For another example, you can take
$$ C:= \{ \sqrt{n} \, e_n \mathrel\mid n \in \mathbb N\}.$$
Then, $A = C$, but again, the weak closure of $C$ contains $0$.
Conclusion: nets are weird.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why didn't Eru and/or the Valar intervene when Sauron corrupted Númenor?
Given that Sauron spent a whopping 47 years (Second Age 3262-3319) in Númenor corrupting the people and making them do unspeakable things (burning Nimloth, human sacrifice, Morgoth worship, slaughtering the wild men of Middle-earth, the Great Armament), why didn't the good Powers stop him at the outset?
One wonders if the Powers truly cared about the race of Men, the Secondborn Children of Eru...
A:
The first thing you need to understand about Tolkien's writing is that even though he was being influenced by Norse mythology, he himself was a Catholic and that shaped what he wrote. It's why he waffled so much on the nature of orcs, because Catholic theology said that the Devil couldn't create but he needed the orcs to be a race of disposable mooks with no moral agency for the plot. It's why Gandalf got a power upgrade after his death and resurrection, because contact with holiness topped up his spiritual tank.
And in Catholic theology, God is not a micro-manager. He allows humankind to choose our way into corruption. Eru (who is God) would not directly intervene or allow his servants to intervene until they were being directly challenged.
A:
There are numerous reasons I elaborated below. And there is also one meta: Why any storytelling works do not eliminate the evil immediately at the beginning? That would set the story unrealistic (compared to human experience) and ultimately there would be no story at all. (Your question could be even rewritten into deeper one: Why Eru didn't destroy Melkor yet before he had chance to disrupt anything in Eru's world?)
Details:
What you describe reflects the fact that intervening by "good powers" is never a straightforward matter. Even in daily reality, if after each transgression of laws there came immediate law enforcement response (from "Eru", from police, from other authorities, whomever...), everyone would end as a kind of a criminal after some time. How do we set a clear line for distinction which, as you wrote, "unspeakable things" are still tolerable and which are not? This always leads to a complex discussion with no end. Also, if the "corrections" would came too quickly, there would be no space for character development through challenges (which is not only a matter of plot construction, but an important aspect of real life, what in turn makes the story more believable).
From supposed Eru's perspective, there is no need to interfere if the things in bigger picture are still under Eru's control and cases of the corruption can be still contained without destroying the entire civilization. The mightier the Powers are, the more space for tolerance they give. Actually, from some viewpoint, there were interferences of Eru inside the books, in those uncountable "details" where protagonists were just "very lucky" to effectively hide at the last moment or to hear something important from the enemy at the right time, to inadvertently find something valuable, to survive uneven battles, to meet key person in the middle of the barren lands/woods etc. So from this perspective, we cannot deny that what happened was influenced. There is even a pun to it in the last chapter of Hobbit (see below). And today, there is a famous quote of Albert Einstein: Coincidence is God's way of remaining anonymous.
“Then the prophecies of the old songs have turned out to be true, after a fashion!” said Bilbo.
“Of course!” said Gandalf. “And why should not they prove true? Surely you don’t disbelieve the prophecies, because you had a hand in bringing them about yourself? You don’t really suppose, do you, that all your adventures and escapes were managed by mere luck, just for your sole benefit? You are a very fine person, Mr. Baggins, and I am very fond of you; but you are only quite a little fellow in a wide world after all!”
“Thank goodness!” said Bilbo laughing, and handed him the tobacco-jar.
A:
For Eru, the history unfolds as it must since the music has been played and history will follow it.
In the published books, Eru is a bit of a jerk here: Melkor's dissonances made Eru's themes stand out better in the music; the consequence is that Melkor's evil will make the story of the world better because it makes Eru's work stand out better.
There's unpublished work with a prophesy that there will be a second Music eventually, and everything that was wronged will be made right. If that's what Tolkien intended (which is unclear), then Eru is accepting a merely temporary evil to make a better story.
For the Valar, the answer is easy: They cared, a lot actually, but Eru had told them to not interfere with mortals.
They were also generally reluctant to punish evildoers, for a multitude of reasons: Partly because they had not yet seen how bad the evildoers really were, partly because they didn't want to overdo punishment and be evil themselves, partly because they knew that any direct action would come with a lot of collateral damage, partly because the amount of evil throughout history was predetermined by the amount of dissonance in the music anyway (the last reason is my speculation, the others have been alluded to in various places in the Silmarillion).
BTW none of these reasons have any relation with Free Will. I don't know if Tolkien ever cared about that specific debate, and as far as I'm aware of his stories, the issue never arises.
The protagonists in his stories generally don't theorize much about ethics; they fail to achieve their goals mostly due to hubris, with a good dose of mistrust, jealousy, and falling to the deception of the evildoers.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSqlDataProvider Complex Query and totalItemCount
I have a very complex query using CSqlDataProvider and I'm trying to get the pagination totalItemCount to work, but it's returning wrong count. I tried to create a second SQL just to COUNT items, but it's really hard, can anyone help me?
CSqlDataProvider Docs: http://www.yiiframework.com/doc/api/1.1/CSqlDataProvider
Controller Code:
$dayofweek = date('w');
$sql = "( SELECT `profile`.`id` as profile_id, `profile`.`name` as profile_name, `events_reminder`.`id`,
CASE WHEN weekday >= $dayofweek
THEN
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL weekday - $dayofweek DAY), ' ', event_time ), '%d/%m/%Y %H:%i')
ELSE
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL 7 - $dayofweek + weekday DAY), ' ', event_time ), '%d/%m/%Y %H:%i')
END as revent_datetime,
CASE WHEN weekday >= $dayofweek
THEN
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL weekday - $dayofweek DAY), ' ', list_time ), '%d/%m/%Y %H:%i')
ELSE
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL 7 - $dayofweek + weekday DAY), ' ', list_time ), '%d/%m/%Y %H:%i')
END as rlist_datetime
FROM events_reminder
LEFT OUTER JOIN `profiles` `profile` ON (`events_reminder`.`profile_id`=`profile`.`id`)
HAVING revent_datetime NOT IN (SELECT DATE_FORMAT(event_datetime, '%d/%m/%Y %H:%i') FROM events WHERE `events`.`profile_id`=`events_reminder`.`profile_id`) )
UNION ALL
( SELECT `profile`.`id` as profile_id, `profile`.`name` as profile_name, `events_reminder`.`id`,
CASE WHEN weekday >= $dayofweek
THEN
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL weekday - $dayofweek + 7 DAY), ' ', event_time ), '%d/%m/%Y %H:%i')
ELSE
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL 7 - $dayofweek + weekday + 7 DAY), ' ', event_time ), '%d/%m/%Y %H:%i')
END as revent_datetime,
CASE WHEN weekday >= $dayofweek
THEN
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL weekday - $dayofweek + 7 DAY), ' ', list_time ), '%d/%m/%Y %H:%i')
ELSE
DATE_FORMAT( CONCAT( DATE_ADD(CURDATE(), INTERVAL 7 - $dayofweek + weekday + 7 DAY), ' ', list_time ), '%d/%m/%Y %H:%i')
END as rlist_datetime
FROM events_reminder
LEFT OUTER JOIN `profiles` `profile` ON (`events_reminder`.`profile_id`=`profile`.`id`)
HAVING revent_datetime NOT IN (SELECT DATE_FORMAT(event_datetime, '%d/%m/%Y %H:%i') FROM events WHERE `events`.`profile_id`=`events_reminder`.`profile_id`) )
ORDER BY revent_datetime";
$count=Yii::app()->db->createCommand($sql)->queryScalar();
$dataProvider=new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
A:
What queryScalar does is:
Executes the SQL statement and returns the value of the first column in the first row of data.
So to use it for getting count you will have to add a count(*) to your sql query, that too in the beginning of the query, like this:
SELECT count(*), `profile`.`id` as profile_id, `profile`.`name` ...
Update:
Since you are using UNION you have to move the count(*) outside, also give an alias:
SELECT count(*) from (((select ...) UNION ALL (select ...)) as alias)
For your exact situation you can do:
$count_sql='SELECT count(*) from (('. $sql .') as alias)';
$count=Yii::app()->db->createCommand($count_sql)->queryScalar();
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up an LP problem on producing linear board in jumbo reels
I have to set up a linear programming problem corresponding to the following scenario:
What I tried:
I think we have 8 templates for 1 $68 \times l$ reel (or whatever):
$22,22,22$ (66)
$20,20,20$ (60)
$12,12,12,12,12$ (60)
$22,22,20$ (64)
$22,20,20$ (62)
$22,20,12,12$ (66)
$22,12,12,12$ (58)
$12,12,12,12,20$ (68)
Let $x_{i,j}$ denote order $j$ from type $i$
for $i = 1,2,...,8$
for $j = 1,2,3$
We want to minimise reels (or whatever) used
$$z = \sum_i \sum_j x_{i,j}$$
s.t.
Nonnegativity:
$$x_{i,j} \ge 0$$
Orders:
$$\sum_i x_{i,1} \ge 110$$
$$\sum_i x_{i,2} \ge 120$$
$$\sum_i x_{i,3} \ge 80$$
Is that right?
From Chapter 2 here.
A:
Your approach, reduce all possible combinations how to cut the jumbo reels to a couple of useful order type cuts, looks very good to me.
Optimization Goal:
Your optimization goal is wrong. You are requested to minimize trim waste.
For this you just need to define the amount of trim waste $w_i$ for each order type $i$ and sum this up multiplied with the order type amounts $x_i$.
E.g. $w_1 = 68\cdot L - 66 \cdot L = 2 \cdot L$. We would just count it in multiples of the fixed length $L$, so we simply say $w_1 = 2$.
Our goal of minimized total waste might be written as:
$$
\min w = \min \sum_i w_i \, x_i
$$
The Constraints:
For each order type $i$ you can define a quantity $n_{ij}$, which describes how many type $j$ reels result from an order of type $i$.
E.g. $n_2 = = (n_{21}, n_{22}, n_{23}) = (0, 3, 0)$, $n_6 = (1,1,2)$.
The constraint of the ordered $j$ reel amounts is e.g.
$$
\sum_i n_{i1} x_i \ge 110
$$
Trim Waste Revisited:
Having those $n_{ij}$ will give you the trim wastes
$$
w_i = 68 - 22 \cdot n_{i1} - 20 \cdot n_{i2} - 12 \cdot n_{i3}
$$
Order Types:
Important for your result is the choice of the order types, which are represented by the $n_{ij}$.
You defined $8$ of them, I do not know if there are more useful order types.
I would consider all with a resulting trim waste
$$
0 \le w_i < 12
$$
and
$$
n_{ij} \ge 0
$$
but different from the null vector.
I would write a small script to determine all by brute force.
Update:
My friend Ruby found $10$ order types, see here. (Source)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can not show Toast in OnItemClickListener inside Fragment
I am trying to create a ListView in a Fragment. The listView appear correctly but when I complied the code shows error.
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ServiceFragment extends Fragment {
private ListView serviceList;
private String[] serviceString;
public ServiceFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_service, container, false);
//build the list service
serviceList = (ListView) rootView.findViewById(R.id.ServiceList);
serviceString = getResources().getStringArray(R.array.service_list);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1,serviceString );
serviceList.setAdapter(objAdapter);
//on click item Listener
serviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) serviceList.getItemAtPosition(position);
int itemPosition = position;
Toast.makeText(ServiceFragment.this,"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG).show();
}
});
return rootView;
}//end of onCreateView
}//end of class ServiceFragment
What's wrong with my code? Why doesn't Toast show up?
is it possible on click item start a detail activity where I can describe the meaning of item
Suppose
List Item = Apple ,Mango, Banana
onClick Item Details view = Apple is a brand or fruit, Banana is a fruit,Mango is a good fruit,
A:
What Wrong with my code ? Why the Toast does not show
Since you are on a Fragment you must use getActivity() instead of yourClass.this.
Change your Toast to this :
Toast.makeText(getActivity(),"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG).show();
EDIT
For a detail Activity you must create an Activity first let's call it DetailActivity then you have to change your onItemClickListener() to this :
serviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) serviceList.getItemAtPosition(position);
int itemPosition = position;
Toast.makeText(getActivity(),"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("DetailProductClicked", itemValue);
startActivity(intent);
}
});
So in your DetailActivity.class you have to put this on your onCreate()
String nameFruit = intent.getStringExtra("DetailProductClicked");
Then depends what you have on this Activity you can do something like :
if (nameFruit.equals("Apple"){
tv.setText(nameFruit +" is a brand or fruit");
}
if (nameFruit.equals("Mango"){
tv.setText(nameFruit +" is a good fruit");
}
if (nameFruit.equals("Banana"){
tv.setText(nameFruit +" is a fruit");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Telerik Radgrid retrieve TextBox value that was dynamically added to column
From code I add a TextBox to a column
protected void grdPartsBeingMonitored_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
TextBox tbEditBox = new TextBox();
tbEditBox.Text = item[column].Text;
tbEditBox.Width = Unit.Pixel(50);
tbEditBox.ID = "editDemand";
item[column].Controls.Clear();
item[column].Controls.Add(tbEditBox);
}
}
}
Now how do I loop through each row and retrieve that rows value of the TextBox? Here's a start I believe:
foreach (GridDataItem item in grd1.MasterTableView.Items)
{
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
//HOW TO RETRIEVE VALUE OF THE TEXTBOX HERE???
I tried this with no luck
foreach (Object c in item[column].Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox tbEditBox = (TextBox)c;
System.Diagnostics.Debug.Write(tbEditBox.Text);
}
}
A:
Please try with the below code snippet.
ASPX
<div>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="Name" DataField="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Show edit" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Get edit value" OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="hide edit" OnClick="Button3_Click" />
</div>
ASPX.CS
public bool IsEditable
{
get
{
if (ViewState["IsEdit"] == null)
return false;
else
return (bool)ViewState["IsEdit"];
}
set
{
ViewState["IsEdit"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Name1");
dt.Rows.Add(2, "Name2");
dt.Rows.Add(3, "Name3");
RadGrid1.DataSource = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
IsEditable = true;
RadGrid1.Rebind();
}
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
Response.Write((item.FindControl("txtName") as TextBox).Text);
//perform your DB update here
}
}
protected void Button3_Click(object sender, EventArgs e)
{
IsEditable = false;
RadGrid1.Rebind();
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
Label lblName = item.FindControl("lblName") as Label;
TextBox txtName = item.FindControl("txtName") as TextBox;
lblName.Visible = !IsEditable;
txtName.Visible = IsEditable;
}
}
Let me know if any concern.
| {
"pile_set_name": "StackExchange"
} |
Q:
Коллективная разработка Eclipse + Android Studio
Здравствуйте!
Возможна ли коллективная разработка под android, используя разные среды?
Я пишу на android studio, коллега - в eclipse. Есть приложение для телефонов, написанное коллегой, мне предстоит написать то же самое для планшетов (основываясь на его коде). Т.к. я неопытный программист, коллега склоняет к тому, чтобы писать на eclipse, и не было каких-то косяков, по-моему, с зависимостями и т.д.
Что же делать? Поддаться давлению?)
A:
Да особых проблем-то нет. Главное, чтобы был одинаковый VCS, смотрящий в одно репо. Каждая IDE будет сохранять свои настройки, но Eclipse будет игнорировать настройки IDE Android Studio, а студии по барабану настройки Eclipse.
Просто в самом начале Eclipse должен выставить в VCS свои исходники, а студия оттуда вытянуть исходники и создать свое окружение на вытянутых исходниках. Далее коммит из студии, и все.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is GObject used much outside of GNOME?
I understand GObject started out as part of gtk+ and was later separated from the GUI related elements. What I would like to know is: it used outside gtk+ ? what about other desktop environments, and other OSs like Windows or Mac OS? Are there any prominent examples of such cases?
A:
There are some things here and there that use GObject without GTK+, but AFAIK they are few and far between.
I'm guessing that the most prominent ones right now are Clutter-based projects (it's a graphics-oriented UI library). There are also a small number of projects based on libgnt (text-based UI library), and possibly various non-GTK+ programs written in Vala (a C#-like programming language with GObject-based classes).
Edit: Also GStreamer (thanks liberforce!), which is a popular multimedia library. The vast majority of GStreamer projects also use GTK+, but I'm sure there are some non-GTK+ ones.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to set the GroupStyle for a ListBox via Style?
I'm trying to create a Style that will set the GroupStyle property for my ListBox controls however I am getting a compile time error:
The Property Setter 'GroupStyle' cannot be set because it does not have an accessible set accessor.
My Style setter looks like this:
<Setter Property="ListBox.GroupStyle">
<Setter.Value>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</Setter.Value>
</Setter>
Is there a work-around for this, and also, if there is no setter for this property, then how are we able to use property-setter syntax for it in XAML to define it inline, in the first place? (still new to WPF)
A:
I just figured out the answer - it's because of the way the XAML compiler treats any content between the element tags, based on the type of the property mapped to the content I just remembered!
If the property is a ContentControl, then the element you define between two tags gets assigned to that Content property, however, if the element is an instance of an IList (which is what GroupStyle is), then .NET actually calls .Add() underneath the covers
In this case, the GroupStyle is actually an ObservableCollection and hence an IList, therefore we are not actually assigning to the GroupStyle object, we are ADDING to the collection.
In otherwords, the type of the property that is represented by content (mapped via the ContentProperty attribute of a control) in between the element tags influences the way the XAML compiler interprets it (direct assignment or calling .Add())
| {
"pile_set_name": "StackExchange"
} |
Q:
Opening and closing UINavigationController
I know it was probably written somewhere about this problem already but I just can't find the solution and am on the problem already for a few days.
I have an application with UITabbar with 4 UINavigationControllers.
On one of this UINavigationControllers there is a UIViewController with a button that opens with modal transition another UINavigationController. On opening everything works normal, but after closing last NC from its UIViewController with code:
self.dismiss(animated: false, completion: nil)
or
self.navigationController?.dismiss(animated: false, completion: nil)
I get a problem.
Whatever the next thing I do, I get a warning Unbalanced calls to begin/end appearance transitions for and on UIViewControllers methods viewWillAppear and viewDidAppear don't get called. But just to make it clear, I don't get this problem only when I open a new view, I also get it if I just switch between tabs to other UINavigationViewController.
I have checked one of the possibilities that I've read about and I' sure that I don't open one thing twice.
I just can't figure out if it is the problem of multiple NavigationControllers or the way I close it or what.
Any suggestion will be helpful.
EDIT1:
Forgot to tell, that the UINavigationController is opened with modal segue, not by code.
All the NC have at least one VC (all 4 on the tabbar and also the one opened later)
EDIT2:
The code that dismisses the VC is run on the last opened VC on last opened NC (not one of the tabbar NC) to return to one of the tabbar NC/ his VC.
To make sure I'll try to write it again
TC -> NC NC NC NC
| | | |
VC VC VC VC
|
NC
|
VC - the one that calls dismiss to return to previous VC
It is just so frustrating that until I open another UINavigationController everything works great, but after that the problem begins. Or too add another thing I noticed, the problem appears after modal presenting another controller, it doesn't matter if it is a UINavigation or just normal ViewController.
EDIT3:
Thanks to @kgkoutio the problem was solved, the mistake I made was that I did't call super.viewDidLoad and super.viewWillAppear somewhere. After adding it to all of VC the problem disappeared.
Again big thanks to @kgkoutio
A:
Your code dismisses the NC not the VC. When the app is started the TabBar is initialized with the set of your Navigation controllers. Consider dismissing the UIViewController instead of NC:
self.navigationController.topViewController?.dismiss(animated: false, completion: nil)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way run a java class when I hit the submit button on my html form?
Is there a way to run a java class when I hit the submit button on an html form? I have this code for my html form: that gets the mean and the standard deviation as inputs.
<form action="Calculation.html" method="get">
<input name="Mean" type="text" style="width:100%">
<input name="Std" type="text" style="width:100%">
<input type="submit" value="Calculate">
</form>
I would like to be able to run code from a java class that does some data analysis on the inputs of this form. But for now I am trying to get a HelloWorld.java class to run when I hit the submit button:
public class test{
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Is there a way to do this?
Thanks in advance for any help!
A:
I think what you're looking for is Java Web Start. That will let you start a Java application from a HTML page, although there are some security restrictions.
You can pass your inputs as arguments to the application as discussed in this thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add textbox value into a list?
I have a list like this :
<p>Please select :</p>
<script type="text/javascript"></script>
<select id='pre-selected-options1' multiple='multiple'>
<option value='elem_1' selected>1</option>
<option value='elem_2'>2</option>
<option value='elem_3'>nextoption</option>
<option value='elem_4' selected>option 1</option>
<option value='elem_100'>option 2</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="js/jquery.multi-select.js"></script>
<script type="text/javascript">
$('#pre-selected-options1').multiSelect();
</script>
</div>
i have a text box and i need to add the text box values into this list. For time being i need it like whenever the page reloads everything entered is reset. Later on i will connect to db.
<label>Enter: </label>
<input type="text" name="" class="input-default"><button type="button" class="btn btn-success btn-sm m-b-10 m-l-5">Add</button>
How to add the value entered in text box to this list on button click?
demo
A:
i am giving you a sample. hope it'll help you out.
<div>
<select id="Select1" name="Select1">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
</select>
<input id="Text1" type="text" />
<input id="Button1" type="submit" value="button" />
</div>
in js using jquery:
$(document).ready(function() {
$("#Button1").click(function() {
$('#Select1').append($("<option>" + $('#Text1').val() + "</option>"));
return false;
});
});
A:
<select id='pre-selected-options1' multiple='multiple'>
<option value='elem_1' selected>1</option>
<option value='elem_2'>2</option>
<option value='elem_3'>nextoption</option>
<option value='elem_4' selected>option 1</option>
<option value='elem_100'>option 2</option>
</select>
<!-- This is the list (above)-->
<br>
<label>Enter: </label>
<input type="text" name="" id="inp" class="input-default">
<button type="button" onclick="add()" class="btn btn-success btn-sm m-b-10 m-l-5">Add</button>
<!-- This is the textbox-->
<script>
function add()
{
var x = document.getElementById("pre-selected-options1");
var option = document.createElement("option");
option.text = document.getElementById("inp").value;
x.add(option);
}
</script>
A:
it may help for you
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var counter = 1;
function enter_task () {
var text = $('#enter_task').val();
$('#todo_list').append('<li><span>'+ text + ' </span><input type="submit" id="edit' + counter + '" value="Edit">' + '<input type="submit" class="done" id="delete' + counter + '" value="Delete">' +'</li>');
$('#edit' + counter).click(function(){
$(this).prev().attr('contenteditable','true');
$(this).prev().focus();
});
$('#delete' + counter).click(function(){
$(this).parent().remove();
});
counter++;
};
$(function() {
$('#add').on('click', enter_task);
});
</script>
<body>
<h1>Todo List</h1>
<input type="text" id="enter_task" placeholder="Enter Task">
<input type="submit" id="add" value="Add Task">
<p>
<ul id="todo_list">
</ul>
</p>
</body>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to group javax validation annotations
public class User {
@NotBlank
@Size(min=2)
private final String firstName;
@NotBlank
@Size(min=2)
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
I want to validate properties firstName and lastName.
But I don't want to repeat the annotations everytime.
How can I create a custom annotation, so the code will be like
public class User {
@UserName
private final String firstName;
@UserName
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
and validation will be the same
A:
Chapter 6. Creating custom constraints. Constraint composition
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails form input fields overflowing with Bootstrap 3 modal dialog
I am using the simple_form gem to make a form in a modal dialog. The issue is that the input fields go over the edge of the modal.
The code cascades as follows: index.html.erb
<div class="row">
<div class="cold-md-2">
<%= link_to "New Author", new_author_path, remote: true, class: "btn btn-primary"%>
</div>
<div id="author-modal" class="modal fade" role="dialog"></div>
</div>
new.js.erb
$('#author-modal').html('<%= escape_javascript(render 'new') %>');
$('#author-modal').modal('show');
_new.html.erb
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h4 class="modal-title" id="myModalLabel">Add New Author</h4>
<%= render 'form'%>
</div>
</div>
</div>
and lastly _form.html.erb
<%= simple_form_for @author, remote: true, html: { class: "form-horizontal" } do |f|%>
<div class="modal-body">
<ul class="errors"></ul>
<div class="form-group">
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :title %>
</div>
</div>
<div class="modal-footer">
<%= f.button :submit, class: "btn btn-primary" %>
<%= link_to "Cancel", "#", class: "btn", data: {dismiss: "modal"}%>
</div>
<% end %>
why isn't the bootstrap default 100% width for form items limited to the modal?
A:
Update the view as below,
<div class="form-group">
<%= f.input :first_name, input_html: { class: "form-control" } %>
<%= f.input :last_name, input_html: { class: "form-control" } %>
<%= f.input :title, input_html: { class: "form-control" } %>
</div>
For width: 100%, you should use form-control class for the input controls.
Refer to Forms Basic Example
Individual form controls automatically receive some global styling.
All textual <input>, <textarea>, and <select> elements with
.form-control are set to width: 100%; by default.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.