text:
Q: SQL Specify 2 different conditions for 2 different columns in where clause with both having to be true How can i write an sql query to only return rows from a table
where for example column A is not null AND columb B is not 0
the way i am writing it is:
where A is not null AND B !=0

but the problem is that the query result is also eliminating rows where only one of the conditions is true such as column a being null but column b being anything but 0 & vice versa
I need the query to only eliminate (not return) the rows where BOTH conditions of my where clause are met.
I only want the result i get from query to be rows from the table where column A is not NUll and column B IS NOT = 0 but i need BOTH conditions to be met not just one of them

A: If I understand correctly, you are looking for:
where A is not null AND B <> 0

If your where clause actually is more complicated (e.g., also has an OR in it), then put brackets around the above, e.g.:
where (A is not null AND B <> 0) OR ...

A:
I need the query to ... not return the rows where BOTH
  conditions of my where clause are met.

It sounds like you want to negate the WHERE clause. Like so:
WHERE NOT (A IS NOT NULL AND B !=0)

This can be rewritten without the double negative:
WHERE (A IS NULL OR B = 0 OR B IS NULL)

A: Someone posted this Answer on here but then they deleted it (not sure why?) but their answer worked and it was.
WHERE NOT(A is null AND B=0)

i tried using
where A is not null AND B <> 0

and
where (A is not null AND B <> 0)

but the where clause would be triggered even if only 1 of the conditions was met and I needed it to be triggered only when both conditions where met.
So again, the answer to my questions was using the below code.
WHERE NOT(A is null AND B=0)

Thanks!


text:
Q: Saving the results of a SELECT Stored procedure ASP.NET Entity Framework I am searching all over the web for an answer to this question and I have come up short.  I have a simple stored procedure that selects columns from a view, I would like to save this data in a Model in my program.  However, when I call the stored procedure it has a return type of ObjectResult, so I have been trying to implement this but I am at a loss for what datatype to use in my model.
CREATE PROCEDURE [dbo].[GetPartnerCompanyRelationships]
    @inputCoid INT
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT [CoId]
      ,[CompanyName]
      ,[CompanyId]
      ,[PartnerCoId]
      ,[PartnerCompanyName]
      ,Count(*) as DocumentTotal
  FROM vwDocuments
  where coid = @inputCoid and DocumentType = 'order' and PartnerCoId <> @inputCoid
  group by [CoId]
      ,[CompanyName]
      ,[CompanyId]
      ,[PartnerCoId]
      ,[PartnerCompanyName]
union all
SELECT [CoId]
      ,[CompanyName]
      ,[CompanyId]
      ,[PartnerCoId]
      ,[PartnerCompanyName]
      ,Count(*) as DocumentTotal
  FROM vwDocuments
  where PartnerCoId = @inputCoid and DocumentType = 'order' and CoId <> @inputCoid
  group by [CoId]
      ,[CompanyName]
      ,[CompanyId]
      ,[PartnerCoId]
      ,[PartnerCompanyName]

END

The procedure just selects these columns.
I want my model to hold this data so I can reference it in a View and build a table from it but the issue is saving this data.
public ObjectResult GetPartnerCompanyRelationships(int coid)
        {
            using (var context = LTPortalEntities.getEntities())
            {
                ObjectResult x = context.GetPartnerCompanyRelationships(coid);
                return x;
            }
        }

This is what I have tried in my datahelper class, and in my Controller:
var companyList = _da.GetPartnerCompanyRelationships(coid);
                    foreach (vwDocument item in companyList)
                    {
                        MyDashBoard.CompanyList.Add(item);
                    }

If this is vague please let me know what to include, this is my first shot at getting information with a stored procedure.
One of the other issues I have encountered is trying to ORDER BY with a select from a view, my procedure didn't like that very much.  So I am wondering if creating a function would be easier? If so, how to get that into the edmx.

A: I was not aware that the stored procedure added an object to my data class
I simply had to update my Model with:
 public List<GetPartnerCompanyRelationships_Result> DashboardCompanyList { get; set; }

Update my DBHelper with:
public List<GetPartnerCompanyRelationships_Result> GetPartnerCompanyRelationships(int coid)
        {
            using (var context = Entities.getEntities())
            {
                var x = context.GetPartnerCompanyRelationships(coid);
                return x.ToList();
            }
        }

And call the method from my controller:
MyDashBoard.DashboardCompanyList = _da.GetPartnerCompanyRelationships(coid);

This allowed me to use all of the complex data in my model.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a Table in SQL I am not sure why this syntax does not work. I want to create a new table that merges two existing tables.
CREATE TABLE blah(
SELECT T1.Q1, T1.Q2, T1.Q3, T1.ID, T1.QOL, T2.ID, T2.L1, T2.L2
FROM T1, T2
WHERE T1.ID = T2.ID)

A: look like you are missing as here,try
CREATE TABLE blah as (
SELECT T1.BUSINESSNAME, T1.STREETADDRESS, T1.CITYNAME, T1.ID, T1.QOL, T2.ID, T2.L1, T2.L2
FROM T1, T2
WHERE T1.ID = T2.ID)

A: Yeah whole query is correct just AS is missing.
CREATE TABLE blah AS (
SELECT T1.Q1, T1.Q2, T1.Q3, T1.ID, T1.QOL, T2.ID, T2.L1, T2.L2
FROM T1, T2
WHERE T1.ID = T2.ID);

A: SELECT T1.Q1, T1.Q2, T1.Q3, T1.ID, T1.QOL, T2.ID, T2.L1, T2.L2
INTO blah
FROM T1, T2
WHERE T1.ID = T2.ID

A: The name of column ID is specified two times: in T1.ID and in T2.ID.
At least in postgres this is not accepted.

A: You can create table using below code
SELECT *
INTO #MyNewTable
FROM SourceTale


text:
Q: ajax json php callback lost css jquery mobile I'm developing a web app, using Jquery Mobile, I have to make an Ajax/Json to a  PHP  to retrieve MySQL data, when I get the JSON Callback, and create the "list" from the array, the path of the jquery mobile css file get lost, and my  is not well formed. This is my code :
$.ajax({
    url: "busca_reservas.php",
    data: "fecha=" + fecha + "",
    dataType: 'json',
    type: "POST",
    cache: false,
    success: function(data){
        var output = '
';

        var logsData = data;
        for (var i in logsData.logs){
            regis  = logsData.logs[i].recid;
            nombre  = logsData.logs[i].nombre;
            ape     = logsData.logs[i].apellido;
            output+= '
' + regis + "  " + nombre + " " + ape + '
';

        }
        output+='
';

        $('.listareservas').listview('refresh');
        $("#result").append(output).fadeIn(500);

        console.log(output)
    }
});

The content in my  looks like plain text, instead of Jquery Mobile "List View".
Any help wil be welcome ?
Thanks in advanced

A: Try putting the refresh after the append:
    $("#result").append(output).fadeIn(500);
    $('.listareservas').listview('refresh');

A: I vaguely remember this issue when I was working on a jquery mobile project ahwile back. I basically came to this solution
function refreshLayout() {
    $("div[data-role=page]").page("destroy").page();
}

which I would call with every ajax success function.  You may have to modify the data-role portion to fit what needs to be refreshed in your project.  Hope that helps


text:
Q: Correct the Code c++ pointers and deletion I'm working through some problems for a C++ class I'm taking but I'm stuck on something that seems quite elementary.
Here is the question:

Correct the code --
string * p, *q;
q = new string;
p = q;
delete p;
delete q;

I entered this code into my IDE and it seemed to compile and run okay with the exception of a malloc error when deleting both p and q.  I changed it to just deleting q, and everything ran fine.  Is that the only error or am I missing something?

A: p is set to point at the same std::string object in memory that q is pointing at.  Once you call delete p, the string object is destroyed and the memory block it occupied is reclaimed by your program's memory manager. Calling delete q afterwards to free the same object and memory a second time is Undefined Behavior, anything at all could happen, a crash is not guaranteed!  Only 1 delete is allowed for each successful new.
This is a job for a smart pointer (either std::unique_ptr or std::shared_ptr) to manage for you, you should not do it manually.

A: You can and should only delete a pointer pointing to memory aquired by new once. deleteing it again is undefined behaviour and not deleteing it at all causes a memory leak.
So you answered the question correctly by changing it to delete only once.


text:
Q: How to catch runtime exceptions in jspx pages This is in continuation with my previous question. I couldn't find solution for that. Hence I am trying to debug my application view layer jspx.
I realized that jspx is quite different from jsp, like it doesn't allow scriptlets. I know, that usage of this(scriptlets) is not at all recommended.
I have a particular SAP Net weaver server where hot deployment of jspx/jsp/html is not working.  I have checked other alternatives like remote debugging, break points in jspx. But, its SAP net weaver, have some configuration issues. I have one option atleast to put sysouts, to trace runtime exceptions. But as its jspx files sysouts in scriptlets are not working. If it was jsp instead of jspx there, I could have traced/debugged the issues quickly using scriptlets temporarily until the issue got resolved atleast by using Sysouts.
Is there any equivalent code to this scriptlet(used in jsp)which we use very rarely.
<% System.out.println("The line above the null pointer exception : "+object.getPropery());%

Any equivalent code in jspx or icefaces components.
How do we debug a jspx page or handle exceptions inside a jspx page and find out errors.
Any eclipse plugins or tools available?


text:
Q: cannot find file in mercurial I am a mercurial noob, and am scratching my head trying to figure this out.
I have added a file to the repository in the past. The repo knows about it:

hg log Purchase.php

changeset:   40:0bb0a5041ae9
parent:      36:b1627cf0f7a3
user:        josh
date:        Wed Jun 30 21:41:07 2010 +0530
summary:     purchase logic

now, if I do a hg pull, Purchase.php is not included. status does not know about it. How do I get this file out?
> hg status Purchase.php

Purchase.php: No such file or directory

A: hg pull only pulls remote changesets to your local repo doing nothing to your working directory. You need to update your working directory from your local repo using hg update.
Use the Mercurial Quick Start cheatsheet for getting the visual model of Mercurial operations. The basic concepts are "repository", "working directory", "changeset" and various verbs that stand for Mercurial commands.


text:
Q: Swear Filter Regex I need a regex that will match a certain string and replace each letter of it with a symbol.
So... "Cheese" would be replaced by "******" but "Pie" would be replaced by "***"
So for example:
"my pie is tasty and so is cake".replace(new RegExp(/(pizza|cake|pie|test|horseshoe)/gi), "'*' x length($1)")

