text:
Q: Python for Smartsheet - Getting _ipython_canary_method_should_not_exist_ All - I am getting this error when loading the Smartsheet Client
I loaded all dependencies as per requirements.
What should I fix?
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
ImportError! Could not load api or model class _ipython_canary_method_should_not_exist_
Also this is what I am trying to run (TOKEN # Garbled)
import smartsheet
import logging
import os.path

access_token = 'TOKENNUMBER'
smartsheet_client = smartsheet.Smartsheet(access_token)
smartsheet_client.errors_as_exceptions(True)

A: The code is working fine, the error is linked to ipython.
If you run this code directly in python shell you should not have any error. You should probably avoid ipython if possible. For more information about this error, see https://stackoverflow.com/a/56317537/2320342


text:
Q: document.getElementsByTagName() contains undefined item I wrote some ES6 code that should be able to read a template from a -tag, pass it through Handlebars and replace every <template data-id="template-id" data-ctx='{"some": "json"}>-tag by the template with given ID, while also filling in the context into the according {{ expressions }} in the template.
I added dependencies to the TemplateManager class so I can add <template>-tags within a

If I now try to run this code, the first <template>-tag in the template with ID a renders correctly, the second one however does not and just throws a TypeError: templateElem is undefined on line 83. When logging the templateElems (same scope) to the console, the returned object has a length of 2, while the second item is undefined.
Why is this, and how can I prevent the error from happening?
PS.: For convenience, here is the plain code served from github pages so the code can be stepped through using the debugger more easily: https://theplatzhalter.github.io/fiddle/templating/

redpajama_set_name: RedPajamaStackExchange


text:
Q: I wanna do a leaderboard using an ArrayList/List with Firebase's realtime database I wanna create a global ranking of people. These people are saved in the Realtime Database on Firebase. I need to display these characters on a list and I need them to be sorted from highest to lowest.
                mAuth = FirebaseAuth.getInstance();
        DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
        Query top10Query = usersRef.orderByChild("lvl").limitToLast(4);

        if (mAuth.getCurrentUser() != null) {
            top10Query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                        Log.i("Firebase", String.valueOf(userSnapshot.child("dati").child("name").getValue()));
                        Log.i("Firebase", String.valueOf(userSnapshot.child("statistiche").child("lvl").getValue()));

                        String stringlvl = (String) userSnapshot.child("statistiche").child("lvl").getValue().toString();
                        String stringname = (String) userSnapshot.child("dati").child("name").getValue().toString();
                        String stringlvl = userSnapshot.getValue().toString();

                        myArrayList.add(0, stringlvl);
                        myArrayAdapter.notifyDataSetChanged();

                        Arrays.sort(new ArrayList[]{myArrayList}, Collections.reverseOrder());
                        reverse(myArrayList);

                        for (int i = 0; i<myArrayList.size(); i++){
                            arrayText[i].setText(myArrayList.get(i));
                        }

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            });
        }

public class Statistic {
    int lvl;

    public Statistic() {
    }

    public Statistic(int lvl) {
        this.lvl = lvl;
    }

    public int getLvl() {
        return lvl;
    }

    public void setLvl(int lvl) {
        this.lvl = lvl;
    }
}

This is my statistic.Class

This is my Realtime Database:
The problem I have right now is that it doesn't sort the values I have in my database in descending order.
Some advice?

A: As I see in your schema, there is an inconsistency, meaning that the children under "users", have different types of names. One is "A0", others are UIDs and others are specific names like "giovanni". It's best to have all children follow the same rule.
Your query doesn't work the way you expect because you are missing a child from your reference. To be able to get accurate results, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("users");
Query queryByLevel = usersRef.orderByChild("statistiche/lvl").limitToLast(4)
queryByLevel.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            for (DataSnapshot ds : snapshot.getChildren()) {
                String name = ds.child("statistiche").child("name").getValue(String.class);
                Log.d("TAG", name);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result of the above code will be as follow in ascending order:
A0
carla
lucio
giovanni

If  you however need a descending order, please see my answer from the following posts:

*

*Sort data to RecyclerView based on latest date from Firebase

*how to sort the key value of a map entry in descending order?


text:
Q: Keep set number of backup files I have some files & folders I want to back up using powershell.  I'm using arrays to hold the file extensions I want to back up into one backup, and then I'm backing up the entire folder as well.  The zip files I create are named TxtFileBkup_yyyymmdd_hhMMss.zip and FldrBkup_yyyymmdd_hhMMss.zip.
I build the list of items to back up (by extension) as follows:
$extArray = @("*.txt","*.asc")
foreach ($ea in $extArray) {
    $filelist += Get-ChildItem $ToBeZipped"\*" -Recurse -Include $ea |Select-Object fullname
}

foreach ($fn in $fileList) {
    $fileName = $fn.FullName
    create-7zip $filename $zipFolder\$DataFileOut
    }

The folder is then backed up separately in an additional step.
Later on, I set the attribute byte of all files in the backup folder, then count the number of files in the folder matching a certain pattern, and if it's over 5, I un-set the attribute byte that is checked (and deleted) in the next run.
$delfiles=0
$delfiles= (dir $zipFolder\TargetBackup*.zip).count-5
if ($delfiles -gt 0)

# If there are more than 5 zipped backups, we'll turn off the archive bit on them
{dir $zipFolder\TargetBackup* | sort-object -property {$_.CreationTime} |
select-object -first $delfiles |
foreach-object { attrib $_.FULLNAME -A} }}

What I would like to do is to store the generic backup names (TxtFileBkup, FldrBkup) in an array along with a number of backups I would want of them, and then use that array & nbr of backups to determine and mark backups to be deleted the next time the script runs. A bonus would be if I could use that array with or without the array of file extensions & the folder backup (so it would be 1 step to create both sets of backups).

A: I'd create a hash table of the file prefixes and retention counts, and export that to xml
$bkup_counts = @{
TxtFileBkup = @('File',5)
FldrBkup = @('Folder',6)
}

$bkup_counts | export-clixml bkup_counts.xml

In your delete script, import that:
$bkup_counts = import-clixml bkup_counts.xml

and foreach through the hash table keys to do the gci, and you've got the desired retention count for that type as value of the table entry with that key.

A: Here is what I have after utilizing your sample code. (Thanks, BTW).
$bkup_Counts = @{
FldrBkup = 5
txtBkup = 6
}

$type = $null
#set Backup Types from the array we just defined
foreach ($type in $bkup_Counts.Keys) {
    $bkupTypeArr += $type
    }
# nameConv has dt stamp of getdate,
# fArray will have filename in it FldrBkupYYYYMMDD_HHmmSS.zip and
#     txtBkupYYYYMMDD_HHmmSS.zip
$type = $null
foreach ($type in $bkup_Counts.Keys) {
    $fArray += $type + $nameConv
    }
# Array of extensions txt, asc
foreach ($ea in $extArray) {
    $filelist += Get-ChildItem $ToBeZipped"\*" -Recurse -Include $ea |Select-Object fullname
}

What I need to do though, is to have a way to associate a set of extensions, with a set of bkup types, and then associate those backup types with a file or folder set of backups.
example -
f1.txt
f2.txt
f3.asc
f4.asc
  all would zip into txtBkup....zip
x1.xml
x2.xml
  all would zip into xmlBkup....zip
folder
  c:\myfiles would zip into fldrBkup....zip
I need to be able to associate a set of file extensions with a backup type and to loop thru those backing up files, then go forward with the folder backups.


text:
Q: Async Await with custom type C# I have a model:
public class News
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public ObservableCollection<Comment> Comments { get; set; }
}

public class Comment
{
    public int CommentId {get;set;}
    public string CommentTitle{get;set;}
    public string CommentBody{get;set;}
}

public class APIData()
{

