text:
Q: Find textbox with the largest number I'm a newbie to JavaScript. I have a series of textboxes and a button on my page. When the button is pressed I want to find which number is the largest, and add a border around that textbox.
Currently when I click the button there is no change, and I am not sure where I went wrong.

Test

    <input type="text" id="number1" />
    <input type="text" id="number2" />
    <input type="text" id="number3" />
    <input type="text" id="number4" />
    <input type="text" id="number5" />

    <button id="findMax">Calculate</button>

A: use Math.max function, here is the working template

document.getElementById("findMax").addEventListener("click", function() {

  var num1 = parseInt(document.getElementById('number1').value) || 0;
  var num2 = parseInt(document.getElementById('number2').value) || 0;
  var num3 = parseInt(document.getElementById('number3').value) || 0;
  var num4 = parseInt(document.getElementById('number4').value) || 0;
  var num5 = parseInt(document.getElementById('number5').value) || 0;

  var max = Math.max(num1, num2, num3, num4, num5);

  document.getElementById("number1").style.borderColor = (max == num1) ? "#008000" : "inherit";
  document.getElementById("number2").style.borderColor = (max == num2) ? "#008000" : "inherit";
  document.getElementById("number3").style.borderColor = (max == num3) ? "#008000" : "inherit";
  document.getElementById("number4").style.borderColor = (max == num4) ? "#008000" : "inherit";
  document.getElementById("number5").style.borderColor = (max == num5) ? "#008000" : "inherit";
});
input[type='text'] {
  width: 50px;
}
textarea {
  width: 500px;
  height: 300px;
}

Test

    <input type="text" id="number1" />
    <input type="text" id="number2" />
    <input type="text" id="number3" />
    <input type="text" id="number4" />
    <input type="text" id="number5" />

  <button id="findMax">Calculate</button>

A: Try this.
var maxNum = -Infinity,
    maxDom = null;

for(var i = 1; i <= 5; i++) {
    var dom = document.getElementById('number' + i),
        num = parseInt(dom.value);

    if(!isNaN(num) && num > maxNum) {
        maxNum = num;
        maxDom = dom;
    }
}

if(maxDom) {
    maxDom.style.borderColor = '#008000';
}


text:
Q: How can I break the Query object into its logical primitives tree? Say - if I has the query
content:table AND propertyfield:now

how can i get two of this items for proper examining later?

A: Here you go (I use Java, sorry ;)
package stack.lucene;

import junit.framework.TestCase;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Version;

public class StackLucene2 extends TestCase
{
    private String sQuery = "field1:playing AND (field2:curse OR field3:something) AND field4:somethingother OR field5:blah";

    public void testQueryParser() throws Exception
    {
        QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, null, new StandardAnalyzer(Version.LUCENE_CURRENT));
        Query q = parser.parse(this.sQuery);

        if( q.getClass() == BooleanQuery.class ){
            breakQuery_recursive(q, 0);
        }
    }

    // level is for indentation
    private void breakQuery_recursive(Query q, int level)
    {
        BooleanQuery castQuery = (BooleanQuery)q;
        for(BooleanClause clause : castQuery.getClauses() ){
            Class queryclazz = clause.getQuery().getClass();

            System.out.println(repeat(' ', level) + "["+queryclazz+"][" + clause.getOccur() + "] " + clause.toString());

            if(queryclazz == BooleanQuery.class) {
                breakQuery_recursive(clause.getQuery(), level+1);
            }
        }
    }

    private String repeat(char c, int times)
    {
        StringBuffer b = new StringBuffer();
        for(int i=0;i < times;i++){
            b.append(c);
        }
        return b.toString();
    }
}

Output:
[class org.apache.lucene.search.TermQuery][+] +field1:playing
[class org.apache.lucene.search.BooleanQuery][+] +field2:curse field3:something
 [class org.apache.lucene.search.TermQuery][] field2:curse
 [class org.apache.lucene.search.TermQuery][] field3:something
[class org.apache.lucene.search.TermQuery][+] +field4:somethingother
[class org.apache.lucene.search.TermQuery][] field5:blah

redpajama_set_name: RedPajamaStackExchange


text:
Q: Define the method once to be virtual in the inheritance hierarchy to make polymorphism to work Is it sufficient to define the method once to be virtual in the inheritance hierarchy to make polymorphism to work.
In the following example Der::f is not defined to be virtual but d2->f(); prints der2
I am using VS IDE (may be it is only there...)
class Base
{
public:
    virtual void f() { std::cout << "base"; }
};
class Der : public Base
{
public:
    void f() { std::cout << "der"; } //should be virtual?
};
class Der2 : public Der
{
public:
    void f() { std::cout << "der2"; }
};

int main()
{
    Der* d2 = new Der2();
    d2->f();
}

A: Everything that inherits from Base - directly or through several layers will have f() virtual as if the class declarion had explicitely placed virtual when f() was declared.

A: Yes, polymorphism will work if you define method as a virtual only in your Base class. However, it is a convention I came across working with some large projects to always repeat virtual keyword in method declarations in derived classes. It may be useful when you are working with a lot of files with complex class hierarchy (many inheritance levels), where classes are declared in separate files. That way you don't have to check which method is virtual by looking for base class declaration while adding another derived class.


text:
Q: Get value from agent failed: TCP successful, cannot establish TLS to ][0.0.0.0]:10050]: connection closed by peer The color of ZBX Availability is changing into red from green and getting following error message on Zabbix Active Check monitoring:
"Get value from agent failed: TCP successful, cannot establish TLS to ][0.0.0.0]:10050]: connection closed by peer"
Please help.

A: That's a passive item error, not active.
The 0.0.0.0 address likely comes from host interfaces - you should fix that. If you wanted to use active items, you still have passive ones configured - change them all, including LLD rules and LLD prototypes to active.


text:
Q: RDCOMClient with COMCreate("Outlook.Application") crashing R I'm using the package RDCOMClient with R version 4.0.2.   It was downloaded using:
devtools::install_github("omegahat/RDCOMClient")
I'd like to use the package for reading and writing email.  I've started this way:
library(RDCOMClient)
folderName <- "AUX"
OutApp <- COMCreate("Outlook.Application")

However, when I try to use any method from OutApp, R crashes, regardless of whether I'm using console R or RStudio.  For example:
outMail = OutApp$CreateItem(0)

outlookNameSpace = OutApp$GetNameSpace("MAPI")

Either of these code chunks cause R to encounter a fatal error and the session to be terminated.   No errors/warnings along the way, just an immediate crash.  str(OutApp) returns that OutApp is of formal class COMIDispatch [package "RDComClient"] with 1 slot (.. @ ref:).  OutApp is of length 1 and mode S4.
Any suggestions?

A: A minimal commit was created by a helpful user, due to which the code in OP will work for R > 4.0.
Use the following installation:
library(remotes)
remotes::install_github("BSchamberger/RDCOMClient", ref = "main")

More discussion at this link.


text:
Q: Collapsing Toolbar - disable scrolling by touch I want to disable scrolling by touch behaviour for the collapsing toolbar. It should only be collapsing, if triggered by the RecyclerView (which is working). I thought why not just disable focus...
    android:focusableInTouchMode="false"
but it is not working. I could change the layout_scrollFlags but then...
My question therefore, is there a simple solution for this?
XML:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/mCollapsingToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="@dimen/header_size"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                ...
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/mToolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        ...
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

A: Found a working solution here: https://stackoverflow.com/a/35465719/2033223.
So now it is only scrollable, if there are enough elements in the recyclerView.
XML:
<android.support.design.widget.CollapsingToolbarLayout
    android:id="@+id/mCollapsingToolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="@dimen/header_size"
    android:fitsSystemWindows="true"
    app:scrimAnimationDuration="300"
    app:contentScrim="?attr/colorPrimary">

Activity:
public class MainActivity extends AppCompatActivity {

    private CollapsingToolbarLayout collapsingToolbarLayout;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        collapsingToolbarLayout =
              (CollapsingToolbarLayout) findViewById(R.id.mCollapsingToolbar);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (rv.canScrollVertically(DOWN) || rv.canScrollVertically(UP)) {
                    controller.enableScroll();
                } else {
                    controller.disableScroll();
                }
            }
        }, 100);
    }

    private void enableScroll() {
        final AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)
                                  collapsingToolbarLayout.getLayoutParams();
        params.setScrollFlags(
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
        );
        collapsingToolbarLayout.setLayoutParams(params);
    }

    private void disableScroll() {
        final AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)
                                  collapsingToolbarLayout.getLayoutParams();
        params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
        collapsingToolbarLayout.setLayoutParams(params);
    }
}

PS:
findLastCompletelyVisibleItemPosition() wasn't enough for my case. But I use it too. (check out link below)
https://stackoverflow.com/a/31460285/2033223
EDIT:
If you want to make sure, that the correct scroll status is set, use notifications/events (not timed update), after the list is initialized (view is updated). Otherwise it can set the scroll flags incorrectly.


text:
Q: how to check JBOSS version using ANT script I have written ant script to check for java version. Similarly I would like to know how to check for JBOSS version using ant script.
  <project basedir="." default="check-java-version">
  <target name="get-java-version">
  <echo message="Java Version: ${java.version}"/>
    <echo message="Java home: ${java.home}"/>
    <fail message="Unsupported Java version: ${java.version}. Make sure that
     the version of the Java compiler is 1.7 or greater.">
        <condition>
            <not>
                <or>
                    <contains string="${java.version}" substring="1.7" casesensitive="false" />
                     <contains string="${java.version}" substring="1.8" casesensitive="false" />
                </or>
            </not>
        </condition>
    </fail>
  </target>
  <target name="check-java-version" depends="get-java-version"
  unless="java.version">

   </target>
 </project>

A: if you are trying to do this from the same box where jboss is installed you can try the exec task on "standalone.bat --version" or the "run.sh --version"
if you want to query a remote JBOSS instance you can execute curl against
http://yourserver:port/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss.system%3Atype%3DServer
you can also check: What version of JBoss I am running? for how to derive it from the jar.
-- Adding a sample on how to implement this in Ant:
<exec dir="${yourJbossDir}" executable="run.sh" outputproperty="JbossVersion">
   <arg line="--version"/>
</exec>

then you would get the vesrsion stored in the JbossVersion property.
see also:  https://ant.apache.org/manual/Tasks/exec.html


text:
Q: MemoryError from numpy.linalg.svd for large matrices The following command will fail on my machine, with Windows 7 ultimate SP1 x64, Python 3.3.3 x64, numpy 1.8.0, and 16GB memory, which seems sufficient for the task. And it also fails on a cluster.
python -c "import numpy as np;np.linalg.svd(np.random.random((25000,10000)))"

Any ideas about the reason? Thanks.

