text:
Q: Your community's current problems, findings, and initiatives Remember how you started programming? I'd bet that when many of you were kids who played with graphic editors after school and at some point decided to find out what the difference between .img and .exe files was. As a result, you installed Turbo Pascal and instead of working with funny pictures, you tried to add something to the downloaded "Hello World." The typical programming approach at that stage looked like this: "How to increase a counter? - Copy the line with the counter a few times!" Findings like functions or a debugger were no less important than the Theory of Relativity.
Also, do you remember when you made the most progress? Probably, when you met a peer as interested in programming as you. It's likely that during the first month of working together, your knowledge increased more than in the previous year, when you had studied programming alone.
It appears that our international communities are growing and following the same scenario. Consider this:

*

*All international communities start with standard settings on the site.

*Each community faces similar problems that other international communities face at some stage.

*At some point, some of the problems become critical.

*The community, after contributing a lot of time and effort, finds solutions to the critical problems one by one.

*All other international communities do not benefit from those solutions because they do not know what happens on other sites and...

*...they continue to suffer, until the same problems become very critical on their sites as well.

Why not to work together?
The problem
International communities face the same problems again and again, but being isolated, they don't know that their problems have often been solved elsewhere.
Two examples
(1) Site settings
At some point, on Stack Overflow in Russian we had gotten a lot of questions with greetings. Some users began to edit the questions, which resulted in a large number of edits in the review queue. Reviewers became angry at the editors and the community began discussing what to do with these edits, whether it was necessary to edit old questions at all, etc. We began digging and it turned out that on the site there is a setting that configures the engine to remove greetings automatically when a question gets posted. Kind of the same story with the "thank-you" like comments.
(2) Initiatives
The company is constantly improving the site, including the user interface. Sometimes this leads to a loss in translation. The situation is very annoying and all the international communities suffered from it until g3rv4 created traducir.win, which helps to avoid losing translations in the most common cases. Unfortunately, traducir.win is not used by all communities which results in some communities still losing translations.
Proposed solution
I think the international communities can be more effective if we move forward together. The first step towards joint development is to start sharing our problems, findings, and initiatives with all international communities.
The essence of the approach
In the context "Feedback And Initiatives On International Sites", it would be great to keep a list of each community's current problems, findings (aka "solved problems") and initiatives on MSE. For example, in the form presented in the wiki answer to this question.
If you have any ideas about the the initiative, please share it!
At the same time, do not hesitate to add your community's current problems, findings, and initiatives to the list. Even if we change the process based on feedback, the list will help us see the actual situation.

Related:

*

*Spanish: Los problemas, hallazgos e iniciativas actuales de la comunidad (thanks to gbianchi)

*Portuguese: Os problemas atuais, as descobertas e as iniciativas da sua comunidade (thanks to Anderson Carlos Woss)

*Japanese: 各コミュニティが抱える問題や気づき、機能提案をまとめてみませんか? (thanks to aki)

A: List of international communities' current problems, findings, and initiatives
Initiatives

*

*traducir.win

*

*Es: Traduciendo el sitio… Esta vez, con más control sobre el proceso.

*Ja: サイトを翻訳するための新ツールの提案: Traducir.

*Ru: Мы переходим на Traducir.win для перевода интерфейса сайта!

*Pt: Estamos mudando para o Traducir.win para as traduções da interface

*Question associations

*

*Ru: Инструменты ассоциации вопросов между сайтами

*Es: Preguntas con enlaces cruzados: identifiquemos las ya existentes en este sitio (a set of the most viewed questions in SO with a link to its related one in SOes; to do: link them somehow from SO to SOes for users with ES settings in their browser), Herramientas de asociación de preguntas entre SO y SOes

*How to make a decision based on community's feedback.

*

*Es: ¿Cómo deberíamos gestionar las propuestas en Meta para que sus respuestas/encuestas tengan efecto?

*Improving the translations on the Help Center articles by doing pull requests to a repo.

*

*Es: Traduzcamos las páginas y enlaces del "Centro de Ayuda" y de "Privilegios". Articles with some flaws were community-wiki translated and then a pull request was done to a repo of a developer, so he pushed to the Stack Overflow en español site.

*The "Translate from English" help center article

*

*Es: ¿Debería traducir preguntas del inglés al español?

*Ru: Следует ли переводить сообщения с английского языка на русский?

*Ja: 英語版サイトの質問や回答を、日本語に翻訳しても良いですか?

*Pt: Central de Ajuda: Posso traduzir conteúdo de outro site no SOpt? Como?

*Compile list of basic tips on how to use the site

*

*Ru: Подсказки о механиках работы Stack Overflow

*Es: Consejos sobre cómo usar el sitio

*Community banners

*

*Ru: Поможем коллегам сделать первый шаг к профессиональному росту

*Ja: オリジナルバナー作成について

*Key values of the community

*

*Ja: スタック・オーバーフロー日本語版で大切にしたい価値観とは

*Es: Los valores fundamentales de Stack Overflow en español

*Ru: Ключевые ценности сообщества Stack Overflow на русском

*Pt: Os valores do Stack Overflow em Português

*What to do with sites that contain of only machine translated content from Stack Overflow in English

*

*Ru: Меньше спама, больше полезных знаний о программировании: как бороться с машинными переводами в поисковой выдаче
Findings

*

*Removing salutations automatically

*

*Should the word "hay" not be deleted at the beginning of posts, especially on Spanish SE?

*Let's make the automatic removal of salutations language specific!

*Ru: Автоматическое удаление приветствий

*Automatically delete a comment when a user flags it as no longer needed

*

*Ru: Автоматическое удаление комментариев по тревоге «более не является необходимым».

*Warnings on question and answers

*

*Es: Advertencias en preguntas potencialmente problemáticas

*Enabling review audits

*

*Es: Ya nos graduamos, habiliten los audits en las colas de revision

*Changing the name of the "Strunk & White" badge for something ES-specific

*

*Es: Cambiemos el nombre de la medalla "Strunk & White" por algo más reconocible

*Alert before posting a question if it's written in English

*

*Es: ¿Podríamos tener un pequeño detector de publicaciones en inglés que notificara a los autores?
based on this answer by Shog9 to Meta SO's False Positive Spanish Language Detection when Asking Question.

*Ja: 英語で投稿されようとしている質問を、未然に誘導する仕組みが欲しい

*Pt: Que tal um alerta para perguntas em outro idiomas?

*Community promotion adds.

*

*Es: ¿Podemos tener anuncios de promoción de la comunidad? --> 2017 edition
Current problems

*

*Add a validation for questions that have only code

*

*Es: Añadamos una alerta en preguntas que son solo código

*Pt: Que tal um alerta para perguntas com apenas código?

*Having the Triage review queue

*