    public async Task<News> myNews()
    {
    var result = new News()
    /// GET xmlDATA

    var objComments = new ObservableCollection<Comment>();
    foreach(x in xmlData)
    {
        var objComment = new Comment();
    ////////////
        objComments.Add(objComment);
    }
    result.Comments = objComments;
    return result;
}

when I try to access it using api.myNews().Comments; I get error said ;

System.Threading.Tasks.Task does not contain a definition for
  Comments and no extension method accept first argument of type
  System.Threading.Tasks.Task could be found.

Please let me know. about this issue.

A: The method will return at Task which does not contain a property named Comments.
You need to await the Task:
var news = await api.myNews();
var comments = news.Comments;

If the method context is not async then use the Result.
var newsTask = api.myNews();
var comments = news.Result.Comments;


text:
Q: Data type for huge binary numbers I have to handle huge binary numbers (<=4096 digits) - what is the best way to handle such big numbers? I have to multiply them afterward and apply the %-operation on these numbers.
Do I have to use structs or how am I supposed to handle such data?

A: If you've got it as a string of 4096 digit, you can convert it into a list with separate smaller chunks (eg into bytes each consisting of 8 bits), then if you need to multiply/apply the %-operation on these numbers, you probably will need create a function that converts those "chunks" from binary to denary (so you can multiply them and so on.)


text:
Q: SQL - Find Record count for multiple tables at a time in snowflake I want to see counts have Tables at 1 time, instead of Running each.
For EX:
select COUNT(*) from  "Fact_MASTER ";
select COUNT(*) from  "Dim_MASTER ";
select COUNT(*) from  "Fact2 ";
select COUNT(*) from  "Dim2";
select COUNT(*) from  "Fact3";
select COUNT(*) from  "Dim3"

Is there any way we can write a CTE to pull as Record count for each in a temp table or so like below:

A: You can use union all:
select 'Fact_MASTER', COUNT(*) from  "Fact_MASTER " union all
select 'Dim_MASTER', COUNT(*) from  "Dim_MASTER " union all
select 'Fact2', COUNT(*) from  "Fact2 " union all
select 'Dim2', COUNT(*) from  "Dim2" union all
select 'Fact3', COUNT(*) from  "Fact3" union all
select 'Dim3', COUNT(*) from  "Dim3"

A: It looks like you want each count in a separate column. If so, you can turn each query to a separate subquery, and select them:
select
    (select count(*) from "Fact_MASTER") as fact_master,
    (select count(*) from "Dim_MASTER ") as dim_master,
    (select count(*) from "Fact2")       as fact2,
    (select count(*) from "Dim2")        as dim2,
    (select count(*) from "Fact3")       as fact3
    (select count(*) from "Dim3")        as dim3

A: Have you tried simply running:
SHOW TABLES;

If you then want to use that information for something else, you can then follow-up with something like:
select "rows" as cnt
from table(result_scan(last_query_id()))
where "name" in (...);

If you have a set list of tables that you want to PIVOT you can also use the result_scan() function to pivot the data:
https://docs.snowflake.com/en/sql-reference/constructs/pivot.html


text:
Q: Resonance of Parallel RLC circuit
For the circuit above, I was wondering how they derived the formula
$$\omega_0 = \sqrt{\dfrac{1}{LC} - \Big(\dfrac{R}{L}\Big)^2}$$
If anyone is able to walk me through this it would be fantastic.

A: Impedance is \$\dfrac{R + j\omega L}{R + j\omega L +\frac{1}{j\omega C}}\cdot\dfrac{1}{j\omega C}\$ = \$\dfrac{R + j\omega L}{j\omega RC + j^2\omega^2 LC +1}\$ = \$\dfrac{R + j\omega L}{j\omega RC - \omega^2 LC +1}\$
If you were to multiply both the numerator and the denominator by the denominator's complex conjugate you'd get a complex equation on the top and a non-complex (real) equation on the bottom. Resonance is when the imaginary part of the new numerator equals zero so, working only on the new numerator we get: -
New Numerator = \$(R+j\omega L)\cdot (-j\omega RC - \omega^2 LC +1)\$
The imaginary part boils down to \$j(\omega L - \omega^3 L^2 C - \omega C R^2)\$
Equating this to zero we get, \$\omega L - \omega^3 L^2 C - \omega C R^2 = 0\$
Therefore, \$\omega^2 L^2 C = L - CR^2\$ and \$\omega^2 = \dfrac{1}{LC} - \dfrac{R^2}{L^2}\$

EDIT section that describes other "resonances"
It's also interesting to note that there is another resonance at play. Firstly, the "resonance" above is defined by the impedance looking into the LCR network being purely resistive - this is slightly different to the "natural" resonant frequency (also purely resistive) when R is ignored.
In this situation \$\omega = \sqrt{\dfrac{1}{LC}}\$
However, the real peak of the response (as would be seen on a spectrum analyser and not purely resistive) is found by equating the denominator to zero and solving for s where s = j\$\omega\$.
\$s^2LC +sRC +1=0\$ or
\$s^2 + s\frac{R}{L} + \frac{1}{LC} = 0\$
Using the general solution to a quadratic, we get: -
\$s= \dfrac{-\frac{R}{L} +/- \sqrt{\frac{R^2}{L^2} - \frac{4}{LC}}}{2}\$
If we use a trick of reversing the signs inside the square root part and bring the square root of -1 (j) outside we get: -
\$s = \dfrac{-\frac{R}{L} +/- j\sqrt{\frac{4}{LC} - \frac{R^2}{L^2}}}{2}\$
Now, divide thru by two and we get: -
\$s = -\frac{R}{2L} +/- j\sqrt{\frac{1}{LC} - \frac{R^2}{4L^2}}\$
As we should know the "jw" part is what we see in a bode plot so the peak magnitude of the response (not when the impedance is purely resistive) is when: -
\$\omega = \sqrt{\dfrac{1}{LC} - \dfrac{R^2}{4L^2}}\$
If you drew a pole zero diagram, the imaginary parts of the poles would be at
+/-\$\sqrt{\dfrac{1}{LC} - \dfrac{R^2}{L^2}}\$ i.e. slightly different to +/-\$\sqrt{\dfrac{1}{LC} - \dfrac{R^2}{4L^2}}\$


text:
Q: Gradle build stuck at compile Java I'm trying to build a project, but the gradle build is stuck on compile java, I don't know how to fix it:

A: Gradle is actually very specific what has happened. There're compilation errors in project gene-model-dom.
Execution failed for task ':gene-model:gene-model-dom:compileJava'.
> Compilation failed; see the compiler output for details

To see the exact errors, run the build again with --info switch. For example (your mileage may vary):

gradlew --info :gene-model:gene-model-dom:compileJava


text:
Q: Is it possible to open Instant app directly without disambiguation dialog? I have deployed a simple instant app to play store and map a URL to my website using App Link, but when I tried to open instant app from another app for the first time, I always got the disambiguation dialog, letting user confirm whether open instant app or open in browser.
Instant app dialog.

but the dialog makes a very bad user experience, is it possible that I can remove it and open my instant app directly?


text:
Q: Plotly Express Scatter Resizing Dots i am creating a bee swarm graph for local windspeed data.
I want to make my dot sizes bigger, as the smallest are not visible enough.
Strangely enough, my list comprehension in resize is not working.
One size is f.e. 10000 but stays at the same volume compared to the sizes before resizing.
I didnt see another post adressing this issue.
Thy for helping. o/
data_wspd = my_data.loc[:, ["time","wspd"]]
print(data_wspd)
wspd_grouped = data_wspd.groupby("wspd")

df = {
    "wspd": [],
    "wspd_count": [],
     "wspd_size" :[]
}

for name, group in wspd_grouped:
    df["wspd"].append(name)
    df["wspd_count"].append(len(group))
df["wspd_size"] = [count*1000 for count in df["wspd_count"]]

fig_wspd = px.scatter(df,
                 x="wspd",
                 y="wspd_count",
                 size="wspd_size",
                 color="wspd",
                 hover_name="wspd",

                 )
#fig_wspd.update_yaxes(visible=False)

fig_wspd.show()
fig_wspd.write_html("wspd_beeswarm.html")

A: This is occurring because plotly.express markers are sized relative to the other markers.
There is an argument called size_max which is set to 20 by default (see the documentation here). So the observation with the largest wspd_size will have a marker size of 20, and if you multiply that column by 1000, that observation will still have the largest wspd_size value, so it will have a marker of size 20, and all of the smaller markers will remain the same size because the ratios between marker sizes in that column haven't changed.
I think the easiest solution is to pass the argument size_max=20*{scaling_factor} to make all of the markers larger.
Try the following:
size_max_default = 20
scaling_factor = 4
fig_wspd = px.scatter(df,
                 x="wspd",
                 y="wspd_count",
                 size="wspd_size",
                 size_max=size_max_default*scaling_factor,
                 color="wspd",
                 hover_name="wspd",

                 )

I tried this with some sample data and you can see the markers increase in size before and after using the size_max argument:
df = pd.DataFrame({
    "wspd":np.linspace(1,21,11),
    "wspd_count":np.linspace(1,21,11),
    "wspd_size":[1,1,1,1,2,2,5,10,20,50,50]
})

df["wspd_size"] = df["wspd_size"]*100

fig_wspd = px.scatter(df,
                 x="wspd",
                 y="wspd_count",
                 size="wspd_size",
                 color="wspd",
                 hover_name="wspd",

                 )

size_max_default = 20
scaling_factor = 4
fig_wspd = px.scatter(df,
                 x="wspd",
                 y="wspd_count",
                 size="wspd_size",
                 size_max=size_max_default*scaling_factor,
                 color="wspd",
                 hover_name="wspd",
                 )


text:
Q: ColorFunction with the function of luminance I want to have a DensityPlot or ListDensityPlot, whose color function is a rainbow but whose luminance is given by another function. For example, I've attached an image of a vortex, whose color function shows the phase and its luminance shows the intensity. In the following plot, you can use F1 =  ArcTan[x,y] function with luminance F2 = (x^2+y^2)*Exp[-x^2-y^2].

A: Edit
Table Case

Kuba, can you add also a solution for tables instead of functions, because in fact I have something like this: table1 = Table[(x^2 + y^2) Exp[-x^2 - y^2], {x, -3, 3}, {y, -3, 3}], table2 = Table[ArcTan[x, y], {x, -2.999, 3}, {y, -3., 3}]
– Mushegh

{
    table1 = Table[(x^2 + y^2) Exp[-x^2 - y^2], {x, ##}, {y, ##}],
    table2 = Table[Arg[x + I y], {x, ##}, {y, ##}]
} & @@ {-3, 3, .2};

Image[
  Reverse[#, 2] & @ Transpose @ MapThread[
    {(#2 - Pi/2.)/Pi, 1, # E } &,
    ArrayResample[#, {500, 500}] & /@ N[{table1, table2}],
    2
  ],
  ColorSpace -> "HSB"
]

You have probably noticed a strange "outflow". That is because of the interpolation of positive "x" axis neighborhood for ArcTan[x,y]:
table2 // ListPlot3D

Here is a fix:
res = ArrayResample[N@#, {500, 500}, ##2] &;
Image[
 Reverse[#, 2] &@Transpose@MapThread[
    {Which[#3 > 0, ArcSin[#2], #2 > 0, ArcCos[#2] + Pi/2, True,
         ArcCos[#2] - 3 Pi/2]/Pi - 1/2., 1, # E} &,
    {
     res@table1,
     res[Sin@table2],
     res[Cos@table2]
     },
    2
    ],
 ColorSpace -> "HSB"
 ]

Functions case
plot = ParametricPlot[{x, y}, {x, -#, #}, {y, -#, #},
     ColorFunction        -> Function[{x, y, u, v},
        Directive[
           Opacity[E (x^2 + y^2)*Exp[-x^2 - y^2]], (*E - scaling factor*)
           Hue[(ArcTan[x, y] - Pi/2)/Pi]
        ]
     ],
     PlotPoints           -> 100,
     ColorFunctionScaling -> False,
     Axes                 -> False,
     Frame                -> False,
     Background           -> Black,
     BoundaryStyle        -> None,
     ImageSize            -> {Automatic, 300},
     Mesh                 -> None
     ] &@3

barLegend = ParametricPlot[{x, y}, {x, 0, .1}, {y, 0, 2 Pi},
   ColorFunction    -> (Hue[#2] &),
   AspectRatio      -> 10,
   PlotRangePadding -> None,
   FrameTicks       -> {{False, {0, 2 Pi}}, {False, False}},
   BaseStyle        -> 24,
   FrameLabel       -> {{None, "Phase"}, {None, None}},
   ImageSize        -> {Automatic, 300},
   Mesh             -> None
]

Grid[{{plot, barLegend}}]

A: No legend for this slight simplification of Kuba's proposal, but it can be easily added if desired:
RegionPlot[True, {x, -3, 3}, {y, -3, 3}, Background -> Black, BoundaryStyle -> None,
           ColorFunction -> Function[{x, y}, Hue[(Arg[x + I y] - Pi/2)/Pi, 1, 1,
                                                 (x^2 + y^2) Exp[1 - x^2 - y^2]]],
           ColorFunctionScaling -> False, Frame -> False, PlotPoints -> 95]


text:
Q: Convert String ["Scenario 1", "Scenario 2"] to Array I have the following code:
String text = "[\"Scenario 1\", \"Scenario 2\"]"

I need to convert "text" to Array. I know that I can replace [ ] " and I do a split(",") but is there a way easy?

A: It seems, you mean "[\"String 1\", \"String 2\"]"
Ofcourse you can use jackson ObjectMapper to read it like a json string and deserialize to array. But it doesn't looks like easier way.

A: If you know that the text is well formatted you can use String.substring() instead of regex.
String text = "['Stack1', 'Stack2']";
StringTokenizer tkn = new StringTokenizer(text.substring(1, text.length() - 1), ", ");
while (tkn.hasMoreTokens()) {
    String v = tkn.nextToken();
    System.out.println(v.substring(1, v.length() - 1)); // Stack1 Stack2
}

A: The shortest version I can come up with is this:
String text = "['Stack1', 'Stack2']";
String[] splitted = text.split("\\['|', *'|'\\]");

Edit: I just see, that the first entry in the array would be an empty String. So maybe better go with the solution in one of the comments:
String[] splitted2 = text.replaceAll("\\[|\\]|'", "").split(", *");

BTW, this allows separating the elements by comma + space or just comma without space.

A: I guess you could split on the " which would give you an array with the contents: [, Scenario 1, ,, Scenario 2, ].
Then it's just the case of taking every value with an odd index to find the final array which is just a simple mathematical calculation. I would imagine this to be fairly efficient as it involves less string manipulation but I don't know if the overhead of doing more splits would be worth it.


text:
Q: How to handle expired assets/content when user has direct URL An E-Commerce site has PDF coupons that expire after a certain date.  What is the best way to handle them?  I've heard allowing 404's aren't great for SEO and 301 redirects can clog up the .htaccess.
There is already a landing page generated through internal links if a coupon is expired, so ideally I would like a way to capture requests to expired assets and redirect to that page.
I'm curious, what ways are there to handle this?

A: Are these pdfs all in a sub-directory somewhere? You could add an .htaccess file to your sub-directory root then put this as the top line.
ErrorDocument 404 /path/to/your404page

This would make it easier to manage and keep it separate from your main htaccess file.


text:
Q: How to capture groups of strings with indentation? I would like to capture every if-construct in this string as a single one
if a > b
    do this
    do that
    if a == c
        do this
        do that

I would like to have a match for
if a > b
    do this
    do that

and
    if a == c
        do this
        do that

What I have so far doesn't seperate between new if-constructs
if(\W+\w+)+\n\t

A: You can use this lookahead based regex:
^(\s*if[\s\S]+?)(?=^\s*if|\z)

in MULTILINE mode.
RegEx Demo
[\s\S]+ will match 1 more characters including newlines and (?=^\s*if|\z) is a lookahead that will make sure to assert that next to current match is another if block or end of input.

A: Whatever you're trying to do, you should consider writing a parser. It'll keep things simpler for you in the long run.
If you insist on using a regex, well...
^([ ]*)if.+\r?\n(\1[ ]+).+(?:\r?\n\2(?!if).+)*

Demo
Usage:
var re = new Regex(@"^([ ]*)if.+\r?\n(\1[ ]+).+(?:\r?\n\2(?!if).+)*", RegexOptions.Multiline);

Let's split it up into pieces:

*

*^([ ]*)if.+\r?\n captures a first if with leading spaces until a line break

*(\1[ ]+).+ captures the next line. It requires more spaces (so it's indented).

*(?:\r?\n\2(?!if).+)* captures the next lines up until the next if. It requires the same amount of spaces as the first line after the if.


text:
Q: Google DoubleClickStudio - video source file After creating a creative banner with an mp4 video in Google Web Designer and then upload that creative to DoubleClick the source file has changed from mp4 to webm. The issue here is that webm in Safari is pixelated and the creative/ad is not shown properly, while on other browsers its ok. Is there a setting in DoubleClickStudio to prevent it from transcoding the mp4 video and use the default mp4 instead ?
...1630672923/mv/u/mvi/1/pl/24/file/file.webm


text:
Q: How to add a PHP script to a .js file? Suppose I have an external JavaScript file named myJavascript.js which has 3 functions like the following:
function myFunc1(){
    //some code
}

function myFunc2(){
    //some code
}

function myFunc3(){
    //some code
}

Now, I want to add some PHP script in myJavascript.js like the following, and it's from a separate PHP file named myView.ctp:
<?php
$url = Router::url($this->here, true);
$url = explode('/', $url);
$baseURL = $url[0] . '//' . $url[2] . '/' . $url[3] . '/' . $url[5];
$baseURL2 = $url[0] . '//' . $url[2]. '/' . $url[3];
?>

Why I need to add this PHP script inside myJavascript.js is this - I want to use the PHP variables $baseURL and $baseURL2 inside the 3 functions I've created.
How can I achieve this?
Edit:
I'm sorry I actually made a mistake in my question. The php view file is actually named as myView.ctp, as it's a CakePHP view file. The extension is .ctp and not .php. I've updated my question accordingly.

A: It's possible if you work into an internal HTML file and the extension is php.
Into your myView.php You can declare a global variable, and assign a response server value, into that file.
For example:
myView.php
<script>
    var globalVar = <?php echo "your_value" ;?>
</script>
<script src="external_file.js"></script>

external_file.js
console.log(globalVar) // your_value

A: You cannot use php variables inside a separate javascript file. Instead what you can do is either to include the script inside the php template like
<script type="text/javascript">
....
</script>

or either to parse the url via javascript if this fits for you. You can get the current url with:
window.loacation.href
then you can parse the string as you wish.

A: I would definitely not do that but instead passing the args to methods or properties.
We usually have one script that takes care of initialization, lazy loading other stuff and so on. This is done in the layout.
<header>
<script src="/js/app.js">
<script>
    app.init(<?php echo json_encode($this->request); ?>);
<script>
</header>

Just make sure you pass only what yo need of the request, it might contain security related data, so be careful by passing the whole thing.
In your specific views:
<script>
    app.nameSpaceForView.someMethod('<?php echo $someStringVar; ?>');
</script>

You can even avoid this by implementing some logic in the above app.init() function that will check if app.controllers.ControllerName.ViewName is set based on the passed request info and if it's present execute it.
You won't need much, in the best case any, JS in your views by this.


text:
Q: Intermittent (time dependent) error when using Node Package rate-limiter-flexible in Express Node.js application My overall goal is to apply the basic logic of the package "rate-limiter-flexible" for my Express Node.js application.  I've gotten the basic functionality with the "Memory" version which does not require any communication with a database (IP address counts stored in Node server memory).  Now I'm trying to get the functionality to work with the MongoDB rate limiter modules (using an instance of rateLimiterMongo object from the package).
The problem I'm encountering is that my rate limiter middleware is throwing an error intermittently...  The only pattern I can find is that the error occurs more frequently if there are > ~10 seconds between requests to the Node app.  This is the error which occurs every 5-10 requests:
[RateLimiter Error]: Rejection object:

TypeError: Cannot read properties of null (reading 'points')

at RateLimiterMongo._getRateLimiterRes (C:\root\node_modules\rate-limiter-flexible\lib\RateLimiterMongo.js:124:33)

at RateLimiterMongo._afterConsume (C:\root\node_modules\rate-limiter-flexible\lib\RateLimiterStoreAbstract.js:51:22)

at C:\root\node_modules\rate-limiter-flexible\lib\RateLimiterStoreAbstract.js:205:16

at processTicksAndRejections (node:internal/process/task_queues:96:5)

So far, I have tried:

*

*Disabling buffering with Mongoose (was a recommendation from the package docs) -- did not work

*Changing from MongoDB Atlas free tier to a locally hosted MongoDB instance -- this resolved all occurrences of the error, but I need to be able to use the cloud service
Here is a minimal reproduction of the error I'm facing when connecting to a MongoDB Atlas free tier cluster (via MONGO_DB_URL):
// Node packages:
require('dotenv').config();
const { RateLimiterMongo } = require('rate-limiter-flexible');
const mongoose = require('mongoose');
const express = require('express');
const app = express();

// open a Mongoose connection and save it:
const dbUrl = process.env.MONGO_DB_URL;
const connectDB = async function () {
    await mongoose
        .connect(dbUrl, {
            // options
        })
        .catch(error => {
            console.log("DB not connected!");
            // handle error here (initial connection)
        });
};
connectDB();
const mongoConn = mongoose.connection;

// options and passing to the RateLimiterMongo constructor:
const opts = {
    storeClient: mongoConn,
    points: 3, // Number of points
    duration: 1, // Per second(s)
};
const rateLimiterMongo = new RateLimiterMongo(opts);

// create the middleware for the express app:
const rateLimiterMiddleware = (req, res, next) => {
    rateLimiterMongo.consume(req.ip, 1)
        .then((rateLimiterRes) => {
            console.log("[RateLimiter Success]: RateLimiterRes object:\n", rateLimiterRes);
            next();
            // Allowed
        })
        .catch((rej) => {
            console.log("[RateLimiter Error]: Rejection object:\n", rej);
            res.status(500).send("RateLimiter error(s)...");
            // Blocked
        });
};

// Express app code:
app.use(rateLimiterMiddleware);
app.get('/', (req, res) => {
    res.status(200).send("Valid Route!");
});
app.listen(3000, () => {
    console.log(`Serving on port 3000!`);
});

Thanks all for any help you can provide with this.  It may just be a side effect of using the MongoDBAtlas free tier...

A: Most likely, you use mongoose v6.x, which changes how connection established. It returns promise, which should be awaited, before connection can be used to make queries. More context in migration to 6 guide.
You should await connectDB() call and only then create middleware. In other words, your Express app should wait until connection to MongoDB Atlas is established. You can read through comments in related closed issue on github.


text:
Q: Spring Security Custom AuthenticationProvider Login post give 302 error I have implement custom AuthenticationProvider spring login security. When i post it using its /login url it gives me 302 HTTP status code. whats the issue in that i have on custom filter for every request for handle every request
Filter
public class AppFilter implements Filter {

private Logger logger = Logger.getLogger(AppFilter.class);
private CommonService commonService;

public AppFilter() {}

public void destroy() {}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    try {
        if (httpServletRequest.getRequestURI().contains("/resources/")) {
            filterChain.doFilter(httpServletRequest, servletResponse);
        }
        else {
            HttpSession session = httpServletRequest.getSession();
            if(session != null && session.getAttribute(CommonConstant.XXX) == null) {

                List<Map<String, Object>> clientDetails = commonService.getXXX(XX);
                if (clientDetails != null && !clientDetails.isEmpty()){

                    session.setAttribute(CommonConstant.CLIENT_SESSION_DATABEAN, clientSessionDataBean);
                }
            }

            HttpServletRequest request = new CustomHttpServletRequestWrapper(httpServletRequest);
            filterChain.doFilter(request, servletResponse);
        }
    } catch (Exception e) {
        logger.error(httpServletRequest.getRequestURI(), e);
        servletRequest.getRequestDispatcher("/WEB-INF/views/common/unauthorized-access.jsp").forward(servletRequest, servletResponse);
    }
}

public void init(FilterConfig arg0) throws ServletException {
    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext());
    commonService = ctx.getBean(CommonService.class);
}

class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private Map<String, String[]> allReqParam;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws Exception {
        super(request);
        allReqParam = new TreeMap<String, String[]>();
        if(ServletFileUpload.isMultipartContent(request)) {
            allReqParam = request.getParameterMap();
            List<FileItem> multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem multipartItem : multipartItems) {
                if (multipartItem.isFormField()) {
                    processFormField(multipartItem, allReqParam);
                } else {
                    processFileField(multipartItem, request);
                }
            }
        } else {
            Map<String, String[]> reqParamMap = super.getParameterMap();

             if(reqParamMap != null && !reqParamMap.isEmpty()) {
                 for(Entry<String, String[]> entry : reqParamMap.entrySet()) {
                     String paramName = entry.getKey();
                     String[] paramValue = entry.getValue();

                     identifyHiddenFields(paramName, paramValue);
                 }
             }
        }
    }

    /**
     * Process multipart request item as regular form field. The name and value of each regular
     * form field will be added to the given parameterMap.
     * @param formField The form field to be processed.
     * @param parameterMap The parameterMap to be used for the HttpServletRequest.
     * @throws Exception
     */
    private void processFormField(FileItem formField, Map<String, String[]> parameterMap) throws Exception {
        String name = formField.getFieldName();
        String value = formField.getString();
        String[] values = null;

        if(parameterMap != null && !parameterMap.isEmpty()) {
            values = parameterMap.get(name);
        }

        if (values == null) {
            identifyHiddenFields(name, new String[] {value});
        } else {
            int length = values.length;
            String[] newValues = new String[length + 1];
            System.arraycopy(values, 0, newValues, 0, length);
            newValues[length] = value;
            allReqParam.put(name, newValues);
            identifyHiddenFields(name, newValues);
        }
    }

    /**
     * Process multipart request item as file field. The name and FileItem object of each file field
     * will be added as attribute of the given HttpServletRequest. If a FileUploadException has
     * occurred when the file size has exceeded the maximum file size, then the FileUploadException
     * will be added as attribute value instead of the FileItem object.
     * @param fileField The file field to be processed.
     * @param request The involved HttpServletRequest.
     * @throws IOException
     */
    private void processFileField(FileItem fileField, HttpServletRequest request) throws IOException {
        request.setAttribute(fileField.getFieldName(), fileField);
        allReqParam.put(fileField.getFieldName(), new String[] {fileField.toString()});
    }

    private void identifyHiddenFields(String paramName, String[] paramValue) throws Exception {
        if(paramName.startsWith("hidden")) {
             String[] tParamVal = new String[paramValue.length];

             for(int i=0; i < paramValue.length; i++) {
                 tParamVal[i] = AppCryptoUtil.decryptHV(paramValue[i]);
             }

             allReqParam.put(paramName.substring(6), tParamVal);
         } else {
             allReqParam.put(paramName, paramValue);
         }
    }

    @Override
    public String getParameter(final String name) {
        String[] strings = allReqParam.get(name);
        if (strings != null) {
            return strings[0];
        }
        return super.getParameter(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return Collections.unmodifiableMap(allReqParam);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}
}


text:
Q: Passing a file via POST to NodeJS and then pass to another API without saving on Disk I need to receive a file from the user in a React UI (using axios), send this file to a NodeJS method via POST using Express and then, I need to send this same file via POST directly to another API (.NET WebAPI) without saving on disk. I'm trying to pass the data file directly (req.files.file.data), but the .NET API doesn't recognise the file in the request.
Is there any possibility to create a temporary file within a "var" and send it as I do when I read a file from disk?
This example works fine with local files:
var formData = {
  form: "{ abn: '666666666' }",
  files: JSON.stringify([
    {
      name: "file1",
      type: "1",
      number: "6666"
    },
    {
      name: "file2",
      type: "3",
      number: "3333"
    },
  ]),
  // Pass multiple values /w an Array
  attachments: [
    fs.createReadStream(__dirname + '/../file1.txt'),
    fs.createReadStream(__dirname + '/../file2.txt')
   ],
};
var reqs = request.post({url:'https://tms-dev-api.micway.com.au/api/company/file', formData: formData, json: true}, function optionalCallback(err, response, body) {
  if (err) {
    return res.send(err);
  }
  return res.send({
    status: response.statusCode,
    body: body
  });
});

I am creating a local file and then sending it through; however, I don't believe that it is the best way to do it. Like This:
router.post('/file', function(req, res) {
  var fstream;
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {
    fstream = fs.createWriteStream(__dirname + '/' + filename);
    file.pipe(fstream);

    var formData = {
    attachments: [
        fs.createReadStream(__dirname + '/' + filename)
      ],
    };
    var reqs = request.post({url:'https://tms-dev-api.micway.com.au/api/company/file', formData: formData, json: true}, function optionalCallback(err, response, body) {
      if (err) {
        return res.send(err);
      }

      console.log({
        status: response.statusCode,
        body: body
      })

      return res.send({
        status: response.statusCode,
        body: body
      });
    });
  });
});

Thanks!

A: The solution that I find effective, is by saving it during execution, reading and manipulating the data in other to send it to the other API, and immediately delete it from Disk as soon as I get the response.

A: Create a PassThrough() stream instead of writing the file to the disk:
const { PassThrough } = require('stream')

...

fstream = new PassThrough()
file.pipe(fstream);


text:
Q: how to capture the data that is outside of the join scope into a tempTBL Let's say we have the tables A and B, where A is the parent table of B
TableA:
ID | VAL
1  | "foo"
2  |  "bar"

TableB:
ID | aID
1  |  2

OK?
Now lets have an join:
select *
from A
inner join B on a.Id = b.aID

Is there a way to use the INTO keyword to immediately store the failed join record into a temporary table. Something similar using the OUTPUT clause?
I know that it is a bit far fetched, but maybe there is a way I'm not aware of. Pays off to try.

A: Failed join record ? do you mean non matching records ?
select *
from A
left join B on a.Id = b.ID
where b.ID IS NULL

To store in temporary table , create table structure with required columns from rows retrived in join operation then do
INSERT INTO #temp
SELECT * from A
left join B on a.Id = b.ID
where b.ID IS NULL

or if you require all the columns then do select * into
SELECT * INTO #temp from A
left join B on a.Id = b.ID
where b.ID IS NULL

A: CREATE TABLE ##tmp  (
    ID int,
    VAL nvarchar(3),
    IDD int,
    aID int
)

CREATE TABLE ##tmp1 (
    ID int,
    VAL nvarchar(3)
)

;WITH TableA AS (
SELECT *
FROM (VALUES
(1, 'foo'),(2, 'bar')) as t(ID, VAL)
), TableB AS (
SELECT *
FROM (VALUES
(1, 2)) as t(ID, aID)
)

INSERT INTO ##tmp
select  a.ID,
        a.VAL,
        b.ID AS IDD,
        b.aID
from TableA a
FULL OUTER JOIN TableB B on a.Id = b.aID

DELETE FROM ##tmp
OUTPUT deleted.ID, deleted.VAL INTO ##tmp1
WHERE IDD IS NULL

Data in ##tmp:
ID          VAL  IDD         aID
----------- ---- ----------- -----------
2           bar  1           2

(1 row(s) affected)

Data in ##tmp1:
ID          VAL
----------- ----
1           foo

(1 row(s) affected)


text:
Q: Is the action of taking the inverse distributive in any way? For example, is $(A+B)^{-1}= A^{-1} + B^{-1}?$ Sorry for not formatting properly, I can't seem to get the exponents to show up properly (ex. $A^{-1}$).
Can you distribute the act of taking the inverse over a pair of brackets?
For example, is $(A+B)^{-1} = A^{-1} + B^{-1}?$
That doesn't seem right, but there are some proofs that I can't see being possible without having a place to start, and the only place to start seems to be to do something with the inverse operator (if I can call it an operator). For example: Show that $(C+DD^{T})^{-1}=C^{-1}D(I+D^{T}C^{-1}D)^{-1}$
I've no idea how proofs on that post are getting started; I don't understand their first step. For example:
$(C+DD^T)^{-1} =((I+DD^TC^{-1})C)^{-1}$
Why is the above true, and how did the answerer get there? This is why I'm thinking there's some kind of way to expand an inverse.
It always seems to involve the identity matrix, and I realize that $A^{-1}A=I,\;$ but I'm still unable to understand those proofs and how they're expanding the expression out in the way that they are.
Any help whatsoever is greatly appreciated.

A: Consider the case of $1\times 1$ matrices.
Observe
\begin{align}
(1+1)^{-1} \neq 1^{-1}+1^{-1}.
\end{align}

A: Actually you can show it more generally. If you show that matrices with standard matirx-addition do have group structure. and it becomes obvious, as for any group, if a,b are elements of your Group (a*b)^-1 =b^-1 * a^-1.

A: Even doesn't hold for diagonal case. Consider$$A=diag(a_1,a_2,\cdots, a_n )\\B=diag(b_1,b_2,\cdots, b_n )$$The we have $$(A+B)^{-1}=diag\left({1\over a_1+b_1},{1\over a_2+b_2},\cdots ,{1\over a_n+b_n}\right)$$and $$A^{-1}+B^{-1}=diag\left({1\over a_1}+{1\over b_1},{1\over a_2}+{1\over b_2},\cdots ,{1\over a_n}+{1\over b_n}\right)$$clearly $${1\over a_i+b_i}\ne {1\over a_i}+{1\over b_i}$$

A: If $A=I$ and $B=-I$ are $n\times n$ matrices, both are invertible and equal their own inverses, but their sum is $0$ matrix


text:
Q: Error creating bean with name 'tilesViewResolver' i am trying to run my app using tilesViewResolver. and run output will print hello form tiles in default.jsp file.
but is not running show some error.
error like

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'tilesViewResolver': Lookup method resolution
  failed; nested exception is java.lang.IllegalStateException: Failed to
  introspect Class
  [org.springframework.web.servlet.view.tiles3.TilesViewResolver] from
  ClassLoader [ParallelWebappClassLoader

servler.xml
        <bean id="tilesViewResolver"
             class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
        </bean>

        <bean id="tilesConfigurer"
            class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
            <property name="definitions">
                <list>
                    <value>/WEB-INF/layout/default.xml</value>
                </list>
            </property>
        </bean>

default.xml
        <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

    <tiles-definitions>
        <definition name="index" template="WEB-INF/templates/default.jsp">
        </definition>
    </tiles-definitions>

default.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 hello from tiles.
</body>
</html>

file
[enter image description here][1]

add jar
tiles-extras 3.0.5
tiles-servlet 3.0.5
tiles-jsp 3.0.5
slf4j-simple 1.7.6

A: There was a problem with jar file. When I added these jar files. Then it works
jar file:
1. tiles-core-3.0.8
2. tiles-jsp-3.0.8
3. tiles-request-api-1.0.7
4. tiles-request-jsp-1.0.7
5. tiles-request-servlet-1.0.7
6. tiles-servlet-3.0.8
7. tiles-template-3.0.8
8. tiles-autotag-core-runtime-1.2
9. tiles-api-3.0.8
10. slf4j-api-1.7.6
11. jcl-over-slf4j-1.7.6
12. commons-digester-2.0
13. commons-beanutils-1.8.0

This link contains all the jar files
https://jar-download.com/artifacts/org.apache.tiles/tiles-jsp/3.0.8/source-code


text:
Q: Instantiate a prefab in a function with unity I'm trying to instantiate some prefabs in my scene, I'm forced to do it in a function (not main thread) because I instantiate a prefab only when I receive some data throught an TCP protocol.
Right now, I'm just testing with a cube prefab, but it's not working :
     private void addAircraft(Plane plane)
    {
        listPlane.Add(plane);
        //THIS 2 LINES ARE THE PROBLEM
        GameObject cube = Instantiate(Resources.Load("Cube", typeof(GameObject))) as GameObject;
        cube.transform.position = new Vector3((float)plane.X, 0, (float)plane.Y);
        //
        planeId_Object_Dictionnary.Add(plane.Flight, cube);
        Debug.Log("Plane " + plane.Flight + " is added");
    }

It return me the error :
Load can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
Even if, a lot of people have encounterd this problem, I can't find a solution that allows me to instantiate my prefab in a function.

A: You could have a private bool checker to see if the plane should be added at any time. When you receive TCP response mark it true, call addAircraft() from the Update() function and mark it false again. Update() runs on main thread so this will make sure addAircraft() also runs on main thread.
I guess 1 frame delay wouldn't matter if you're waiting anyways.


text:
Q: 'Unbalanced quote exception' while running html file on Netbeans I have a problem running any html file on Netbeans 8.0. It gives me following exception -
unbalanced quotes in -Xbootclasspath/p:
C:\Users\KEM'S PC\Documents\NetBeansProjects\PrisonWare\lib\javaee-endorsed-api-6.0\javax.annotation.jar;
C:\Users\KEM'S PC\Documents\NetBeansProjects\PrisonWare\lib\javaee-endorsed-api-6.0\jaxb-api-osgi.jar;
C:\Users\KEM'S PC\Documents\NetBeansProjects\PrisonWare\lib\javaee-endorsed-api-6.0\webservices-api-osgi.jar

I really don't understand this exception at all.

A: Yes, the quotes and the spaces in the path look like the culprit.


text:
Q: Spring autowiring fails with Ibatis I am new to Spring and trying to use @Autowire annotation for my DAOImpl class (@Repository) from Service layer (@Service)
Here is my code:
@Service
public class DefaultLocationService implements LocationService
{
@Autowired
@Qualifier("countryDao")
private CountryDAO countryDao; // This is an interface

public void setCountryDao(CountryDAO countryDao) {
    this.countryDao = countryDao;
}

// More code
}

And then I have CountryDaoImpl class (@Repository) which implements CountryDAO
@Repository("countryDao")
public class CountryDAOImpl extends InstrumentedSqlMapDaoTemplate implements CountryDAO {

@Autowired
public CountryDAOImpl(DaoManager daoManager) {
    super(daoManager);
}
// More code
}

public class InstrumentedSqlMapDaoTemplate extends SqlMapDaoTemplate
{

public InstrumentedSqlMapDaoTemplate(DaoManager daoManager)
{
    super(daoManager);
}
// More code
}

The problem happens with SqlMapDaoTemplate as it has a constructor with argument and therefore Spring can not instantiate a default constructor and fails. For that I autowired the constructor in my DAOImpl class but still no luck and it fails with this exception:
  Unsatisfied dependency expressed through constructor argument  with
 index 0 of type [com.ibatis.dao.client.DaoManager]: : No matching bean
 of type [com.ibatis.dao.client.DaoManager] found for dependency:
 expected at least 1 bean which qualifies as autowire candidate for
 this dependency. Dependency ann otations: {}; nested exception is
 org.springframework.beans.factory.NoSuchBeanDefinitionException: No
 matching bean of t ype [com.ibatis.dao.client.DaoManager] found for
 dependency: expected at least 1 bean which qualifies as autowire
 candid ate for this dependency. Dependency annotations: {}

Can you guys please let me know what I am doing wrong here.
Thanks,
Troy

A: The problem is exactly What the message says. You are missing bean of type DaoManager. When countryDay bean is being created by Spring, it tries to use constructor public CountryDAOImpl(DaoManager daoManager). But it also needs (according to your configuration) find the bean with type DaoManager.
Just annotate DaoManager class with @Repository annotation also.


text:
Q: ADO.net Entity One Relationship is always returning null I have setup 4 separate tables that have fk relationships between all of them.  The main problem I am having is between a table called EmployeeQuestions and Questions tables.  I am using Entity to model the objects.  When I get my EmployeeQuestions object I check it to make sure that the relationship between the EmployeeQuestions and Employee is there and I can get all the information through that relationship however the relationship between EmployeeQuestions and Questions is always null.  I have checked to make sure that the relationship was setup correctly and it is.  Also I have tried to do a search on a list of all EmployeeQuestions and I can query those results for the QuestionID in the Questions table however I cannot get the description field.
I am very new to working with databases at all, any help would be much appreciated.
Thanks.

A: Can you show us the query you're using?
By default, Entity Framework will not traverse associations to grab the objects "on the other end" of the association - you will have to do this explicitly.
var emps = from e in ObjectContext.Employees
           where (some condition)
           select e;

In this case, you "Employee.Questions" association (assuming it's called that) would always be NULL - by design.
You can specify an "Include" in your query:
var emps = from e in ObjectContext.Employees.Include("Questions")
           where (some condition)
           select e;

and now in this case, when fetching an employee, the associated "Questions" would also be loaded.
Or you can do:
var emps = from e in ObjectContext.Employees
           where (some condition)
           select e;

foreach(Employee e1 in emps)
{
  if(!e1.QuestionReference.IsLoaded)
  {
     e1.QuestionReference.Load();
  }
}

to explicitly and in code load the associated objects.
Since this has been regarded by a lot of people as a shortcoming, in EFv4, there will be an option to turn on this automatic "deferred" loading on - but again, you have to do it explicitly and knowingly.
Marc


text:
Q: changing webpage randomly without getting the same page twice I am trying to link 35 webpages with math.random. However I dont want it to go to each site more then once. So I have this:
function myFunction() {
var pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
var page, visitedPages = JSON.parse(localStorage.getItem("visitedPages"));
if (visitedPages === null) {
    visitedPages = [];
}
if (pages.length !== visitedPages.length) {
    for (var i = 0; i < pages.length; i++) {
        page = pages[Math.floor((Math.random() * pages.length) + 1)];
        if (visitedPages.indexOf(page) === -1) { //unvisited yet
            localStorage.setItem("visitedPages", JSON.stringify(visitedPages.push(page)));
            window.location.href = page;
            break;
        }
    }
} else {window.location.href = score.html //All pages visited at once

}
}

a random page:

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Gæt en sang</title>
<link rel="stylesheet" type="text/css" href="main.css">

    <audio class="hidden" controls autoplay>
  <source src="horse.ogg" type="audio/ogg">
  <source src="Original GhostBusters Theme Song.mp3" type="audio/mpeg">
    </audio>

 Gæt sangen og hejs flagstangen!

 Hvilken sang er dette?

            <button type="button" onclick="myFunction()">

 Ghost busters

            </button>

            <button type="button" onclick="myFunction()">

 Poltergeist

            </button>

            <button type="button" onclick="myFunction()">

 Something strange

            </button>

            <button type="button" onclick="myFunction()">

 Who are you gonna call

            </button>

so I have a button you press and then it starts myfunction. This goes for all my sites. However when i press my button it always goes to page 2. And only from page 1. Any suggestions to what is wrong?

A: Instead of having a list of visited pages, have a list of all pages which you splice a random one out of on every click. An example without the finishing page:
var pages = JSON.parse(localStorage.getItem("pages"));

if (pages === null) {
    pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
}

function onClick () {
    var randomIdx = Math.floor(Math.random() * pages.length),
        page = pages[randomIdx];

    pages.splice(randomIdx, 0);
    localStorage.setItem("pages", JSON.stringify(pages));

    window.location.href = page;
}


text:
Q: Vertical Scrollbar Causes Horizontal Scrollbar There seems to be a similar question to this, and it was resolved by adding padding-right. However, in my case, that won't work because I don't know the width for any of my div until contents are rendered at run time via ajax call.  I have something similar to this
Assuming below pseudocodes are syntactically correct.

 Lots of contents

 Lots of contents

#parent {
    overflow: auto;
    max-width: 600px;
}
#child1 , #child2 {
    display: inline-block;
    max-width: 300px;
}

A: You can set your overflow-x to hidden, and overflow-y to auto.  That will give you vertical scrolling without horizontal scrolling.
#parent { overflow-x:hidden; overflow-y:auto; }
#child1, #child2 { overflow-x:hidden; overflow-y:auto; }

A: You are attempting to use self closing tags on the child1 and child2 elements.  This will not render properly in most browsers.  Though some browsers will re-write the DOM with a closing tag, it is not good practice as these browsers will only re-write within certain perimeters (truly dependent on the type of containing element).
Here is the code with self closing tags:  http://jsfiddle.net/nMPwV/
Here is the code with closing tags:  http://jsfiddle.net/nMPwV/1/


text:
Q: How do I write Foreach to get as same result as my query? I have a code like that:
List<BankDepositHistoryDTO> BankDepositHistoryDTOs = new List<BankDepositHistoryDTO>();

for (int i = 0; i < query.Count; i++)
{
   BankDepositHistoryDTO b = new BankDepositHistoryDTO();

   b.AccountId = query[i].AccountId;
   b.Id = query[i].Id;
   b.Amount = query[i].Amount;
   b.AdditionalData = query[i].AdditionalData;
   b.ClientIp = query[i].ClientIp;
   b.Gateway = query[i].Gateway;
   b.PaymentRefNumber = query[i].PaymentRefNumber;
   b.ReturnUrl = query[i].ReturnUrl;
   b.State = query[i].State;
   b.Uuid = query[i].Uuid;

   BankDepositHistoryDTOs.Add(b);
}

I was wondering if I can get it with foreach loop. Is that possible ?

A: You can use projection with Linq Select, it maybe a little more succinct
var dtos = query.Select(x => new BankDepositHistoryDTO()
                             {
                                AccountId = x.AccountId,
                                Id = x.Id,
                                Amount = x.Amount,
                                AdditionalData = x.AdditionalData,
                                ClientIp = x.ClientIp,
                                Gateway = x.Gateway,
                                PaymentRefNumber = x.PaymentRefNumber,
                                ReturnUrl = x.ReturnUrl,
                                State = x.State,
                                Uuid = x.Uuid
                             }).ToList();

or
List<BankDepositHistoryDTO> BankDepositHistoryDTOs = new List<BankDepositHistoryDTO>();

foreach(var item in query)
{
   BankDepositHistoryDTO b = new BankDepositHistoryDTO();

   b.AccountId = item.AccountId;
   b.Id = item.Id;
   b.Amount = item.Amount;
   b.AdditionalData = item.AdditionalData;
   b.ClientIp = item.ClientIp;
   b.Gateway = item.Gateway;
   b.PaymentRefNumber = item.PaymentRefNumber;
   b.ReturnUrl = item.ReturnUrl;
   b.State = item.State;
   b.Uuid = item.Uuid;

   BankDepositHistoryDTOs.Add(b);
}

A: You can use foreach like
        List<item> query = new List<item>();
        List<itemDto> test = new List<itemDto>();

        // either use this or the next method where mapping is done seperately
        query.ForEach(q => test.Add(new itemDto {id= q.id, type= q.type }));

        // Where the convert method is your conversion code
        // you can use a automapper/reflection to make it more generic
        query.ForEach(q => test.Add(Convert(q)));

My structures for completeness
    public class item
    {
        public string id { get; set; }
        public string type { get; set; }
    }

    public class itemDto
    {
        public string id { get; set; }
        public string type { get; set; }
    }

    public itemDto Convert(item source)
    {
        itemDto target = new itemDto();
        target.id = source.id;
        target.type = source.type;
        return target;
    }

A: I would suggest for loop instead of using foreach or linq beacuse of performance. For loop will always be faster than all.


text:
Q: How do I have numbers increment slowly over a course of time throughout runtime I am trying to make a text based game in which the user is a pilot in space. I want to create a movement system but am unsure how to do it. I want the user to be able to put in the desired grid coordinates, and his vehicle will begin to change its grid coords to get closer and closer to the ones he inputted.
Now, to do this I will probably need multithreading and a time element. But I am unsure how I can use a time element. Any advice is greatly appreciate, i'm just trying to learn here. Thanks guys!
from Gundam2 import Mobilesuits

#Main Variable/Object declarations:

Leo1=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,100,100])
Leo2=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[300,100,100])
Leo3=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,150,100])
currentmobilesuit=Leo1

#Main Function declarations
def commands(user_input,currentmobilesuit):
    if user_input == "radar":
        currentmobilesuit.radar()
    elif user_input == "commands":
        print("Command list:\nradar")
    else:
        print("Invalid command\nType 'commands' for a list of valid commands")

#Main execution
while True:
    commands(raw_input(),currentmobilesuit)

class Mobilesuits:
    #class global variables/methods here
    instances = [] #grid cords here
    def __init__(self,armor,speed,name,description,cockpit_description,\
                 radar_range, coordinates):
        Mobilesuits.instances.append(self)
        self.armor=armor
        self.speed=speed
        self.name=name
        self.description=description
        self.cockpit_description=cockpit_description
        self.radar_range=radar_range
        self.coordinates=coordinates

    def can_detect(self, other):
        for own_coord, other_coord in zip(self.coordinates, other.coordinates):
            if abs(own_coord - other_coord) > self.radar_range:
                return False
            return True

    def radar(self):
        for other in Mobilesuits.instances:
            if other is not self  and self.can_detect(other):
                print "%s detected at %s" % (other.description, other.coordinates)

A: Games typically have a "master loop" of some kind; yours does here:
#Main execution
while True:
    commands(raw_input(),currentmobilesuit)

The simplest thing to do is to count in the loop:
#Main execution
turn_count = 0
while True:
    commands(raw_input(),currentmobilesuit)
    turn_count += 1

If you wanted the real time taken to have some impact on the counter, or be the counter, you can get the current time from the time module calling time.time().
#Main execution
import time
time_start = time.time()
time_elapsed = 0
while True:
    commands(raw_input(),currentmobilesuit)
    time_elapsed = time.time() - time_start

A couple other thoughts:
Make a Game class, and put the turn counter and game loop in that.
Have the commands function return a number that is the number of time units that took place during the command; for example, entering an invalid command might take 0 turns, while repairing a robot might take 5.
#Main execution
turn_count = 0
while True:
    turns_taken = commands(raw_input(),currentmobilesuit)
    turn_count += turns_taken

A: You can use non-blocking I/O.  This will help you avoid the complications of threading.  Here's your sample code implemented with a non-blocking read of stdin:
#!/usr/bin/python
import sys
import select
call_count = 0
#Main Function declarations
def commands(user_input):
   global call_count
   if len(user_input) > 0:
      print('call count: ' + str(call_count) + ' user entered: ' + user_input)

def raw_input_no_block():
   global call_count
   call_count = call_count + 1
   input_avail = select.select([sys.stdin], [], [], 0.1)[0] #wait for 0.1 seconds
   if input_avail:
      return sys.stdin.readline()
   else:
      return ''

#Main execution
while True:
    commands(raw_input_no_block())


text:
Q: Factory pattern versus Immutability I wanted to create a factory for a product.
However, in order to have the factory class have access to the product class, I would have had to give the setters in the product class package access.
So, instead I decided to give a public static create method directly on the product so that the created product does not get mutated later.
For simple classes, I am inclined to adopt this approach and I want to use the factory pattern only when the product class has quite some reasonable functionality that I want to separate the functionality from the creation.
Am I missing something by preferring the immutability approach?


text:
Q: Bootstrap popover loading Hello I am trying to show "Loading..." text or spinner image until the dynamic ajax content loads because I have a very large number of data to fetch with takes at least 2-3 seconds to fully load here is my Ajax code
$(document).ready(function(){
     $('[data-toggle="popover"]').popover({
    trigger: "hover",
    title:fetchData,
    html:true,
    placement:'right'
     });
     function fetchData(){
    var fetch_data = '';
    var element = $(this);
    var id = element.attr("id");
    $.ajax({
   url:"includes/modDashboard/GetSummaryInfo.php",
   method:"POST",
   async:false,
   data:{id:id},
   success:function(data){
  fetch_data = data;
   }
    });
    return fetch_data;
     }
});

A: My solution related to the issue:
jshiddle

        Cash Summary

Good luck and regards Rtra :)


text:
Q: redmine and mod_vhost_dbd I've problem to run redmine with vhost_dbd_module from apache. Redmine was installed under /var/www/redmine/ directory. My apache config look:

<VirtualHost *:80>
    ServerName HOSTNAME
    DocumentRoot "/var/www/" # THIS IS NOT WORKING
    # DocumentRoot "/var/www/redmine/public" # THIS WORKS WITH REDMINE
    <Directory />
        Options FollowSymLinks -MultiViews -Indexes
        AllowOverride All
    </Directory>
    DBDriver mysql
    DBDParams host=localhost,user=test,pass=test,dbname=test
    DBDocRoot "SELECT document_root FROM vhosts WHERE server_name = %s"  HOSTNAME
</VirtualHost>

Field document_root from database return '/var/www/redmain/public' - so it should works. It works for php projects where index file is under '/var/www/project/public'. Besides the page return 404 because in /var/www/redmain/public there is no index file. I want universal config
Any suggestions?
Best regards, Peter

A: Not havng a index.html is ok :) Check your config/routes.rb.
If rails service is running then your redmine rails check your routes.rb and deliver the default page there (view).

A: Passenger as an apache module is not compatible with about all modules used to define "dynamic" document roots (including mod_vhost_dbd). For passenger, you have to statically configure your apps in the Apache configuration.
Generally, you will have a hard time emulating your PHP setup with any Ruby app server, as they expect to be started once and run continuously, unlike PHP "apps" which act as scripts resolved and started new for each request. You should rethink your setup for persistent application server processes.

A: I created .htaccess with content below and it working :)

RailsBaseURI /
PassengerAppRoot /var/www/redmine


text:
Q: How to test with dbunit using Composite I try test with dbunit using composite something like this exeample but I have the error said that PHPUnit_Extensions_Database_DB_DefaultConnection not found.
even including the require_once 'PHPUnit/Extensions/Database/TestCase.php' I have this error.

A: The Samples contain a typo.
Here's the fix
diff --git a/Samples/BankAccountDB/BankAccountCompositeTest.php b/Samples/BankAccountDB/BankAccountCompositeTest.php
index 3dc0035..d314c39 100644
--- a/Samples/BankAccountDB/BankAccountCompositeTest.php
+++ b/Samples/BankAccountDB/BankAccountCompositeTest.php
@@ -70,7 +70,7 @@ public function setUp()
      */
     protected function getDatabaseTester()
     {
-        $connection = new PHPUnit_Extensions_Database_DB_DefaultConnection($this->pdo, 'sqlite');
+        $connection = new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection($this->pdo, 'sqlite');
         $tester = new PHPUnit_Extensions_Database_DefaultTester($connection);
         $tester->setSetUpOperation(PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT());
         $tester->setTearDownOperation(PHPUnit_Extensions_Database_Operation_Factory::NONE());


text:
Q: Best way to let multiple UIButtons share the same appearance What is the best practice to let multiple buttons share the same appearance?
Right now I'm creating those buttons in a loop like this:
for i in 0..<10{
    let button = UIButton()
    button.setTitle(String(i), for: .normal)
    button.backgroundColor = #colorLiteral(red: 0.3137254902, green: 0.2745098039, blue: 0.2745098039, alpha: 0.5977632705)
    numberButtons.append(button)
    button.layer.borderColor = #colorLiteral(red: 0.04296875, green: 0.04296875, blue: 0.04296875, alpha: 0.5).cgColor
    button.layer.borderWidth = 1.0
    button.addTarget(self, action:  #selector(buttonAction), for: .touchUpInside)
}

What is Swift way to do such things? Subclass UIButton? Or add some initialising method as extension?

A: 1- Create a subclass of UIButton.
2- Put all your customizations in its constructor.
3- Use it for your buttons (in your storyboard or in code).
The discussion in this answer will help you subclass UIButton and customize it in the way you want.
And this answer provides a general rule of thumb on when to use extensions and when to use inheritance.


text:
Q: Como fazer isso em LINQ? Passei o dia procurando como funciona LINQ e tentei usar em um projetinho que estou usando para estudar, depois de muito tempo tentando o código usando LINQ ficou assim:
for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
        {
            if((from Hospedagem hospedagem in db.Hospedagens.ToList()
               where (hospedagem.DataEntrada <= dia && dia <= hospedagem.DataSaida)
               select hospedagem) != null)
            {
                hospedagens.Concat((from Hospedagem hospedagem in db.Hospedagens.ToList()
                                    where (hospedagem.DataEntrada <= dia && dia <= hospedagem.DataSaida)
                                    select hospedagem).ToList());
            }

        }
        if (hospedagens != null)
        {
            hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
        }

Mas não funcionou, então fiz usando foreach, assim funcionou:
        List<Hospedagem> lista = db.Hospedagens.ToList();
        List<Hospedagem> hospedagens = new List<Hospedagem>();
        for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
        {
            foreach (Hospedagem h in lista)
            {
                if (h.DataEntrada <= dia && dia <= h.DataSaida)
                {
                        hospedagens.Add(h);
                }
            }
        }
        if (hospedagens != null)
        {
            hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
        }

queria entender o por que do primeiro código não funcionar e como que eu poderia corrigir os problemas dele.

A: Se quer só o que está dentro do for, ficaria assim:
List<Hospedagem> hospedagens = new List<Hospedagem>();

for (var dia = comeco.Date; dia.Date <= fim.Date; dia = dia.AddDays(1))
{
    hospedagens.AddRange(from h in db.Hospedagens where h.DataEntrada <= dia && dia <= h.DataSaida select h);
}

if (hospedagens != null)
{
    hospedagens = hospedagens.GroupBy(x => x.HospedagemID).Select(g => g.First()).ToList();
}

Seu código não funciona porque o concat não modifica a lista, ele retorna uma nova, no seu caso o melhor seria usar o AddRange.


text:
Q: apache keeps old .htaccess settings (in rewriterule) I am testing some basic .htaccess rewriterules and I am pretty sure that even after deleting a rule in .htaccess and saving the document, apache ignores it and acts like the rule was still there (only for earlier requested sites) - even after apache restart. It is driving me crazy, the behavior is really mad. Is there any apache cache which is about to be cleaned or the problem is elsewhere?

A: It's madness! Not really, it's just annoying.
When you set a redirect in Apache what you're doing is actually configuring headers that are passed to your browser. Your browser keeps a cache of 301 and 302 redirect headers (and other things like DNS) in the event you go back to those pages, so it can save you time. 301 redirects are supposed to be permanent (that's what you're indicating), so if there is no need for the browser to do something like perform a DNS lookup or visit a page based on a redirect, then it will cut corners and use the cache in order to provide you with a faster browsing experience.
You need to flush your browser's cache to prevent the store redirects from happening.
Additionally, you'll want to resubmit your page to Google (in the event it's on the web) in case they've crawled your site while the invalid headers existed.


text:
Q: django model filter with validate_unique There is an error that says 'invalid syntax'
but i am a newbie to django and python...
What is the error in this code?
The first if-block works well
The second doesn't...
class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    is_joined = models.BooleanField(default = False) #if True, joined, else wish_member
    is_master = models.BooleanField(default = False)
    def __str__(self):
        if(self.is_joined):
            return self.person.name + " is a member in Group " + self.group.name
        return self.person.name + " wishes to join in Group " + self.group.name
    def validate_unique(self, *args, **kwargs):
        #super(Person, self.person).validate_unique(*args, **kwargs)
        #tests if there is already the same person in the same group.
        if(self.__class__.objects.filter(person_id = self.person.id, group_id = self.group.id,).exists()):
        raise ValidationError(
            {
                NON_FIELD_ERRORS:
                ('The person already exists.',)
            }
        )
    elif(self.__class__objects.filter(is_master = True, group_id = self.group.id,).exists()):
        raise ValidationError(
            {
                NON_FIELD_ERRORS:
                ('The master already exists.')
            })

Edits: noticed the dot missing.leaving it there for the credit who found it. Error occurs in:
elif(self.__class__.objects.filter(is_master = True, group_id = self.group.id,).exists()):

A: You are missing a dot between __class__ and __objects__ in the elif statement. It should be:
elif(self.__class__.objects.filter(is_master = True, group_id = self.group.id,).exists()):

However, that would give you an attribute error, and you say you got a syntax error, so there may be another problem I haven't spotted.

A: You can use unique_together to make a set of fields, taken together, unique. In your case, you specify
class Membership(models.Model):
....

    class Meta:
        unique_together = (
                               ("person", "group"),
                               ("is_master", "group"),
                          )

This will make sure that person and group and is_master and group will be unique together. Read more information here.


text:
Q: Looking for a way to break up a string with multiple \n and turn it into innerHTML I have been writing JavaScript since yesterday and am brand new at it.
I have a string that I am breaking up and turning into input for a table.  The entries are separated by '\n' like 'a\nb', which indicates the need for a new row between a and b.
The current code that I have works for a single instance of '\n', but it quit working when it was back to back entries, specifically "1.1\n2.1\n3.1\n4.1\n".
It has worked with other examples that are comma separated, such as "a,b,c\n1,2,3", "1.1,1.2,1.3,1.4,1.5\n", and "1.1,1.2,1.3,1.4,1.5\n2.1,2.2,2.3,2.4,2.5\n3.1,3.2,3.3,3.4,3.5\n4.1,4.2,4.3,4.4,4.5\n".  Because some inputs are comma separated, it must work with those as well as with the input that is separated by '\n'.
My method up to this point has been to split the string into an array, and then search the index of the array to see if it contains the '\n'.  If it does, I split the array at the '\n', and splice it with two entries instead of one.  I then set a variable indicating that I need to go to the next row, which moves into an if else if right below.
var functionCreate = function (strInput) {

            var array = strInput.split(",");

            var html = "

";

            for (var i = 0; i < array.length; i++) {
                var newL = false;
                if (array[i].indexOf("\n") >= 0) {
                    newL = true;
                    newStr = array[i].split("\n");
                    array.splice(i, 1, newStr[0]);
                    array.splice(i + 1, 0, newStr[1]);
                }
                if (newL === true) {
                    html += "" + array[i] + "
";
                }
                else if (array[i]) {
                    html += "" + array[i] + "	"
                }
            }

            html += "
"
            document.getElementById('output').innerHTML = html;

What I output currently is:
output: "

1.1

2.1

"

And my expected is:
"

1.1

2.1

3.1

4.1

"

The 3.1 and 4.1 are getting cut off, which is understandable because I believe everything trailing the 2.1 is in i + 1 of newStr.
Does anyone have any idea how to get past this?  Is there a way to split it at only the first '\n' and run the through the loop again until there are no more newlines?

A: Change
var array = strInput.split(",");
to
var array = strInput.split("\n");


text:
Q: charts.js tooltips on different data ranges I'm using charts.js (with angular-charts directive), and I'm facing a problem with different dataset sizez. I have to display in a line-chart some values in a timeline. So my data is structured like this :
datasets : [
  [ {"x" : date1, "y" : 2 }, {"x" : date1, "y" : 5 } ..], //first dataset
  [ {"x" : date2, "y" : 3 }, {"x" : date4, "y" : 7 } ..] //second one
];

where date1, date2, .. date4 are moment dates, and y are random values.
Now, if the first dataset has the same number of values of the second dataset, everything is okay. But if i have different dataset sizes (for example, the first one has values for yesterday, and today, the second one for today and tomorrow) then the legend tooltip is completely wrong. It always shows the NTH value of each series, even if they are in different dates. It's a little difficult to explain in words and english is not my language. I leave self-explaining screenshot here :

How can I avoid this behavior?

A: Just in case it could be helpful for other developers, I've managed to solve the problem normalizing data. I.E. i've transformed my data from :
[
  [{"x" : date1, "y" : valueA }, {"x" : date2, "y" : valueB }, {"x" : date3, "y" : valueC }],
  [{"x" : date3, "y" : valueD }, {"x" : date4, "y" : valueE }]
]

to :
[
  [{"x" : date1, "y" : valueA }, {"x" : date2, "y" : valueB }, {"x" : date3, "y" : valueC }, {"x" : date4, "y" : undefined }],
  [{"x" : date1, "y" : undefined }, {"x" : date2, "y" : undefined },{"x" : date3, "y" : valueD }, {"x" : date4, "y" : valueE }]
]

So, each dataset contains the same number of tuples, that is the result of merging dates from the first dataset and the second one and removing duplicates.


text:
Q: Is 'concomitant' intentional? Is the word 'concomitant' utilized only when intention attends the usage? The word 'attendant' means the same in many cases but doesn't seem to carry the sense of intentional concurrency. Should these two words be treated as we treat 'look' and 'see', 'listen' and 'hear'? (I was thinking about these examples... 'look' is intentioned while 'see' is not necessarily intentioned.)
(information from some later comments made by the original poster):

*

*In fact, I think I have it all backwards. I was focused less on definition and more on application - but after another click, 'Attend' seems to suggest more intention than 'concomitant' (Merriam-Webster: "attend").

*There is even a suggestion that no intention attends the usage (Merriam-Webster: "concomitant").

A: Checking OLD, Cambridge and Merriam-Webster for meaning, we glean the following:

Naturally accompanying or associated. OLD
Something that happens with something else and is connected with it. Cambridge
Accompanying especially in a subordinate or incidental way.
Merriam-Webster.

Note nowhere in any of the above defintions is the word intended used (or any similar connotation).
Concomitant was Merriam Webster's word of the day on 03/07/2007, this special privilege afforded the word its own short podcast, which can be found a short way down M-W reference. The podcast relates the Latin roots of the word:

...a descendant of Latin concomitari ("to accompany") and
ultimately of "comes," the Latin word for companion...

The podcast continues to describe two related words:

The two associated words, the verb concomitate, meaning "to
accompany," and another adjective, concomitaneous, meaning "of a
concomitant nature," didn't survive to accompany "concomitant" into
the 18th century.

It is noticeable then that the Latin roots of the word are also absent of any intentional quality.
Steven J. Jensen, in Good and Evil Actions: A Journey Through Saint Thomas Aquinas makes use of the compound adjective concomitant-intentional when describing three scopes of object regarding intention:

We will call these views, respectively, concomitant-intention,
end-intention, and means-intention.

This would make no sense at all if there was some inherent quality of intention in the word concomitant.
Having considered the above we can state with confidence then that there is no intentional quality to the word concomitant.
Concomitant refers to the quality of 'accompanying' (OLD, Merriam-Webster) or 'connect[ing]' (Cambridge). It has nothing at all to do with intention.


text:
Q: datetime offset issue while saving data into parquet for day light saving time screenshot from source and destinationWhile we are writing into parquet file using spark/scala, DST(day light saving times) times are auto converting by one hour delay time for example (2011-09-20 00:00:00.000 into "2011-09-19 23:00:00.000").
Source(reading data from) : sql server
Destination(writing into ):  AWS S3
code:
val ssdf= spark.read.format("jdbc").option("driver" , "${ssDriver}").
option("url", "${ssConnectionString}").
option("dbtable", "${SCHEMANAME}.${RESULTTABLENAME}").
option("user", "${ssUsername}").
option("password", "${ssPassword}").
load()

ssdf.write.format("parquet").mode("overwrite").option("header", "true").save("s3://targetS3path/")`

###########################################################
Code is running fine, but which dates are DST datetime, delaying by 1 hour. check screenshot.
Expecting datetime value as per source, 2011-09-20 00:00:00.000.

A: Set the JVM timezone you will need to add extra JVM options for the driver and executors:
val spark = SparkSession.builder()
      .master("local[1]")
      .appName("SparkByExamples.com")
      .config("spark.driver.extraJavaOptions", "-Duser.timezone=GMT")
      .config("spark.executor.extraJavaOptions", "-Duser.timezone=GMT")
      .config("spark.sql.session.timeZone", "UTC")
      .getOrCreate();


text:
Q: Inner queries in LINQ I have the folowing SQL query:
Select *
from aspnet_Users
where UserId Not in
(select UN.ConnectedToUserID
from    tblUserNetwork UN )
    and UserId <> '82522f05-2650-466a-a430-72e6c9fb68b7'

What will be the LINQ equivalent to this SQL.
Thanks

A: This would be a similar query for Northwind database,
it excludes customers from london and with customer id ALFKI
var query =
from c in Customers
where c.CustomerID != "ALFKI" &&
!(from cc in Customers
        where cc.City == "London"
        select cc.CustomerID)
       .Contains(c.CustomerID)
select c;

Transposing onto your query gives,
var query =
from c in aspnet_Users
where c.UserId != "82522f05-2650-466a-a430-72e6c9fb68b7" &&
!(from cc in tblUserNetwork
        select cc.ConnectedToUserID)
       .Contains(c.UserId)
select c;

A: Try this:
aspnet_Users.Where(s => tblUserNetwork
                  .Where(t => s.UserId == t.ConnectedToUserID).Count() == 0)
            .Select(s => s);

EDIT: Plus this I suppose:
aspnet_Users.Where(s => tblUserNetwork
                  .Where(t => s.UserId == t.ConnectedToUserID).Count() == 0
                     && s.UserId != '82522f05-2650-466a-a430-72e6c9fb68b7')
            .Select(s => s);

A: Here's a different approach using Join and Except operators:
var connectedUsers = aspnetUsers
    .Join(networkUsers, a => a.UserId, n => n.UserId, (a, n) => a);

var exceptions = aspnetUsers
    .Where(a => a.UserId == "82522f05-2650-466a-a430-72e6c9fb68b7")
    .Union(connectedUsers);

var query = aspnetUsers.Except(exceptions);


text:
Q: SPServices applications on SharePoint 2010. Will it work on SharePoint 2013? I'm using SPServices to develop on SharePoint 2010. My organization will be upgrading to SharePoint 2013 sometime in the future. What will I need to do (if anything) when the new SharePoint server is installed to keep using the SPServices library? Primarily I'm using GetListItems, updatelistitems, createlistitems and Query operations.

A: Per the article linked in response to your question - it does depend on a number of factors and what is deprecated between 2010 and 2013...but I can tell you that I was able to successfully port a company news site/portal that made extensive use of GetListItem AJAX calls and Search queries with no issues.
Keep in mind that a lot of stuff still works in 2013 but was deprecated and will probably be removed entirely in future releases. Here's a good list for starters:
http://www.c-sharpcorner.com/UploadFile/Roji.Joy/deprecated-features-in-sharepoint-2013-from-sharepoint-2010/


text:
Q: Level of uncertainty when measuring a period of time? I need to create a raw data table for my science experiment, but I'm unsure what the level of uncertainty would be when measuring days. How would I determine the level of uncertainty when measuring a period of time?

A: Exactly as you do with any other uncertainty, I don't see how measuring days is different from measuring meters.
That is, you can find SEM if you have some statistics of measurements or decide on some measurement uncertainty for each individual one (if you check 'em every day, the uncertainty is probably 0.5 day or so, if you aren't sure if it happened or not within a couple of days, it can be more etc.). Exactly as for any other measurement.


text:
Q: Saving/Fetching CoreData Relationships Swift 3 I am making a budgeting app for the purposes of learning and I have a few questions about storing and fetching entities in CoreData.
I have two entities "Budget" and "Expense".

Every Budget has its own Expenses. As an example I can have an 'Entertainment' budget and it can have expenses such as 'Bowling' and 'Movies' etc.
I can create a Budget and save it. And then add expenses to it.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let expense = Expense(context: context)
.
. // Filling out the expense here
.
budget?.addToExpense(expense)
(UIApplication.shared.delegate as! AppDelegate).saveContext()

I then retrieve the collection of Expenses and display the store name in a TableView
// Inside cellForRowAt
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
let myArray = Array((budget?.expense)!)
cell.textLabel?.text = (myArray[indexPath.row] as! Expense).store
return cell

So far so good. My issue is that when I store an expense it is stored in a Set. Which means the order is random when I retrieve that set and typecast it into an Array.
What I want is to store the Expenses and retrieve them in such a way that I can display the expenses in a FIFO order in the TableView. In other words the first expense I add in the budget should be the first element in the table view and so on and so forth.

A: There could be several ways to achieve that. The most straightforward would be to use Ordered relation for expense.
To do that,

*

*Open expense relationship properties in DataModel editor.

*Check Ordered option

Then budget.expense will be not Set, but OrderedSet, and you won't need to convert it to Array, but access it directly by index.

A: VIEWCONTROLLER  1:
=====================>
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var txt_user: UITextField!

@IBOutlet weak var txt_password: UITextField!

var result = NSArray()

override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    txt_password.isSecureTextEntry = true

}

@IBAction func login_action(_ sender: Any)

{

   if(txt_user.text == "" || txt_password.text == "")

   {

    let alert = UIAlertController(title: "info", message: "fields are empty", preferredStyle: .alert)

    let ok = UIAlertAction(title: "OK", style: .default, handler: nil)

    alert.addAction(ok)

    self.present(alert, animated: true, completion: nil)

    }

    else

   {

    self.CheckForUserNameAndPasswordMatch(empName: txt_user.text! , empPwd: txt_password.text!)

    }

}

func CheckForUserNameAndPasswordMatch(empName:String,empPwd:String)

{

    let app = UIApplication.shared.delegate as! AppDelegate

    let context = app.persistentContainer.viewContext

    let fetchdata = NSFetchRequest<NSManagedObject>(entityName: "Employee")

    let predicate = NSPredicate(format: "empName = %@",empName)

    fetchdata.predicate = predicate

    do

    {

        self.result = try context.fetch(fetchdata as! NSFetchRequest<NSFetchRequestResult>)as NSArray

        if result.count>0

        {

            let objcetEntity = result.firstObject as! Employee

            if objcetEntity.empName == empName && objcetEntity.empPwd == empPwd

            {

                print("Login Successfully")

                // Entered Username & password matched

            }

            else

            {

                print("Wrong password/username")

                //Wrong password/username

            }

        }

    }

    catch let error as NSError

    {

        print("error",error.localizedDescription)

    }

}

 @IBAction func unwindToVC1(sender:UIStoryboardSegue)

 {

    if sender.source is ViewController2

    {

        let secvc = sender.source as! ViewController2

        txt_password.text = secvc.str1! as String

    }

}

VIEWCONTROLLER  2:
=====================>
class ViewController2: UIViewController ,UITextFieldDelegate{
@IBOutlet weak var txt_name: UITextField!

@IBOutlet weak var txt_mail: UITextField!

@IBOutlet weak var txt_pwd: UITextField!

@IBOutlet weak var txt_cpwd: UITextField!

@IBOutlet weak var txt_phone: UITextField!

@IBOutlet weak var err: UILabel!

var str1:NSString!

var str2:NSString!

//var update:NSManagedObject!

override func viewDidLoad() {

    super.viewDidLoad()

    /*if(update != nil)

    {

    txt_name.text = update.value(forKey: "empName") as? String

    txt_mail.text = update.value(forKey: "empMail") as? String

    txt_pwd.text = update.value(forKey: "empPwd") as? String

    txt_cpwd.text = update.value(forKey: "empCpwd") as? String

    txt_phone.text = update.value(forKey: "empPhone") as? String

    }*/

    txt_pwd.isSecureTextEntry = true

    txt_cpwd.isSecureTextEntry = true

}

override func viewWillAppear(_ animated: Bool)

{

    txt_name.becomeFirstResponder()

}

@IBAction func regis_clicked(_ sender: Any)

{

    if(txt_name.text == "" || txt_mail.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == "" )

    {

        let alert = UIAlertController(title: "information", message: "fields are empty", preferredStyle: .alert)

        let ok = UIAlertAction(title: "OK", style: .default, handler:

        {

           (actionsheet) in

            if(self.txt_name.text == "")

            {

                self.txt_name.becomeFirstResponder()

            }

            if(self.txt_mail.text == "")

            {

                self.txt_mail.becomeFirstResponder()

            }

            if(self.txt_pwd.text == "")

            {

                self.txt_pwd.becomeFirstResponder()

            }

            if(self.txt_cpwd.text == "")

            {

                self.txt_cpwd.becomeFirstResponder()

            }

            if(self.txt_phone.text == "")

            {

                self.txt_phone.becomeFirstResponder()

            }

        })

        let cancel = UIAlertAction(title: "cancel", style: .default, handler: nil)

        alert.addAction(ok)

        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)

    }

    else if(txt_pwd.text != txt_cpwd.text)

    {

        let alert1 = UIAlertController(title: "information", message: "password mismatched", preferredStyle: .alert)

        let ok = UIAlertAction(title: "OK", style: .default, handler:nil)

        let cancel = UIAlertAction(title: "cancel", style: .default, handler: nil)

        alert1.addAction(ok)

        alert1.addAction(cancel)

        self.present(alert1, animated: true, completion: nil)

    }

    else

    {

        let app = UIApplication.shared.delegate as! AppDelegate

        let context = app.persistentContainer.viewContext

        let newuser = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context)

        newuser.setValue(txt_name.text, forKey: "empName")

        newuser.setValue(txt_mail.text, forKey: "empMail")

         newuser.setValue(txt_pwd.text, forKey: "empPwd")

         newuser.setValue(txt_cpwd.text, forKey: "empCpwd")

         newuser.setValue(txt_phone.text, forKey: "empPhone")

        do

        {

            try context.save()

        }

        catch let error as NSError

        {

            print("error",error.localizedDescription)

        }

    }

   // self.navigationController?.popViewController(animated: true)

    performSegue(withIdentifier: "unwind", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if let newlabel = txt_pwd.text

    {

        str1 = newlabel as NSString

    }

}


text:
Q: laravel password hash in seed doesn't match the one login on the seeder I've used \Hash::make('password'); on login I've used this on login controller .
protected function credentials(Request $request)
    {
        return array_merge($request->only($this->username(), 'password'), ['is_banned' => 0]);
    }

but it returns These credentials do not match our records.
I even used bcrypt('password'); on seeder and the same result