A: I think you are just hitting a limit of your RAM: I run this on my Linux box (64Gb of RAM) and the process occupies 14.4 Gb. If you have a 16Gb machine then some of it is occupied by OS and other stuff, so perhaps you just miss a bit of spare RAM for the process.

A: My thought would be you have insufficient resources available.
This ran on my Mac Mini with 16GB of RAM.  Python peaked at 8.5GB and my swapfile grew to almost 15GB during processing.
What is the size of your swapfile and is it dynamic or preallocated?  I would consider bumping it to 32GB, preallocated, if you have disk available.


text:
Q: Android app does not resume when someone comes back after clicking ad When someone clicks on the ad and comes back to the app the app is not resuming.
I have added android:launchMode="singleInstance" in the mainfest and android:alwaysRetainTaskState="true" in the activity declaration in manifest.
I am not getting where am i going wrong.
My code for .java file  is as follows :
 public class MainActivity extends Activity implements AdListener{

 public static int count=0,dispad=0;
 public static LinearLayout lay1;
 private static final Class<?>[] NUMBERS = {First.class};
  protected AdView adView;
    View admobAds;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = (AdView)findViewById(R.id.ad);

Toast toast = Toast.makeText(getApplicationContext(), "Click on the ad to
       make        it     disappear" +
            "", Toast.LENGTH_LONG);
    toast.show();

 adView.loadAd(new AdRequest());

 lay1=(LinearLayout)this.findViewById(R.id.mainlay);

 admobAds = (View) findViewById(R.id.ad);

   //More code

    public void onDismissScreen(Ad arg0) {

    lay1.removeView(admobAds);
    dispad=1;
    // TODO Auto-generated method stub

}
   }

A: u should go through this.....
 http://developer.android.com/reference/android/app/Activity.html

A: There was a problem with android:alwaysRetainTaskState="true" as i was not including it in every activity.
when i added this code in the activity my app is now not restarting but the ads are still shown up.


text:
Q: Thermal expansion for two objects Among two bodies of same mass, specific heat capacity but different coefficients of linear expansion which would require more heat for same change in temperature considering concepts of thermal expansion?

A: So long as the specific heat capacity of the two materials remain the same, it will take the same amount of energy to increase the temperature in both materials.  That is because the heat required is defined through $Q = m C \Delta T$. By definition they will require the same amount of heat to change the temperature.
I understand your question as "doesn't some of the energy go into changing the materials properties?", and the answer is that if it does, this will be factored into the definition of $C$.

A: To me your question implies that you are asking about solids but even so the specific capacity will depend on not only the material but also the temperature and the expansion or otherwise of the material.
Because of this dependence of the specific heat capacity on a number of variables it is usual to quote the value of specific heat capacity for a material at a given temperature and then quote values when the material is not allowed to expand which is called the specific heat capacity at constant volume $C_V$ and when the material is allowed to expand at constant external pressure $C_P$.
The difference between these two so called principal specific heat capacities is significant for gases but very much less so for liquids and solids primarily because for gases their volume changes much more than liquids and solids for a given temperature change.
So if it is $C_V$ which you are making equal then that does not include the work which must be done (extra heat added) when a material expands.
In that case $C_P$ will be larger for the material which has the larger coefficient of thermal expansion.
On the other hand if it is $C_P$ that you have assumed to be equal then that already includes the heat input which has to be added to expand the material.
If you look at tables of specific heat capacities (e.g. Kaye and Laby) you will note that both $C_V$ and $C_P$ (or their ratio) are listed for gases whereas only $C_P$ is listed for liquids and solids because for most purposes when their temperature changes liquid and solids can be assumed not to change their volume by very much and the specific heat capacity is measured at constant pressure.

A: While expansion, more coefficient of linear expansion implies more kinetic energy, thus more heat is required.


text:
Q: Python equivalent for batch Choice command I'm working on a small project in python, and after a bit of work on it I was wondering if there was a way of inputting data in python 3 which was somewhat similar to batch's choice command. Pretty much only take in one key of input and then end the input prompt.
For example:
Choice(['Y', 'N'], "Yes or No? ")

Where the user could either press "Y" or "N" and the program would continue.
I've done some brief surfing, but haven't found anything I can use.
Bonus:
What would be even more useful is if this "choice" command could except multiple characters.
Pretty much input but capping the limit of characters they can input, and then immediately continuing. The latter of which is proving to be hard.

A: There's no built-in for this, but you could do something like this:
def choice(options, prompt):
    while True:
        output = input(prompt)    # Use raw_input(prompt) for Python 2.x
        if output in options:
            return output
        else:
            print("Bad option. Options: " + ", ".join(options))

This would let the user enter in arbitrary strings (of any length) into the command line, and would continue once the user hits enter. Unfortunately, there's no easy way that I know of to automatically stop after a set number of characters.
However, this post does discuss ways of grabbing a single character from the command line. You may be able to adapt it into the above function so that it will automatically continue after a certain number of characters, without waiting for the enter key to be pressed.


text:
Q: Debug on Android studio How can I debug an Android app to find out which line is not correct?
Noted that I'm using Android Studio. Also I've done every things exactly the same as what my master did. It works for him as well but it doesn't for me. I mean it closes the app and throws "has stopped" error. Ok well, what's wrong?

A: You can put breakpoints via Run -> View Breakpoints.
The Breakpoints dialog appears. In the left pane, scroll to the bottom. Select Any exception under Java Exception Breakpoints With Any exception selected, on the right pane, configure as follows:
Suspend: checked
All: selected
Condition: !(this instanceof java.lang.ClassNotFoundException)
Notifications: both Caught exception and Uncaught exception selected

You can refer this for better understanding.


text:
Q: How to make a function wait X amount of time in LUA (Love2d)? I am very new to programming and coming from a "custom map" background in games like SC2. I am currently trying to make a platformer game in Love2d. But I wonder how I can make something wait X amount of seconds before doing the next thing.
Say I want to make the protagonist immortal for 5 seconds, how should that code look like ?
Immortal = true
????????????????
Immortal = false

As I have understood there is no built in wait in Lua nor Love2d.

A: I normally use cron.lua for what you're talking about: https://github.com/kikito/cron.lua
Immortal = true
immortalTimer = cron.after(5, function()
  Immortal = false
end)

and then just stick immortalTimer:update(dt) in your love.update.

A: It sounds like you're interested in a temporary state for one of your game entities. This is pretty common - a powerup lasts for six seconds, an enemy is stunned for two seconds, your character looks different while jumping, etc. A temporary state is different than waiting. Waiting suggests that absolutely nothing else happens during your five seconds of immortality. It sounds like you want the game to continue as normal, but with an immortal protagonist for five seconds.
Consider using a "time remaining" variable versus a boolean to represent temporary states. For example:
local protagonist = {
    -- This is the amount of immortality remaining, in seconds
    immortalityRemaining = 0,
    health = 100
}

-- Then, imagine grabbing an immortality powerup somewhere in the game.
-- Simply set immortalityRemaining to the desired length of immortality.
function protagonistGrabbedImmortalityPowerup()
    protagonist.immortalityRemaining = 5
end

-- You then shave off a little bit of the remaining time during each love.update
-- Remember, dt is the time passed since the last update.
function love.update(dt)
    protagonist.immortalityRemaining = protagonist.immortalityRemaining - dt
end

-- When resolving damage to your protagonist, consider immortalityRemaining
function applyDamageToProtagonist(damage)
    if protagonist.immortalityRemaining <= 0 then
        protagonist.health = protagonist.health - damage
    end
end

Be careful with concepts like wait and timer. They typically refer to managing threads. In a game with many moving parts, it's often easier and more predictable to manage things without threads. When possible, treat your game like a giant state machine versus synchronizing work between threads. If threads are absolutely necessary, Löve does offer them in its love.thread module.

A: You could do this:
function delay_s(delay)
  delay = delay or 1
  local time_to = os.time() + delay
  while os.time() < time_to do end
end

Then you can just do:
Immortal == true
delay_s(5)
Immortal == false

Of course, it'll prevent you from doing anything else unless you run it in its own thread. But this is strictly Lua as I know nothing of Love2d, unfortunately.

A: I reccomend that you use hump.timer in your game,like this:
function love.load()
timer=require'hump.timer'
Immortal=true
timer.after(1,function()
Immortal=false
end)
end

instead of using timer.after,you can also use timer.script,like this:
function love.load
timer=require'hump.timer'
timer.script(function(wait)
Immortal=true
wait(5)
Immortal=false
end)
end

don't forget to add timer.updateinto function love.update!
function love.update(dt)
timer.update(dt)
end

hope this helped ;)
Download link:https://github.com/vrld/hump


text:
Q: PHP: Check string for certain words How can I check if data submitted from a form or querystring has certain words in it?
I'm trying to look for words containing admin, drop, create etc in form [Post] data and querystring data so I can accept or reject it.
I'm converting from ASP to PHP. I used to do this using an array in ASP (keep all illegal words in a string and use ubound to check the whole string for those words), but is there a better (efficient) way to do this in PHP?
Eg: A string like this would be rejected: "The administrator dropped a blah blah" because it has admin and drop in it.
I intend using this to check usernames when creating accounts and for other things too.
Thanks

A: You could use stripos()
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )

You could have a function like:
function checkBadWords($str, $badwords) {
    foreach ($badwords as $word) {
        if (stripos(" $str ", " $word ") !== false) {
            return false;
        }
    }
    return true;
}

And to use it:
if (!checkBadWords('something admin', array('admin')) {
    // ...
}

A: strpos() will let you search for a substring within a larger string.  It's quick and works well.  It returns false if the string's not found, and a number (which could be zero, so you need to use === to check) if it finds the string.
stripos() is a case-insensitive version of the same.

I'm trying to look for words containing admin, drop, create etc in form [Post] data and querystring data so I can accept or reject it.

I suspect that you are  trying to filter the string so it's suitable for including in something like a database query, or something like that.  If this is the case, this is probably not a good way to go about it, and you'd need to actually need to escape the string using mysql_real_escape_string() or equivalent.

A: $badwords = array("admin", "drop",);
foreach (str_word_count($string, 1) as $word) {
    foreach ($badwords as $bw) {
        if (strpos($word, $bw) === 0) {
            //contains word $word that starts with bad word $bw
        }
    }
}

For JGB146, here is a performance comparison with regular expressions:
<?php
function has_bad_words($badwords, $string) {

    foreach (str_word_count($string, 1) as $word) {
        foreach ($badwords as $bw) {
            if (stripos($word, $bw) === 0) {
                return true;
            }
        }
        return false;
    }

}

function has_bad_words2($badwords, $string) {

    $regex = array_map(function ($w) {
        return "(?:\\b". preg_quote($w, "/") . ")"; }, $badwords);
    $regex = "/" . implode("|", $regex) . "/";
    return preg_match($regex, $string) != 0;

}

$badwords = array("abc", "def", "ghi", "jkl", "mnop");
$string = "The quick brown fox jumps over the lazy dog";

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
 has_bad_words($badwords, $string);
}