*Es: Instauremos una cola de revisión "triaje" para que solo las preguntas con cierto nivel entren en la página de inicio (let's have the Triage review queue)

*Having posters for universities and learning centers.

*

*Es: Proposed by the CM, not clear how to get them.

*[CR] A notification need to be sent when someone adds a new help center article or edits existing one.


text:
Q: Convert utc date to local date using momentjs I have a DateTime string like 2/24/2017 17:00:00 which comes from a web service. The time is UTC time. Now i want to convert it to user's local time and display it in browser. And i'm using Moment.js.
I've tried:
var utcTime= moment('2/24/2017 17:00:00' + " +0000", "MM/DD/YYYY HH:mm:ss Z");

var localTime = utcTime.add(new Date().getTimezoneOffset().toString(), 'm').toDate();

It will work but somehow looks strange. Am i missing something? Is there a better way to do this?

A: Write it like this:
moment.utc('2/24/2017 17:00:00', "MM/DD/YYYY HH:mm:ss").local().format('lll');

Reference: http://momentjs.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass a parameter to dashDB query using Node-RED editor? In Bluemix Node-RED application I use Cloudant and dashDB services. I replicated Cloudant database into dashDB which contains multiple values stored in a table like DALERT,DEVICE,ID etc.
I am trying to search records from the CLOUDANT table in my dashDB using DALERT column which value is equal to critical.
I am trying these way in Node-RED editor but unable to retrieve data from dashDB:
[
{"id":"9941f62b.66be08","type":"http in","name":"","url":"/get/specificcritical","method":"get","swaggerDoc":"","x":103.5,"y":409,"z":"c96fb1cb.36905","wires":[["b52196bf.4ade68","292d3e2e.d6d2c2"]]},
{"id":"b52196bf.4ade68","type":"function","name":"","func":"msg.Dalert=msg.payload.Dalert;\n\nreturn msg;","outputs":1,"noerr":0,"x":326,"y":353,"z":"c96fb1cb.36905","wires":[["457cf34.fba830c","d937915d.26c87"]]},
{"id":"457cf34.fba830c","type":"dashDB in","service":"dashDB-9a","query":"select * from XXXXX.CLOUDANT WHERE DALERT=?;","params":"msg.Dalert","name":"","x":510,"y":404,"z":"c96fb1cb.36905","wires":[["60d36407.9f2c9c","886c48df.7793b8"]]},
{"id":"d937915d.26c87","type":"debug","name":"","active":false,"console":"true","complete":"payload","x":599,"y":327,"z":"c96fb1cb.36905","wires":[]},
{"id":"60d36407.9f2c9c","type":"debug","name":"","active":true,"console":"false","complete":"false","x":758,"y":397,"z":"c96fb1cb.36905","wires":[]},
{"id":"886c48df.7793b8","type":"http response","name":"","x":771,"y":477,"z":"c96fb1cb.36905","wires":[]},
{"id":"292d3e2e.d6d2c2","type":"debug","name":"","active":true,"console":"true","complete":"payload","x":321,"y":483,"z":"c96fb1cb.36905","wires":[]}
]

Please let me know if there is any solution.

A: If I understood correct your question, you just need to modify your function node with something similar to this:
msg.dalert="critical";
return msg;

Assuming your DALERT column in the CLOUDANT table is of type VARCHAR. You may need to change it if is a different type on your database.
Running the application like:
http://yourappname.mybluemix.net/get/specificcritical
will result in output similar to this for my table:
[
  {
    "DALERT": "critical",
    "DEVICE": "device1",
    "ID": 1
  },
  {
    "DALERT": "critical",
    "DEVICE": "device3",
    "ID": 3
  },
  {
    "DALERT": "critical",
    "DEVICE": "device5",
    "ID": 5
  }
]

Here is the new node flow I created with the changes (I added an input node with blank message just to test the flow in the editor):
[{"id":"c7468303.38b98","type":"http in","name":"","url":"/get/specificcritical","method":"get","swaggerDoc":"","x":125,"y":245,"z":"8e2ae4a.f71d518","wires":[["c685ce8c.397a3","20dfeeba.df2012"]]},{"id":"c685ce8c.397a3","type":"function","name":"","func":"msg.dalert=\"critical\";\nreturn msg;","outputs":1,"noerr":0,"x":347.5,"y":189,"z":"8e2ae4a.f71d518","wires":[["e1f8c153.1e074","1f2d6f8e.e0d29"]]},{"id":"e1f8c153.1e074","type":"dashDB in","service":"dashDB-0a","query":"select * from CLOUDANT WHERE DALERT=?;","params":"msg.dalert","name":"","x":531.5,"y":240,"z":"8e2ae4a.f71d518","wires":[["f1810e4c.0e7ef","1401dc1a.ebfe24"]]},{"id":"1f2d6f8e.e0d29","type":"debug","name":"","active":false,"console":"true","complete":"payload","x":620.5,"y":163,"z":"8e2ae4a.f71d518","wires":[]},{"id":"f1810e4c.0e7ef","type":"debug","name":"dashDB Output","active":true,"console":"false","complete":"payload","x":779.5,"y":233,"z":"8e2ae4a.f71d518","wires":[]},{"id":"1401dc1a.ebfe24","type":"http response","name":"","x":792.5,"y":313,"z":"8e2ae4a.f71d518","wires":[]},{"id":"20dfeeba.df2012","type":"debug","name":"","active":true,"console":"true","complete":"payload","x":342.5,"y":319,"z":"8e2ae4a.f71d518","wires":[]},{"id":"1f530672.e0acfa","type":"inject","name":"","topic":"","payload":"","payloadType":"none","repeat":"","crontab":"","once":false,"x":122,"y":112,"z":"8e2ae4a.f71d518","wires":[["c685ce8c.397a3"]]}]

A: I got ans for question.
if we want to pass value as parameter just write msg.variable=msg.payload.variable; and return msg;
inside function node and msg.variable also declare in query parm inside dashDB IN node. eg:msg.Dalert=msg.payload.Dalert; and
critical value pass with url as http://yourappname.mybluemix.net/get/specificcritical?Dalert=critical
Its simple working node red flow
[
{"id":"9941f62b.66be08","type":"http in","name":"","url":"/get/specificcritical","method":"get","swaggerDoc":"","x":103.5,"y":409,"z":"c96fb1cb.36905","wires":[["b52196bf.4ade68","292d3e2e.d6d2c2"]]},
{"id":"b52196bf.4ade68","type":"function","name":"","func":"msg.Device=msg.payload.Device;\n\nreturn msg;","outputs":1,"noerr":0,"x":326,"y":353,"z":"c96fb1cb.36905","wires":[["457cf34.fba830c","d937915d.26c87"]]},
{"id":"457cf34.fba830c","type":"dashDB in","service":"dashDB-XX","query":"select * from XXXXX.CLOUDANT WHERE DEVICE=?","params":"msg.Device","name":"","x":510,"y":404,"z":"c96fb1cb.36905","wires":[["60d36407.9f2c9c","886c48df.7793b8"]]},
{"id":"d937915d.26c87","type":"debug","name":"","active":false,"console":"true","complete":"payload","x":599,"y":327,"z":"c96fb1cb.36905","wires":[]},
{"id":"60d36407.9f2c9c","type":"debug","name":"","active":true,"console":"false","complete":"false","x":758,"y":397,"z":"c96fb1cb.36905","wires":[]},
{"id":"886c48df.7793b8","type":"http response","name":"","x":771,"y":477,"z":"c96fb1cb.36905","wires":[]},
{"id":"292d3e2e.d6d2c2","type":"debug","name":"","active":true,"console":"true","complete":"payload","x":321,"y":483,"z":"c96fb1cb.36905","wires":[]}
]


text:
Q: Azure Logic App - Foreach over sql resultset I'm using an Execute Sql Query action in logic app.
Returned result is composed of 1..n tables ("selects").
I want to create a csv table and send it over tfs.
The issue I'm having is that the tables are elements of resultset, and not part of an array.
Is there some way to perform ForEach action on the resultset elements (i.e. - 'Table1', 'Table2', etc...)?

A:
Is there some way to perform ForEach action on the resultset elements (i.e. - 'Table1', 'Table2', etc...)?'

According to the mentioned data format, it seems that it is not supported via foreach action in logic app.
If Azure function is acceptable, I recommend that you could use the Azure function to implement it with your customized logic to deal with data.

A: Foreach on a Resultset will return JSON object of each row.
I couldn't find any option DesignView to extract the value but you can achieve same in CodeView by assigning following code to your variable in CodeView.
In below MEETINGID is my column name.
"@{items('For_each')?['MEETINGID']}"
    "imeetingid": "@{items('For_each')?['MEETINGID']}"

A: In DesignView, you can use Parse JSON after SQL querying step.
Then, you can use for each in order to reach each database record. Because SQL resultset returns as JSON object in the Logic App.


text:
Q: How to handle multiple optional arguments in Absinthe GraphQL resolver while constructing a query in a DSL? Imagine a GraphQL query like this:
Query {
  projects(platforms: [String], languages: [String])
}

And a Neo4j graph containing nodes labeled Project, Platform and Language.
When none of the optional arguments are passed, the resolver should return the list of all projects in the graph with no filtering (possibly with pagination in future). When either or all arguments are passed, those should be applied in the underlying query; i.e. we should get projects that are implemented in given languages or for given platforms.
I am using Bolt.Sips driver for Neo4j in my Elixir backend, and this driver offers minimal functionality as for wrapping the Cypher query language, so for the most part I need to write queries on my own. So far I have this implementation of the resolver, since I have yet to implement the second argument:
def get_projects!(_parent, %{languages: _} = args, _resolution) do
  """
  match (node:Project)<-[:LANGUAGE_FOR]-(l:Language)
  where l.name in {props}.languages
  return node
  """
  |> generic_query!(%{props: args})
end

def get_projects!(_parent, _args, _resolution) do
  get_all_entities_of_type!("Project")
end

where generic_query!/2 and get_all_entities_of_type!/1 are just wrappers for Bolt.Sips query execution.
My question is: what's the best way to construct a Cypher query in this case? Should I just write a bunch of functions that will construct a query string before execution? Maybe it's just my general lack of GraphQL experience and query schemas like this are to be constructed differently? Any tips would be appreciated.


text:
Q: Data sanitisation question - regular expression for removing combinations of trailing spaces and commas I have address strings which were (due to poor initial programming) allowed far too much entry of free text. In the course of cleaning up this inherited mess, I have noticed that at the end of the address fields, there are frequently (and frequently not) commmas which I want to get rid of.
The problem is that (again, frequently!) those inputting the data (paid by the line...) input strings like:
`address_1_string  ,  `

That's address_1_string followed by two spaces followed by the comma I wish to delete, followed by two more spaces. The number of spaces (either before or after the comma) is arbitrary, typically going from 0 - 5. The problem is further compounded by the fact that address_string_1 itself may have internal (valid) commas.
So, what I am looking for is a regular expression that goes to the end of the line, deletes any trailing spaces, the first comma and then any more spaces until a valid [a-zA-Z0-9] ([:alphanum:]?) character is found.
I have notions of regular expressions, but this is above my pay grade. This is my first post on Stackexchange, so if I'm in the wrong place, please redirect me. TIA.

A: < input sed 's/[[:space:],]*$//' > output

Would delete all the spacing and comma characters at the end of the line.
To edit the file in place, some sed implementations have a -i option inspired from perl's -i option:
sed -i 's/[[:space:],]*$//' input-and-output    # GNU, busybox, NetBSD, OpenBSD
sed -i '' 's/[[:space:],]*$//' input-and-output # FreeBSD, macOS


text:
Q: .htaccess denied vs out of wwwroot I need to upload to my server a high sensitive data file to be used by PHP scripts. Please, tell me what's the most secure way and why:

*

*Putting it in a folder not under www root

*Putting it under www root but denying access with .htaccess rule

Thank you very much

A: If you have ftp/sftp/ssh access to this server, there's no reason not to put it outside of the www document root. If you have a hosting service that only grants you access to the www document root, then you'll have to go with the second solution, but the first is much more secure.
Htaccess can be bypassed if there is a vulnerable script on your site. There are tools that, if placed correctly, files inside the document root and be uploaded by a remote attacker or even replaced. For example, there are php "remote file managers" that allows a remote attacker to change permissions, edit, or replace existing files, including your htaccess file. If you're running a site like Wordpress, or some other CMS, that aren't exactly super secure by themselves, that have a lot of third party plugins, those plugins could be vulnerable to attacks, and if you happen to be using one, your htaccess file's access restrictions could be bypassed.
When the sensitive information is outside of the document root, an attacker who has access to the document root won't be able to access these files and vulnerabilities in your scripts are a lot less likely to affect access to these files. There most likely needs to be a system level exploit to be able to gain access to files outside of the docuement root.


text:
Q: Jquery replace in html string 2 times separatly So i have a html template:

                $QuestionUpButton
              <%----%>
              $QuestionVote
              $textboxText

              $AnswerUpVote
              <%----%>

              $AnswerVotes
              Answer :
              $AnswerSpan
              <input type='button' id='editButton' data-editlinkbuttongroup="$i" value='Edit' />
              <input type='button' id='deleteButton' data-deletelinkbuttongroup="$i" value='Delete Question' />

on document load i run code where i replace all $ variables like this:
function MyFunction(result) {
    //console.log(result);
    var panel = $('#mypanel');
    var userGuid = GetUserGuid().d;
    var panel = $('#MainContent_AnsweredQuestions_mypanel');

    for (var k = 0; k < result.d.length; k++) {
        var notVotedQuestion = "";
        var notVotedQuestion1 = "hulabula";
        var notVotedAnswer = "notVotedAnswer";
        var votedAnswer = "";

        console.log(result.d[k].Uid)
        var html = $("#OwnerTemplateQuestionWithoutAnswer").html().replace(/\$i/g, i)
            .replace(/\$AnswerSpan/g, result.d[k].Answers[0].Conetent)
            .replace(/\$answerGuid/g, result.d[k].Answers[0].Uid)
            .replace(/\$questionUid/g, result.d[k].Uid)
            .replace(/\$QuestionVote/g, result.d[k].QuestionVotes.length)
            .replace(/\$AnswerVotes/g, result.d[k].Answers[0].AnswerVotes.length)
            .replace(/\$textboxText/g, result.d[k].Content);

        //var html1 = $("#OwnerTemplateQuestionWithoutAnswer").html(html);

        if (didUserVote(result.d[k], userGuid) == false){
            html.html().replace("$AnswerUpVote", notVotedQuestion);
        }

        panel.append(html);
        i++;

    }

}

part where i replace first time is working great and exactly how i want:
 var html = $("#OwnerTemplateQuestionWithoutAnswer").html().replace(/\$i/g, i)
                .replace(/\$AnswerSpan/g, result.d[k].Answers[0].Conetent)
                .replace(/\$answerGuid/g, result.d[k].Answers[0].Uid)
                .replace(/\$questionUid/g, result.d[k].Uid)
                .replace(/\$QuestionVote/g, result.d[k].QuestionVotes.length)
                .replace(/\$AnswerVotes/g, result.d[k].Answers[0].AnswerVotes.length)
                .replace(/\$textboxText/g, result.d[k].Content);

but later in the code i need to load image differently depends on some conditions
   if (didUserVote(result.d[k], userGuid) == false){
        html.html().replace("$AnswerUpVote", notVotedQuestion);
    }

and this part of cide doesnt work at all... Any suggestions on how to solve this, or how i can improve replacement in some kind of a way??

A: Change this:
html.html().replace("$AnswerUpVote", notVotedQuestion);

To this:
var html = $("#OwnerTemplateQuestionWithoutAnswer");
html.html(html.html().replace("$AnswerUpVote", notVotedQuestion));

The reason why your code doesn't work is because in the first instance you are assigning the new Html to the var html; later, since the object is already created, you need to set its Html value to the updated (replaced/filtered) html code of itself. when you call .html() you are getting a string that is passed by value, not by reference, which is why when you were just replace the .html(), you were replacing it but you weren't doing anything with the result.

A: well I am not sure you concluded a solution for above but I would strongly recomend you to use mustache js.
Mustache is a "logic-less" template syntax. "Logic-less" means that it doesn't rely on procedural statements (if, else, for, etc.): Mustache templates are entirely defined with tags.
So you do not need above hard to understand javascript logic to do what you want to achive.
Check Mustache.JS  and it's template tutorials.


text:
Q: Python: Coloring 1-D swarmplots in seaborn I am trying to make a 1-D swarm plot using the below dataframe(only first few rows are shown):
      value    color
0   0.446928    1
1   0.258523    0
2   0.716512    2
3   0.288698    0
4   0.132203    0
5   0.871158    3
6   0.613292    2
7   0.697033    2
8   0.333995    1
9   0.549433    2

Using the below code I made a 1D swarm plot:
import matplotlib.pyplot as plt
import seaborn as sns

plt.style.use('ggplot')
sns.swarmplot(x=df['value'], hue=df['color'])

Here is the plot generated:

The problem here is I want to define colours to each group like value from 0 to 0.3 should have red colour(say), 0.3 to 0.5 should have the second colour(say green) and so on. For that, I have defined the colour column in the dataframe but on passing hue=df['color'], the plot is not generating colours. I want my plot to look something like this:

What changes should I make in my code so that my program works as expected?

A: The generated scatter points are stored in ax.collections[-1]. You can extract their x-coordinates, use np.digitize() to divide them into groups and use those values for coloring:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np

plt.style.use('ggplot')
df = pd.DataFrame({'value': np.random.uniform(0, 1, 1000)})
ax = sns.swarmplot(x=df['value'])
scatter_dots = ax.collections[-1]
xpos = scatter_dots.get_offsets()[:, 0]
boundaries = [0, .3, .5, .7, 1]  # one more than the number of colors
colors = np.digitize(xpos, boundaries)
scatter_dots.set_array(colors)
scatter_dots.set_cmap(ListedColormap(['crimson', 'limegreen', 'gold', 'skyblue']))
plt.show()


text:
Q: Creating select all checkbox in VueJS trough loop I've created some data that are displayed trough a loop as table.
That code seems fine, however in my methods I get an error 'page is not defined'.
Does anyone know how do I define it?
Table:

                  <input type="checkbox" v-model="pageIds" @click="select" :value="page.id">

                {{page.name}}

                  <v-tooltip bottom>
                    <template v-slot:activator="{ on, attrs }">
                      <v-icon class="icon delete">mdi-delete</v-icon>
                    </template>
                    Delete Page
                  </v-tooltip>

Methods:

A: change this in your code. it will resolve your error
from
v-for="page in pages" v-bind:key="page"

to
v-for="(page, index) in pages"
v-bind:key="index"


text:
Q: Centering 3 auto-fill items I have a grid container with 3 items inside. I want it to be center if the 3rd item is moved to another row (like how it's displayed in the Expect section).
The wrapper's width depends on viewport's width, so I think I can use media queries here. I'm looking for an one-liner instead if possible.
My question is: how can I do that? Thanks for your time.

    .wrap {
        border: 1px solid #3498db;
        margin: 16px;
    }

    .wrap1 {
        width: 400px;
    }

    .wrap2 {
        width: 300px;
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 16px;
    }

    .item {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #2c3e50;
        background: #95a5a6;
        height: 50px;
    }

    .expect {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
    }
    .expect > .item {
        flex: 0 0 142px;
    }

                Item 1

                Item 2

                Item 3

                Item 1

                Item 2

                Item 3

    Expect:

                Item 1

                Item 2

                Item 3


text:
Q: Pre-selection option in vue.js Usually in bootstrap I do it like this. All targets in array " this.targets", and selected in array "selected_targets"
   <input type="checkbox" class="form-check-input" name="tags[]" value="{{$tag}}"
                       @if(in_array($tag,$anketTarget)) checked="1" @endif >

But how to use pre-election in Vue?
 <div v-for="target in targets">
    <input type="checkbox" id="target" v-model="checkedTarget" checked> {{target.name}}
    <input type="checkbox" id="target" v-model="checkedTarget">{{target.name}}
                                 </div>

<script>
    export default {
   data() {
            return {
                targets: "",
                selected_targets: [],
                checkedTarget: []
            }
        },
</scrpt>

A: Have a look at this answer for checking if the checkbox should be checked or not.
This documentation page can help you for retrieving checked checkboxes.


text:
Q: How to modify the internet application for mvc projcect in Visual Studio 2012 code and connect with database? I am beginner in ASP.NET MVC. I have been trying to create a web application in ASP.NET MVC 4 by using Visual Studio 2012. I started with internet application and open with default template that has registration, login, home etc pages. I have tried to modify the code available for the registration form as I want and connect with SQL Server database, but it does not work and also only connected with local database it is not connected with my database table I have created in SQL Server. What will I do? Thank you for your help

A: Have you changed your default connection string in your web.config to point your sql server?
The default connection string will be like this
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-yourproj-timestamp;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-yourproj-timestamp.mdf" providerName="System.Data.SqlClient" />

In your case you should have changed as follows,
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=aspnet-yourproj-timestamp;User Id = xxx;Password = xxxxxx" providerName="System.Data.SqlClient" />


text:
Q: Space Complexity for dictionary in Python3 What is the space complexity of this dictionary in Python?
(1) My Guess: O(V+E) where V is the number of key and E is the maximum length of array value in dictionary.
{
    'key' : ['value', 'value2', ...],
    'key2': ['value30', 'value31', ...],
    ...
}

Small Question: If the dictionary is formed of directed graph, should its space complexity be O(2E)?
(2) My Guess: O(V) where V is the number of key.
{
    'key' : 4,
    'key2': 5,
    ...
}

A: Dictionaries in Python are implemented as hash tables.
Typically Hash tables will have n keys and n elements (one for each key).  This will give them make them have O(n) space since we can drop constants in O(2n).
What you are trying to do is take a hash table like data structure and have it exhibit behavior it typically does not... The way I understand you are trying to use it is that you have lists of elements and each list can be identified by a key. Since each list can have its own length, a better representation of space complexity is O(k + v1 + v2... + vn), where v1 is the length of list 1 and vn the length of the last list.
If you are using the dictionary as you would use a hash table then the space complexity is O(n).


text:
Q: Узнать, есть ли значение по умолчанию в свойстве class MyClass {
  public int IntProperty {get; set;}
  public string StrProperty {get; set;} = "Hello"
}

Как узнать через рефлексию, установлено ли значение по умолчанию, у свойства IntProperty?

A: Через рефлексию (имеются ввиду мета-данные) никак, потому что компилятор такие значения по умолчанию кидает в конструктор. Вот как выглядит конструктор для вашего класса:
.method public hidebysig specialname rtspecialname
    instance void .ctor () cil managed
{
    // Method begins at RVA 0x20ab
    // Code size 19 (0x13)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldstr "Hello"
    IL_0006: stfld string ConsoleApp1.Program/MyClass::'<StrProperty>k__BackingField'
    IL_000b: ldarg.0
    IL_000c: call instance void [mscorlib]System.Object::.ctor()
    IL_0011: nop
    IL_0012: ret
} // end of method MyClass::.ctor

Если вам уж очень нужно такое реализовать, то придется анализировать IL-код конструктора.


text:
Q: React setState call inside a custom hook useEffect is not updating the state I have a basic custom hook in that I am changing a state inside useEffect but state is not changing
Below Users component is calling custom hook and passing items prop
const Users = (props) => {
  const [users] = usePivot(props.items)
}

usePivot custom hook
const usePivot = (propItems) => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // this is printing in whenever propItems changes
    console.log("propItems in useUserPivot: ", propItems);

    // this is not setting
    setUsers(propItems);
  }, [propItems]);

  useEffect(() => {
    // this is not printing in console
    console.log("users: ", users);
  }, [users]);

  return [
    users
  ];

}