(Obviously the substitution doesn't exist)

A: Personally I think this is a very bad idea, because:

*

*It will mangle valid text which can annoy valid users.

*It is easy to trick the filter by using misspellings so it won't hinder malicious users.

However to solve your problem you can pass a function to replace:
var regex = /(pizza|cake|pie|test|horseshoe)/gi;
var s = "my pie is tasty and so is cake";
s = s.replace(regex, function(match) { return match.replace(/./g, '*'); });

A: Disclaimer: These filters don't work.. That being said, you would want to use the callback function with replace:
"my pie is tasty and so is cake".replace(/(pizza|cake|pie|test|horseshoe)/gi, function (match) {
    return match.replace(/./g, '*');
});

Working example: http://jsfiddle.net/mRF9m/

A: To prevent the aforementioned classic issue by @ThiefMaster you might consider adding word boundaries to the pattern. However, keep in mind that you will still have to take care of the plural and misspelled forms of those words as well.
var str = 'pie and cake are tasty but not spies or protests';
str = str.replace(/\b(pizza|cake|pie|test|horseshoe)\b/gi, function (match) {
    return match.replace(/\w/g, '*');
});


text:
Q: CSS a:hover moving text I am having issues with text moving them I hover over the element. It is working fine until you hover over it.
So just to clarify you run the mouse over the text and the background colour and everything changes correctly, just the text moved higher than origional text.
This is the CSS code I have for this element:
 #top_login_panel ul.menu_topPanel li.item-8 {
        background: url("../images/menu/top-panel-login-bg.png") no-repeat scroll 0 0 hsla(0, 0%, 0%, 0);
        height: 43px;
        width: 145px;
    }
    #top_login_panel ul.menu_topPanel li.item-8 a {
        width: 145px;
    }
    #top_login_panel ul.menu_topPanel li.item-8 a:hover {
      background-image: url("../images/menu/top-panel-login-bg1.png") !important;
      background-position: center center !important;
      background-repeat: no-repeat !important;
      color: hsl(0, 1%, 25%);
      margin-left: -3px;
      margin-top: -8px;
      width: 114px;
    }
    #top_login_panel ul.menu_topPanel li.item-8 a {
        display: block;
        font-size: 12px;
        padding: 22px 0 0 35px;
    }

Can you please advice how to resolve this issue?
Thanks

A: The problem is that the hover block of CSS code has properties and values that the normal state doesn't have so it moves as the new properties are applied. Let the color be the only difference if you don't want it to move.

li.item-8 a {
        background-image: url("../images/menu/top-panel-login-bg1.png") !important;
      background-position: center center !important;
      background-repeat: no-repeat !important;
      margin-left: -3px;
      margin-top: -8px;
      width: 114px;
    }
 li.item-8 a:hover {
      background-image: url("../images/menu/top-panel-login-bg1.png") !important;
      background-position: center center !important;
      background-repeat: no-repeat !important;
      color: hsl(0, 1%, 25%);
      margin-left: -3px;
      margin-top: -8px;
      width: 114px;
    }

One

One

One

One

A: try this.,
 #top_login_panel ul.menu_topPanel li.item-8 a:hover {
      background-image: url("../images/menu/top-panel-login-bg1.png") !important;
      background-position: center center !important;
      background-repeat: no-repeat !important;
      color: hsl(0, 1%, 25%);
    }
    #top_login_panel ul.menu_topPanel li.item-8 a {
        display: block;
        font-size: 12px;
        padding: 22px 0 0 35px;
        margin-left: -3px;
        margin-top: -8px;
        width: 114px;
    }

I changed the margin property to a tag

A: Thanks @Sathish S I used the moving of the elements but then just placed the padding in a different location and that worked.
#top_login_panel ul.menu_topPanel li.item-8 a {
    display: block;
    font-size: 12px;
  margin-left: -3px;
  margin-top: -12px;
  width: 114px;
}

#top_login_panel ul.menu_topPanel li.item-8 a:hover {
  background-image: url("../images/menu/top-panel-login-bg1.png") !important;
  background-position: center center !important;
  background-repeat: no-repeat !important;
  color: hsl(0, 1%, 25%);
}

#top_login_panel ul.menu_topPanel li.item-8 a {
   padding: 31px 0 0 35px;
}


text:
Q: In Python, how to refactor a loop? I construct a Newton polynomial for a function. It has a fairly simple structure:

Here, the deltas for y are taken from the string_one list, and x_0 - for each block-summands have different values (from the x_col_list list) - actually, this is indicated by non-steps in square brackets: [1] [2] [n].
I'm trying to build a formula where:

*

*x remains x without getting values (this is served by the sympy module);

*the denominator of each fraction increases by one;

*element (x - x_0) in each summand-block we add one additional bracket, keeping the already accumulated:
(−0)
(−0)(−0.3142)
(−0)(−0.3142)(−0.6283)
with the last term:
(−0)*(−0.3142)(−0.6283)(−0.9425)(−1.2566)(−1.5708)(−1.885)(−2.1991)
I'm in trouble right now:

*

*I get too much in the opposite direction: (-2.1991)(-1.885)...(−0.3142)

*x with zero is immediately truncated to x, and I need (x - 0)

*and somehow now it has to be folded.
Code:
from sympy import symbols, prod
from scipy.special import factorial

x = symbols('x')

string_one = [0.3091,-0.0304,-0.0271,0.0054,0.0025,-0.0016,0.0019,-0.0046,0.0099,-0.019]
x_col_list = [0.0, 0.3142, 0.6283, 0.9425, 1.2566, 1.5708, 1.885, 2.1991, 2.5133]
h=1.25665

x = symbols('x')

 # we go along the deltas:
num=1
for delta in string_one:
    # we go along the column of x's:
    polynom = round( ( delta/(factorial(num)*h**num) ), 4 ) * prod([x - args for args in x_col_list[::-1]])
    num+=1
    print(polynom)

Now the way out is this:
0.246*x*(x - 2.5133)*(x - 2.1991)*(x - 1.885)*(x - 1.5708)*(x - 1.2566)*(x - 0.9425)*(x - 0.6283)*(x - 0.3142) -0.0096*x*(x - 2.5133)*(x - 2.1991)...
As you can see, brackets are attached to each term. And all the other flaws. What can be done? Thanks


text:
Q: How to check specific columns for values and assign weighted integer values when checking against variables of lists I have a dataset containing diagnosis columns (DIAGX1-DIAGX42) for patients and I need to create a variable that sums the values for these based on weights from an external index.
df_patients
patients = [('pat1', 'Z509', 'M33', 'M32', 'M315'),
         ('pat2', 'I099', 'I278', 'M05', 'F01'),
         ('pat3', 'N057', 'N057', 'N058', 'N057')]
labels = ['patient_num', 'DIAGX1', 'DIAGX2', 'DIAGX3', 'DIAGX4']
df_patients = pd.DataFrame.from_records(patients, columns=labels)
df_patients

Input
patient_num DIAGX1  DIAGX2  DIAGX3  DIAGX4
pat1        Z509    M33     M32     M315
pat2        I099    I278    M05     F01
pat3        N057    N057    N058    N057

Output
patient_num DIAGX1  DIAGX2  DIAGX3  DIAGX4 Score
pat1        Z509    M33     M32     M315   1
pat2        I099    I278    M05     F01    6
pat3        N057    N057    N058    N057   0

external_index, where if a column from the dataset above contains a value in any of the below that the value would be added. Only one member contributes to a value been given, e.g a value of  both F01, F02 both in dementia will only result in 2 being allocated for that record/patient, values are only added/summed if they occur across grouped indexes e.g. F01=2 and I099=1 sum to 3

*

*congestive_heart_failure = 2

*dementia = 2

*chronic_pulmonary_disease= 1

*rheumatologic_disease = 1
congestive_heart_failure = [
    "I099",
    "I255",
    "I420",
    "I425",
    "I426",
    "I427",
    "I428",
    "I429",
    "I43",
    "I50",
    "P290",
]
dementia = ["F01", "F02", "F03", "F051", "G30", "G311"]
chronic_pulmonary_disease = [
    "I278",
    "I279",
    "J40",
    "J41",
    "J42",
    "J43",
    "J44",
    "J45",
    "J47",
    "J60",
    "J61",
    "J62",
    "J63",
    "J64",
    "J65",
    "J66",
    "J67",
    "J684",
    "J701",
    "J703",
]
rheumatologic_disease = [
    "M05",
    "M06",
    "M315",
    "M32",
    "M33",
    "M34",
    "M351",
    "M353",
    "M360",
]

A: Annotated code
idx = {
    'dementia': dementia,
    'rheumatologic_disease': rheumatologic_disease,
    'congestive_heart_failure': congestive_heart_failure,
    'chronic_pulmonary_disease': chronic_pulmonary_disease,
}
mapping = {v: k for k, vals in idx.items() for v in vals}

weights = {
    'dementia': 2,
    'rheumatologic_disease': 1,
    'congestive_heart_failure': 2,
    'chronic_pulmonary_disease': 1,
}

# Convert the dataframe into long format
df = df_patients.melt('patient_num')

# Substitute disease name inplace of codes
df['value'] = df['value'].map(mapping)

# Drop dupes per patient and disease
df = df.drop_duplicates(['patient_num', 'value'])

# Map the weights assigned to diseases
df['value'] = df['value'].map(weights)

# Sum the weights per patient and map it back to original dataframe
df_patients['Score'] = df['patient_num'].map(df.groupby('patient_num')['value'].sum())

Result
  patient_num DIAGX1 DIAGX2 DIAGX3 DIAGX4  Score
0        pat1   Z509    M33    M32   M315    1.0
1        pat2   I099   I278    M05    F01    6.0
2        pat3   N057   N057   N058   N057    0.0

A: You can do it this way and probably a few other ways more efficiently:
chf_dict = dict(zip(congestive_heart_failure,['chf']*len(congestive_heart_failure)))
dementia_dict = dict(zip(dementia,['dem']*len(dementia)))
cpd_dict = dict(zip(chronic_pulmonary_disease,['cpd']*len(chronic_pulmonary_disease)))
rd_dict = dict(zip(rheumatologic_disease,['rd']*len(rheumatologic_disease)))

disease_map = chf_dict
disease_map.update(dementia_dict)
disease_map.update(cpd_dict)
disease_map.update(rd_dict)

score_dict = {'cpd':1,
              'chf':2,
              'rd':1,
              'dem':2}

score_df = df_patients.set_index('patient_num').stack().map(disease_map)\
           .droplevel(1).reset_index(name='disease')\
           .drop_duplicates().set_index('patient_num')['disease']\
           .map(score_dict)\
           .groupby(level=0).sum().rename('Score')

df_patients.merge(score_df, left_on='patient_num', right_index=True)

Output:
  patient_num DIAGX1 DIAGX2 DIAGX3 DIAGX4  Score
0        pat1   Z509    M33    M32   M315    1.0
1        pat2   I099   I278    M05    F01    6.0
2        pat3   N057   N057   N058   N057    0.0