echo "elapsed: ". (microtime(true) - $start);

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
 has_bad_words2($badwords, $string);
}

echo "elapsed: ". (microtime(true) - $start);

Example output:

elapsed: 0.076514959335327
elapsed: 0.29999899864197

So regular expressions are much slower.

A: You can certainly do a loop, as others have suggested. But I think you can get closer to the behavior you're looking for with an operation that directly uses arrays, plus it allows execution via a single if statement.
Originally, I was thinking you could do this with a simple preg_match() call (hence the downvote), however preg_match does not support arrays. Instead, you can do a replacement via preg_replace to have all rejected strings replaced with nothing, and then check to see if the string is changed. This is simple and avoids requiring a loop iteration for each rejected string.
$rejectedStrs = array("/admin/", "/drop/", "/create/");
if($input == preg_replace($rejectedStrs, "", $input)) {
   //do stuff
} else {
   //reject
}

Note also that you can provide case-insensitive searches by using the i flag on the regex patterns, changing the array of patterns to $rejectedStrs = array("/admin/i", "/drop/i", "/create/i");
On Efficiency
There has been some debate about the efficiency of doing it this way vs the accepted nested loop method. I ran some tests and found the preg_replace method executed around twice as fast as the nested loop. Here is the code and output of those tests:
$input = "You can certainly do a loop, as others have suggested. But I think you can get closer to the behavior you're looking for with an operation that directly uses arrays, plus it allows execution via a single if statement. You can certainly do a loop, as others have suggested. But I think you can get closer to the behavior you're looking for with an operation that directly uses arrays, plus it allows execution via a single if statement.";

$input = "Short string with no matches";
$input2 = "Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. Longer string with a lot more words but still no matches. ";
$input3 = "Short string which loop will match quickly";
$input4 = "Longer string that will eventually be matches but first has a lot of words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words, followed by more words and then more words and then finally the word create near the end";

$start1 = microtime(true);
$rejectedStrs = array("/loop/", "/operation/", "/create/");
$p_matches = 0;
for ($i = 0; $i < 10000; $i++) {
    if (preg_check($rejectedStrs, $input)) $p_matches++;
    if (preg_check($rejectedStrs, $input2)) $p_matches++;
    if (preg_check($rejectedStrs, $input3)) $p_matches++;
    if (preg_check($rejectedStrs, $input4)) $p_matches++;
}

$start2 = microtime(true);
$rejectedStrs = array("loop", "operation", "create");
$l_matches = 0;
for ($i = 0; $i < 10000; $i++) {
    if (loop_check($rejectedStrs, $input)) $l_matches++;
    if (loop_check($rejectedStrs, $input2)) $l_matches++;
    if (loop_check($rejectedStrs, $input3)) $l_matches++;
    if (loop_check($rejectedStrs, $input4)) $l_matches++;
}

$end = microtime(true);
echo "preg_match: ".$start1." ".$start2."= ".($start2-$start1)."\nloop_match: ".$start2." ".$end."=".($end-$start2);

function preg_check($rejectedStrs, $input) {
    if($input == preg_replace($rejectedStrs, "", $input))
        return true;
    return false;
}

function loop_check($badwords, $string) {

    foreach (str_word_count($string, 1) as $word) {
        foreach ($badwords as $bw) {
            if (stripos($word, $bw) === 0) {
                return true;
            }
        }
        return false;
    }

}

Output:

preg_match: 1281908071.4032 1281908071.9947= 0.5915060043335
loop_match: 1281908071.9947 1281908073.006=1.0112948417664

A: You could use regular expression like this:
preg_match("~(admin)|(drop)|(another token)|(yet another)~",$subject);

building the pattern string from array
$pattern = implode(")|(", $banned_words);
$pattern = "~(".$pattern.")~";

A: function check($string, $array) {
    foreach($array as $item) {
        if( preg_match("/($item)/", $string)  )
            return true;
    }
    return false;
}

A: This is actually pretty simple, use substr_count.
And example for you would be:
if (substr_count($variable_to_search, "drop"))
{
    echo "error";
}

And to make things even simpler, put your keywords (ie. "drop", "create", "alter") in an array and use foreach to check them.  That way you cover all your words.  An example
foreach ($keywordArray as $keyword)
{
    if (substr_count($variable_to_search, $keyword))
    {
        echo "error"; //or do whatever you want to do went you find something you don't like
    }
}


text:
Q: ROW_NUMBER and multiple JOIN When I test this request:
SELECT
    *, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb
FROM
    (SELECT DISTINCT
        tab1.test1, tab2.test2
     FROM TB_tab1 tab1
     JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3
     JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4
     WHERE tab3.test5 != 'test') AS sub
WHERE lineNumb BETWEEN 1 AND 5

I get:

Error: column name invalid : 'lineNumb'. SQLState: S0001 ErrorCode: 207

Why and how can I correct my request?

A: SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb FROM (
SELECT DISTINCT tab1.test1, tab2.test2
FROM TB_tab1 tab1
JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3
JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4 WHERE tab3.test5 !='test') as sub
) as sub2
WHERE lineNumb BETWEEN 1 AND 5

A: Why:
You cannot access the aliased lineNumb column in the where clause of your select--it isn't defined in the context.
How to correct:
Use what you have as a subquery or CTE and select from that using your where.
SELECT *
  FROM (<you existing query without the where>)
 WHERE lineNumb <= 5

A: You cannot use a column alias in a where at the same level.  You can do what you want with analytic functions.  You don't even need the distinct:
SELECT *
FROM (SELECT tab1.test1, tab2.test2,
             ROW_NUMBER() OVER (PARTITION BY tab1.test1, tab2.test2 ORDER BY test1) as seqnum,
             DENSE_RANK() OVER (ORDER BY test1) as lineNumb
      FROM TB_tab1 tab1
      JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3
      JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4
      WHERE tab3.test5 <> 'test'
     ) sub
WHERE lineNumb BETWEEN 1 AND 5 AND seqnum = 1;

A: Check out the order of execution in a SELECT statement in this question:
What's the execute order of the different parts of a SQL select statement?
The SELECT clause isn't read until late in the execution of the statement. So, you can't reference the alias until you get to the ORDER BY clause.


text:
Q: Creation of custom e-mail inbox for each tenant (customer) programatically We pair bank transactions via information e-mails. We need to solve: create own custom domain e-mail inbox (e-mail account) programatically (PHP), which will serve only for pairing bank transactions. This e-mail will be created for every new tenant (customer). I am not sure if we need own SMTP server or we can buy any outsourcing service (MailGun, Sendgrid ...). Do you have any idea how to solve this please ?
We have own Windows servers and we use Office365 atm, but we are thinking about Microsoft Azure to the future.
Thanks for your answers.


text:
Q: How to overide equals for array in Java? I wish to overide the equals for int[] arrays. Such that the following will be true
int[] a = {1,2,3};
int[] b = {1,2,3};
System.out.println(a.equals(b));

Is there a way to do that?

A: Overriding the equals method of int[] is both not possible and not necessary.  The functionality you desire can be achieved by using Arrays.equals(int[], int[]).
int[] a = {1,2,3};
int[] b = {1,2,3};
System.out.println(Arrays.equals(a, b));

A: Arrays are low-level constructions of Java, so you can't create sublasses, so you can't override methods. But you can use java.util.List instead of an array. Modern JREs shows the same performance both for arrays and lists.