value of users is always [], it never changes.

A: I used your same code here and everything is fine

make sure you are passing items as props to your users component
based on your code
   <Users items={[1,2,3]} />

A: users state was getting set again in another function with sorted list, which is getting called in useEffect. I commented that function call and then issue got solved. I am not sure why this issue would come because of that.


text:
Q: shell script to read values from one file and replace it in other file I would like to replace a set of strings into a new file. Source file file1.json values has to be replaced by values from file1.config into file file2.json. I have following script that is failing to do so.
file1.json
{
    "colorsArray":[{
            "red":"$ALERT_LEVEL",
            "green":"$NORMAL_LEVEL",
            "blue":"$RELAX_LEVEL"
        }
    ]
}

file1.config
[root@ip10]# cat file1.config
ALERT_LEVEL=DANGER
NORMAL_LEVEL=NORMAL
RELAX_LEVEL=RELAX

run.sh
    #!/bin/bash
set -x
if [ $# -ne 3 ]; then
  echo "USAGE:
        ./$0 file1.json file2.json file1.config"
  exit 1
fi
echo "#!/bin/bash
cat > $2 << EOF
`cat $1`
EOF" > $2;
chmod +x $2;
# load variables into env
. $3
# actually replace variables
./$2

Error:
[root@ip10]# ./run2.sh file1.json file2.json file1.config
./file2.json: line 11: warning: here-document at line 2 delimited by end-of-file (wanted `EOF')

file2.json appears, but it has no values replaced.
root@ip10]# cat file2.json
    {
        "colorsArray":[{
                "red":"",
                "green":"",
                "blue":""
            }
        ]
    }

A: Just explaining the comment of @user3159253. Your file1.config should look like this for your code to work properly:
export ALERT_LEVEL=DANGER
export NORMAL_LEVEL=NORMAL
export RELAX_LEVEL=RELAX

P.S. IMHO the way you do the thing is a bit overelaborate. I'd prefer using sed to complete this task -- takes only one string:
sed file1.json -e 's/$ALERT_LEVEL/DANGER/g' -e's/$NORMAL_LEVEL/NORMAL/g' -e's/$RELAX_LEVEL/RELAX/g' >file2.json

A: This is the classic problem of reading env vars from a file, and substituting those values in another file. There is an inherent danger is using eval with your input file, so that should be avoided.
The simplest way is if your system already has the command envsubst, which does this for you. Usage:
$ var1=value1 var2=value2 envsubst < input.txt > output.txt

The trick here, though, is that your env vars are in another text file. So they aren't specified on the command line itself; they'll need to be exported to be seen by envsubst. E.g,
#!/bin/bash
export var1=value1
export var2=value2
envsubst < input.txt > output.txt

Here's one possible way to do this with an input file of env vars:
#!/bin/bash
eval $(sed 's/^.*=/export &/' file1.config)
envsubst < file1.json > file2.json

If you don't have envsubst available, then see this answer for other options (e.g., eval, sed, m4, ...): How to replace ${} placeholders in a text file?


text:
Q: T-SQL Multi Use Function to Replace SQL in Procedures Let's assume I have the same following code in three procedures:
    SELECT CASE
           WHEN [column1] LIKE '%/[a-z][a-z]-[a-z][a-z]/%' THEN REVERSE ( SUBSTRING ( REVERSE ( [column1] ) ,1,PATINDEX ( '%/%',REVERSE ( [column1] )) - 1 ))
           WHEN [column1] LIKE '' THEN ISNULL ( NULLIF ( [column1],'' ) ,'(not set)' )
           ELSE 'Other'
           END AS ColumnReturned
FROM X

1) Is it possible to have a "function" instead of this piece of code stored somewhere else, in one place? So then I can call only:
SELECT myFunction (column1)
FROM X

in the procedures. So if I want to change the logic, I'd change it only in one place.
2) If I could have such function as per 1) point, can I have also multiple functions in one "file"? So I have list of different functions in one place? Then I'd be able to call:
SELECT functionList.myFunction1 (column1)
      ,functionList.myFunction2 (column2)
FROM X

Or the functions need to be separeated and only share scheme?
I am new to T-SQL functions so will be happy if you could point me some starting point.

A: The basic syntax for what you want is:
CREATE FUNCTION dbo.YourFunction (@Column VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
    RETURN  CASE
                WHEN @Column LIKE '%/[a-z][a-z]-[a-z][a-z]/%'
                    THEN REVERSE ( SUBSTRING ( REVERSE ( @Column ) ,1,PATINDEX ( '%/%',REVERSE ( @Column )) - 1 ))
                WHEN @Column LIKE ''
                    THEN ISNULL ( NULLIF ( @Column,'' ) ,'(not set)' )
                    ELSE 'Other'
                END
END

You would then just use:
SELECT dbo.YourFunction (x.column1) AS ColumnReturned
FROM X;

HOWEVER, scalar user defined functions can be a massive performance drain, and it may improve performance to convert it to an inline table valued function instead, so the function would be:
CREATE FUNCTION dbo.YourFunction (@Column VARCHAR(50))
RETURNS TABLE
AS
RETURN
(   SELECT  CASE
                WHEN @Column LIKE '%/[a-z][a-z]-[a-z][a-z]/%'
                    THEN REVERSE ( SUBSTRING ( REVERSE ( @Column ) ,1,PATINDEX ( '%/%',REVERSE ( @Column )) - 1 ))
                WHEN @Column LIKE ''
                    THEN ISNULL ( NULLIF ( @Column,'' ) ,'(not set)' )
                    ELSE 'Other'
            END AS ColumnReturned
);

This makes calling the function a bit more complicated, but it is often worth it:
SELECT (SELECT f.ColumnReturned FROM dbo.YourFunction (x.column1) AS f) AS ColumnReturned
FROM X;

OR
SELECT f.ColumnReturned
FROM X
    CROSS APPLY dbo.YourFunction (x.Column1) AS f;


text:
Q: Hide individual sections of a RSFormPro form when submission limit has been reached I use RsForm Pro on Joomla CMS, and there I have created a form. In my form, I have 5 sections with a checkbox. I want to display individual sections up to a certain limit (let's say a max of 20 users), after the submission limit has been reached the form section needs to be disabled.
I found a limit for submit form, but if 20 users submit only one section in the form (not for checkbox), another 4 can't be available for other users. In other words, I don't want to disable all sections unless all sections have reached there limit.
This is code for limit submit form:
// Define the maximum number of submissions. For this example we'll use 25.
$max = 25;

// Get a database connection.
$db = JFactory::getDbo();

// Setup the query. This query counts the number of submissions for the current form.
// $formId contains the ID of the current form.
$db->setQuery("SELECT COUNT(`SubmissionId`) FROM #__rsform_submissions WHERE `FormId`='".(int) $formId."'");
$submissions = $db->loadResult();

if ($submissions >= $max) {
    $formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!.';
}

EDIT SOLVED:
$limit25 = 25;
$limit21 = 21;
$limit20 = 20;

$db = JFactory::getDbo();

$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 11th'");

$first_submission_value = $db->loadResult();

if ($first_submission_value >= $limit25) {
    echo '<style>.rsform-block-bus-blockchain-march-11th { display:none;}</style>';
}

$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 13'");

$secont_submission_value = $db->loadResult();

if ($second_submission_value >= $limit25) {
    echo '<style>.rsform-block-bus-blockchain-march-13 { display:none;}</style>';
}

$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 18'");

$third_submission_value = $db->loadResult();

if ($third_submission_value >= $limit25) {
    echo '<style>.rsform-block-bus-blockchain-march-18 { display:none;}</style>';
}

$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA'");

$fourth_submission_value = $db->loadResult();

if ($fourth_submission_value >= $limit20) {
    echo '<style>.rsform-block-evening-qa {  display:none;}</style>';
}

$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA_2'");

$fifth_submission_value = $db->loadResult();

if ($fifth_submission_value >= $limit21) {
    echo '<style>.rsform-block-evening-qa-2 { display:none;}</style>';
}

if(
    $first_submission_value >= $limit25
    && $secont_submission_value >= $limit25
    && $third_submission_value >= $limit25
    && $fourth_submission_value >= $limit20
    && $fifth_submission_value >= $limit21
) {
    $formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
}

A: I see that you have edited your question to reveal your solution.  Rather than to ask you to post your solution as an answer (which you should have done), I'll do you one better -- I've taken the time to refactor your code, implement Joomla's query building methods, make it more efficient, cleaner, more direct, and easier to manage.
Most importantly, because all of the database interactions can be performed with a single query, they should be.
Because your field names seamlessly relate to your classnames, a "lookup array" or "mapping array" will allow my snippet to reliably deliver your desired results dynamically. You will never need to adjust more than $formId and $field_maxes.
Code: (tested locally with my own rsform pro table)
$formId = 3;  // or whatever the correct formId value is
$field_maxes = [
    'Bus_Blockchain_March 11th' => 25,
    'Bus_Blockchain_March 13' => 25,
    'Bus_Blockchain_March 18' => 25,
    'evening_QA' => 20,
    'evening_QA_2' => 21
];

$classes_to_hide = [];                    // initiate as empty array
$formLayout = '';                         // initiate as empty string

$db = JFactory::getDbo();

$quoted_fields = implode(',', $db->q(array_keys($field_maxes)));  // create quoted comma-separated values

$query = $db->getQuery(true)
    ->select("FieldName, COUNT(1) AS " . $db->qn("Count"))
    ->from("#__rsform_submission_values")
    ->where([
        "FormId = " . (int) $formId,
        "FieldName IN ($quoted_fields)"
    ])
    ->group("FieldName")
    ->order("FIELD ($quoted_fields)");

// if you wish to see the rendered query, uncomment the next line (do not show to public)
// JFactory::getApplication()->enqueueMessage("<div>" . $query->dump() . "</div>", "notice");

try                                           // listen for syntax errors
{
    $db->setQuery($query);
    if (!$results = $db->loadAssocList())     // declare and check for empty result set
    {
        echo "No Results in Form";
    }
    else
    {
        foreach ($results as $row)            // iterate rows
        {
            if ($row['Count'] >= $field_maxes[$row['FieldName']]) {  // if fieldname has reached limit
                $classes_to_hide[] = ".rsform-" . str_replace(['_', ' '], '-', $row['FieldName']);
            }
        }

        if ($tally = sizeof($classes_to_hide))  // declare and check if not empty
        {
            echo "<style>" , implode(", ", $classes_to_hide) , " {display:none;}</style>";  // apply css styling to one or more designated classes
            if ($tally == sizeof($field_maxes))  // if all fieldnames are full
            {
                $formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
            }
        }
    }
}
catch (Exception $e)
{
    JFactory::getApplication()->enqueueMessage("Query Syntax Error", "error");
    // if you have a syntax error and wish to see the message, uncomment the next line (do not show to public)
    //JFactory::getApplication()->enqueueMessage($e->getMessage(), "error");

}


text:
Q: PHP tag inside a PHP tag? So I just follow this guide:
http://www.bitrepository.com/php-how-to-add-multi-language-support-to-a-website.html
And everything is working but now I got in to a problem:
Everywhere that I want text I place: <?php echo $lang['FOOTER_CURRENCY']; ?>
But I have a php code for RSS feed: (right inside my php file)
<?php
    // Show number of items
    $items = 6;

    // Load rss into simplexml rss from pctuts http://www.pctuts.be/external.php?do=rss&type=newcontent&sectionid=1&days=120&count=10 just replace this link voor the right one
    $rss        = simplexml_load_file('http://test.blogspot.com/feeds/posts/default?alt=rss');

    // show last items
    for($i=0;$i<$items;$i+=1)
       {
       echo "
channel->item[$i]->link}\" target=\"_blank\">{$rss->channel->item[$i]->title}
\n";
       }

    ?>

Now I wan't to replace the RSS Feed link with every language. So I replaced this like I usualy do:
This:
$rss        = simplexml_load_file('http://cupandsaucersweden.blogspot.nl/feeds/posts/default?alt=rss');

To:
$rss        = simplexml_load_file('<?php echo $lang['FOOTER_RSSFEED']; ?>');

Well ofcourse a php tag inside a php tag won't work so I did this:
$rss        = simplexml_load_file('echo $lang['FOOTER_RSSFEED']; ');

Doesn't work either, I tried many other things but it just won't work. Can someone help me with this?

A: As @john-conde and @barmar mentioned in the comments, you already "in the php tag", so there is no need for another one inside it. You just need to specify your variable without echo.
$rss = simplexml_load_file($lang['FOOTER_RSSFEED']);


text:
Q: Is using single quotes for string literals faster than double quotes? This is not a question about micro optimization. I'm just interested if using single quotes for string literals is faster than using double quotes (because no variable expansion will happen).
Example:
echo 'This is a string' # should a faster
echo "This is a string"

I've tried to measure this (using a large loop and time) but couldn't come up with a real conclusion.
Any ideas on this?
EDIT
I'm also interested why the performance difference is so small... one would think that variable expansion requires some sort of parsing the string, which should make a notable difference.

A: I was curious about this too, so I ran a few measurement on an Intel i7-8700 Hackintosh.
Here are the results:
Single quotes
for i in {1..1000000}
do
        echo 'abcdefghijklmnopqrstuvwxyz'
done

sh test.sh  7,40s user 0,80s system 97% cpu 8,403 total

Double quotes
for i in {1..1000000}
do
        echo "abcdefghijklmnopqrstuvwxyz"
done

sh test.sh  9,96s user 0,87s system 97% cpu 11,050 total

No quotes (effectively same as double quotes)
for i in {1..1000000}
do
        echo abcdefghijklmnopqrstuvwxyz
done

sh test.sh  9,97s user 0,88s system 98% cpu 11,068 total

Singles quotes with variable concatenation
for i in {1..1000000}
do
        echo 'abc'$i'defghijklmnopqrstuvwxyz'
done

sh test.sh  9,53s user 0,91s system 97% cpu 10,707 total

Double quotes with variable concatenation
for i in {1..1000000}
do
        echo "abc${i}defghijklmnopqrstuvwxyz"
done

sh test.sh  11,78s user 0,94s system 97% cpu 13,028 total

So yeah using single or double quotes have an impact on performances. As said before, this is because of the parsing that bash does when trying to expand variables in strings.
As to why the difference is "so small", I'm not entirely sure, but bash is itself an interpreter, so a lot of operations still occurs when using single quotes, and I guess the test to search a "$" character in the string doesn't have much impact on performances next to all those other operations.

A: In theory yes (because it won't look for expansions of $var etc).
In reality, doubt that you'll ever see a difference.

A: I believe it should be (just a little bit)faster. Do a little experiment - echo a string with 10 000 $ signs. In the first case (double quotes) you will have to escape them, while in the second you don't need to. The first string is twice longer and thus processing it will be slower. This is an extreme example and I doubt you will observe difference anywhere in real life.
EDIT: in response to your edit. I believe the parsing in the double qoute case happens using determined automata and thus again is linear. This is just speculation. Still you can imagine how variable parsing happens - if one sees non-escaped $ sign, then you have a variable to follow.


text:
Q: How can I overcome the error "unknown parent" when applying a Mercurial bundle. I bundle changes from one repository, email them to another machine and apply them there to a repository (for a workflow description see this question).
Suddenly I get the following error message (when applying a bundle with a command like hg unbundle -u "bundle_123.hg"):
adding changesets transaction abort!
rollback completed
abort: 00changelog.i@24ecac5680c1: unknown parent!

How can I apply this bundle despite the "unknown parent"? I hoped for a --forceoption, but unbundle doesn't have one...
Or can I avoid this error in an other way?

A: Short answer: you can't unbundle this bundle, because autonomous changesets are impossible in Mercurial
You don't have parent of 24ecac5680c1 (?) CSET in destination repository (while you must have it) - your bundle is bad and you selected wrong base on bundling


text:
Q: gcc error generation Why does neither gcc or clang generate an error when I try to compile code containing the following two lines?
int palindrome(char s[]){
    char s2[strlen(s)];

I thought in such an instance you would have to dynamically allocate memory to s2.

A: GCC has an extension for this behavior, and it's also standard in C99, known as variable length arrays.
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
Clang supports it due to GCC C and C99: http://clang.llvm.org/compatibility.html#vla

A: Section 6.7.5.2 Array declarators:

If the size is not present, the array type is an incomplete type. If
  the size is * instead of
  being an expression, the array type is a variable length array type
  of unspecified size,
  which can only be used in declarations with function prototype
  scope) such arrays are
  nonetheless complete types. If the size is an integer constant expression
  and the element
  type has a known constant size, the array type is not a variable
  length array type;
  otherwise, the array type is a variable length array type.

And an example from 6.5.3.4:

#include <stddef.h>
size_t fsize3(int n)
{
      char b[n+3];     // variable length array
      return sizeof b; // execution time sizeof
}

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf (not the standard, but a draft, and free. :)


text:
Q: Laravel database and controller issues I'm creating a website by using Laravel 5.3. There is a problems about database connection. I have 2 independent tables called languages and documents
when I retrieve data from these tables the problems happen.
Here is my code in language controller
use App\Languages;
use Illuminate\Support\Facades\DB;
class LanguageController extends Controller {
    public function getLanName(){
        $lans = Languages::all();
        return view('index',compact('lans'));
    }
}

and here is the code of language model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Languages extends Model{
    protected  $table = 'languages';
    public $timestamps = true;
    protected  $primaryKey = 'lan_id';
}

the Document controller and model are same as language
namespace App\Http\Controllers;
use App\Documents;
use Illuminate\Support\Facades\DB;
class DocumentController extends Controller{
    public function getDocName(){
        $docs = Documents::all();
            return view('index',compact('docs'));

    }
}

and this is my route and  some of html in the view:
Route::get('/',['uses' => 'DocumentController@getDocName']);
Route::get('/',['uses' => 'LanguageController@getLanName']);

        <select >
                <option  >Select Document</option>
                @foreach($docs as $doc)
                    <option value="{{$doc->docName}}">{{$doc->docName}}    </option>
                @endforeach
            </select>
            <select>
                <option >Select Language</option>
                @foreach($lans as $lan)
                    <option value="{{$lan->language}}">{{$lan->language}}</option>
                @endforeach
        </select>

I can only retrieve either language or document. If I comment language or document, the other one works well.Can't I use two controller in same route?
Many Thanks to help..

A: No, this isnt possible. You can not bind two separate controllers to a single Route. One could even argue that it is very bad practice. You could create something like an OverviewController for this single page, and just call the 2 models in your controller method.
You could also use a Repository, answered here:
https://stackoverflow.com/a/26092119


text:
Q: Execution failed for task ':app:mergeDebugAssets' i create a nativescript project from scratch --ng, dont add any code and build android; send me this error:
* What went wrong:
Execution failed for task ':app:mergeDebugAssets'.

unable to create new native thread

i add and remove platforms, uninstall full nativescript and install...
pls help me


text:
Q: Mapped-list patterns which act like enumerate So I am creating a function which behaves in a similar way to the built-in enumerate function but returns a list of tuples (index, value).
This is my function:
def my_enumerate(items):
    """return a list of tuples (i, item) where item is the ith item,
    with 0 origin, of the list items"""
    result = []
    for i in items:
        tuples = ((items.index(i)), i)
        result.append(tuples)
    return result

So when testing with the following:
ans = my_enumerate([10, 20, 30])
print(ans)

It will return:
[(0, 10), (1, 20), (2, 30)]

So it does work, but when testing with:
ans = my_enumerate(['x', 'x', 'x'])
print(ans)

It returns:
[(0, 'x'), (0, 'x'), (0, 'x')]

Where it should be:
[(0, 'x'), (1, 'x'), (2, 'x')]

How can I get it so it returns this instead?

A: The problem is items.index(i). The index function returns the first index if there are multiple of the same object. Since you have 3 'x', it will always return the index of the first 'x'.
def my_enumerate(items):
    """
    return a list of tuples (i, item) where item is the ith item, with 0 origin, of the list items
    """

    result = []
    for index in range(len(items)):
        tuples = (index, items[index])
        result.append(tuples)

    return result


text:
Q: using the iniparser Linker error I'Ve download the inparser library , and I'm trying to use the lib, by running its test program :
 gcc iniexqample.c -o o -liniparser.a

just like the documentation said. but I get this error:
     /usr/bin/ld: cannot find -liniparser.a
collect2 : error : ld returned 1 exit status

I've run  exactly the the installation steps , and  copied the the output file :
libparser.a

and
libiniparser.so.0

into    usr/bin/
I don't understand what the error message means, and how its possible to solve it .
any idea ?
By the way I'm using Ubuntu14.04


text:
Q: UnhandledPromiseRejection Hello guys i create a website and everything works locally but when i deployed in heroku its not working and i cant find why thanks for the help
heroku error:

2022-02-10T03:13:43.014545+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2022-02-10T03:13:43.014570+00:00 app[web.1]: (node:22) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2022-02-10T03:14:13.009344+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=websitechina.herokuapp.com request_id=ab93f3f6-9ccf-49e0-be7b-fe765239c47b fwd="61.219.114.7" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https

index.js:

const express = require('express')
const app = express()
const port = process.env.port || 3000
const nodemailer = require('nodemailer')

//Importer la logique de la page d acceuil
const generatorModele = require('./api/page/page-get')

//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})

app.get ('/tech', async(req,res) => {
    const techHtml = await generatorModele('tech')
    res.send(techHtml)
})

app.get ('/contact', async(req,res) => {
    const contactHtml = await generatorModele('contact')
    res.send(contactHtml)
})

app.get ('/signUp', async(req,res) => {
    const signUpHtml = await generatorModele('signUp')
    res.send(signUpHtml)
})

//ecouter la methode Post et la route
app.post('/', (req,res)=>{
    console.log(req.body)

    //nodemailer

    not working yet i know // const transporter =
      nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '',
            pass: ''
        }
    })

    transporter.sendMail(mailOptions, (error, info)=>{
        if(error){
            console.log(error)
            res.send('error')
        }else{
            console.log('Email sent' + info.response)
            res.send('success')
        }
    })

})

//ecoute les requete du repertoire styles,js,images/
app.use('/styles', express.static('/Users/hi/code/dotfiles/dev/websitechina1/styles'))
app.use('/images', express.static('/Users/hi/code/dotfiles/dev/websitechina1/images/'))
app.use('/js', express.static('/Users/hi/code/dotfiles/dev/websitechina1/js/'))
app.use(express.json())

//demarrer le  serveur et ecouter un port donne
app.listen(process.env.PORT || port,() => {
    console.log
    (`Example app listening on port ${port}`)
})

app.js

const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar_menu');

menu.addEventListener('click', function(){
    menu.classList.toggle('is-active');
    menuLinks.classList.toggle('active');
});

const contactForm = document.querySelector('.contact-form')
let fname = document.getElementById('fname')
let lname = document.getElementById('lname')
let email = document.getElementById('email')
let country = document.getElementById('country')
let subject = document.getElementById('subject')

contactForm.addEventListener('submit', (e)=>{
    e.preventDefault();

    let formData = {
        fname: fname.value,
        lname: lname.value,
        email: email.value,
        country: country.value,
        subject: subject.value
    }

    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/')
    xhr.setRequestHeader('content-type','application/json')
    xhr.onload = function(){
        console.log(xhr.responseText)
        if (xhr.responseText == 'success'){
          alert('Email sent');
          fname.value = '';
          lname.value = '';
          email.value =  '';
          country.value = '';
          subject.value = '';
        }else{
            alert('Something went wrong')
        }

    }
    xhr.send(JSON.stringify(formData))
})

A: All uses of await that can reject must be handled in some way.  They must either be surrounded by a try/catch or the caller of the async function must handle the rejection.
In this case, app.get() does not pay any attention to a returned/rejected promise from the async callback so you have to catch rejections locally.  So, in this code:
//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    const indexHtml = await generatorModele('index')

    res.send(indexHtml)

})

You aren't catching a rejection from generatorModele().  You can do that like this:
//ecouter la methode GET et la route
app.get('/', async(req,res) => {
    try {
        const indexHtml = await generatorModele('index');
        res.send(indexHtml);
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});

All, your other uses of await need something similar.

FYI, when you have a problem like this and the error message doesn't point exactly to the problem, the first thing to do is make sure you're catching and logging all possible errors.  This code I show above is one such example.


text:
Q: why are .pc files not listed in one place I am on Debian buster. I was reading the manpage of pkg-config and found that .pc files are and can be listed in many places . From the manpage -

pkg-config  retrieves  information  about  packages from special
  metadata files. These files are named after the package, and has a .pc
  extension.  On most systems, pkg-config looks in /usr/lib/pkgconfig,
  /usr/share/pkgconfig, /usr/local/lib/pkgconfig and
  /usr/local/share/pkgconfig for these files.  It will additionally look
  in the colon-separated (on Windows, semicolon-separated) list of
  directories specified by the PKG_CONFIG_PATH environment variable.

*

*From pkg-config manpage

sure enough I saw that there are packages in /usr/lib/pkgconfig/, /usr/lib/x86_64-linux-gnu/pkgconfig/ and /usr/share/pkgconfig/ , while I can understand the /usr/local/.. part for locally compiled/built apps. I do not understand why there is a distinction between /usr/lib/pkgconfig/ and /usr/share/pkgconfig . Is it something to do with some things need to be in userspace https://en.wikipedia.org/wiki/User_space or something else entirely ?

A: The distinction is related to architecture independence. .pc files which might be architecture-specific go in /usr/lib (on Debian, /usr/lib/pkgconfig for pre-multiarch packages, /usr/lib/<triplet>/pkgconfig for multiarch packages), .pc files which are sure to be architecture-independent can go in /usr/share (only /usr/share/pkgconfig, no need to distinguish triplets here).


text:
Q: Multi select and button function together python kivy mobileapp I am using ListAdapter to create a list of buttons and also use them as multiselect.
I want something like button + multiselect  that means; when I touch and hold a button for sometime, it should go for multi selection. On a single button click, it should work as a normal button.
Any idea how this is done in Kivy?
self.list_adapter = ListAdapter(data=[],selection_mode='multiple',
                                cls=ListItemButton, sorted_keys=[])


text:
Q: C# Convert nested groups to List So here is a bunch of classes that will end up being grouped.
public class Component
{
    public string Name { get; set;}

    public int ComponentType { get; set; }

    public float Range { get; set; }
}

public class ComponentGroup
{
    /// <summary>
    /// Type of component in the group
    /// </summary>
    public int Type { get; set; }

    /// <summary>
    /// List of Components
    /// </summary>
    public List<Component> Components { get; set; }

    /// <summary>
    /// Range
    /// </summary>
    public float Range { get; set; }
}

public class ComponentGroupType
{
    public ComponentType ComponentType { get; set; }
    public List<ComponentGroup> ComponentGroups { get; set; }

    public ComponentGroupType()
    {
        ComponentGroups = new List<ComponentGroup>();
    }

    public ComponentGroupType(List<ComponentGroup> componentGroups )
    {
        ComponentGroups = componentGroups;
    }
}

Now lets say I have List<Component> which is populated like so.
Component() { Name = "A", ComponentType = 1, Range = 10000 }
Component() { Name = "B", ComponentType = 1, Range = 10000 }
Component() { Name = "C", ComponentType = 1, Range = 10000 }
Component() { Name = "D", ComponentType = 1, Range = 1000 }
Component() { Name = "E", ComponentType = 1, Range = 1000 }
Component() { Name = "F", ComponentType = 2, Range = 1000000 }
Component() { Name = "G", ComponentType = 2, Range = 1000000 }
Component() { Name = "H", ComponentType = 3, Range = 1000000 }

What I want to do is group the items by ComponentType and then by Range which means I should end up with something like this.
List<ComponentGroupType>
 |- ComponentGroupType() ComponentType = 1
    |-- ComponentGroup() Range = 10000
        |--- Component() { Name = "A", ComponentType = 1, Range = 10000 }
        |--- Component() { Name = "B", ComponentType = 1, Range = 10000 }
        |--- Component() { Name = "C", ComponentType = 1, Range = 10000 }
    |-- ComponentGroup() Range = 1000
        |--- Component() { Name = "D", ComponentType = 1, Range = 1000 }
        |--- Component() { Name = "E", ComponentType = 1, Range = 1000 }

|- ComponentGroupType() ComponentType = 2
    |-- ComponentGroup() Range = 1000000
        |--- Component() { Name = "F", ComponentType = 2, Range = 1000000 }
        |--- Component() { Name = "G", ComponentType = 2, Range = 1000000 }

|- ComponentGroupType() ComponentType = 3
        |-- ComponentGroup() Range = 1000000
        |--- Component() { Name = "H", ComponentType = 3, Range = 1000000 }

Sorry for the poor representation but hopefully you get an idea of how they are grouped.
So here is my nested grouping code which seems to do the grouping part ok.
var groups = from component in _components
             group component by component.ComponentType into group1
             from group2 in
                 (from component in group1
                 group component by component.Range)
             group group2 by group1.Key;

What I want is to convert the grouping data to the above types i.e. groups is TypeOf(List<ComponentGroupType>) which contains a lists of ComponentGroups which contains lists of Component etc etc.

A: Actually the LINQ query for producing the desired result is more natural than the nested grouping example. Just do exactly what you want - group by ComponentType, then by Range:
var groups = (
    from component in _components
    group component by component.ComponentType into typeGroup
    select new ComponentGroupType
    {
        ComponentType = typeGroup.Key,
        ComponentGroups = (
           from component in typeGroup
           group component by component.Range into rangeGroup
           select new ComponentGroup
           {
               Type = typeGroup.Key,
               Range = rangeGroup.Key,
               Components = rangeGroup.ToList()
           }
       ).ToList()
    }
).ToList();


text:
Q: NuGet - managing and removing multi version packages in single solution SCENARIO
One VS solution with n projects. Project A references package Y v1, Project B references package Y v2. It is now not possible to update all references to package Y for all projects in the solution using the NuGet package manage dialog at the solution level, it is only possible to do this when all projects reference the same version of package Y. Not a big deal for only two projects, but I'm dealing with lots of projects that through poor package management are referencing many package versions when they should all reference the same version.
Before I spend the afternoon writing a console app. to auto update all package.config files for a solution so that each referenced package is only referenced via it's latest version (latest referenced, not the very latest, with exceptions/caveats etc)....is there a tool/method for doing this already? Or some other approach I am unaware of?

A: Firstly, only changing the xml files is not enough for NuGet to change the references. In fact, sometimes you get errors when you modify packages.config files by hand. package manager console has the ability to update all packages in the solution; you can simply call "Get-Project -All | Update-Package" command.
And secondly, before calling this command, make sure you have proper package sources available.

A: You can accomplish this in the Nuget Package Manager for Solution (To find the menu, right-click on the solution or go in Tools->Library Package Manager). The Update tab in this dialog will propose to update for multiple projects where the update is applicable. The same applies with uninstall from the Installed tab.
Or with the solution opened, open the NuGet Console, run "Update-Package" to update all packages for all projects. It can also work to update specific packages/projects :
Update-Package [-Id] <string> [-IgnoreDependencies] [-ProjectName <string>] [-Version <string>] [-Safe] [-Source <string>] [-IncludePrerelease]

It will find the same updates than in the dialog, just make sure the right feed (or "All") is selected in "Package Source:" dropdown.
example:
PM> install-package NUnit -version 2.5.9.10348 -ProjectName ProjectA
Successfully installed 'NUnit 2.5.9.10348'.
Successfully added 'NUnit 2.5.9.10348' to ProjectA.

PM> install-package NUnit -version 2.5.10.11092 -ProjectName ProjectB
Successfully installed 'NUnit 2.5.10.11092'.
Successfully added 'NUnit 2.5.10.11092' to ProjectB.

PM> update-package
Updating 'NUnit' from version '2.5.9.10348' to '2.6.0.12054' in project 'ProjectA'.
Successfully removed 'NUnit 2.5.9.10348' from ProjectA.
Successfully installed 'NUnit 2.6.0.12054'.
Successfully added 'NUnit 2.6.0.12054' to ProjectA.
Successfully uninstalled 'NUnit 2.5.9.10348'.
Updating 'NUnit' from version '2.5.10.11092' to '2.6.0.12054' in project 'ProjectB'.
Successfully removed 'NUnit 2.5.10.11092' from ProjectB.
Successfully added 'NUnit 2.6.0.12054' to ProjectB.
Successfully uninstalled 'NUnit 2.5.10.11092'.


text:
Q: Laravel Resource is empty I'm passing data to these functions via Axios/Vue. The Eloquent interactions work perfectly. When I store (i.e. create a new call) the resource returns as expected. When I update a record, it updates in the database, however, I get a blank response. In other words the return new CallResource($call) returns nothing. I can't work out where I've gone wrong.
public function store(Request $request)
{
    $call = $this->validate($request, [
        'title' => 'required',
        'job_id' => 'required',
        'location' => 'required',
        'starts' => 'required|date|before:ends',
        'ends' => 'required|date|after:starts',
        'rate' => 'required'
    ]);

    $call = Call::create($call);

    return new CallResource($call);
}

public function update(Request $request, $id)
{
    $data = $this->validate($request, [
        'title' => 'required',
        'job_id' => 'required',
        'location' => 'required',
        'starts' => 'required|date|before:ends',
        'ends' => 'required|date|after:starts',
        'rate' => 'required'
    ]);

     $call = Call::find($id);
     $call->update($data);

    return new CallResource($call);
}

The call resource is really simple
class CallResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
        'id' => $this->id,
        'title' => $this->title,
        'location' => $this->location,
        'starts' => $this->starts,
        'ends' => $this->ends,
        'rate' => $this->rate
        ];
    }
}

Laravel 5.6 fyi.


text:
Q: Why is code in that is only supposed to be accessible to one target failing to compile for a different target? I'm having a weird issue. I'm trying to merge two projects (one iOS and one tvOS, both with a mix of objective-c and Swift) into a new single xcode project so that going forward they can share code.
I created a new project, created an iOS target and tvOS target, and brought all of the iOS code over, pretty quickly it was compiling fine for the iOS target. When bringing all of the code from the previous iOS project over I set all of the files to only be accessible to the iOS target.
Then I did the same with the tvOS code, once again only setting the files to be accessible to the tvOS target.
So because both of these code bases are very similar there are a lot of duplicated classes, but that over time have slightly diverged. Eventually my goal is to unify these, but for now I just need to get all the code in the same place. So I have classes with the same name, I was hoping that just having files only accessible to the relevant target would solve this problem for me, but it only kind of does.
After migrating all of the code, the iOS target (which I got working before starting with the tvOS code) still compiles, however, the tvOS target doesn't. It fails on errors that should only be accessible to the iOS target, because the classnames and method are already used ('Duplicate interface definition for class' and similar errors).
So I really don't understand what's happening here -
Why does the the tvOS target have access to code that is only supposed to be available to the iOS target, but not the other way around? What can I do to fix this? (besides just wrapping all of the code in #if Target_OS_ios).
One other thing, the tvOS target only seems to have access to objective-c files from the iOS target, none of the errors have come up in any of the swift classes. Not sure if that is relevant or not.


text:
Q: Why is it hard to find a Eevee in the Trophy Garden in Diamond and Pearl? It's just hard to find one Eevee in Pearl and Diamond. Why is it?

A: Eevee is a special Pokemon in the Trophy Garden, which means it has to be one of the last two Pokemon mentioned by the owner, Mr. Backlot. He mentions a new Pokemon every 24 hours and you can soft reset which Pokemon he mentions, but you have to do it in the first place, otherwise Eevee won't be there at all.
This also requires the National Pokedex, otherwise only the "normal" Pokemon appear in the Trophy Garden.
Finally, when Eevee does appear, it's still only a 5% chance, so you'll have to search for a while.


text:
Q: JavaFX not accepting the correct URL for Image object While attempting to mess around with JavaFX and its basic functions on java 1.8 I kept running into the issue that my Image objects would not accept the URL for a png file contained within my src folder. The icon image object gave me trouble at first but when I copied the file name via the "Copy Path/Reference..." option it worked. This was not the case for the coinImage object where no matter how I format the image URL it will not accept it. To clarify, my files are named "icon.png" and "coin.png" and they are placed in the src folder. I have tried the following formats:
Image coinImage = new Image("coin.png");
Image coinImage = new Image("/coin.png");
Image coinImage = new Image("file:coin.png");
Image coinImage = new Image("file:/coin.png");

Below is the code which most relates to the problem to reduce on the size of this question:
public class MainStage extends Application {
    public void start(Stage stage) throws Exception{
        Group root = new Group();
        Scene scene = new Scene(root,1000,1000,Color.LIGHTSKYBLUE);
        Image icon = new Image("icon.png");

        Image coinImage = new Image("coin.png");
        ImageView imageView = new ImageView(coinImage);
        imageView.setX(400);
        imageView.setY(500);

        root.getChildren().add(imageView);
        stage.getIcons().add(icon);
        stage.setTitle("Test");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Here are all of my imports as well but I do not think they are the issue here:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

If any additional information is needed I should be able to provide it. Thanks.

A: It is recommended to keep images and resources in a dedicated assets folder.
You need to have the assets folder in your classpath.
Set the assets directory as a resource directory and then create a javafx Image from location: "/coinImage.png":
If you are using IntelliJ To set folder as resource directory follow this guide

A: This issue is coming from the fact that Java will search for your image file in the bin directory. You should put your image in the bin directory.
I added a small print in your code that can help for debugging
System.out.println("GET  PATH"+this.getClass().getClassLoader().getResource("").getPath());

The output that i got
GET PATH /D:/Nabil-local/eclipse-workspace/Stackoverflow/bin/

I think there is another way to specify a folder


text:
Q: Apache+django pythonpath confusion: ImportError: Could not import settings 'mysite.settings' I use python 2.4 and django 1.2.2 and apache 2.2.3
Write httpd.conf section like this:
<Location "/mysite/">
    PythonPath "['/home/usr/www'] + sys.path"
    SetHandler python-program
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE mysite.settings
    PythonOption django.root /mysite
    PythonDebug On
</Location>

settings.py path: /home/usr/www/mysite/
but it doesn't work, when i visit http://localhost/mysite/

ImportError: Could not import settings
  'mysite.settings'

i modified it, change /home/usr/www to /var/www and copy settings.py in /var/www it works.
So why apache treat two directories differently?

A: Are you using SELinux? Compare the output of
ls -laZ /var/www

and
ls -laZ /home/usr/www

Chances are that your home directory cannot be accessed by the apache process. If this is the problem, it might be solved as simply as
chcon -R --reference=/var/www /home/usr/www
chmod og+x /home/usr /home/usr/www

BTW: http://docs.djangoproject.com/en/dev/howto/deployment/modpython/ warns that "Support for mod_python will be deprecated in a future release of Django. If you are configuring a new deployment, you are strongly encouraged to consider using mod_wsgi or any of the other supported backends."

A: Add PythonPath "['/home/usr/www/mysite'] + sys.path"


text:
Q: Popular uma ListView com ArrayAdapter Preciso popular uma ListView. Tenho uma classe que representa a Entidade Cliete,
um classe que é responsável pelas persistências do Banco de Dados e por fim uma classe ClienteDAO, que persiste os dados da entidade Cliente.
Seguem as Classes:
ClienteDAO
public class ClienteDAO {

private SQLiteDatabase DB;
    protected Banco auxBanco;
    private String TABELA = "CLIENTE";

    public ClienteDAO(Context context)
    {
            Banco newBanco = new Banco(context);
    DB = newBanco.getWritableDatabase();
    //newBanco.onCreate(DB);
    this.auxBanco = newBanco;
}

public ArrayList<Cliente> Listar_Clientes(){

    ArrayList<Cliente> list = new ArrayList<Cliente>();

    String[] colunas = new String[]{"_ID",
                                    "NOME",
                                    "APELIDO",
                                    "OBSERVACAO",
                                    "CELULAR",
                                    "DATA_CADASTRO",
                                    "DDD"};

    Cursor Sn = DB.query(this.TABELA, colunas, null, null, null, null, "NOME ASC");

    if(Sn.getCount() > 0){
        Sn.moveToFirst();

        do{
            Cliente newCliente = new Cliente();
            newCliente.set_ID(Sn.getLong(Sn.getColumnIndex("_ID")));
            newCliente.setNome(Sn.getString(Sn.getColumnIndex("NOME")));
            newCliente.setApelido(Sn.getString(Sn.getColumnIndex("APELIDO")));
            newCliente.setCelular(Sn.getString(Sn.getColumnIndex("CELULAR")));
            newCliente.setDDD(Sn.getString(Sn.getColumnIndex("DDD")));
            newCliente.setObservacao(Sn.getString(Sn.getColumnIndex("OBSERVACAO")));
            newCliente.setCelular(Sn.getString(Sn.getColumnIndex("DATA_CADASTRO")));
            list.add(newCliente);

        }while(Sn.moveToNext());
    }
    return(list);
    }

ClienteAdapter
public class ClienteAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Cliente> list;

    public ClienteAdapter(Context context, ArrayList<Cliente> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        list.size();
        return 0;
    }

    @Override
    public Object getItem(int position) {
        list.get(position);
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Cliente cCliente = list.get(position);
        View layout;

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            layout  = inflater.inflate(R.layout.itens_relacao_cliente, null);
        }else
        {
            layout = convertView;
        }

        TextView Nome = (TextView) layout.findViewById(R.id.lblNome);
        Nome.setText(cCliente.getNome());

        TextView Apelido = (TextView) layout.findViewById(R.id.lblApelido);
        Apelido.setText(cCliente.getApelido());

        return layout;
        }
    }

Relacao_Clientes
public class Relacao_cliente extends Activity {

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

    try {
        ClienteDAO BD = new ClienteDAO(this);
        ArrayList<Cliente> Lista_Clientes =  BD.Listar_Clientes();

        ListView ListViewR_Cliente = (ListView)     findViewById(R.id.lvRelacao_Cliente);
        ListViewR_Cliente.setAdapter(new ClienteAdapter(this,  Lista_Clientes));

            } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
        }
    }
}

A: Agora entendi o problema com seu código, na verdade tem um pequeno erro no Adapter, esqueceu de retornar os dados de verdade.
A classe com os acertos é:
public class ClienteAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Cliente> list;

    public ClienteAdapter(Context context, ArrayList<Cliente> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
        // Em vez de return 0;
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
        // Em vez de return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Restante do codigo ok
    }
}

Como retornou 0 no getCount, o ListView acha que o Adapter esta vazio, logo nada é gerado. Acredito que com esses acertos seu Adapter funcione.


text:
Q: Enable "performance mode" for existing aws amplify env I was looking for ways to improve performance of my aws amplify application and got some hits to enable for my existing application here. But when I follow the given steps, I don't see the option "Enable performance mode." in step 5, given the screenshot below.

In the action dropdown I only see "Disconnect branch". I am not sure what's wrong with my amplify app settings.

A: So its not obvious if its possible to enable performance mode from aws console. What worked for me was from aws cli. I updated my aws cli to latest version (2.2.3) from (2.0.3) which does not had option --enable-performance-mode, and ran update command e.g
aws amplify update-branch --app-id xxxxx --branch-name prod --enable-performance-mode
Now I can see performance mode is enabled in aws console.


text:
Q: Search places by category over a corridor returns too many in some spots of the corridor Search places by category over a corridor returns often too many places in some areas of the corridor and nothing on the others due to the maxitems.
Is there a way to ask the searchEngine to return few places for each areas of the corridor. Basically a spread?
Thank you


text:
Q: How to show that this integral of the normal distribution is finite? Numerically, I have noticed that
$$\int_{-\infty}^{\infty} \dfrac{\phi(x)^2}{\Phi(x)}dx < \infty$$
where $\phi$ and $\Phi$ are the standard normal pdf and cdf. However, I do not see how to prove it. I would appreciate any hints.

A: Here is a self-contained elementary argument, by a comparison with the Laplace distribution. We show
$$\int_{-\infty}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<\frac{1}{2\sqrt{\pi}}+\sqrt{\frac\pi2}\simeq 1.535<\infty$$
The positive side of the integral has the bound
$$\int_{0}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<
\int_{0}^{\infty}\frac{\phi(x)^2}{1/2}dx=\frac{1}{2\sqrt{\pi}}$$
The negative side of the integral has the bound
$$\int_{-\infty}^{0}\frac{\phi(x)^2}{\Phi(x)}dx<
\int_{-\infty}^{0}\sqrt{2\pi}\frac{f_L(x)^2}{F_L(x)}dx=\sqrt{\frac\pi2}\phantom{1<\infty}$$
Since the Laplace distribution has $f_L(x)=F_L(x)=\frac12 e^x$ on $x<0$, the integral is easy.
To prove that $\phi^2/\Phi<\sqrt{2\pi} f_L^2/F_L$, we start by proving
$$g(u)=\frac{-(2u+1)\exp\left(\frac{-u^2}2-u\right)}{\pi}<1$$

Using the first-derivative test, the maximum occurs at exactly $u_\max=-(3+\sqrt{17})/4$, and by numerical evaluation $g(u_\max)<1$. Thus for $x<0$,
\begin{align}
\phi(x)^2\frac{F_L(x)}{f_L^2(x)}
&=\frac{\exp(-x^2)}{2\pi}\frac{\frac12 \exp(x)}{\frac14 \exp(2x)}\\
&=\frac{\exp(-x^2-x)}{\pi}\\
&=\int_{u=-\infty}^{x}\frac{-(2u+1)\exp(-u^2-u)}{\pi}du\\
&<\int_{u=-\infty}^{x}\exp(-u^2/2)du\\
&=\sqrt{2\pi}\Phi(x)
\end{align}
which is what we need.

A: The integral relates to the expectation value of the normal hazard function
$$E_X[h(x)] = E_X\left[\dfrac{\phi(x)}{1-\Phi(x)}\right] = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{1-\Phi(x)}\right) \phi(x) dx  = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{\Phi(x)}\right) \phi(x) dx$$
The last step is due to the symmetry.
This hazard function will be approximately asymptotic to $x$ at positive infinity and will be smaller than $x^2$ (except in some region where it is finite).
Since $E_X[x^2]$ is finite so must be $E_X[h(x)]$

The big difference between $x^2$, which is already resulting in a finite integral, and the hazard function $h(x)$ indicates that this is not a hard problem and there are probably many approaches to show that the integral does not diverge (as seen in many answers to the question).
For instance, we can more precisely see this asymptotic behaviour of the hazard function in the expression
$$log(1-F(t)) = log(S(t)) = -\int_{-\infty}^x h(t) dt$$
This can be related to the asymptotic behavior of the error function (as $\text{erfc}(x/\sqrt{2})/2 = 1-F(x)$), which has exponential bounds with factor $e^{-x^2}$ for $x>0$.

A: Intuitive approach
$\Phi(x)$ is changing in the interval $[0,1]$, whereas $\phi(x)^2$ is itself a normal distribution which is integrable. Thus, the only reason why the integral could not be finite, is because it diverges in the limit $x\rightarrow -\infty$.
By L'Hôpital's rule:
$$
\frac{\phi^2(x)}{\Phi(x)}\sim
\frac{2\phi(x)\phi'(x)}{\phi(x)}\sim
\phi'(x)= -\frac{2x}{\sigma^2}\phi(x)\\(\text{as }x\rightarrow -\infty)
$$
In other words, the asymptotic form of the integrand for $x\rightarrow-\infty$ is
$$
\frac{\phi^2(x)}{\Phi(x)}\sim -\frac{2x}{\sigma^2}\phi(x),
$$
the integral of which converges in the desired limit.
Rigorous approach
Perhaps, a more rigorous way could be to show that in the limit $x\rightarrow -\infty$ the integrand decays faster than $1/x$,a nd hence convergent.
We this apply the L'Hôpital's rule to the following:
By L'Hôpital's rule:
$$
\lim_{x\rightarrow -\infty}\frac{x\phi^2(x)}{\Phi(x)}=
\lim_{x\rightarrow -\infty}\frac{\phi^2(x)+x\phi(x)\phi'(x)}{\phi(x)}=
\lim_{x\rightarrow -\infty}\left[\phi(x)+x\phi'(x)\right]=
\lim_{x\rightarrow -\infty}\left[1-\frac{x}{\sigma^2}\right]\phi(x)=0.
$$Thus, the integral converges in the limit in question.
Remarks:

*

*I appreciate @SextusEmpiricus remarks, which led to improvement of this answer.

*$$\phi(x)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{x^2}{2\sigma^2}}$$

A: The integral on any interval $[a, \infty)$ is clearly finite. Now $\varphi(x)$ is convex on $(-\infty, -1]$ and so the tangent line to $\varphi$ at any $x < -1$ lies below $\varphi$.  This tangent intersects the $x$-axis in $x+x^{-1}$. This gives the lower bound $$\Phi(x) > -\frac1{2x} \varphi(x)$$ for all $x < -1$ and so $$\frac{\varphi(x)^2}{\Phi(x)} < -2x \varphi(x)$$ for all $x<-1$.  This shows that the integral over $(-\infty, -1]$ is also finite.

A: Intuitively, the result is obvious because (a) $\phi$ is a rapidly decreasing function (its magnitude decreases at a quadratic exponential rate) and (b) $\Phi$ is bounded above and, for negative $x,$ is also rapidly decreasing at essentially the same rate as $\phi.$  Thus the fraction $\phi^2/\Phi$ decreases rapidly for both positive and negative $x,$ while remaining bounded in between, whence its integral is very nicely behaved and finite.

The problem, then, is to make this intuition rigorous.  The rigor merely parallels the foregoing argument by making suitable quantitative comparisons.
When $x\gt 0,$ $\Phi(x)\ge 1/2$ (by a familiar symmetry argument).  Whence (in this case) the integrand is bounded above in magnitude by
$$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| \le 2\phi(x)^2 \lt 2\exp(-x^2)/\sqrt{2\pi}$$
which (because it is proportional to the density of another Normal distribution) has a finite integral.
The harder part is the integral over negative $x.$  But here, the Mills Ratio is
$$R(-x) = \frac{\Phi(x)}{\phi(x)}$$
which, as the linked post explains, is bounded below by $-x/(x^2+1).$  Thus, for large negative $x$ (say, $x \le -1$),
$$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| = \bigg|\phi(x)\left(\frac{1}{R(-x)}\right)\bigg| \le \phi(x) \frac{x^2+1}{|x|} \le 2|x|\phi(x)$$
whose integral also converges (it can integrated exactly using elementary techniques).

Since $\phi(x)^2/\Phi(x)$ is bounded on the remaining interval $[-1,0],$ we have established that its integral over the entire real line is bounded in magnitude by the sum of three convergent quantities, whence it is finite, QED.

This argument continues to apply, essentially without change, to any integrand of the form $\phi(x)^k/\Phi(x)$ for $k\gt 1.$  It also shows (look more closely at the upper and lower bounds for Mills' Ratio) that the integral diverges when $k\le 1.$

(For a plot with $k=1$ -- which is just the inverse Mills' Ratio -- see the last figure of https://stats.stackexchange.com/a/166277/919.)


text:
Q: Strange ListView with UIL Refreshing Issue The ListView always shows different pictures as soon as the pictures get into the view, and then change back to the correct pictures.
I do understand the view is recycling, but why it is doing this?
Neither Gallery app or QuickPic app has this behavior.  This app is quick loading and doesn't consume a lot of memory either.
What's going on???  How do I make it perform like QuickPic or Gallery?
Adapter class:
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
      ViewHolder viewHolder = new ViewHolder();

      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      if (convertView == null) {
          convertView = inflater.inflate(R.layout.gridview_layout, parent, false);

          viewHolder.imageView = (ImageView)convertView.findViewById(R.id.GridViewImage);
          convertView.setTag(viewHolder);
      }
      else
      {
          viewHolder = (ViewHolder)convertView.getTag();
      }

      GridViewImageLoader.getImageLoader(mContext).displayImage(getItem(position).getImageUrl(), viewHolder.imageView);

      return convertView;
    }

ImageLoader class:
public class GridViewImageLoader {

    private GridViewImageLoader(){   }

    public static ImageLoader getImageLoader(Context context){
        try {
            if (ImageLoader.getInstance().isInited()) {
                return ImageLoader.getInstance();
            }
            DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.automatic_icon)
            .showImageForEmptyUri(R.drawable.ic_empty)
            .showImageOnFail(R.drawable.ic_error)
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .considerExifParams(true)
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.RGB_565) // default
//            .decodingOptions()
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();

            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            .threadPriority(Thread.NORM_PRIORITY)
            .denyCacheImageMultipleSizesInMemory()
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .defaultDisplayImageOptions(defaultOptions).build();

            ImageLoader.getInstance().init(config);
            return ImageLoader.getInstance();
        } catch (Exception ex) {
            return null;
        }
    }
}

Thank you so much

A: Try :
viewHolder.imageView.setImageResource(0);

right before you call:
GridViewImageLoader.getImageLoader(mContext).displayImage(getItem(position).getImageUrl(), viewHolder.imageView);


text:
Q: Issue on localhost index page not working I am using the wamp server locally, my project index page not working. However, this project is working perfectly fine on live hosting.
I find something in browser network were showing with stop icon Provisional headers are shown
I am attaching some pictures to define the issue easily.


text:
Q: UIView not autoreleased. Where is my issue? I create UIViews based on xib files programmaticaly and add them to a scrollView. This works so far. If the amount changes I recreate the grid of UIViews (in my case so called theme thumbs). I remove the old ones before I recreate the new ones. The problem is the memory is never released and for every new creation memory usage piles up. Even if I remove one single thumb the memory isn´t released.
Instruments doesn´t show leaks. Dealloc in my ViewController is never called.
I use ARC and I know that I have to avoid retained references. But clearly I have used them and don´t understand where. It would be great if someone could give me a hint where I did it as I have read a lot of posts here but still don´t understand it. NSZombiesEnabled is off.
My code:
-(void)createGrid
{
    for (UIView *subview in self.scrollView.subviews) {
        if ([subview tag] < 10000 && ![subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
    }
    int col = 0;
    int row = 0;
    [self setupFetchedResultsController];
    for (int i = 0; i<[[self.fetchedResultsController fetchedObjects] count]; i++)
    {
        col = i % THEME_COLUMNS;
        row = i / THEME_COLUMNS;
        ThemeThumbVC *themeThumb = [[ThemeThumbVC alloc] init];
        [self.scrollView addSubview:themeThumb.view];

        // configurate thumb
        themeThumb.managedObjectContext = self.managedObjectContext;
        themeThumb.fetchedResultsController = self.fetchedResultsController;
        themeThumb.theme = [[self.fetchedResultsController fetchedObjects] objectAtIndex:i];
        [themeThumb.themeThumbImage setImage:[UIImage imageWithContentsOfFile:[[[self.fetchedResultsController fetchedObjects] objectAtIndex:i] iconImageURL]]];
        [themeThumb setTag:i];
        [themeThumb.view setTag:i];
        [themeThumb.view setFrame:CGRectMake(col*kThemeGritXOffset+(col*1), row*kThemeGritYOffset, kThemeGritXOffset+1, kThemeGritYOffset)];
        [self addChildViewController:(UIViewController*) themeThumb];
    }
    [self.scrollView setContentSize:CGSizeMake(320, row*kThemeGritYOffset+kThemeGritYOffset)];
}

A: If a thumb view is encapsulated by a child view controller, then wouldn't you need to remove the child view controller from the parent view controller at some point?
If the child view controller is not being removed from the parent view controller, then my best guess is that the child view controller is retaining its thumb view.
Have you thought about using a UICollectionViewController to create a grid of thumb views?


text:
Q: Combine a Flow and a non Flow api response Kotlin I currently have a piece of logic as follows:
interface anotherRepository {
      fun getThings():  Flow<List<String>>
}

interface repository {
    suspend fun getSomeThings(): AsyncResult<SomeThings>
}

when (val result = repository.getSomeThings()) {
            is AsyncResult.Success -> {
                anotherRepository.getThings().collectLatest {
                    // update the state
                }
                else -> { }
            }
        }

The problem I am having is that, if repository.getSomeThings has been triggered multiple times before, anotherRepository.getThings is getting triggered for the amount of all the pre-loaded values from repository.getSomeThings. I was wondering what is the proper way to use these repositories, one a suspend function, the other a Flow together. The equivalent behaviour that is combineLatest{} in Rx.
Thank you.

A: There are a couple of ways to solve your problem. One way is just to call
repository.getSomeThings() in the collectLatest block and cache last result:
var lastResult: AsyncResult<SomeThings>? = null

anotherRepository.getThings().collectLatest {
    if (lastResult == null) {
        lastResult = repository.getSomeThings()
    }
    // use lastResult and List<String>
}

Another approach is to create a Flow, which will be calling repository.getSomeThings() function, and combine two Flows:
combine(
  anotherRepository.getThings(),
  flow {emit(repository.getSomeThings())}
) { result1: List<String>, result2: AsyncResult<SomeThings>  ->
  ...
}