text:
Q: A more rigorous way to show that $x^5 - 3x = 1$ has at least $3$ roots in $\Bbb R$
Given an equation:
  $$
x^5 - 3x = 1
$$
  Show that:

*

*It has at least $1$ root on $(1, 2)$;

*It has at least $3$ roots on $\Bbb R$

I've started with considering a function $f(x)$ for $x\in [1, 2]$:
$$
f(x) = x^5 - 3x - 1
$$
Then calculating its value on the left and right sides of the closed interval yields:
$$
f(1) = -3\\
f(2) = 25
$$
Applying the Intermediate Value Theorem yields that there exists a point for $x_0 \in [1, 2]$ such that $f(x_0) = 0$. Which means that indeed at least one root exists.
However, for the second part of the question if we consider $f(x)$ for $x \in \Bbb R$, the only way I see is to try and guess the intervals where the function changes its sign and then apply IVT again. Consider for example $f(x)$ for $x \in \{-2, -1, 1, 2\}$.
I see how derivatives could be to the rescue here, the problem is that I'm not allowed to use derivatives.
Is there a rigorous way to prove what's stated without guessing and without using derivatives? Thank you!

A: Let us use Descartes' sign Rule
$f(x)=x^5-3x-1=0$, the number of sign changes in $f(x)$ is one and number of sigm changes in $f(-x)$ are two. So as per Descarte's rule this equation can have atmost one real positive and atmost two real negative roots. So Descarte's rules permits at most three real root which can be located as : $f(-\infty)<0, f(-1)=+1, f(0)=-1$ means there is at least one real root in $(-\infty, -1)$ and at least one in $(-1,0)$. Next $f(1)=-3, f(2)=+25$.
So one real positive roots is in $(1,2)$. In all this equation has three real roots two negative and one positive.

A: Graphical method can help.
$$x^5-3x=1 \stackrel{x\ne 0}{\iff} x^4-3=\frac1x$$
Sketch:
$\hspace{4cm}$
Note: You can quickly jump to the intervals of interest and compare the values and increase/decrease of the functions.

A: (1)$f(x)=x^5-3x-1$ has one sign change in its coefficients so at most $1$ positive root. Also, $f(1).f(2)<0$ assures exactly one positive root lying in $(1,2)$.
(2) $f(-x)=-x^5+3x-1$ has two sign changes in its coefficients so at most $2$ negative roots OR more precisely $0$ or $2$ negative roots (possibility of exactly $1$ negative root is discarded due to pairwise occurrence of remaining complex conjugate roots). Now $f(-1).f(0)<0$ is sufficient to assure the existence of exactly $2$ negative roots of $f(x)$.

A: The coefficient $-3$ in the middle is dominant enough to allow to consider the two binomial expressions $x^5-3x$ and $-3x-1$ from the sides of the Newton polygon as separate approximations for large and small roots, with their real roots at $\pm\sqrt[4]3$ and $-\frac13$. To get a more precise connection to the given polynomial, consider the product of the binomials
$$
(x^4-3)(x+\tfrac13)=x^5+\tfrac13x^4-3x-1.
$$
This is close to the given polynomial $x^5-3x-1$ so that in moving from one to the other the roots do not change much. The pairwise distance between the $3$ real roots and the $2$ imaginary roots $\pm i\sqrt[4]3$ is large enough that the nature of these roots will not change under the perturbation to the given polynomial. To verify this more or less heuristic consideration, compute the values of the polynomial at enclosing intervals around $-\frac43, -\frac13,\frac43$, for instance $[-\frac32,-1]$, $[-\frac12,0]$, $[1,\frac32]$.

A bit more certainty and general applicability one gets from computing the root radius. Recall that for $f(x)=x^n+a_{n-1}x^{n-1}+...+a_1x+a_0$ a radius enclosing all the roots is obtained as
$$
R=1+\max_{k<n}|a_k|\text{ or } R=\max(1,|a_{n-1}|+...+|a_1|+|a_0|)
$$
which gives here $R=4$ in both cases. As there is a large degree gap, scaling the polynomial might help reduce the radius, set $x=2y$, then
$$
f(2y)=32y^5-6y-1=32(y^5-\tfrac3{16}y-\tfrac1{32})
$$
which results in the bounds $R=2+\frac3{16}$ or $R=2$ for $x$. Now that the range of the roots is sufficiently restrained, computing values at $x=-2,-1,0,1,2$ is now a well-founded strategy. Counting sign changes as per Descartes then confirms that there are exactly two negative roots.

A more precise guessing can be performed using derivatives.
$f'(x)=5x^4-3$ has 2 real roots at $\pm\sqrt[4]{\frac35}$, thus $f(x)$ has local extrema there. Check the function value at the local maximum $-\sqrt[4]{\frac35}$, for simplicity check at the close-by point $x=-1$:
$$
f(-1)=-1+3-1=1>0.
$$
Together with $f(0)=-1$ and $f(-\infty)=-\infty$ one can conclude for the existence of $2$ negative roots.
There can be no more roots, as then by Rolle the derivative would have to have more than $2$ real roots.

A: Quick and dirty without calculus. Plugging in some small integer values in $x^5 -3x -1$ (always a good place to start on this kind of problem) shows that the sign changes between $-2$ and $-1$, then again between $-1$ and $0$, then again before the values grow to $\infty$. That guarantees at least three real roots.