A: You can't override equals on arrays directly - arrays are a primitive construct in Java and you can't override methods or operators that act on them.
You should consider using ArrayLists instead of arrays - ArrayLists provide an equals() implementation that works as you are looking for (as well as many other useful features that arrays don't have, such as the ability to add new elements to the list etc.)

A: The other answers here are correct in that you should really either just use Arrays.equals() or switch to using a List<Integer> instead of an int[].
However, what you want to do is almost possible using reflection and javassist.util.proxy.ProxyFactory.  Here's some example code that would do the trick, more or less:
public static void main(String[] args) throws Exception {
    int[] test = {0, 1, 2, 3};
    int[] empty1 = {};
    int[] empty2 = {};

    Class clss = int[].class;
    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(clss);
    factory.setFilter(new MethodFilter() {
         public boolean isHandled(Method m) {
             // ignore finalize()
             return !m.getName().equals("finalize");
         }
     });
    factory.setHandler(new IntArrayEqualsHandler());

    Class newArrayClass = factory.createClass();

    int[] specialArray = (int[])newArrayClass.newInstance();
    System.out.println(empty1.equals(empty2));
    System.out.println(specialArray.equals(empty1));
    System.out.println(specialArray.equals(empty2));
    System.out.println(specialArray.equals(test));
}

private static class IntArrayEqualsHandler implements MethodHandler {
    @Override
    public Object invoke(Object thisObj, Method method, Method original, Object[] params) throws Throwable {
        if (method.getName().equals("equals")) {
            int[] left = (int[])thisObj;
            int[] right = (int[])params[0];
            return Arrays.equals(left, right);
        }
        return original.invoke(thisObj, params);
    }

}

Unfortunately, this won't work because int[].class is declared as final in the language, so even using reflection it cannot be extended.  At least as far as I can tell.  There are tricks you can pull to remove the 'final' modifier from a field, but there doesn't seem to be an equivalent hack available for removing the final modifier from an entire class.
If there was such a thing, you could use the code above, or something like it, to generate a custom subclass of int[] at runtime that implemented your desired equals() behavior.
Really though that's all more trouble than it's worth, especially when you start looking at how to actually use the custom subclass in the rest of your project.  So all things considered you are much better off just using Arrays.equals() or List<Integer>.


text:
Q: Vue3 Wait till Child Component is Mounted I want to wait for a child component to mount before rendering a tooltip. While waiting, I will have a placeholder to display to the user.
An example component would be:
<template>

Loading...

   <child-component></child-component>
</template>

After doing research, it looks like Vue2 supports life-cycle hooks on the components, which would change the above code to:
<template>

Loading...

   <child-component @hook:mounted="mountedCheck"></child-component>
</template>

parent
<template>

Loading...

   <child-component @mounted="mountedCheck"></child-component>
</template>


text:
Q: build a wxPython wx.Icon from a resource file I have a wxPython application and I load an icon on the main form in the code like below
        icon = wx.Icon()
        icon.CopyFromBitmap(wx.Bitmap("icons/sm.ico", wx.BITMAP_TYPE_ANY))
        # icon.LoadFile("icons/sm.ico", wx.BITMAP_TYPE_ANY)
        self.SetIcon(icon)

This works in the python code when running in the development environment, where I have a icons/ folder that contains the sm.ico file, but when I package it up, the final exe cannot find "icons/sm.ico".
So, I tried to put this ico file into a resource file, so I built the following qrc file:
<RCC>
  <qresource prefix="/">
    <file>icons/sm.ico</file>
  </qresource>
</RCC>

Then, I use the pyrcc5.exe command to convert it to a python file (e.g. sm_rc.py), but I don't know how to load the ico image from that resource file. I tried 'LoadFile' as below, didn't work:
import src.ui.sm_rc
icon.LoadFile("icons/sm.ico", wx.BITMAP_TYPE_ANY)

So, the fundamental question is how to build a resource file that wxPython can read image from.

A: You are reinventing the wheel.
wxpython has a facility for incorporating png images into a python module.
You may then access them as an image, a bitmap or an icon.
https://docs.wxpython.org/wx.tools.img2py.html#module-wx.tools.img2py
Here is the code I use in a Linux project, adapt as necessary:
#!/bin/bash
rm fs_images.py
touch fs_images.py
img2py -n footswitch24 -c -i -f ../footswitch24.png fs_images.py
img2py -a -n footswitch24HiVis -c -i -f ../footswitch24HiVis.png fs_images.py
img2py -a -n footswitch24HiVisB -c -i -f ../footswitch24HiVisB.png fs_images.py
img2py -a -n footswitch24HiVisY -c -i -f ../footswitch24HiVisY.png fs_images.py
for image in *.png
do
 short=$(echo "$image" | awk -F'.' '{print $1}')
 img2py -a -n $short -c -f $image fs_images.py
done
cp fs_images.py ../

In your code, import fs_images then access the images with:
self.pause = wx.BitmapButton(self.panel3, -1, size=pb_size, bitmap=fs_images.getpauseBitmap())

or for the ico:
self.ico = fs_images.getfootswitch24Icon()
self.SetIcon(self.ico)

Voila! No more missing image files, you wrap the whole lot up in a single python module.


text:
Q: CLISP tries to load weird directory in SLIME on Windows 10 I've previously successfully installed Emacs + SLIME + SBCL on this machine.
I'm trying to install CLISP to work through some of the "Land of Lisp" examples that are CLISP specific.
When I start up SLIME with CLISP, it breaks when trying to load some SLIME files:
*** - OPEN: Directory #P"C:\\Users\\GUSTAV~1.BER\\AppData\\Local\\Temp\\" does not exist

I've explicitly set the temporary-file-directory to a fully expanded directory ("C:\\Users\\Gustav.Bertram\\AppData\\Local\\Temp\\") in .clisprc.lisp and I made sure that the variable is available at the point where the break happens.
The backtrace immediately after the error shows:
<1/164> #<SYSTEM-FUNCTION SHOW-STACK> 3
<2/157> #<COMPILED-FUNCTION SYSTEM::PRINT-BACKTRACE>
<3/151> #<COMPILED-FUNCTION SYSTEM::DEBUG-BACKTRACE>
<4/142> #<SYSTEM-FUNCTION SYSTEM::READ-EVAL-PRINT> 2
<5/139> #<COMPILED-FUNCTION SYSTEM::BREAK-LOOP-2-3>
<6/135> #<SYSTEM-FUNCTION SYSTEM::SAME-ENV-AS> 2
<7/121> #<COMPILED-FUNCTION SYSTEM::BREAK-LOOP-2>
<8/119> #<SYSTEM-FUNCTION SYSTEM::DRIVER>
<9/79> #<COMPILED-FUNCTION SYSTEM::BREAK-LOOP>
<10/76> #<SYSTEM-FUNCTION INVOKE-DEBUGGER> 1
<11/65> #<SYSTEM-FUNCTION OPEN>
<12/57> #<COMPILED-FUNCTION SWANK::ANNOUNCE-SERVER-PORT>
<13/54> #<COMPILED-FUNCTION SWANK::START-SERVER-1>
<14/49> #<COMPILED-FUNCTION SWANK::SETUP-SERVER>
<15/42> #<COMPILED-FUNCTION SWANK:START-SERVER>
<16/40> #<SYSTEM-FUNCTION FUNCALL> 2
[38] EVAL frame for form (FUNCALL (READ-FROM-STRING "swank:start-server") "c:\\Users\\GUSTAV~1.BER\\AppData\\Local\\Temp\\slime.34812")
<17/35> #<SPECIAL-OPERATOR PROGN>
[34] EVAL frame for form
(PROGN
 (LOAD "c:\\Users\\Gustav.Bertram\\AppData\\Roaming\\.emacs.d\\elpa\\slime-20170921.1000\\swank-loader.lisp" :VERBOSE T)
 (FUNCALL (READ-FROM-STRING "swank-loader:init"))
 (FUNCALL (READ-FROM-STRING "swank:start-server") "c:\\Users\\GUSTAV~1.BER\\AppData\\Local\\Temp\\slime.34812"))
Printed 17 frames

How can I figure out where the function call is coming from?

A: In the stack trace you can see that CLISP is evaluating the following:
(PROGN
 (LOAD "c:\\Users\\Gustav.Bertram\\AppData\\Roaming\\.emacs.d\\elpa\\slime-20170921.1000\\swank-loader.lisp" :VERBOSE T)
 (FUNCALL (READ-FROM-STRING "swank-loader:init"))
 (FUNCALL (READ-FROM-STRING "swank:start-server") "c:\\Users\\GUSTAV~1.BER\\AppData\\Local\\Temp\\slime.34812"))

This is what Slime passes to the Common Lisp after launching it in order to load Swank and start up a server to communicate with. You can see that the wrong path to the temporary file directory is passed as a string here, which means the directory must be resolved on the Emacs side. Emacs has a variable temporary-file-directory for this, which can be set in your initialization file, or via customize.


text:
Q: How to mock multiple rows in a SELECT in a stored procedure? This might be a silly question but I have tried several things and can't obtain the result I want.
I am currently testing a very tiny API that consumes data from an SQL Server database. In order to test it I am using a stored procedure that "mocks" a row and returns it. Like this:
CREATE PROCEDURE ONE
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA' as NAME
    WHERE
        @FRUITCODE > 0;
END;

This works fine to simulate one row, but I want to return more rows like this:
NAME
---------
BANANA
STRAWBERRY
MELON

I have tried
CREATE PROCEDURE TWO
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA', 'STRAWBERRY', 'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But that results in multiple columns, one is NAME and the others have a blank column name.
I also tried
CREATE PROCEDURE THREE
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 'BANANA' AS NAME
    WHERE @FRUITCODE > 0;

    SELECT 'STRAWBERRY' AS NAME
    WHERE @FRUITCODE > 0;

    SELECT 'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But this generates separate "tables" instead of a single one with multiple rows.
Lastly I tried
CREATE EPROCEDURE FOUR
    (@FRUITCODE VARCHAR(12))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        'BANANA' AS NAME,
        'STRAWBERRY' AS NAME,
        'MELON' AS NAME
    WHERE @FRUITCODE > 0;
END;

But this returns multiple "NAME" columns.
How can I return several rows? I am using SQL Server.

A: We need to use the VALUES table constructor, basically an inline 'invented' table, see the docs on this.
It can also be done with UNION ALL but that is more verbose.
SELECT *
FROM (VALUES
        ('BANANA'),
        ('STRAWBERRY'),
        ('MELON')
) AS v (NAME)
WHERE @FRUITCODE > 0


text:
Q: Invoking Android dialer application in background? My professor has given me the following assignment:
The screen should look as follows from top to bottom:

*

*A top bar showing in the center the called phone number

*A bar showing in the center the string "Calling..." while the destination phone number is being called. When the recipient replies, this message should disappear and a timer should appear in its place showing minutes and seconds. The time should tick by seconds. The timer should be formatted as MM:SS where MM are the minutes while SS are the seconds. When the call ends, a brief message "Call ended" should appear in this bar before the call is terminated.

*A button labeled "End Call". When this button is pushed, the call is terminated. This button can be tapped at any time during the phone conversation.

OK, so those are the software specification requirements. Obviously, because this is a school project I don't want the answer provided. What I do want to know, is how should I go about tackling this problem in terms of starting a phone call and moving to my own custom activity? If I create an Intent, won't it invoke the dialer application? Is there a way to put the dialer application in the background and stay on my activity?
Also, I thought it wasn't possible to manually end an Android phone call with the exception of the built in dialer?

A:
If I create an Intent, won't it invoke the dialer application?

There are different Intents for dialing the phone and calling a phone number. The former brings up the dialer. The latter brings up the in-call screen.

Is there a way to put the dialer application in the background and stay on my activity?

AFAIK, there is no way to do this that is officially supported. There are a variety of hacks for this.

I thought it wasn't possible to manually end an Android phone call with the exception of the built in dialer?

Same thing -- AFAIK there is no way that is officially supported, but there is at least one hack for this, but it uses techniques (reflection to get at non-SDK classes) that is so not a good idea.
Now, if this happens to be an Android firmware course, the story presumably changes. Given the nature of your question, though, I'm assuming that this is a course on building apps with the SDK, in which case while it's certainly possible to do what your professor wants, and there are apps on the Market that do it, it's not exactly what I'd call a stellar example of professional Android application development.


text:
Q: Sparx Enterprise Architect 15.1 issue with Master Document and Report Package I try to define more complex project reports. For this, I tried to
1) generate a new diagram (Extended -> Model Diagram)
2) Add both a Master document and a Report Package, and a Model Document
Now my issue is, neither Master nor Report Package are shown in the diagram, and only shown as normal packages in the browser. Only the Model Document is visible as a class.

left: part of the project browser, right: part of the diagram.
What am I doing wrong?

A: The logging add-in I used ("EAlogging") is not compliant with the current version of EA (15.1).
Switching it off solved the issue.


text:
Q: Why does using *= on numpy arrays modify the original array? The following code demonstrates that using a*=3 modifies the original dataset whereas a=a*3 does not:
data=np.array([[1,0],[3,4]])
a=data[0]
b=data[1]
a*=3
b=b*3
print(data)

gives:
[[3 0] [3 4]]

the a*=3 statement modified matrix data, but the b=b*3 statement did not.
I expect neither of the 2 assignments to modify data as both a and b are defined as slices of data and should therefore no longer be linked.
Is this behaviour intended? If so, what is the logic behind it?

A: Look at the flags on a and b, specifically the OWNDATA flag
>>> a.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : False   # <--- a does not copy data (a*=3 mutates original data)
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> b.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True   # <--- b is copied (the multiplication b*3 creates the copy)
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The object data[0] is not a slice, it's a writable view into the array.
 Modifying the contents will modify data.

Is this behaviour intended? If so, what is the logic behind it?

Yes, this is by design.  It's intended to prevent copying unless necessary.  If you need a copy in numpy, request it explicitly with a = data[0].copy().

A: I think this is not specific to numpy but true for any mutable object. See for example the following code which modify a list (the archetype mutable object):
a = [1]
b = a
b += [2]
print(a, b) #prints [1, 2] [1, 2]
print(id(a), id(b)) #The same id

a = [1]
b = a
b = b + [2]
print(a, b) #prints [1], [1, 2]
print(id(a), id(b)) #Not the same id

So an assignment will create a copy while an operator (+=) will modify the object. The numpy object simply behaves in the same way.


text:
Q: A Service determining whether a user is logged on I have a .NET application with both a Service and an application. I ask the service to alert me when the application is not running and vice versa. This is running on over 1000 machines with different logon credentials (normal login user names, ie bob, sam, fred for machine 1-PC, 2-PC, 3-PC).
I want to know when the application is not running so I can address it, however when the computer reboots and waits at the login screen I am constantly being told my app is not running, but actually there is no one logged in. Is there a way to see if a user is logged in? I have seen a few hacks but nothing concrete/no elegant way to achieve this.
That way I will be able to see the service is running, but not expect the application to be running until someone has logged onto the machine.

A: If your service is rock solid (i.e. rarely crashes), what I would do is write a temporary value somewhere (file, registry, database) when the service starts.
Then, the first time you see the application running clear the flag.
Thereafter, if the flag is not set and the application is not running, there is an issue.
This approach does not solve the case where the user logs off, only the reboot scenario, so I am not 100% sure this will work for you, but you only mention the reboot scenario, so I am hoping this may give you some ideas.

A: You could use a Global\MYUniqueEvent Object inside your Application and provide the necessary security credentials on that so that your Service can Check for it.
You can also possibly listen for Microsoft.Win32.SystemEvents.SessionSwitch to determine that a user is logging in. (I haven't personally used that, but Know it's there). Have a look at this for an example http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.asp

A: This couple links can be useful

*

*http://www.codeproject.com/Articles/10937/Retrieving-Logged-In-User-Name-using-a-Windows-Ser - checks if there is currently logged in user by checking who, if any runs explorer.exe.

*How do you retrieve a list of logged-in/connected users in .NET? - uses Win32 PInvoke to get user's information.

Note: there is a good chance that there is much better built in way of doing so - serverfault maybe a better site to ask question about managing large number of machines (unless you do shady activity with you tools).

A: var ntuser = new NTAccount(UserName);

var securityIdentifier = (SecurityIdentifier)ntuser.Translate(typeof(SecurityIdentifier));

var okey = Registry.Users.OpenSubKey(securityIdentifier + @"\Control Panel\Desktop", true); //any key is ok

if (okey != null)
//login
else
//not login


text:
Q: How to view my ubuntu screen on my android phone My laptop's built in display is broken, and I don't have another monitor. I want to use my android phone as a monitor, using either usb cable or local wifi network (It should work offline, using hotspot without any data connection)
Is there any way to do that?

A: Try plugging your laptop to your tv via hdmi. When you get to a purple screen press enter then type your password and press enter.


text:
Q: How do convert row result to like array($result) How do add my row result to to array like array($output_variable); i have tried:
<?php
    require('init.php');
    session_start();
    $result = mysqli_query($conn, 'SELECT item_name , quantity FROM books WHERE book = 1644445');
    while($row = mysqli_fetch_assoc($result)){
        $da  = $row['item_name'];
        $qty  = $row['quantity'];
        $sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
        while ($row = mysqli_fetch_array($sql)){
            $id = $row['id'];
            $type = $row['name'];
            $code = $row['recharge'];
            if(preg_match('/(9mobile)/i', $type))
                $type   = '5';
            if(preg_match('/(Glo)/i', $type))
                $type   = '5';
            if(preg_match('/(MTN)/i', $type))
                $type   = '5';
            if(preg_match('/(AIRTEL)/i', $type))
                $type   = '5';
            $disp = str_split($code, $type);
            $num = $qty;
            for($b = 0; $b<$num; $b++){
                $shown .= $disp[$b];
            }
            for($c = $num; $c<sizeof($disp); $c++){
                $dreturn .= $disp[$c]; #dreturn
            }
            $pa = array('$disp[$b]');
            $pa = implode(' ' ,$pa);
            echo "<br/>$pa";
            mysqli_query($conn, "UPDATE IGNORE promo SET recharge='12345678910' WHERE id=$id");
        }
    }
?>

all i get as output is $disp[$b]
 i appliciate your time in my soluction

A: 1) First thing, by using ' you tell PHP not to parse the string for any variables but to show it "as-is" ($ as dollar character, not variable beginning). By removing the ' from it, you have the value of $disp[$b] copied to $pa.
Example 1 (proposed fix):
$pa = array($disp[$b]);

Example 2:
<?php
$foo = 'bar!';
echo '$foo';
?>

If you execute example 2, you see $foo as output, no bar!. Just replace single quote in line 3 with double quote and you see bar!. Like: echo "$foo";
You even have the same result by using curly braces: echo '{$foo}'; versus echo "{$foo}";.
PHP version: PHP 7.1.11 (cli) (built: Oct 25 2017 20:54:15) ( NTS MSVC14 (Visual C++ 2015) x64 )
Getting off-topic, but still worth to improve:
2) Then you double-use $row (see both while() declarations). You should rename these both into separate variables. You may want to name your first $row as $book and second as $promo to clarify your code and not loose any data that you may later depend on.
3) Then there is no need to copy array elements to (local) variables (since PHP4 as I remember correctly). You can directly use the array elements, after you have fixed 1) and 2). Means, do something like $disp = str_split($promo['recharge'], $type);. It also looks like that the whole code is really messy, asking for further problems. I would recommend using error_reporting(-1); to be sure that all future warnings are enabled, see docs. This however should only be enabled for debugging, of course.


text:
Q: What is the best way to setup default snippets in Wagtail I would like to setup default snippets (article categories) in a Wagtail blog project.
My option would be to add the following line at the end of the models.py module:
if BlogPageCategory.objects.filter(name = 'Association').count() == 0:
    category = BlogPageCategory(name='Association')
    category.save()

Is it the best way to do it? Would it have any impact on the site performance?
Thanks

A: There are multiple ways to achieve what you want:

*

*The recommended way to do this is using Data migrations. The advantage of this method is that setting defaults in your database will be done when initializing, instead of a runtime action.