A: This is inefficient and it may not always work but
$x^5 - 3x-1 = x(x^4-3)-1$.
If we can find $a<b$ but that $a(a^4 - 3) \ge 1$ and $b$ so that $b(b^4 -3) \le 1$, then we will done. (Why?[*])
If we can find an $a$ where $a < 0; k= a^4 - 3 < 0$ then $ak > 0$. And if  $|a| \ge 1$ and $|k| \ge 1$ then $ak \ge 1$.  And that will do for our $a$.
(Note: this is sufficient but much stronger and much more than necessary.)
That's easy enough.  $k = a^4 - 3 \le -1$ implies $a^4 \le 2$ implies $|a| \le \sqrt[4]{2}$ so we just need $-\sqrt[4]{2} \le a \le -1$ for our $a$.
Likewise  if we have $b >0$ but $j = b^4-3 < 0$. Because $bj < 0$ and $bj - 1< -1 < 0$.    (And again sufficient, albeit much stronger than necessary.
So $b^4 -3  <0$ so $b^4 < 3$ so $|b| < \sqrt[4]{3}$ so any $b; 0 < b < \sqrt[4]{3}$ will do.
[*]Thus  we have $\lim_{x\to -\infty} x^5 - 3x -1 = -\infty$ so there are plenty of $n < a$ so that $n^5 -3n -1 < 0$.  And $a(a^4-3) -1 > 0$ so there is a root between $n$ and $a$.  And $b(b^4-3) -1 < -2 < 0$ so there is a root between $a$ and $b$.  And $\lim_{x\to \infty} x^5 - 3x -1 = \infty$ so there are plenty of $m> b$ so that $m^5 -3m -1 > 0$ so there is a root between $b$ and $m$.
But that was inefficient and required some educated guesses.


text:
Q: Magento2 - Translate custom links (name) at main menu How can I translate custom links (name) at my main menu?
e.g
Home (/)  ->  Strona glowna  (/)
About Us (/about-us)      -> O nas  (/o-nas)
Contact (/contact)    ->  Kontakt  (/kontakt)
I add custom posiotion to mainmenu in this code:
E:\xampp7\htdocs\mgnt2\app\design\frontend\TemplateMonster\framework\TemplateMonster_Megamenu\templates\html\topmenu.phtml

        <button class="rd-navbar-toggle" data-rd-navbar-toggle=".rd-navbar-nav-wrap"></button>

                <?php echo $_menu;?>

                    <a href="<?php echo $this->getBaseUrl()."o-nas"; ?>"  role="menuitem"> <?php echo __("Your Custom Menu")?>

A: Enable the Translate Inline Tool
1.   On the Admin sidebar, tap Stores. Then under Settings, choose Configuration.
2.To work with a specific store view, set the Store View that is to be updated.
3.   In the panel on the left under Advanced, choose Developer.
4.   Expand  the Translate Inline section.
5. Set Enabled for Storefront to "Yes."
6. Save Config and flush cache.
7. Open your storefront in a browser, and go to the page that you want to edit.


text:
Q: Templating lambda inside a map I'm trying to create a templated method that takes in an array and a lambda as a transformation function.
I want the API to look as follow:
template <class T, class R>
void sort(std::vector<T>& array, std::function<R(const T&)> key);

// I want to call it
sort<SOME_CLASS,RETURN_TYPE>(some_array, [] (const SOME_CLASS& v) -> RETURN_TYPE { return v.property });

Maybe the approach I'm taking is not the ideal, I just want to know if its possible.
Ideally I would like the template to deduce the return type, so I can just do:
sort(array, [] (const SOME_CLASS& v) -> RETURN_TYPE { return v.property });

I want to know whats the best approach for this problem, because this is not working.
I hope to get something similar to the python sort, https://docs.python.org/3/howto/sorting.html

A: Usually in C++ you write template in more generic approach, for example std::function is usable when you have regular function that needs to accept a functor, template can use pretty much any functor (if it would bind of course):
template<typename Container,typename Functor>
void sort( Container &c, Functor f )
{
    std::sort( std::begin(c), std::end(c), std::move(f) );
}

And it will deduce data types:
int main()
{
    std::vector<int> v = { 4, 3, 7, 1 };
    sort( v, []( int i1, int i2 ) { return i1 > i2; } );
    ...
}

Live example
If you can use C++20 you may want to add concept verification for data types, otherwise you may get some cryptic error messages if you use inappropriate ones.


text:
Q: SAS expander or better controller? In the past, servers I've put together have all had 8 or fewer disks, so I've not had to give the storage controller much thought - a standard controller like the P440ar (my experience is with HP) that supports up to 8 disks is sufficient.
The server I'm currently spec'ing up will likely have between 10 and 12 SFF disks, meaning the usual standard P440ar will not be sufficient. To support >8 disks, it seems I have a couple of options:

*

*Stick with the P440 and add a SAS expander card

*Switch the controller to something like a P840 that supports up to 16 disks without a SAS expander card

Therefore, I've been trying to understands the pros/cons of each approach.
I appreciate that you have no option but to use a SAS expander if you want to create a RAID array that spans more disks than the controller itself supports. Assuming that's not the case, what are the pros/cons/differences between:

*

*Smaller controller + expander

*Larger controller

(where 'smaller' is a controller that doesn't support the required number of drives without an expander, and 'larger' is a controller that does)
... and when/why would one choose one option over the other?

A: Based on my own experience with expanders I would go for better controller for few reasons:
1) Price of expander + controller comes close to one more expensive controller.
2) You have to deal with compatibility issues between controller and expander and then also cable issues (right cable between controller and expander) then disk cables between expander and disks. They aren't all born the same.
3) Flashing expander is painful, you need windows port or original linux utilities e.g. sg_write_buffer and lsscsi/sg_scan.exe and that's already good reason to avoid it (unless you buy both of them from same manufacturer and I know that HP sometimes requires HP mobo).
4) In 12G arena has quite some incompatibilities between expander and controller of different manufacturers (e.g. LSI and HPE). I've heard that identical configurations work for some people but not for others.
Maybe consider two RAID controllers if it suits you, you might get same price and better performance.
PS: if you decide to go with spearate manufacturers get familiarized with flashing expander before you buy it. I suggest windows utilities that come with Intel expanders to start with (sg_write_buffer.exe, sg_scan.exe, update.bat (need to modify it for non intel ones) and they also give RPMs for linux or this article to see what you are getting involved into.

A: Theoretically, a SAS expander may be limiting throughput. If you're using a SAS RAID controller with SFF-8087 4-lanes connectors (quite typical), the SAS expander will multiplex a number of disks on these 4 lanes, while without expander each disk will be driven by only one lane.
However be aware that many RAID controller with more than 8 SAS lanes actually use an on-board SAS expander (I don't know the technical details of P840); in which case using an internal or external SAS expander will make little difference, if any.
Raw numbers follow:

*

*SAS-2 (6 Gbps), expander, 16 drives: throughput 3 GB/s

*SAS-2 (6 Gbps), native, 16 drives: throughput 12 GB/s

*SAS-3 (12 Gbps), expander, 16 drives: throughput 6 GB/s

*SAS-3 (12 Gbps), native, 16 drives: throughput 24 GB/s

As you can see, the SAS expander may severly limit maximum disk throughput. However, keep in mind that most RAID controllers and disks combinations absolutely can't reach even the low values. If you plan on using 7200 RPM drives, a SAS expander is not the limiting factor. On the other hand, with SSDs it may easily become a point of contention...


text:
Q: How do i code in SpriteKit Spawning balls from the top that are now appearing from the side? I am working on a simple game for the iPhone in SpriteKit and am trying to spawn balls coming from the top of the screen. However, the balls keep spawning from the side and I don't know how to make them appear from the top....Anyone an idea on how to change this? (see code). Also is this a good way to randomly spawn? Or should I spawn them and let them fall with gravity rules?
//ENEMIES

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

// 1
func spawnEnemy() {
    // 2
    let enemy = SKSpriteNode(imageNamed: "ball")
    // 3
    enemy.name = "enemy"
    // 4
    enemy.position = CGPoint(x: frame.size.width + enemy.size.width/2,
                             y: frame.size.height * random(min: 0, max: 1))
    // 5
    addChild(enemy)

    enemy.run(
        SKAction.moveBy(x: -size.width - enemy.size.width, y: 0.0,
                         duration: TimeInterval(random(min: 1, max: 2))))

}

A: Remember that location (0,0) is the bottom left of the screen, with increasing x values going across the screen from left to right and increasing y values going up the screen from bottom to top.
Your spawn point is always
(x: frame.size.width + enemy.size.width/2, y: frame.size.height * random(min: 0, max: 1)

which is off the right-hand side of the screen, with a random y value (i.e. a random height). Your x value needs to be random and your y value needs to be:
(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height + enemy.size.height/2)

Then, as Dreamer said, your movement SKAction needs to move the enemy from its current y value to 0 whilst keeping its x value constant (assuming you want it to move straight down the screen.
As to your question about spawning and gravity - do you want your objects to move down at a constant speed (which is what your corrected SKAction will do) or to look as though they are falling under gravity, in which case they'd appear, then start moving slowly but constantly accelerating.
Edit: As KnightOfDragons said - the actual location of the (0, 0) co-ordinate is governed by a property known as the anchorPoint (which itself is a CGPoint, but this doesn't relate to an actual co-ordinate). It used to always be (0, 0) which means the bottom left-hand corner, but now it may to be (0.5, 0.5), which means the centre of the screen i.e. a sprite placed at (0,0) will be in the middle of the screen. Increasing x or y will move the sprite right or up respectively, and decreasing x or y will move the sprite left or down.
This means that if your scene has an anchorPoint of (0.5, 0.5), then the edges of the screen will have a co-ordinates of:

*

*top of screen - y: frame.size.height/2

*bottom of screen - y: -frame.size.height/2

*right-hand edge of screen - x: frame.size.width/2

*left-hand edge of screen - x: -frame.size.height/2

Whether or not the anchorPont is (0, 0) or (0.5, 0.5) may be dependant upon if your scene came from an .sks file or through code.

A: Instead of
enemy.run(
        SKAction.moveBy(x: -size.width - enemy.size.width, y: 0.0,
                         duration: TimeInterval(random(min: 1, max: 2))))

You need to be moving by -Y. X is left and right, Y is up and down. So it would be....
enemy.run(
        SKAction.moveBy(x: 0.0 , y: -size.height - enemy.size.height,
                         duration: TimeInterval(random(min: 1, max: 2))))


text:
Q: Swift Unit Testing IBAction I have a UIViewController that contains each of UITextField, UIButton and UILabel. I put something in the UITextField, press a button and the string is now capitalized in the UILabel.
My question is: how do I set up the IBAction in Swift for unit tests? If there is no way to test the action in Swift, what else can I do to test this?

A: In the unit-testing world, the most difficult work could be UI testing. So, what you can do is to check whatever is available to you from the API.
You can not toggle an action or event like you are a phone user. So, you have to programmatically toggle actions or events in order to test on that. You will also have to programmatically initialize the UI elements yourself.
IBAction is just nothing but an indicator to tell UIStoryboard that this is a connector method, you can ignore and treat it as a normal method.

A: Unit Tests are not designed to test visual interface. It's made to test your code.
For testing the interface, you can use Apple's UI Automation tool or other external tools.

A: Personally I tried to do a mock for the class and send the following code:
controllerMock.btnNoResults.sendActionsForControlEvents(UIControlEvents.TouchUpInside)

The problem is that the call is not being made to the mock so the test is useless.
The same method executed in Objective-C with OCMock works perfectly so what I do is I mix swift tests and Objective-C tests.
In order to setup the Objective-C test to test swift source code I need to basically do the following:

*

*Add OCMock to my test project

*Create an Objective-C test. It will ask me for the bridging header as usual

*Import "OCMock.h"

*VERY IMPORTANT: Import the header to access the swift functions on my project. This header is normally "ProjectName_Tests-Swift.h"

*Use the following code:
-(void) testSeeMoreInformationAction{
    id mock = [OCMockObject partialMockForObject:pController];
    [[mock expect]seeMoreInformation];

    [pController.btnSeeMoreDetails sendActionsForControlEvents:UIControlEventTouchUpInside];

    [mock verify];
}

Like this my test works. Also the good thing of mixing Objective-C with Swift and adding OCMock is that you now can test many other things in an easier way. Please note that when you use OCMock and Swift it only works with iOS SDK functions, it will not work well with you swift functions.
Here is an example of another OCMock test very useful with AlertView:
- (void)testLoginShowsAlertViewWhenNoUserNameAndPassword{
    pController.txtUserName.text = @"";
    pController.txtPassword.text = @"";
    id mock = [OCMockObject partialMockForObject:pController];
    [[mock expect]presentViewController:OCMOCK_ANY animated:YES completion:nil];

    [pController loginAction];

    [mock verify];
}

Please feel free to contact me if you need further assistance with Unit Testing. I think is one of the most interesting parts of swift development.


text:
Q: Can VS Code debugging use sourceMapPathOverrides along with serverReadyAction / debugWithChrome? When debugging web app server code in VS Code (.NET Core in my case), there is a launch.json configuration option called serverReadyAction to open the web browser, e.g.:
"serverReadyAction": {
    "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"   ,
    "action": "openExternally"
}

openExternally is one possible action, and debugWithChrome is another. The latter starts a Chrome debug session using the Debugger for Chrome extension. In this mode, a webRoot property can be added that is passed to the Chrome debug session:
"serverReadyAction": {
    "action": "debugWithChrome",
    "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"   ,
    "webRoot": "${workspaceRoot}/wwwroot"
}

The nice thing about this is that now I can hit breakpoints in my C# and my client-side JavaScript - lovely!
However, my JS is actually compiled from TypeScript and bundled (with Webpack in this case). Ordinarily when using the Debugger for Chrome extension, I can tell it about sourceMapPathOverrides. A typical config would be:
{
    "type": "chrome",
    "request": "launch",
    "name": "Launch Chrome",
    "url": "https://localhost:5001",
    "webRoot": "${workspaceRoot}/src",
    "sourceMapPathOverrides": {
        "webpack:///./src/*": "${webRoot}/*"
    }
}

My question is if this is possible when using the a Chrome debug session created by serverReadyAction / debugWithChrome. It's not immediately apparent.

A: I haven't found a way to pass this option in, but I did see that the Chrome debugger extension has default properties for it:
 "sourceMapPathOverrides": {
                "type": "object",
                "description": "%chrome.sourceMapPathOverrides.description%",
                "default": {
                  "webpack:///./*": "${webRoot}/*",
                  "webpack:///src/*": "${webRoot}/*",
                  "webpack:///*": "*",
                  "webpack:///./~/*": "${webRoot}/node_modules/*",
                  "meteor://app/*": "${webRoot}/*"
                }
              },

https://github.com/microsoft/vscode-chrome-debug/blob/3771e9343c0776be19db6ba4653a7e4e7fdb96a6/package.json
So I can debug my TypeScript so long as my project files match one of those.


text:
Q: Many functions in pocketsphinx (like bin_mdef_free) not exported to lib on Windows I am writing an simple phoneme forced alignment demo. I just copied some initialization code in the unit test file.
However, there are some functions causing LNK2019 error. Here is the list:
bin_mdef_free
dict_init
dict_free
dict2pid_build
dict2pid_free
ps_alignment_init
ps_alignment_free

I manually listed the symbols in pocketsphinx.lib, and I found many bin_mdef functions are listed, but except bin_mdef_free. (using DUMPBIN /ALL) All alignment functions are missed.
What should I do to include them in my lib file?

A: This is just because pocketsphinx did not export these functions. One should add POCKETSPHINX_EXPORT macro to these functions and recompile the source code to lib file.


text:
Q: Cannot connect to EC2 PostgreSQL database from ASP.Net Core lambda function I am new to AWS and my question is regarding connection to Postgresql database hosted as a EC2 instance in AWS.
I have an Asp.net core web api published as a AWS Serverless Application and an endpoint which connects to the mentioned DB. When running the api on localhost or connecting to DB from any DB client everything is ok but it does not work when testing on AWS. I assume it is connected to security configurations of EC2 but don't know how to figure it out.
Here's the serverless.template code
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Transform" : "AWS::Serverless-2016-10-31",
  "Description" : "Starting template for an AWS Serverless Application.",
  "Parameters" : {
  },
  "Resources" : {
    "DefaultFunction" : {
      "Type" : "AWS::Serverless::Function",
      "Properties": {
        "Handler": "AwsApp.WebApi::AwsApp.WebApi.LambdaEntryPoint::FunctionHandlerAsync",
        "Runtime": "dotnetcore2.1",
        "CodeUri": "",
        "Description": "Default function",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "Policies": [ "AWSLambdaFullAccess" ],
        "Events": {
          "ProxyResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/{proxy+}",
              "Method": "ANY"
            }
          }
        }
      }
    }
  },
  "Outputs" : {
    "ApiURL" : {
        "Description" : "API endpoint URL for Prod environment",
        "Value" : { "Fn::Sub" : "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" }
    }
  }
}

And this is the error message
An exception has been raised that is likely due to a transient failure.
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
   at lambda_method(Closure )
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable`1 results, QueryContext queryContext, IList`1 entityTrackingInfos, IList`1 entityAccessors)+MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Find(Object[] keyValues)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Find(Object[] keyValues)
   at AwsApp.WebApi.Controllers.ValuesController.Get(Int32 id) in D:\TEST\.NET Core\AwsApp\AwsApp.WebApi\Controllers\ValuesController.cs:line 33

Also it is strange why there's a path to the file within the error message
Edit
PostgreSQL is running under VPC.
There's a dummy Get method in controller which returns a simple array:
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
   return new string[] { "value1", "value2" };
}

When I set my lambda function VPC then this function also fails with error 500.
Solution
I was able to fix it.
The role assigned to my lambda function didn't have required policies (see here).
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:CreateNetworkInterface",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DeleteNetworkInterface"
            ],
            "Resource": "*"
        }
    ]
}

A: John,
There can be multiple issues....

*

*If your PostgreSQL is running inside a VPC with private subnet configured, open the port in firewall (inbound traffic) so that your lambda can connect.

*You need to create a new role with permission to PostgreSQL and assign it to the Lambda.
Please try and post your comments.


text:
Q: symfony: about passing parameters with url_for() I have this line in a template:
<a href="<?php echo url_for('category_set_representative_image', array('aux' => 4, 'sf_subject' => $category)) ?>">jander

So as you can guess when I click that link, it executes an action. Inside that action I have this:
var_dump($request->getParameter('aux'));var_dump($request->getParameter('sf_subject'));die("fasf");

It's printing 4 and NULL. Why NULL? I expected the $category object was showed..

A: You can't get the sf_subject parameter that way. You can only use the sf_subject with the sfDoctrineRoute or sfPropelRoute. In your code, you can then get the selected object with $this->getRoute()->getObject().

A: What is the html representation of your first line?
Seems like in your template $category is not defined, so the   should looks like
foo.php?aux=4&sf_subject=null or
foo.php?aux=4

Define the category in your template :-)


text:
Q: Prove that any semisimple Lie algebra can be generated with two elements I saw this question on a previous test paper of Lie algebra. I tried using Cartan decomposition yet got no clue what to do next.

A: Over an arbitrary field we have the following result:
Theorem: Let $L$ be a finite-dimensional simple Lie algebra in characteristic $p\neq 2,3$. Then $L$ is generated by $2$ elements.
Proof: See here, Theorem A.
For a proof for real or complex semisimple Lie algebras see Kuranishi's proof here, §2, Theorem $6$.


text:
Q: mysqli database backup file save in folder I need to how to backup database and save backup file selected folder, using php
i'm try to use this one but it's not work...

$backupFile = $file . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump --opt -h localhost -u testUser -p test123 testDb | gzip > $backupFile";
system($command);


text:
Q: minted or listings input a file between markers Is it possible, using the minted or listings package to format
a file between or till a certain textual marker automatically.
E.g. consider a source file:
code
code
//marker
code ...
//end marker
code

I would like to input the code between the two markers
without manually specifying the firstline & lastline
as they can change during the project.


text:
Q: multiple pager on a single page In my customer review page
There presents 2 pager
I don't know how to delete the pager please help me
i am a magento beginer

A: The toolbar section will be placed on your themes "review/customer/list.phtml". If it is not found there you can find this file in your base theme folder. Just comment this line
<?php echo $this->getToolbarHtml() ?>

Thats it. You are done.


text:
Q: Is there a .Net.Standard alternative to Microsoft.AspNetCore.Mvc.TagHelpers I need the wildcard functionality of the script and link tags in Microsoft.AspNetCore.Mvc.TagHelpers to load my angular bundles with hashes, in a large .NET standard MVC 5.2 application, as described in this article:
http://michaco.net/blog/Angular4GettingHashedWebpackBundlesWorkingInASPNETCoreMVC
which is for .Net Core. But converting to Core is not an option because of the scale of the application.
Are there any alternatives?


text:
Q: change background color and a view color inside a listview row when touched I need to change a row view background color to blue, it's something like this:

the xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="@dimen/main_info_cell_view_width"
android:layout_height="@dimen/main_info_cell_view_height"
android:background="@color/main_info_cell_background_color" >

<FrameLayout
    android:id="@+id/pic_frame"
    android:layout_width="@dimen/channel_pic_background_widht"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true" >

    <View
        android:id="@+id/channel_pic_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/main_info_cell_pic_background_color" />

    <ImageView
        android:id="@+id/channel_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/c__no_image" />
</FrameLayout>

<View
    android:id="@+id/divider"
    android:layout_width="@dimen/main_info_cell_divider_widht"
    android:layout_height="match_parent"
    android:layout_toRightOf="@+id/pic_frame"
    android:background="@color/main_info_cell_divider_color" />

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/title_margin_left"
    android:layout_marginRight="@dimen/title_margin_right"
    android:layout_marginTop="@dimen/title_margin_top"
    android:layout_toRightOf="@+id/divider"
    android:ellipsize="end"
    android:lines="2"
    android:textColor="@color/main_info_cell_title_color"
    android:textSize="@dimen/title_text_size" />

<TextView
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="@dimen/time_margin_bottom"
    android:layout_marginLeft="@dimen/time_margin_left"
    android:layout_toRightOf="@+id/divider"
    android:textColor="@color/main_info_cell_time_color"
    android:textSize="@dimen/time_text_size" />

<TextView
    android:id="@+id/pos_number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="@dimen/pos_nr_margin_right"
    android:textColor="@color/main_info_cell_pos_nr_color"
    android:textSize="@dimen/pos_nr_size" />

</RelativeLayout>

I tried using a selector for the row but the problem is that the selector changes only the background color of the view and the black square that is under the ImageView still remains black, how can i change its color along with the row background?

A: Use a StateListDrawable as your background to the root/parent ViewGroup of the hierarchy.
Thus, android:background="@drawable/mystatelistdrawable" where mystatelistdrawable is the file laid out using this guide.
You might also want to look at android:duplicateParentState.


text:
Q: NSPredicate Password Format I'm trying to figure out an accurate solution for validating a password field using NSPredicate. Here's my code:
-(int)checkPasswordStrength:(NSString *)password
{
    NSPredicate *validPassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b"];
    NSString *escapedPassword = [NSRegularExpression escapedPatternForString:password];
    if(![validPassword evaluateWithObject:escapedPassword]) {
        [Helper showAlertWithTitle:@"" Message:@"Password should contain 8 to 20 alphanumeric characters, one capitalized letter, and with at least one of the symbols (e.g. !@#$%?)"];
        return 0;
    }

    return 1;
}

I've tried the patterns:
\\b^(?=.*[0-9]+?)(?=(.*\\d){1})(?=.*[a-zA-Z])(?=.*[!@#$%?]).*[0-9a-zA-Z!@#$%?]{8,20}\\b

\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b

\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b

... Both without escaping and escaping the strings, but it would not just work for this type of password patterns (wherein the special characters are found after the first and last password string):
OverAndUnder21!
AreYouHere2?
PleaseDial9#
!4Ngrier!
!D4ngerZone

All the other passwords work:
P@MyF8fulDog
classM8s4L!fe

And so on...
I tried to test my RegEx patterns in regex101.com, and it seems to have a full match.
What is the right validation pattern in NSPredicate to allow the special characters as the first and last characters?

A: You need to remove word boundaries and add a question mark to the pattern:
@"^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%?])[0-9A-Za-z!@#$%?]{8,20}$"

See the regex demo.
The word boundary at the start and end of the pattern requires the first and last char to be a word char (a letter, digit or _).
Also, note +? is not necessary inside lookaheads as you just require at least 1 instance of the patterns.


text:
Q: How to display the similar information in every view? I would like to display the information about user's registration state. It should be displayed on every view, but i consider, that writting this code for about 20 times is a bad idea.  By the way, this is the code, it works, i guarantee that:
View/RegistrationInfo:

Simple Blog

    @if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
    {
        using (Html.BeginForm("LogOff", "Account"))
        {

                        Hello, @System.Web.HttpContext.Current.User.Identity.Name
                        <input type="submit" value="Exit" />

        }
    }
    else
    {
            using (Html.BeginForm("LogIn", "Home"))
            {

                        Login:
                        Password:

                                <input type="text" name="login" />

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

                            <input type="submit" value="Enter" />

                            @Html.ActionLink("Register", "Register", "Account")

            }

        }

As you can see, this view doesn't require to be strongly typed... and i don't know, should I modify any controllers (because, all information is stored in HTML Context), and how. I tried to call
@Html.RenderAction("RegistrationInfo", "Home");

or
    @Html.RenderPartial("RegistrationInfo", "Home");
and every time i receive compile error with message about invalid parametres

A: While Darin's answer perfectly covers your question, I would point out that registration information seems like it's part of your layout more (master page for the .aspx-inclined) than an actual action.
So what I would do (and indeed, do do) is put it either in the header part of your layout in the top right or under your side menu or something, and let the layout handle all the details of rendering it (with a conditional around it to hide it when you're not logged in, so you don't see it on the login screen).

A: The following should work:
@Html.Partial("~/Views/Home/RegistrationInfo.cshtml")

Or if you are inside a view of the Home controller simply:
@Html.Partial("RegistrationInfo")

Or if you put this partial in ~/Views/Shared/RegistrationInfo.cshtml you will be able to reference with the shorthand syntax.


text:
Q: Strange ListView issue, android. Repeated output? I have created a custom list adapter, which outputs a list of names. I am passing the list only ONCE to the custom array adapter, which outputs the names on the screen just ok. But if I look at the Logcat, I can see that it loops over and over about 4 times again, even if the query which supplies the data returns only 3 rows!!
Can this be caused because of a GetterSetter class (ImageItems) which I often reuse in other custom ArrayAdapters??
I would be really glad if someone could help me figuring this out! :)
main class:
...

public void getTastemakers() {

        List<ImageItem> values = datasource.getTopTastemakers();
        for (int i = 0; i < values.size(); i++) {

            TasteMakers ii = new TasteMakers();
            ii.setUser(values.get(i).getUser());
            ii.setUserId(values.get(i).getUserId());
            ii.setPostCount(values.get(i).getPostCount());

            tasteMakersList.add(ii);
            if(tasteMakersList.size() == values.size()){
            addToRecomendedList();
        }

        }
    }

    private void addToRecomendedList() {
        // Find the ListView resource.
        ArrayAdapter<TasteMakers> adapt = new RecomendedListAdapter(
                getActivity(), tasteMakersList);
        TasteMakersListView.setAdapter(adapt);
        TasteMakersListView.setOnItemClickListener(this);

    }

...

custom ArrayAdapter.class :
public class RecomendedListAdapter extends ArrayAdapter<TasteMakers> {
    Context context;
    List<TasteMakers> info;
    private String LOGTAG;
    private SendNotification sender;

    public RecomendedListAdapter(Context context, List<TasteMakers> info) {
        super(context, android.R.id.content, info);
        this.context = context;
        this.info = info;
    }

    @SuppressLint({ "DefaultLocale", "SimpleDateFormat" })
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = vi.inflate(R.layout.recomended_users_rowlayout, null);

        TasteMakers member = info.get(position);
        System.out.println("position: " + position + "," + " Member name: " + member.getUser());

        Button followUserShort = (Button) view
                .findViewById(R.id.followUserQuick);
        followUserShort.setTag(position);

        ImageView userImg = (ImageView) view.findViewById(R.id.userImg);
        TextView name = (TextView) view.findViewById(R.id.userName);
        name.setText(member.getUser());
        TextView postCount = (TextView) view.findViewById(R.id.postCount);
        postCount.setText(member.getPostCount() + " postari");

        return view;
    }

Logcat with repeated outputs:
12-19 13:46:25.616: I/LOGTAG(5789): Returned Tastemakers 3 rows
12-19 13:46:25.731: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:25.746: W/Settings(5789): Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
12-19 13:46:25.771: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:25.776: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:25.791: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:25.816: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:25.826: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:25.876: D/libEGL(5789): loaded /system/lib/egl/libEGL_mali.so
12-19 13:46:25.876: D/libEGL(5789): loaded /system/lib/egl/libGLESv1_CM_mali.so
12-19 13:46:25.881: D/libEGL(5789): loaded /system/lib/egl/libGLESv2_mali.so
12-19 13:46:25.886: E/(5789): Device driver API match
12-19 13:46:25.886: E/(5789): Device driver API version: 29
12-19 13:46:25.886: E/(5789): User space API version: 29
12-19 13:46:25.886: E/(5789): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Tue Jul 22 19:59:34 KST 2014
12-19 13:46:25.971: D/OpenGLRenderer(5789): Enabling debug mode 0
12-19 13:46:26.011: D/dalvikvm(5789): GC_FOR_ALLOC freed 3131K, 27% free 12029K/16276K, paused 26ms, total 26ms
12-19 13:46:26.021: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:26.041: D/dalvikvm(5789): GC_FOR_ALLOC freed 156K, 20% free 13064K/16276K, paused 16ms, total 16ms
12-19 13:46:26.046: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:26.071: D/dalvikvm(5789): GC_FOR_ALLOC freed 233K, 15% free 13979K/16276K, paused 15ms, total 15ms
12-19 13:46:26.181: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:26.196: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:26.201: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:26.211: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:26.221: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:26.226: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:27.731: V/AsyncHttpResponseHandler(5789): Progress 80 from 75 (107%)
12-19 13:46:27.741: I/LOGTAG(5789): Returned 1 feed rows
12-19 13:46:27.866: I/LOGTAG(5789): Returned 1 feed rows
12-19 13:46:27.891: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:27.901: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:27.906: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:27.941: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:27.951: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:27.956: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:28.986: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:29.001: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:29.011: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:46:29.066: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:29.076: I/System.out(5789): position: 0, Member name: Reka Benefi
12-19 13:46:29.081: I/System.out(5789): position: 1, Member name: Varga Edmond
12-19 13:48:20.206: I/System.out(5789): paused!

A: Not issue. Try to reuse views.
Try to see
custom listview adapter getView method being called multiple times, and in no coherent order
ListView - getView is called too much times
Getview Called multiple times in android
Yet another getView called multiple times

A: Use ViewHolder design pattern and BaseAdapter for your custom adapter :
public class RecomendedListAdapter extends BaseAdapter {

    Context context;
    List<TasteMakers> info;
    private String LOGTAG;
    private SendNotification sender;

    public RecomendedListAdapter(Context context, List<TasteMakers> info) {
        this.context = context;
        this.info = info;
    }

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

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

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.recomended_users_rowlayout, null);
            holder.followUserShort = (Button) view.findViewById(R.id.followUserQuick);
            holder.userImg = (ImageView) view.findViewById(R.id.userImg);
            holder.name = (TextView) view.findViewById(R.id.userName);
            holder.postCount = (TextView) view.findViewById(R.id.postCount);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        TasteMakers member = info.get(position);
        System.out.println("position: " + position + "," + " Member name: " + member.getUser());

        holder.followUserShort.setTag(position);
        holder.name.setText(member.getUser());
        holder.postCount.setText(member.getPostCount() + " postari");

        return convertView;
    }

    class ViewHolder {
        Button followUserShort;
        ImageView userImg;
        TextView name;
        TextView postCount;
    }
}


text:
Q: Do I have to use TypeScript with the MultiSelect (labs) component in Blueprint.js I'm busy experimenting with Blueprint.js and the MultiSelect component, which I undestand is still in active development: http://blueprintjs.com/docs/#labs.multiselect
I have never used TypeScript and it is stated that
// Select<T> is a generic component to work with your data types.
// In TypeScript, you must first obtain a non-generic reference:
const FilmSelect = Select.ofType<Film>();

So my question is, is it possible to use this component in Javascript without using TypeScript?
My react component is not rendering at present, with the following error:
multiSelect.js?64c9:37 Uncaught TypeError: Cannot read property 'map' of undefined

The component is defined as:
import React from 'react';
import Flexbox from 'flexbox-react';
import {Dialog, Button, Intent} from '@blueprintjs/core';
import {MultiSelect} from '@blueprintjs/labs';
import {inject, observer} from 'mobx-react';
import Avatar from 'react-avatar';

@inject('AccountRelationshipsStore', 'AccountUsersStore', 'ToastStore')@observer
export default class AccountRelationshipsNewRelationship extends React.Component {
constructor(props) {
    super(props);

    this.state = ({isSubmitting: false});
}

renderUser(handleClick, isActive, user) {
    return (
        {user.fullName}
    );
}

renderTag(user) {
    return user.fullName;
}

handleItemSelect(item) {
    console.log(item);
}

render() {
    return (
        <Dialog isOpen={this.props.dialogOpen} onClose={() => this.props.toggleDialog()} canOutsideClickClose={true} title={I18n.t('js.add_a_new_user_relationship', {
            type: this.props.AccountRelationshipsStore.activeRelationship.name.toLowerCase(),
            name: this.props.AccountRelationshipsStore.activeUser.fullName
        })} className='side-dialog' inline={true}>
            <form>

                    <Flexbox flexDirection='column' flexGrow={1}>
                        <Flexbox flexDirection='row' justifyContent='center' flexGrow={1}>
                            <Avatar src={this.props.AccountRelationshipsStore.activeUser.imageFileName} size={100} round={true} className=''/>
                        </Flexbox>
                        <Flexbox flexDirection='row' justifyContent='center' flexGrow={1} marginTop='10px'>

{this.props.AccountRelationshipsStore.activeUser.fullName}

                        </Flexbox>
                        <Flexbox>
                            <MultiSelect items={this.props.AccountUsersStore.users} itemRenderer={this.renderUser.bind(this)} onItemSelect={this.handleItemSelect.bind(this)} tagRenderer={this.renderTag.bind(this)}/>
                        </Flexbox>
                    </Flexbox>

                        <Button text={I18n.t('js.cancel')} onClick={() => this.props.toggleDialog()}/>
                        <Button intent={Intent.PRIMARY} type='submit' text={I18n.t('js.set_relationships')} loading={this.state.isSubmitting}/>

            </form>
        </Dialog>
    );
  }
}

A: Yes, you can use the component with JS. Just omit the generic type param:
const UserMultiSelect = MultiSelect.ofType();

<UserMultiSelect items={this.props.AccountUsersStore.users} ... />

I admit this is somewhat unintuitive, so it probably deserves a documentation update.


text:
Q: Stop my website from defaulting to Times New Roman for a pre full render font @font-face {
    font-family: 'helvetica_ce_35_thinregular';
    src:
         url('Font/helvetica_neue_ce_35_thin-webfont.woff2') format('woff2'),
         url('Font/helvetica_neue_ce_35_thin-webfont.woff') format('woff');
    font-weight: normal;
    font-stretch: normal;
    font-style: normal;
    font-display: swap;
}

html, body {
    margin: 0 auto;
    color: white;
    letter-spacing: 1px;
    font-family: "helvetica_ce_35_thinregular", Helvetica, sans-serif;
    background-color: #242529;
}

Ok so I'm trying to load Helvetica, whilst my custom font downloads so it doesn't show up as the yucky Times New Roman loading font.
I've tried with and with out font-display as well as font-display: swap and fallback and still no luck!
Additionally I've used:
<link rel="preload" as="font" href="path/to/font" type="font/woff2" crossorigin="anonymous">


text:
Q: Scala/Play: load template dynamically I have this Scala/Play application and I have to fetch a bunch of templates via AJAX. I'm doing something like this now:
def home = Action {
    Ok(views.html.home())
}

def about = Action {
    Ok(views.html.about())
}

def contact = Action {
    Ok(views.html.contact())
}

//etc

But this is just creating an action for every template. Can I do something like this instead:
def loadTemplate(templateName) = Action {
    //Load template from "views" with name being value of parameter templateName
}

Is this possible on Play Framework? If so then how?
Play Framework 2.2.1 / Scala 2.10.3 / Java 8 64bit
UPDATE: My original question might have been misunderstood. I don't want to compile a template, I want to fetch already compiled one in a more dynamic way.
UPDATE2: I think I found something very close, if not exactly what I need on this answer, but it's in Java and I need it in Scala.

A: Using scala reflection:
object Application extends Controller {

  import reflect.runtime.universe._
  val currentMirror = runtimeMirror(Play.current.classloader)
  val packageName = "views.html."

  def index(name: String) = Action {
    val templateName = packageName + name

    val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
    val methodSymbol = moduleMirror.symbol.typeSignature.declaration(newTermName("apply")).asMethod

    val instanceMirror = currentMirror.reflect(moduleMirror.instance)
    val methodMirror = instanceMirror.reflectMethod(methodSymbol)

    Ok(methodMirror.apply().asInstanceOf[Html])
 }

 }

A: Based on @Nilanjan answer and for play-2.4 scala-2.11.7
  def page(page: String) = Action.async { implicit request =>
    Future.successful(Ok(loadTemplate(page)))
  }

  import reflect.runtime.universe._
  import play.api._
  import play.twirl.api.Html
  val currentMirror = runtimeMirror(Play.current.classloader)
  val packageName = "views.html."
  private def loadTemplate(name: String) = {
    val templateName = packageName + name
    val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
    val methodSymbol = moduleMirror.symbol.info.member(TermName("apply")).asMethod
    val instanceMirror = currentMirror.reflect(moduleMirror.instance)
    val methodMirror = instanceMirror.reflectMethod(methodSymbol)
    methodMirror.apply().asInstanceOf[Html]
  }

A: Here we go again! @Nilanjan answer adopted to Scala 2.12 and Play 2.6 (as moving to DI play.api.Play.current, TermName and declaration have been deprecated). For app, I had to use injector because @Inject()(app: Application) was causing circular dependency
class HomeController @Inject()(injector: Injector, cc: ControllerComponents) extends AbstractController(cc) {
  def index(name: String = "index") = Action { implicit request: Request[AnyContent] =>
    import reflect.runtime.universe._

    val app = injector.instanceOf[Application]
    val currentMirror = runtimeMirror(app.classloader)
    val packageName = "views.html."

    val templateName = packageName + name

    val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
    val methodSymbol = moduleMirror.symbol.typeSignature.decl(TermName("apply")).asMethod

    val instanceMirror = currentMirror.reflect(moduleMirror.instance)
    val methodMirror = instanceMirror.reflectMethod(methodSymbol)

    Ok(methodMirror.apply("some", "content").asInstanceOf[Html])
  }
}

A: It's not quite good idea to allow search view by any text (for security reasons) as such can be passed in param, instead, you can resolve this quite easy with match statement - it will allow you restrict request to allowed views only and will handle wrong requests as well, probably Scala geeks can demonstrate nicer code, but this will work for you out of the box:
def loadTemplate(templateName: String) = Action {

  templateName match {
    case "about" => Ok(about())
    case "home" => Ok(home())
    case "contact" => Ok(contact())
    case _ => NotFound(notFoundView())
  }

}

route:
GET  /load-template/:templateName   controllers.Application.loadTemplate(templateName)

Additional benefit is that you can grab additional data from request and pass it to the resolved view depending on templateName param

A: In your Template file
general_template.scala.html
@(templateName : String = "none")

@templateName match {

 case "about" => { //html elements}

 case "home" => {//html elements}

 case "contact" => {//html elements}

 case _ => { }

}

and in your controller
def loadTemplate(templateName) = Action {
    Ok(views.html.general_template(templateName))
}


text:
Q: Azure what's the least amount of memory you can allocate to a container For simple containers with tiny memory requirements, what's the least amount of memory Azure will allow to allocate?

A: The least amount is 100MB (0.1 in the CLI parameter).
As evidence, the following error appears when you try to use less:

The memory requirement is '0.01' in container 'sftp' of container
  group 'sftp'. The memory requirement should be in incrememts of 0.1
  GB.


text:
Q: interactive queue for command line tasks windows Sorry if this question is a bit vague. I don't know the right technical terms.
Basically in my research group we use a shared windows machine with a lot of RAM to run models, using remote desktop to access it from our own computers.
It would be great if we could build a queue so that we get the most use out of the machine, especially if we could then rearrange the order once it is up and running. Often someone will want to run say 50 runs of a 2 hour model, and someone else will just want to run once and check the results immediately, so they should get priority, but it's a pain stopping and starting large sets of runs.
We run models via command line, any ideas?

A: You could store the total time each user has spent on the computer and it would also be a good feature to let the users estimate the time they intend to use the computer. The queue could be built based on these data and if it is possible, when the estimated time is left 110%, then automatically kick out the user and allow the next to use the computer. I think you should implement a very basic system without too much effort. When all of you see it, you will have ideas about the optimal direction where the project should be headed.


text:
Q: Appcelerator Titanium json mysql tableview How do I get this into a tableviewRow which then goes into a tableview? :
sendit.open('GET', 'http://redirect.intocept.com/read.php');

sendit.send();
sendit.onload = function(){

var json = JSON.parse(this.responseText);

var json = json.lystsejler;

var dataArray = [];
var pos;
var theheader = 0;
for( pos=0; pos < json.length; pos++){
    var firstletter = json[pos].navn[0];
    if (theheader==0){
        theheader = firstletter;
        data.push({title:'' + json[pos].navn + Math.floor(Distance(latitude, longitude, json[pos].lat, json[pos].lng)) +' sømil',  header:''+firstletter+'',  hasChild:true, test:json[pos].navn, billedeupload:json[pos].billedeupload,billede1:json[pos].billede1, billede2:json[pos].billede2, billede3:json[pos].billede3,});};

A: To elaborate on what @rajesh.adhi said; assuming your response will be structured something like this:
{
    array:[
        {title:'FOO'},
        {title:'BAR'}
    ]
}

Then your code for generating the table view rows should look like this:
var json = JSON.parse(this.responseText);
var data = [];

for( var i=0; i < json.length; i++){
    row = Ti.UI.createTableViewRow({
        title: json.array[i].title
    });
    data.push(row);
}

tableView.setData(data);


text:
Q: arm template virtualNetworkName creation appendix issue I am trying to get a arm template running and have hit an issue with the virtualnetwork creation.
azuredeploy.json
"virtualNetworkName": {
      "type": "string",
      "metadata": {
        "description": "Name of virtual network to be created"
      },
      "defaultValue": "autohav2VNET"
    },

vnet-net.json
"resources": [
    {
      "name": "[parameters('virtualNetworkName')]",
      "type": "Microsoft.Network/virtualNetworks",
      "location": "[parameters('location')]",
      "apiVersion": "2015-06-15",
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[parameters('virtualNetworkAddressRange')]"
          ]
        },
        "subnets": "[parameters('subnets')]"
      }
    }
  ]

The issue I am getting is that the vnet gets created with an appendix such as this: autohav2VNETl5g
So when this gets used to create a loadblancer, the names doe not match the defined parameter and the creation fails.
..../virtualNetworks/AUTOHAV2VNET referenced by resource .... /Microsoft.Network/loadBalancers/sqlLoadBalancer was not found.
Any suggestions?

A: with the data given it impossible to be sure why this is happening. you are probably passing in a value to the parameter virtualNetworkName. because if you wouldn't, than the vnet name would be: autohav2VNET.
ARM templates do not append anything anywhere just because they are arm templates. they only do what you designed them to do.
to help with debugging: how you are invoking the template and full template + full parameters file.


text:
Q: Jquery on hover start sliding images this is what i got

just random images inside div, positioned : absolute; so all are in the same position
What i need to do is, When somebody hovers on 'slides' div, it starts to slide images, inside it, on unhover sliding stops, and so on if i got more than 'slides' div, tried with jquery Cycle the following code
$('.slides').hover(
        function() {
                $(this).cycle({
                        fx:     'fade',
                    speed:   400,
                    timeout: 300,
                    pause:   0
                });
        },
        function(){
                $(this).cycle('stop');
        }
);

but it does not do the job, hope i find a solution, all help appreciated, thanks

A: Try this:
$(".slides").cycle({
                    fx:     'fade',
                    speed:   400,
                    timeout: 400,
                    pause:   0
                })
            .cycle('pause')
            .hover(
                function() {
                    $(this).cycle('resume');
                },
                function(){
                    $(this).cycle('pause');
                }
             );

It initiates the plugin and then immediately pauses it, then the hover will play and pause it respectively. Here's a demo: http://jsfiddle.net/JKirchartz/HSE62/


text:
Q: Issues with fstream and eof() (have spent a combined 5 hours debugging, searching for a solution, and testing) int i = 0;
while(!fin.eof())
{

    fin >> fname;
    fin >> lname;
    fin >> id;

    customer[i].setFname(fname);
    customer[i].setLname(lname);
    customer[i].setId(id);

    i++;
}
fin.close();

When my program gets to the fourth iteration of this while loop (and runs out of text from my input .txt file) visual studio prompts me with this:
Unhandled exception at 0x754bc41f in program5.exe: Microsoft C++ exception: std::ios_base::failure at memory location 0x003ceb64..
I'm clueless as to why. I've tried replacing !fin.eof() with (fin >> x) where x is an int, I've tried a do-while instead of a while, I've tried using get, getline. I thought it might be an issue that eof wasn't triggering with my >> operator so I added fin.peek(); at the very end of the loop so it would trigger eof when it peeked. I just have no idea what I'm doing wrong. Assume my customer class works properly, I've tested outside of this loop at it works perfectly.

A: If I recall, one of the idioms when working with streams is to make loops like
while (cin >> x){
   //do something...

You should be checking the state of the stream while you read in the values.  You could do something like
while(fin >> fname && fin >> lname && fin >> id){
...

This could probably be made more elegant


text:
Q: I am trying to deploy my djangorest api contactsapp to heroku Iam new to python and djangorestframework.
When i run python manage.py check, i get ModuleNotFoundError  No module named 'drf-yasg'.
The fact is i already installed this module using pip install drf-yasg. I also installed it in the pipfile and Pipfile.lock file using pipenv install drf-yasg
I also added the module in the settings.py file, But still the error persists. I
Here the screenshot of the error


text:
Q: Extracting N elements of the table satisfying the given condition Consider the following table:
tab = Join[Partition[RandomReal[{0, 1}, 100], 1],
   Partition[RandomInteger[{0, 1}, 100], 1], 2];

I would like to obtain the following. If more than 74 elements of the second column are equal to 1, then the list of 74 elements of the first column for which the second column == 1 (the order of elements does not matter). If there are less than 74 elements (say, this number is m), then the joined list made of these m elements + 74-m elements that are equal to $\pi/2$.
Could you please tell me how to do this?

A: Clear["Global`*"]

A more direct and more efficient approach for generating tab is
SeedRandom[1234];
tab = Transpose[{RandomReal[{0, 1}, 100], RandomInteger[{0, 1}, 100]}];

cnt = 74;

out = Take[PadRight[Pick[##, 1] & @@ Transpose[tab], cnt, Pi/2],
  cnt]

(* {0.876608, 0.521964, 0.0862234, 0.377913, 0.543757, 0.245349, 0.884729, \
0.91956, 0.423835, 0.98729, 0.751866, 0.824395, 0.471262, 0.216368, 0.211603, \
0.879378, 0.651802, 0.323889, 0.766977, 0.606002, 0.616014, 0.938081, \
0.376572, 0.900864, 0.120901, 0.226994, 0.121503, 0.620155, 0.821888, \
0.350603, 0.709353, 0.56393, 0.971864, 0.57182, 0.505445, 0.388272, 0.469119, \
0.436177, 0.473556, 0.129717, 0.353704, 0.696489, 0.478682, 0.0451599, \
0.809682, 0.150546, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2} *)

A: Using Position, Extract and PadRight:
n = 74;
SeedRandom[1234];
tab = Transpose[{RandomReal[{0, 1}, 100],
    RandomInteger[{0, 1}, 100]}];

Extract the 74 positions with 1s if possible and PadRight to make up for the difference.
pos = Position[tab[[All, 2]], 1, {1}, n]
res1 = PadRight[Extract[tab, pos][[All, 1]], n, π/2]

{0.876608, 0.521964, 0.0862234, 0.377913, 0.543757, 0.245349,
0.884729, 0.91956, 0.423835, 0.98729, 0.751866, 0.824395, 0.471262,
0.216368, 0.211603, 0.879378, 0.651802, 0.323889, 0.766977, 0.606002,
0.616014, 0.938081, 0.376572, 0.900864, 0.120901, 0.226994, 0.121503,
0.620155, 0.821888, 0.350603, 0.709353, 0.56393, 0.971864, 0.57182,
0.505445, 0.388272, 0.469119, 0.436177, 0.473556, 0.129717, 0.353704,
0.696489, 0.478682, 0.0451599, 0.809682, 0.150546, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2,  π/2, π/2, π/2, π/2, π/2, π/2, π/2,
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2}


text:
Q: OpenCV SurfFeatureDetector heap corruption I use this tiny code:
    Mat roulette_template = imread( "roulette_vorlage.jpg", CV_LOAD_IMAGE_GRAYSCALE );
    Mat greyMat = imread( "roulette_vorlage.jpg", CV_LOAD_IMAGE_GRAYSCALE );
    int minHessian = 400;
    SurfFeatureDetector detector( minHessian );
    std::vector<KeyPoint> keypoints_1, keypoints_2;

    detector.detect( roulette_template, keypoints_1 );
    detector.detect( greyMat, keypoints_2 );

After detector.dectet the heap is corrupted.
When I use this snippet in my other project it works fine.
Its called at the moment in my ProcessingCallback function which is called from my framegrabber.
I dont use any opencv function for getting the immage from my camera.
The entire code looks like that:
void PicoloVideo::ProcessingCallback2(PMCSIGNALINFO SigInfo)
{
    switch(SigInfo->Signal)
    {
        case MC_SIG_SURFACE_PROCESSING:
            // Update "current" surface address pointer
            McGetParamInt (SigInfo->SignalInfo, MC_SurfaceAddr, (PINT32) &m_pCurrent);

            // Post screen refresh message only if previous refresh completed
            if(m_bScreenRefreshCompleted)
            {
                Mat roulette_template = imread( "roulette_vorlage.jpg", CV_LOAD_IMAGE_GRAYSCALE );
                Mat greyMat = imread( "roulette_vorlage.jpg", CV_LOAD_IMAGE_GRAYSCALE );
                int minHessian = 400;
                SurfFeatureDetector detector( minHessian );
                std::vector<KeyPoint> keypoints_1, keypoints_2;

                detector.detect( roulette_template, keypoints_1 );
                detector.detect( greyMat, keypoints_2 );

                if(waitKey(5) >= 0) break;
            }
            break;
        case MC_SIG_END_CHANNEL_ACTIVITY:
            m_bChannelActive = FALSE;
            break;
        case MC_SIG_ACQUISITION_FAILURE:
            //MessageBox(NULL, "Acquisition Failure !", "PicoloVideo", MB_OK);
            break;
        default:
            break;

    }
}

If have no idea why I get probs with the heap.
Anyone an idea why the detect stuff is killing it?


text:
Q: c# should i use string with regex matchs or not I have a text that I am going to find matchs within that text and after that putting the results on array .
when I tried to make string array and string variables I found that it's really confusing to change from MatchCollection type to String type . and I get the error cannot convert .
what type of array and variables should I use ?
and what is the need for string type . I was just using it since I deal with string.
I want to notice that I am going to compare between arrays to find common matchs
here is my full code so far
c# regex array or list and which type string or what?

A: use:
string sample = "1a2b3c4d";
MatchCollection matches = Regex.Matches(sample, @"\d");

List<string> matchesList = new List<string>();

foreach (Match match in matches)
    matchesList.Add(match.Value);

matchesList.ForEach(Console.WriteLine);

or use LINQ:
List<string> matchesList2 = new List<string>();

matchesList2.AddRange(
    from Match match in matches
    select match.Value
);

matchesList2.ForEach(Console.WriteLine);


text:
Q: android custom listview now showing I have custom listview, i have provided all the necessary codes, but still my custom listview don't show up. I'm jsut wondering if you could help me,  Here is the code.
MainActivity.java
    public void parseJSON (String strJSON){
    try {

        person_name = new ArrayList<>();
        id_list = new ArrayList<>();
        personCase = new ArrayList<>();
        caseNumber= new ArrayList<>();
        person_img= new ArrayList<>();
        jsonObject = new JSONObject(strJSON);
        jsonArray = jsonObject.getJSONArray("persons");

        int i =0;
        while(jsonArray.length()>i){
            jsonObject = jsonArray.getJSONObject(i);
            String strid = jsonObject.getString("id");
            String strname = jsonObject.getString("name");
            String strperson_case = jsonObject.getString("person_case");
            String strcaseNumber = jsonObject.getString("caseNumber");
            String strperson_img = jsonObject.getString("person_img");

            personCase.add(strperson_case);
            person_name.add(strname);
            id_list.add(strid);
            caseNumber.add(strcaseNumber);
            person_img.add(strperson_img);
            i++;
        }
        ListView listView = (ListView) findViewById(R.id.listview);
        CustomListView mAdapter =  new CustomListView(MainActivity.this, person_name,personCase,caseNumber,id_list );
        listView.setAdapter(null);
        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                positionList = position;
                Toast.makeText(MainActivity.this, "" +
                        "ID: " +id_list.get(positionList)+
                        "\nNAME: "+person_name.get(positionList)+
                        "\nCase: "+ personCase.get(positionList)+
                        "\nCase Number: "+ caseNumber.get(positionList), Toast.LENGTH_SHORT).show();

            }
        });
    } catch (Exception e) {
        Log.i("Check",String.valueOf(e));

    }
}

class MyTask extends AsyncTask<Void, Void, String>{
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Fetching some data..");
        dialog.setIndeterminate(false);
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {

        try {
            URL url = new URL(MyConfig.URL_STR);
            HttpURLConnection httpURLConnection =
                    (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb =new StringBuilder();
            String str = "";
            while ((str=bufferedReader.readLine())!=null){
                sb.append(str);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String strJSON) {
        dialog.dismiss();
        parseJSON(strJSON);
    }
}
}

Here is the CustomListView.java
package com.example.moy.json;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by Moy on 19/06/2017.
 */

public class CustomListView extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> Name;
    private ArrayList<String> Case;
    private ArrayList<String> CaseNumber;
    private ArrayList<String> Idee;
    LayoutInflater inflater;
    public CustomListView(Context mContext, ArrayList<String> name,
                          ArrayList<String> personCase, ArrayList<String> caseNumber,
                          ArrayList<String> idee) {
        this.mContext = mContext;
        this.Name = name;
        this.Case = personCase;
        this.CaseNumber = caseNumber;
        this.Idee = idee;
         inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listView;

        if(convertView == null){

            listView = inflater.inflate(R.layout.customlistview, null);

            TextView personCase = (TextView) listView.findViewById(R.id.personCase);
            TextView personName = (TextView) listView.findViewById(R.id.personName);
            TextView personCaseNumber = (TextView) listView.findViewById(R.id.personCaseNum);
            ImageView image = (ImageView) listView.findViewById(R.id.imageView);

            personName.setText(Name.get(position));
            personCase.setText(Case.get(position));
            personCaseNumber.setText(CaseNumber.get(position));
            Picasso.with(mContext)
                    .load("http://192.168.0.11/android/img/"+Idee.get(position)+".png")
                    .into(image);
        }
        else{
            listView = convertView;
        }

        return listView;
    }
}

A: You are returning 0 for the count.
@Override
public int getCount() {
    return 1;
}


text:
Q: Get cell color from a conditionally formatted cell I can read the background colors from normal cells, but if the cell has some sort of conditional formatting the background color obtained from [RangeObject].Interior.Color is not the same as the conditional formatter gave it.
My question is, is there a way to obtain this certain property or do I have to work my way around it, like programmatically set the same conditions in my code to change the background colors instead of read and write?

A: If your version of Excel is 2010 or more recent, you can use the Range.DisplayFormat Property.


text:
Q: GNU "install" -d flag -- how's it work? I'm trying to write a makefile rule to copy a directory, maintaining its structure, and since all the other rules in our makefiles use install, I wanted to be consistent.
In the manpage, it says:

SYNOPSIS
   install [OPTION]... [-T] SOURCE DEST
   install [OPTION]... SOURCE... DIRECTORY
   install [OPTION]... -t DIRECTORY SOURCE...
   install [OPTION]... -d DIRECTORY...

   -d, --directory
          treat all arguments as directory names; create all components of
          the specified directories

OK, that sounds like what I need... but the flags don't make sense. How do you specify the destination directory to install to?
I tried doing a basic test by making an arbitrary directory structure on my local hard disk:
~>tree test
test
├── a
│   └── b
│       └── c
│           └── e.txt
└── d

4 directories, 1 file

And then running install -d and looking at what was created:
~>install -d test test2
~>tree test2
test2

0 directories, 0 files

Nothing happened!
Can anyone point me in the right direction? Googling "gnu install -d flag" isn't bringing me much.

A: Usually what you want is to install files at right folder, without repeating your self. You can use find and install to help to keep your installation scripts more DRY
find SOURCE/ -type f -exec install -vDm 755 {} THERE/{} \;

A: It looks like the install -D command is actually what I want.
Manpage:

-D     create all leading components of DEST except the last, then copy SOURCE to DEST

Works great, except you have to specify every file individually.

A: install -d is just used to create directories. You told it to create two directories, test and test2. test already existed, so all it needed to do was make test2. I don't think install supports copying entire directory trees; it's normally used on files. You probably need to use cp