*The way you described (Although it'd be best to do this in your AppConfig's ready() method (as described here), as that is most commonly the place to run any code upon server startup. It won't have a very big impact on performance, because it is only run once (When your server is started)

*Using fixtures, which IMO is only necessary when loading large amounts of data into your database.


text:
Q: Expanding a dynamic memory block as needed I want to assign data to a block of memory but I don't know what's the size which I need.
For example, the following is just a simple example which illustrates the purpose:
char *str = (char*)malloc(2);
for (int i = 1; i < 10; i++) {
    str[i] = i;
    realloc(str, strlen(str) + 1);
}
printf("%s\n", str);

The previous code prints unknown symbols like the following:

What is the problem, then?

A: You are allocating memory, that's OK. You are writing a character inside the
limits, that's OK too. But then you use strlen, that's not OK, because
strlen expects a valid string, you are not passing string.
In C a string is just a sequence of characters that ends with the
'\0'-terminating byte. You are not doing that, so strlen will go beyond the
limit until it finds the '\0'-terminating byte and this is undefined
behaviour.
Also realloc might change the memory location when expanding the memory. You
are not accounting for that. If realloc returns a different pointer, the old
location is invalid and the next realloc call will yield undefined behaviour.
The way you are filling the data, you don't even need the strlen call, i
gives you that information already.
To fix your code:
char *str = calloc(2, 1);
if(str == NULL)
{
    // error handling
    // do not continue
    return;
}

for (int i = 0; i < 9; i++) {
    str[i] = i + 1 + '0';
    str[i+1] = 0; // making sure you have a valid c-string

    char *tmp = realloc(str, strlen(str) + 2);
    if(tmp == NULL)
    {
        // error handling,
        // do not continue
        free(str);
        return;
    }

    // making sure that str points to the new location
    // if realloc returned a different pointer
    str = tmp;
}

printf("%s\n", str);
free(str);

You should always check for the return value of malloc, calloc, realloc.
Also the realloc should be strlen(str) + 2. The +2 because you want to add
a new character and you have to have space for the '\0'-terminating byte.
Note that for the first allocation I used calloc, because calloc also sets
the allocated memory to 0, great for initialization. But regardless of that, you
should set the '\0'-terminating byte every time you add a new character
(str[i+1] = 0; line). I also store the value i + '0', which is most probably
what you want. 1 != '1', because the character '1' has the value 49, not 1.
See: ASCII table.
I've changed the str[i] = i + '0'; to str[i] = i + 1 + '0';, because it
seems that you want the string to start with a '1', not a '0'.
Also never forget to free the memory you've allocated. You can free the memory
at the end of the program or better still, when you don't need it anymore.

A: What is the problem, then?
very simple, the values in i are
0x00000000
0x00000001
...
0x00000009
(which do not fit into a char)
and those values are not part of the 'printable' ascii character set.
Suggest adding 0 (0x30) to each of the values as they are assigned to the array.
Also, suggest casting the int i to (char) at each assignment
the values in the array do not make a 'string' as there is no terminating NUL (0x00) byte.
Following edited for the comment from lion king
Suggest writing the code similar to the following:
#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char *str = malloc(2);   // do not 'cast' the returned value
    if( !str )
    {
        perror( "malloc failed" ); // output enclosed text and reason
                                   // system thinks the 'malloc` failed
                                   // to `stderr`
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    int i;
    for ( i = 0; i < MAX_CHARS; i++)
    {
        str[i] = (char)('0' + i);
        char *temp = realloc(str, i+3);  // assign to temp variable
                                         // and check if successful
                                         // to avoid causing a memory
                                         // leak when it fails
        if( !temp )
        {
            perror( "realloc failed" );
            free( str );  // cleanup
            exit( EXIT_FAILURE );
        }

        // implied else, realloc successful

        str = temp;   // update the target variable
    }

    // terminate the string
    str[ i ] = '\0';

    printf("%s\n", str);

    free( str );  // cleanup

    return 0;
}


text:
Q: python swap two elements I have the following code for a small program:
def get_different_number(arr):
  if len(arr) == 0 or arr is None:
    return 0
  n = len(arr)
  for i in range(n):
    print (str(i))
    temp = arr[i]
    while (temp < n and temp != arr[temp]):
      temp, arr[temp] = arr[temp],temp
  for i in range(n):
    if arr[i] != i:
      return i
  return n

test = [0,1,2,4,5]
get_different_number(test)

however, when it executes, it tells me there is a problem in the line where I swap temp and arr[temp], it gives me a list index out of range error at i is 3 (temp is 4).
When I change that line to arr[temp], temp = arr[temp], temp (reversed assign order), it worked fine. Why is this happening? I thought the a,b = b,a assignment in python assign both elements at the same time?


text:
Q: jQuery does not work when reload the page content via ajax I use Bootstrap to display a popover, until there is with all this code below everything works normal.
$(".emoticons").popover({
    html : true,
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
});

I only need to load the content of the page via ajax, then I changed the code because when I load the content dynamically I need to delegate events, changed the code and it looked like this:
$('body').on('click','.emoticons',function()
{
 $(".emoticons").popover({
    html : true,
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
 });
});

Now my troubles started. The code works however when I click the first time it does not work, so it works when I click more than once on the link. What to do?

A: It doesn't work the first time because the first click if firing off the body onclick handler which binds your popover.
Try something like this in your $(document).ready() function.
$(".emoticons").click(function(){

  $(this).popover({
    html : true,
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {return $('.emoticonimg').html();
    }
 });

});

A: What's happening is that when you are clicking on the .emoticons and executing your popover function, it is at that moment that you are binding it to your click. That's why it doesn't work the first time, but it works afterwards. It starts listening to the click event after that.
Ideally, the solution is to run the .popover function when the new content is loaded (on your AJAX callback).
If you want to just copy paste my code and see if it works, you can do this:
$('body').on('click','.emoticons',function()
{
// Convert this element into a popover and then display it
 $(this).popover({
    html : true,
    placement : 'bottom',
    animation : true,
    delay: { show: 100, hide: 500 },
    content: function() {
      return $('.emoticonimg').html();
    }
 }).popover('toggle');
});

But, I would NOT recommend this code specifically, since you are re-initializing your popover every time you click on it.
It's better and more clear if you bind all popovers after your AJAX request is done:
$.ajax( "BlaBlaBla.php" )
  .done(function() {
    // Convert all emoticons to popovers
    $(".emoticons").popover({
        html : true,
        placement : 'bottom',
        animation : true,
        delay: { show: 100, hide: 500 },
        content: function() {
           return $('.emoticonimg').html();
        }
     });
  });


text:
Q: linux dialog --checklist error I am working on following linux dialog box. I am not able to understand it's behavior. This works correctly i.e. correctly displays three checkboxes.
#!/bin/sh

dialog --backtitle "Test" \
--title "Checkbox test " \
--checklist "Choose from following"  0 0 0 \
apple "The apple is green" on \
mango "The mango is golden" on \
pappaya "The pappaya is brown" on \
2> /tmp/optional.out
OPTIONAL=`cat /tmp/optional.out | \
    sed -e "s/\"//g" -e "s/ /|/g" -e "s/|$//"`
    echo 'optional :'$OPTIONAL

After execution i get following output as.
optional :apple|mango|pappaya
However I want to show the user only two options. So I made the following changes.
#!/bin/sh

dialog --backtitle "Test" \
--title "Checkbox test " \
--checklist "Choose from following"  0 0 0 \
apple "The apple is green" on \
mango "The mango is golden" on \
#pappaya "The pappaya is brown" on \
2> /tmp/optional.out
OPTIONAL=`cat /tmp/optional.out | \
    sed -e "s/\"//g" -e "s/ /|/g" -e "s/|$//"`
    echo 'optional :'$OPTIONAL

But after doing this I get no output i.e. optional :. Why is that? How can I make it work.

A: I'm now thinking you did comment and broke your line. (it happens many times to me)
You may try this:
#!/bin/sh

dialog --backtitle "Test" \
--title "Checkbox test " \
--checklist "Choose from following"  0 0 0 \
apple "The apple is green" on \
mango "The mango is golden" on \
2> /var/tmp/optional.out
OPTIONAL=`cat /var/tmp/optional.out | \
    sed -e "s/\"//g" -e "s/ /|/g" -e "s/|$//"`
    echo 'optional :'$OPTIONAL


text:
Q: How to merge work from detached state I was working on a git branch called feature-branch when I realized that I had introduced some bugs at some unknown commit in the past. I worked back through my commits and found the commit where the error was introduced. I checked out this commit, 277be1c and fixed the bug, and would now like to stage and merge this work back onto feature-branch.
How can I do this? Do I use cherrypick? I am not sure how I should go about staging and committing this work which is in a detached head state back onto my feature branch.

A: Simply create a branch where you are now, then merge that new branch back into feature-branch.
The message that appears when you enter detached HEAD state includes this instruction for just your scenario:

If you want to create a new branch to retain commits you create, you may
  do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name


text:
Q: MPMoviePlayerController error _itemFailedToPlayToEnd while playing youtube video iOS 7 I've seen this mentioned a few places around the web but have yet to find answer anywhere.
I am using ALMovieplayercontroller library. Everything works fine but when i am trying to play Youtube video it gives me error.
_itemFailedToPlayToEnd: {
    kind = 1;
    new = 2;
    old = 0;
}
EDIT
- (void)setContentURL:(NSURL *)contentURL {

    self.movieSourceType = MPMovieSourceTypeStreaming;
    [super setContentURL:contentURL];
    [[NSNotificationCenter defaultCenter] postNotificationName:ALMoviePlayerContentURLDidChangeNotification object:nil];
    [self play];
}

Here is my code
ALMoviePlayerControls *movieControls = [[ALMoviePlayerControls alloc] initWithMoviePlayer:self.moviePlayer style:ALMoviePlayerControlsStyleDefault];
//[movieControls setAdjustsFullscreenImage:NO];
[movieControls setBarColor:[UIColor colorWithRed:195/255.0 green:29/255.0 blue:29/255.0 alpha:0.5]];
[movieControls setTimeRemainingDecrements:YES];

//assign controls
[self.moviePlayer setControls:movieControls];
[self.view addSubview:self.moviePlayer.view];
self.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;

//THEN set contentURL
[self.moviePlayer setContentURL:[NSURL URLWithString:@"http://www.youtube.com/watch?v=NaosmAGx8NM"]];

I am not able to find the solution for this.
Please Help.

A: Ok!!! the problem is that the player doesn't know what you are trying to play,

*

*you can try to change the name to x.mp4

*you can debug the project and see that the path and the file you are trying to play exists.

A: Yes after so much researching i found to the following soluction.
MPMoviePlayerController directly will not play the youtube videos. you have to extract the video URL and set video URL to MPMoviePlayerController. after this video will be played.
There are lots of API available that gives the extracted video URL.
Some of them are below
XCDYouTubeKit
HCYoutubeParser
But using this API your application might be rejected. you should have to use on your risk.
Best way to play youtube videos is the WebView.

A: If im not mistaken ALMovieplayercontroller is an extension of MPMoviePlayerController.
So try setting the source type of the player to stream.
moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;


text:
Q: Why is my replace not working for this content "planning cycle [M\\u0026S]"? I've got a huge JSON String that I provide to this function. I need to replace some entries as they contain spaces and make my life difficult at a later time (JSON Parser).
Now the first line works flawlessly. The last line, however doesn't. To ensure I have something to be found I tried the index (line 2 and 3). So line 2 provides me a (correct) result, so the String is actually found. Line 3 doesn't (and that's fine).
        JSON = JSON.Replace(@"cap type", "CapType");
        int index = JSON.IndexOf("planning cycle [M\\u0026S]");
        int index2 = JSON.IndexOf("planning cycle [M&S]");
        JSON = JSON.Replace(@"planning cycle [M\\u0026S]", "PlanningCycleMS");

My thoughts are going towards escape sequence, like you have "\" instead of "\ for the "[" and "]".
So my question is, what can I do to make line 4 work, or get the result of that string be replaced for all occurrences in my data file?

thx

A: In line 2, you are using normal string "...", the \\ is translated to a single character \
In line 4, you are using verbatim string @"...", so each \ is a different character, so you have two chars \\
It is not the same string in these two lines.


text:
Q: Dyanamic Query by Passing a String as Conditon for checking This is my procedure:
PROCEDURE SP_SALARYADVANCE_RPT_TEST
  (
    txtExtraQuery IN STRING,
    refcur OUT sys_refcursor )
OPEN refcur FOR
    SELECT DISTINCT( SAL.ADVANCENO ), SALARYADVANCEID, SAL.TRANSDATE, SAL.APPROVEDREMARKS, SAL.APPROVEDAMOUNT, SAL.PAYRECAMOUNT, EMP.EMPLOYEENAME, EMP.EMPLOYEECODE
      FROM HRM_SALARYADVANCE SAL, HRM_EMPLOYEE EMP, HRM_EMPLOYEEDEPARTMENTS DEPTS
      WHERE SAL.EMPLOYEEID     = EMP.EMPLOYEEID AND
        SAL.EMPLOYEEID     = DEPTS.EMPLOYEEID AND
        DEPTS.DEPARTMENTID = txtdeptid || txtextraquery;

Here my problem is I am sending AND SAL.STATUS in (1,2,3) as parameter This 1,2,3 may change i wish to pass it from frontend itself.
While excuting this query I am getting and error of

ORA-01722: invalid number

A: I'm guessing that your "parameter" AND SAL.STATUS in (1, 2, 3) is put into txtExtraQuery. Of course, you can't concatenate that to your existing query like you did, because then you'd concatenate txtdeptid with txtextraquery. And that doesn't have any meaning. That's why you get an ORA-01722 error, when comparing that with DEPTS.DEPARTMENTID
What you want to do is run an EXECUTE IMMEDIATE command. Check out these links:

*

*http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm

*http://www.dba-oracle.com/t_execute_dynamic_pl_sql_procedures.htm
But on the other hand, I think you should re-design your procedure. This doesn't look very nice. Why not pass a VARRAY or some other UDT to your procedure?


text:
Q: UWP Passing an Image Source to a user control for a background I am making a small UWP app in which each page has a similar layout.  I have created a custom UserControl following this thread, but I am not able to wrap my head around how to pass an Image Source to the background image of the UserControl.
If I remove the references to bgImage, and only mainContent, the whole thing works as expected.
How do I pass a background image source or URI to a UserControl for use with a control?
UserControl XAML:
<UserControl
    x:Class="App1.MainTemplate"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid Background="Black">
        <!-- Background image grid -->
        <Grid Margin="0">
            <Grid.Background>
                <ImageBrush Opacity="100" ImageSource="{x:Bind bgImage}" Stretch="UniformToFill"/>
            </Grid.Background>

            <!-- Content grid -->
            <Grid Margin="25" x:Name="contentGrid" Opacity="100">
                <!-- Darkened insert -->
                <Border BorderThickness="1" CornerRadius="8" BorderBrush="Black">
                    <Rectangle Name="Background" Opacity="0.55" Fill="Black" />
                </Border>

                <StackPanel VerticalAlignment="Center">
                    <!-- Content here. -->
                    <ContentPresenter Content="{x:Bind mainContent}" />

                </StackPanel>
            </Grid>
        </Grid>
    </Grid>
</UserControl>

MainTemplate.CS:
   public sealed partial class MainTemplate : UserControl
    {
        public MainTemplate()
        {
            this.InitializeComponent();
        }

        public static readonly DependencyProperty bgImageProperty = DependencyProperty.Register("bgImage", typeof(ImageSource), typeof(MainTemplate), new PropertyMetadata(null));
        public object bgImage
        {
            get { return GetValue(bgImageProperty); }
            set { SetValue(bgImageProperty, value); }
        }

        public static readonly DependencyProperty mainContentProperty = DependencyProperty.Register("mainContent", typeof(object), typeof(MainTemplate), new PropertyMetadata(null));
        public object mainContent
        {
            get { return GetValue(mainContentProperty); }
            set { SetValue(mainContentProperty, value); }
        }

    }

And finally, an example from one of the pages I am trying to use (MainPage.xaml):
<local:MainTemplate>
    <local:MainTemplate.bgImage>
        <Image Source="Assets/backgrounds/tailings 2.jpg"/>
    </local:MainTemplate.bgImage>

    <local:MainTemplate.mainContent>
        <Button
                    x:Name="app1"
                    Content=""
                    HorizontalAlignment="Center"
                    Click="app1_Click"
                    Width="426"
                    Height="134"
                    Style="{StaticResource noMouseoverHover}"
                    >
            <Button.Background>
                <ImageBrush ImageSource="Assets/logos/image.png"/>
            </Button.Background>
        </Button>
    </local:MainTemplate.mainContent>

</local:MainTemplate>

The error I get on compile/run is:
Error       Invalid binding path 'bgImage' : Cannot bind type 'System.Object' to 'Windows.UI.Xaml.Media.ImageSource' without a converter    App1

A: As already shown in Matt's answer, the type of the bgImage property should be ImageSource:
public ImageSource bgImage
{
    get { return (ImageSource)GetValue(bgImageProperty); }
    set { SetValue(bgImageProperty, value); }
}

Besides that, you can't assign an Image control to the property, as you are trying to do here:
<local:MainTemplate>
    <local:MainTemplate.bgImage>
        <Image Source="Assets/backgrounds/tailings 2.jpg"/>
    </local:MainTemplate.bgImage>
    ...
</local:MainTheme>

Instead, you should assign a BitmapImage, like:
<local:MainTemplate>
    <local:MainTemplate.bgImage>
        <BitmapImage UriSource="Assets/backgrounds/tailings 2.jpg"/>
    </local:MainTemplate.bgImage>
    ...
</local:MainTheme>

Or shorter, taking advantage of built-in type conversion:
<local:MainTheme bgImage="/Assets/backgrounds/tailings 2.jpg">
    ...
</local:MainTheme>

In addition to the above, you should also set the x:Bind Mode to OneWay, because the default is OneTime. Later changes to the bgImage property would otherwise be ignored:
<ImageBrush ImageSource="{x:Bind bgImage, Mode=OneWay}" ... />

Finally, there are widely accepted naming conventions regarding property names in .NET. They should start with an uppercase letter, so yours should probably be BgImage.

A: Don't you just need to set the property to be an ImageSource and not an object
public ImageSource bgImage
{
    get { return (ImageSource)GetValue(bgImageProperty); }
    set { SetValue(bgImageProperty, value); }
}


text:
Q: Insert static content or some erb in activeadmin in nested form Trying to render some information about the object in active admin:
  f.inputs 'Devices' do
    f.has_many :devices, new_record: false do |device|
     "html or some ERB goes here"

      device.input :status_activated, as: :bool
    end
  end

I've tried the following, which I found here:
device.form_buffers.last << (<<END

  Activate interlock

Dynatherms connected

END
).html_safe

without success.
Thanks in advance!

A: insert_tag(Arbre::HTML::Div) { content_tag(:span, "foo") }

Seems to be answered (but not accepted) here.
See the arbre repo for more info.

A: If you have some simple HTML only, just do
f.inputs 'Devices' do
    f.has_many :devices, new_record: false do |device|
      span "html or some ERB goes here"

      device.input :status_activated, as: :bool
    end
end

However, if you need something more complex, you're better off just extracting a partial, as in replace the form do block with form partial: 'form' and put your form layout and data in a _form.html.erb file in app/views/admin/...


text:
Q: awk with variable pattern with square paranthesis In my variable pattern there is square parentheses ( abc[0] ), but awk is unable to find pattern. If I change my pattern from abc[0] to abc_0, then it works.
echo "test_var=$test_var, test_var_1=$test_var_1"
# Output - test_var=abc[0], test_var_1=abc[0]

echo "$test_var" | awk -v variable="$test_var_1" '$0 ~ variable {print $variable}'
# "NO OUTPUT"

echo "test_var=$test_var, test_var_1=$test_var_1"
# test_var=abc_0, test_var_1=abc_0

echo "$test_var" | awk -v variable="$test_var_1" '$0 ~ variable {print $variable}'
# Here Output is abc_0

How to find pattern variable which has square parenthesis by awk command?

A: square brackets are special regex characters.
Check the following three cases, perhaps it will clarify
$ awk 'BEGIN{if("abc[0]" ~ /abc[0]/) print "match"; else print "no match"}'
no match

$ awk 'BEGIN{if("abc0" ~ /abc[0]/) print "match"; else print "no match"}'
match

$ awk 'BEGIN{if("abc[0]" ~ /abc\[0\]/) print "match"; else print "no match"}'
match


text:
Q: MyBatis 3.x trying to read a collection and populate the objects I'm new to MyBatis and my project requires me to read the data from the Oracle database, populate the objects, reset the data if necessary and insert it back into the database.
I'm trying to read data of a nested table. The nested table column consists of a collection of Oracle defined Custom Objects. To be more specific each record in the table is associated to a collection of Custom Object and the Custom Object consists of three fields namely nickname, date of birth and address.
I'm actually getting an oracle.sql.ARRAY data type when trying to retrieve the data. The problem I have here is that I'm not able to map this oracle.sql.ARRAY which is being fetched by the JDBC through MyBatis to my objects. All I'm able to do is get the ARRAY cast it to an object array and then to a Struct and iterate through the attributes to get the values.
I can always hand build the beans, but I know its not an efficient way of doing it. I want to configure my result map in a way that it populates my objects. But, I have not been able to do that so far. If anyone has any advice regarding this issue please help me out.

A: That would require a lot of Oracle specific code in Mybatis and I know they have tried to avoid RDMS specific code in general. I would write your own data mappers to map the arrays to whatever model objects you need.

A: I think you can get this to work with a custom TypeHandler.
In your ResultMap, do something like this:
<result property="arrayOne" column="array[1]" typeHandler="customArrayHandler" />
<result property="arrayTwo" column="array[2]" typeHandler="customArrayHandler" />

Then in your CustomArrayHandler.getResult() implementation, you can parse the real column name and index out. Then retrieve the array from the ResultSet and get the needed value from the index.


text:
Q: Linq statement returning same results for all entries I need to code a linq statement that codes the grade display button so it allows the user to display either all records or only records matching a specific grade. Also it has to calculate a gpa where a=4, b=3, c=2, d=1, f=0. I have changed the code to implement a where clause but I get
but i get an error
for the grades saying option strict on disallows implicit conversions from
string to boolean can anyone give me suggestions on this where clause?
     Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

    Dim dic As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
    dic.Add("A", 4)
    dic.Add("B", 3)
    dic.Add("C", 2)
    dic.Add("D", 1)
    dic.Add("F", 0)

    Dim gpa = Aggregate Grade In CoursesDataSet.tblCourses.AsEnumerable()
       Where Grade.Grade = "A" Or "B" Or "C" Or "D" Or "F"
       Select Grade.Field(Of Integer)("CreditHours") * dic(Grade.Field(Of String)("Grade"))
       Into Sum()

    MessageBox.Show("GPa:" & gpa.ToString(CInt("C2")),
                   "College Courses", MessageBoxButtons.OK,

MessageBoxIcon.Information)
End Sub

End Class
![enter image description here][1]

A: I was working on this exact problem. In fact, we were likely in the same class!
I divided each category of grades into aggregate sums after declaring the letter grades as constants:
        Dim ALetterAvg As Double =
        Aggregate ID In CoursesDataSet.tblCourses
        Where ID.Grade.ToUpper = "A"
        Select (ID.CreditHours * gradeAPoints) Into Sum()

Aggregated the total number of hours:
        Dim totalHours As Double =
        Aggregate hrs In CoursesDataSet.tblCourses
        Select hrs.CreditHours Into Sum()

Then divided the grade sums by the total hours:
        Dim GPA As Double = (ALetterAvg + BLetterAvg + CLetterAvg + DLetterAvg + FLetterAvg) / totalHours

A: Variable scopes in LINQ queries work the same as anywhere else. So for example if your query is within a loop, your variable Grade has to be in scope for that loop.
It would help in being able to provide a more specific answer if you specify where and how you are currently declaring Grade.

A: Assuming that you want to "translate" Grade into corresponding numeric values, i'd suggest to use Dictionary.
Dim dic As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
dic.Add("A", 4)
dic.Add("B", 3)
dic.Add("C", 2)
dic.Add("D", 1)
dic.Add("F", 0)

Now, you're able to aggregate data to get sum of Grades.
'LinqToDataSet example:
Dim qry = Aggregate r In CoursesDataSet.tblCourses.AsEnumerable()
           Select  r.Field(Of Double)("CreditHours") * dic(r.Field(Of String)("Grade"))
           Into Sum()

For further information, please see: Linq To DataSet Examples (VB.NET)


text:
Q: PHP Laravel Framework Routing Error I installed laravel+composer in my localhost and then I tried to run basic routes.php with this block of codes:
 Route::get('/x', function()
{
    return 'Hello World';
});

and then I tried to run it by using this http://localhost/laravel/app/x and http://localhost/laravel/x
and I'm gettin this error type:
Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.4 (Unix) PHP/5.5.3 OpenSSL/1.0.1e mod_perl/2.0.8-dev Perl/v5.16.3

How can I overcome this issue?

A: All of the Laravel routes go through the public folder.
Assuming your project name is Laravel, this should work.
http://localhost/laravel/public/x


text:
Q: Is RStudio editing scripts upon saving? I am reading pdf files with R. Before I analyze them, I perform a cleaning process.
More specifically, I am using this custom function:
cleanFile = function(x) {
    x = str_replace_all(string = x, pattern = "\\s+", replacement = " ") # not interesting for this post
    x = str_replace_all(string = x, pattern = "–", replacement = "-")
}

The second line is replacing a special character which my pdf files contain and looks just like a hyphen, with the "normal" hyphen character, "-".
This is some code afterwards:
pdfClean = lapply(pdfList, cleanFile) # files cleansed
str_detect(pdfClean[[1]], "–") # checking if the special character appears - this last bit is not part of the script, I type it in the console so it's not affected by save.

When I save and run my script, the last line surprisingly returns TRUE.
I understand that the "–" character has been replaced with something different, because if I replace it back in my code and run the same script without saving, the last line returns FALSE, as expected.
Furthermore, this issue has only appeared now that I have changed my computer. In the past, I was using a different one and my code was running without any issue whatsoever.
I tried to experiment a bit with Tools --> Global Options --> Code --> Saving --> Default text encoding, but I didn't manage to fix anything.
Any help would be greatly appreciated.


text:
Q: Prompting Database Login When generating report from a listview contents to crystal reports I got  this  code and getting an error prompt. Database Login. Even I put the right password, it always says Login Failed.
Dim report As New ReportDocument
report.Load("rptPrntIss.rpt")

report.RecordSelectionFormula = "{tbl_issued.TransactionID}=" & txtIssID.Text & "AND ({tbl_transaction.Department}=" & cBoxDpt.Text & ")"
frmPrnt.CrystalReportViewer1.ReportSource = report
frmPrnt.CrystalReportViewer1.Refresh()
frmPrnt.ShowDialog()

Maybe this code is not right, because everything was perfect without this code.

A: use setdatabaselogon() function to prevent prompting database logon each time.
it will be like
report.SetDatabaseLogon("username", "password", "server", "dbname", false)

in some cases this will also wont work(had some situations recently for me),in that case we need to specify database login for each tables in report.
like
dim connInfo as new ConnectionInfo()
connInfo.ServerName = yourserver
connInfo.DatabaseName = "dbname"
connInfo.UserID = "username"
connInfo.Password = "password"
dim  tableLogOnInfo as new TableLogOnInfo()
tableLogOnInfo.ConnectionInfo = connInfo

   foreach Table as table in reportDoc.Database.Tables

      table.ApplyLogOnInfo(tableLogOnInfo)
      table.LogOnInfo.ConnectionInfo.ServerName = connInfo.ServerName
      table.LogOnInfo.ConnectionInfo.DatabaseName = connInfo.DatabaseName
      table.LogOnInfo.ConnectionInfo.UserID = connInfo.UserID
      table.LogOnInfo.ConnectionInfo.Password = connInfo.Password
   next

hope this helps.


text:
Q: How to encrypt nvarchar column in oracle? I have a table containing nvarchar  datatype columns (contains text in different languages). I want to encrypt data before inserting into table and decrypt the same while fetching records.
Please suggest how i can achieve this.
Encryption and decryption should be done through a private key.
Hoping, my question is clear. Please confirm if i need to provide more information.

A: Note that it is probably wiser to crypt and decrypt your data directly in your application rather than in the database.
You can use Oracle's DBMS_CRYPTO package. There is an example in the middle of the documentation page.
First you need to make a package to access the cipher type from SQL expression. Let's say you want AES256 in CBC mode with padding:
CREATE PACKAGE pkg_so_42979606
AS
    FUNCTION cipher_type RETURN PLS_INTEGER;
END pkg_so_42979606;
/
CREATE PACKAGE BODY pkg_so_42979606
AS
    ctype CONSTANT PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                  + DBMS_CRYPTO.CHAIN_CBC
                                  + DBMS_CRYPTO.PAD_PKCS5;
    FUNCTION cipher_type RETURN PLS_INTEGER
    IS
    BEGIN
        RETURN ctype;
    END;
END pkg_so_42979606;
/

Then you will need a key. You can ask Oracle to generate one. To easily handle it I'll move it in Base64. Let's draw one:
DECLARE
    key_bytes_raw RAW(32);
    key_char NVARCHAR2(64);
BEGIN
    key_bytes_raw := DBMS_CRYPTO.RANDOMBYTES(32);
    key_char := UTL_I18N.RAW_TO_CHAR(UTL_ENCODE.BASE64_ENCODE(key_bytes_raw), 'AL32UTF8');
    DBMS_OUTPUT.PUT_LINE('Key: ' || key_char);
END;
/
Key: pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=

Thus the cipher key I'll use is pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=.
Now I'll use a test table
CREATE TABLE so_42979606 (
    id NUMBER PRIMARY KEY,
    data NVARCHAR2(2000));

You can insert encrypted data:
INSERT INTO so_42979606
    VALUES (1,
            DBMS_CRYPTO.ENCRYPT(UTL_I18N.STRING_TO_RAW('My clear data', 'AL32UTF8'),
                                pkg_so_42979606.cipher_type(),
                                UTL_ENCODE.BASE64_DECODE(UTL_I18N.STRING_TO_RAW('pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=', 'AL32UTF8'))));

And retrieve the encrypted data in clear.
SELECT id, UTL_I18N.RAW_TO_NCHAR(DBMS_CRYPTO.DECRYPT(data,
                                    pkg_so_42979606.cipher_type(),
                                    UTL_ENCODE.BASE64_DECODE(UTL_I18N.STRING_TO_RAW('pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=', 'AL32UTF8'))),
                                 'AL32UTF8') data
    FROM so_42979606;

ID DATA
-- ----------------------
 1 My clear data


text:
Q: How much Partition? i'm a new linux user and I feel like I messed up my Partitions. I have around 600GB to use and it shows I have 5.5 GB of free space, so did I mess up my free space partitioning and would I just need to boot from the CD and change it?

I wasn't 100% sure on partitioning so  I think I failed >.<

A: That is swap, which has nothing to do with your free space don't worry. /dev/sda2 is where your files and Operating System are stored. Do not touch swap, as it is important for your OS to boot. You don't have to change it, there is nothing wrong.

A: Actually, there is a bit of a problem with this partition scheme (but it's not the memory, which is fine.  You've allocated 571 GiB for / (root) but only 17 GiB for /home, which is possibly back to front from what you intended.
As you can see there's only 12 GiB used on / and it's likely that it will not get much larger than this unless you are going to install a huge database program or just about every other program in the repository.  On the other hand /home is where you be putting all your data (/home/username) and 17 GiB is a little small.
I would suggest you boot off the LiveCD and use gparted to adjust / to be about 25 GiB and use the rest for /home.


text:
Q: Choosing action that maximize expectation but with uncertain estimates Hi CrossValidated community,
I am looking to understand how to adjust the typical bayesian decision theory to a situation when probability estimates have high uncertainty. In my specific case I am playing the game additively, i.e. the optimal strategy is to act greedy, i.e. choosing maximum expectation action at every single timestep. In math, ($r$ is some well defined return function and $a$ stands for a specific action out of the action set $A$, Action set is the same everytime):
$$
\DeclareMathOperator{\EX}{\mathbb{E}}
\begin{equation}
\begin{aligned}
& \underset{a \in A}{\text{maximize}}~
& & \underset{Pr(X,Y,Z)}{\EX}[r(a)]
\end{aligned}
\end{equation}
$$
The question is what to do with a fact that my estimate of $Pr(X,Y,Z)$ is very uncertain. In practice, I have the estimators of $Pr(X), Pr(Y), Pr(Z)$, they are practically independent but they each have their own error and hence uncertainty of $Pr(X,Y,Z)$ is quite high.
Q: What are my options?
Possible Ideas?:

*

*some form of robust optimization, i.e. choosing the best action for the worst case setting out of Pr(X,Y,Z)

*somehow quantifying the uncertainty from data and adjusting the calculation of expectation.

Thanks for your patience and expertise. : )


text:
Q: Deserialize HttpCookie object from JSON For some reason HttpCookie object fails deserialization from JSON. I get this error -

Cannot populate list type System.Web.HttpValueCollection. Path 'Values', line .., position ..

I managed to deserialize the JSON into a custom class (HttpCookieModel) that doesn't have the Values property, and then rebuild the HttpCookie from the data.
But isn't there a simpler way?
using Newtonsoft.Json; //  v7.0.1

public JsonResult GetCookie() {
     return Json(new { Success = true, Username = model.UserName, Cookie = FormsAuthentication.GetAuthCookie(model.UserName, true) });
}

private static void DoSomeTests()
{
      // HttpWebRequest request....
      // Call GetCookie()
      // ...
      var httpResponse = (HttpWebResponse)request.GetResponse();
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), true))
      {
           res = streamReader.ReadToEnd();
      }
      // Deserialize
      try
      {
           MyResponse mr = JsonConvert.DeserializeObject<MyResponse>(res);
      }
      catch (Exception ex)
      {
          string message = ex.Message;   // message: Cannot populate list type System.Web.HttpValueCollection. Path 'Values'....
      }

    public class MyResponse
    {
        public bool Success { get; set; }
        public string Username { get; set; }
       // public HttpCookie Cookie { get; set; } // Problems deserializing Values collection.
        public HttpCookieModel Cookie { get; set; }
    }

   // This model works - but is there a simpler way?
    public class HttpCookieModel
    {
        public string Domain { get; set; }
        public DateTime Expires { get; set; }
        public bool HasKeys { get; set; }
        public bool HttpOnly { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
        public bool Secure { get; set; }
        public bool Shareable { get; set; }
        public string Value { get; set; }

        public HttpCookie ConvertToHttpCookie()
        {
            HttpCookie result           = new HttpCookie(this.Name);
            result.Domain               = this.Domain;
            result.Expires              = this.Expires;
            result.HttpOnly             = this.HttpOnly;
            result.Path                 = this.Path;
            result.Secure               = this.Secure;
            result.Shareable            = this.Shareable;
            result.Value                = this.Value;
            return result;
        }
    }
}

A: Take the json response and import it here http://json2csharp.com/ this will create the necessary classes needed for proper deserialisation, then just deserialise to the RootObject class (RootObject is the default name that json2csharp gives, change it to whatever suits your needs

A: Try MissingMemberHandling.Ignore:
Example usage:
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

JsonConvert.DeserializeObject<YourClass>(jsonResponse, jsonSerializerSettings);

With your code:
public class MyResponse
    {
        public bool Success { get; set; }
        public string Username { get; set; }
        public HttpCookie Cookie { get; set; } //use HttpCookie as normal
    }

Apply MissingMemberHandling.Ignore:
var jsonSerializerSettings = new JsonSerializerSettings();
 jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
 MyResponse mr = JsonConvert.DeserializeObject<MyResponse>(res, jsonSerializerSettings);