Programs & Examples On #Flashpaper

How to convert a string to character array in c (or) how to extract a single char form string?

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);

How to get the range of occupied cells in excel sheet

You should not delete the data in box by pressing "delete", i think thats the problem , because excel will still detected the box as "" <- still have value, u should delete by right click the box and click delete.

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

List of Timezone IDs for use with FindTimeZoneById() in C#?

This is the code fully tested and working for me. You can use it just copy and paste in your aspx page and cs page.

This is my blog you can download full code here. thanks.

http://www.c-sharpcorner.com/blogs/display-all-the-timezone-information-in-dropdown-list-of-a-local-system-using-c-sharp-with-asp-net

_x000D_
_x000D_
<form id="form1" runat="server">_x000D_
    <div style="font-size: 30px; padding: 25px; text-align: center;">_x000D_
        Get Current Date And Time Of All TimeZones_x000D_
    </div>_x000D_
    <hr />_x000D_
    <div style="font-size: 18px; padding: 25px; text-align: center;">_x000D_
        <div class="clsLeft">_x000D_
            Select TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTimeZone_SelectedIndexChanged"_x000D_
                Font-Size="18px">_x000D_
            </asp:DropDownList>_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Selected TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblTimeZone" runat="server" Text="" />_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Current Date And Time :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblCurrentDateTime" runat="server" Text="" />_x000D_
        </div>_x000D_
    </div>_x000D_
    <p>_x000D_
        &nbsp;</p>_x000D_
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTimeZone();
            GetSelectedTimeZone();
        }
    }

    protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSelectedTimeZone();
    }

    /// <summary>
    /// Get all timezone from local system and bind it in dropdownlist
    /// </summary>
    private void BindTimeZone()
    {
        foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
        {
            ddlTimeZone.Items.Add(new ListItem(z.DisplayName, z.Id));
        }
    }

    /// <summary>
    /// Get selected timezone and current date & time
    /// </summary>
    private void GetSelectedTimeZone()
    {
        DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        //DateTimeOffset newTime2 = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        lblTimeZone.Text = ddlTimeZone.SelectedItem.Text;
        lblCurrentDateTime.Text = newTime.ToString();
        string str;
        str = lblCurrentDateTime.Text;
        string s=str.Substring(0, 10);
        DateTime dt = new DateTime();
        dt = Convert.ToDateTime(s);
       // Response.Write(dt.ToString());
        Response.Write(ddlTimeZone.SelectedValue);

    }

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

What is the reason for a red exclamation mark next to my project in Eclipse?

If your IDE doesn't find JRE from the path you given. Then you manually need to add JRE path in eclipse to remove red exclamation mark from the project. To do this please follow below steps :-

Go to to Properties>Java Build Path>Libraries> Click on Edit

Then Select Alternate JRE and click on Finish.

Note : If you don't have Java Run time Environment (JRE) installed, please install.

What is the difference between declarative and imperative paradigm in programming?

From my understanding, both terms have roots in philosophy, there are declarative and imperative kinds of knowledge. Declarative knowledge are assertions of truth, statements of fact like math axioms. It tells you something. Imperative, or procedural knowledge, tells you step by step how to arrive at something. That's what the definition of an algorithm essentially is. If you would, compare a computer programming language with the English language. Declarative sentences state something. A boring example, but here's a declarative way of displaying whether two numbers are equal to each other, in Java:

public static void main(String[] args)
{
    System.out.print("4 = 4.");
}

Imperative sentences in English, on the other hand, give a command or make some sort of request. Imperative programming, then, is just a list of commands (do this, do that). Here's an imperative way of displaying whether two numbers are equal to each other or not while accepting user input, in Java:

private static Scanner input;    

public static void main(String[] args) 
{
    input = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter an integer value for x: ");
    int x = input.nextInt();
    System.out.print("Enter an integer value for y: ");        
    int y = input.nextInt();

    System.out.println();
    System.out.printf("%d == %d? %s\n", x, y, x == y);
}

Essentially, declarative knowledge skips over certain elements to form a layer of abstraction over those elements. Declarative programming does the same.

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

yii2 hidden input value

you can also do this

$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);

this is a better option if you set value on controller

$model = new SomeModelName();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
    return $this->redirect(['view', 'id' => $model->group_id]);
 } else {
    $model->hidden1 = 'your value';
    return $this->render('create', [
        'model' => $model,
    ]);
 }

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

Clicking HTML 5 Video element to play, pause video, breaks play button

The simplest form is to use the onclick listener:

<video height="auto" controls="controls" preload="none" onclick="this.play()">
 <source type="video/mp4" src="vid.mp4">
</video>

No jQuery or complicated Javascript code needed.

Play/Pause can be done with onclick="this.paused ? this.play() : this.pause();".

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

get launchable activity name of package from adb

You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.

enter image description here

How to store the hostname in a variable in a .bat file?

hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.

FloatingActionButton example with Support Library

So in your build.gradle file, add this:

compile 'com.android.support:design:27.1.1'

AndroidX Note: Google is introducing new AndroidX extension libraries to replace the older Support Libraries. To use AndroidX, first make sure you've updated your gradle.properties file, edited build.gradle to set compileSdkVersion to 28 (or higher), and use the following line instead of the previous compile one.

implementation 'com.google.android.material:material:1.0.0'

Next, in your themes.xml or styles.xml or whatever, make sure you set this- it's your app's accent color-- and the color of your FAB unless you override it (see below):

        <item name="colorAccent">@color/floating_action_button_color</item>

In the layout's XML:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <android.support.design.widget.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

Or if you are using the AndroidX material library above, you'd instead use this:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:srcCompat="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

You can see more options in the docs (material docs here) (setRippleColor, etc.), but one of note is:

    app:fabSize="mini"

Another interesting one-- to change the background color of just one FAB, add:

    app:backgroundTint="#FF0000"

(for example to change it to red) to the XML above.

Anyway, in code, after the Activity/Fragment's view is inflated....

    FloatingActionButton myFab = (FloatingActionButton)  myView.findViewById(R.id.myFAB);
    myFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            doMyThing();
        }
    });

Observations:

  • If you have one of those buttons that's on a "seam" splitting two views (using a RelativeLayout, for example) with, say, a negative bottom layout margin to overlap the border, you'll notice an issue: the FAB's size is actually very different on lollipop vs. pre-lollipop. You can actually see this in AS's visual layout editor when you flip between APIs-- it suddenly "puffs out" when you switch to pre-lollipop. The reason for the extra size seems to be that the shadow expands the size of the view in every direction. So you have to account for this when you're adjusting the FAB's margins if it's close to other stuff.
  • Here's a way to remove or change the padding if there's too much:

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) myFab.getLayoutParams();
        p.setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
        myFab.setLayoutParams(p);
    }
    
  • Also, I was going to programmatically place the FAB on the "seam" between two areas in a RelativeLayout by grabbing the FAB's height, dividing by two, and using that as the margin offset. But myFab.getHeight() returned zero, even after the view was inflated, it seemed. Instead I used a ViewTreeObserver to get the height only after it's laid out and then set the position. See this tip here. It looked like this:

        ViewTreeObserver viewTreeObserver = closeButton.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        closeButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        closeButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    // not sure the above is equivalent, but that's beside the point for this example...
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) closeButton.getLayoutParams();
                    params.setMargins(0, 0, 16, -closeButton.getHeight() / 2); // (int left, int top, int right, int bottom)
                    closeButton.setLayoutParams(params);
                }
            });
        }
    

    Not sure if this is the right way to do it, but it seems to work.

  • It seems you can make the shadow-space of the button smaller by decreasing the elevation.
  • If you want the FAB on a "seam" you can use layout_anchor and layout_anchorGravity here is an example:

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>
    

Remember that you can automatically have the button jump out of the way when a Snackbar comes up by wrapping it in a CoordinatorLayout.

More:

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

Python Pandas iterate over rows and access column names

How to iterate efficiently

If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows() is far from being the best. itertuples() can be 100 times faster.

In short:

  • As a general rule, use df.itertuples(name=None). In particular, when you have a fixed number columns and less than 255 columns. See point (3)
  • Otherwise, use df.itertuples() except if your columns have special characters such as spaces or '-'. See point (2)
  • It is possible to use itertuples() even if your dataframe has strange columns by using the last example. See point (4)
  • Only use iterrows() if you cannot the previous solutions. See point (1)

Different methods to iterate over rows in a Pandas dataframe:

Generate a random dataframe with a million rows and 4 columns:

    df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
    print(df)

1) The usual iterrows() is convenient, but damn slow:

start_time = time.clock()
result = 0
for _, row in df.iterrows():
    result += max(row['B'], row['C'])

total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))

2) The default itertuples() is already much faster, but it doesn't work with column names such as My Col-Name is very Strange (you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row.B, row.C)

total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

3) The default itertuples() using name=None is even faster but not really convenient as you have to define a variable per column.

start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
    result += max(col2, col3)

total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

4) Finally, the named itertuples() is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange.

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))

Output:

         A   B   C   D
0       41  63  42  23
1       54   9  24  65
2       15  34  10   9
3       39  94  82  97
4        4  88  79  54
...     ..  ..  ..  ..
999995  48  27   4  25
999996  16  51  34  28
999997   1  39  61  14
999998  66  51  27  70
999999  51  53  47  99

[1000000 rows x 4 columns]

1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519

This article is a very interesting comparison between iterrows and itertuples

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

Unit tests vs Functional tests

"Functional test" does not mean you are testing a function (method) in your code. It means, generally, that you are testing system functionality -- when I run foo file.txt at the command line, the lines in file.txt become reversed, perhaps. In contrast, a single unit test generally covers a single case of a single method -- length("hello") should return 5, and length("hi") should return 2.

See also IBM's take on the line between unit testing and functional testing.

Is it possible to style a mouseover on an image map using CSS?

Sorry to jump on this question late in the game but I have an answer for irregular (non-rectangular) shapes. I solved it using SVGs to generate masks of where I want to have the event attached.

The idea is to attach events to inlined SVGs, super cheap and even user friendly because there are plenty of programs for generating SVGs. The SVG can have a layer of the image as a background.

http://jcrogel.com/code/2015/03/18/mapping-images-using-javascript-events/

ShowAllData method of Worksheet class failed

The simple way to avoid this is not to use the worksheet method ShowAllData

Autofilter has the same ShowAllData method which doesn't throw an error when the filter is enabled but no filter is set

If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData

Redirecting unauthorized controller in ASP.NET MVC

This problem has hounded me for some days now, so on finding the answer that affirmatively works with tvanfosson's answer above, I thought it would be worthwhile to emphasize the core part of the answer, and address some related catch ya's.

The core answer is this, sweet and simple:

filterContext.Result = new HttpUnauthorizedResult();

In my case I inherit from a base controller, so in each controller that inherits from it I override OnAuthorize:

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    base.OnAuthorization(filterContext);
    YourAuth(filterContext); // do your own authorization logic here
}

The problem was that in 'YourAuth', I tried two things that I thought would not only work, but would also immediately terminate the request. Well, that is not how it works. So first, the two things that DO NOT work, unexpectedly:

filterContext.RequestContext.HttpContext.Response.Redirect("/Login"); // doesn't work!
FormsAuthentication.RedirectToLoginPage(); // doesn't work!

Not only do those not work, they don't end the request either. Which means the following:

if (!success) {
    filterContext.Result = new HttpUnauthorizedResult();
}
DoMoreStuffNowThatYouThinkYourAuthorized();

Well, even with the correct answer above, the flow of logic still continues! You will still hit DoMoreStuff... within OnAuthorize. So keep that in mind (DoMore... should be in an else therefore).

But with the correct answer, while OnAuthorize flow of logic continues till the end still, after that you really do get what you expect: a redirect to your login page (if you have one set in Forms auth in your webconfig).

But unexpectedly, 1) Response.Redirect("/Login") does not work: the Action method still gets called, and 2) FormsAuthentication.RedirectToLoginPage(); does the same thing: the Action method still gets called!

Which seems totally wrong to me, particularly with the latter: who would have thought that FormsAuthentication.RedirectToLoginPage does not end the request, or do the equivalant above of what filterContext.Result = new HttpUnauthorizedResult() does?

Inner join of DataTables in C#

I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:

private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
    DataTable result = new DataTable();
    foreach (DataColumn col in t1.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataColumn col in t2.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataRow row1 in t1.Rows)
    {
        var joinRows = t2.AsEnumerable().Where(row2 =>
            {
                foreach (var parameter in joinOn)
                {
                    if (!parameter(row1, row2)) return false;
                }
                return true;
            });
        foreach (DataRow fromRow in joinRows)
        {
            DataRow insertRow = result.NewRow();
            foreach (DataColumn col1 in t1.Columns)
            {
                insertRow[col1.ColumnName] = row1[col1.ColumnName];
            }
            foreach (DataColumn col2 in t2.Columns)
            {
                insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
            }
            result.Rows.Add(insertRow);
        }
    }
    return result;
}

An example of how you might use this:

var test = JoinDataTables(transactionInfo, transactionItems,
               (row1, row2) =>
               row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));

One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.

Setting up Vim for Python

In general, vim is a very powerful regular language editor (macros extend this but we'll ignore that for now). This is because vim's a thin layer on top of ed, and ed isn't much more than a line editor that speaks regex. Emacs has the advantage of being built on top of ELisp; lending it the ability to easily parse complex grammars and perform indentation tricks like the one you shared above.

To be honest, I've never been able to dive into the depths of emacs because it is simply delightful meditating within my vim cave. With that said, let's jump in.

Getting Started

Janus

For beginners, I highly recommend installing the readymade Janus plugin (fwiw, the name hails from a Star Trek episode featuring Janus Vim). If you want a quick shortcut to a vim IDE it's your best bang for your buck.

I've never used it much, but I've seen others use it happily and my current setup is borrowed heavily from an old Janus build.

Vim Pathogen

Otherwise, do some exploring on your own! I'd highly recommend installing vim pathogen if you want to see the universe of vim plugins.

It's a package manager of sorts. Once you install it, you can git clone packages to your ~/.vim/bundle directory and they're auto-installed. No more plugin installation, maintenance, or uninstall headaches!

You can run the following script from the GitHub page to install pathogen:

mkdir -p ~/.vim/autoload ~/.vim/bundle; \
curl -so ~/.vim/autoload/pathogen.vim \
    https://raw.github.com/tpope/vim-pathogen/HEAD/autoload/pathogen.vim

Helpful Links

Here are some links on extending vim I've found and enjoyed:

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

Why am I getting tree conflicts in Subversion?

I don't know if this is happening to you, but sometimes I choose the wrong directory to merge and I get this error even though all the files appear completely fine.

Example:

Merge /svn/Project/branches/some-branch/Sources to /svn/Project/trunk ---> Tree conflict

Merge /svn/Project/branches/some-branch to /svn/Project/trunk ---> OK

This might be a stupid mistake, but it's not always obvious because you think it's something more complicated.

How to open an Excel file in C#?

You need to have installed Microsoft Visual Studio Tools for Office (VSTO).

VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.

After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);

Missing.Value is a special reflection struct for unnecessary parameters replacement


In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.

enter image description here

Animate background image change with jQuery

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>?

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});?

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}?

Apache - MySQL Service detected with wrong path. / Ports already in use

Ok so i found out the problem :)

ctrl+alt+delete to start task manager, once you get to task manager go to services. find MySQL and right click on it. Then click stop process. That worked for me and i hope it works for you :D

Multiple cases in switch statement

In C# 7 we now have Pattern Matching so you can do something like:

switch (age)
{
  case 50:
    ageBlock = "the big five-oh";
    break;
  case var testAge when (new List<int>()
      { 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):
    ageBlock = "octogenarian";
    break;
  case var testAge when ((testAge >= 90) & (testAge <= 99)):
    ageBlock = "nonagenarian";
    break;
  case var testAge when (testAge >= 100):
    ageBlock = "centenarian";
    break;
  default:
    ageBlock = "just old";
    break;
}

Radio Buttons "Checked" Attribute Not Working

also try this way

$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

How to develop or migrate apps for iPhone 5 screen resolution?

Use the Auto Layout feature for views. It will adjust automatically to all resolutions.

Create two xibs for a controller having controller name with suffix either ~iphone or ~ipad. At compile time, Xcode will take the right xib based on the device.

Use size classes, if you want to create a single xib for both iPhone and iPad, if the view is simple enough to port to iPhone and iPad.

Including dependencies in a jar with Maven

Putting Maven aside, you can put JAR libraries inside the Main Jar but you will need to use your own classloader.

Check this project: One-JAR link text

Last element in .each() set

For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

This directly compares elements rather than just checking index numbers.

$yourset.each(function() {
    var $this = $(this);
    if($this[0] === $yourset.last()[0]) {
        //$this is the last one
    }
});

add new row in gridview after binding C#, ASP.net

If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:

adapter.Fill(ds);
ds.Tables(0).Rows.Add();

How can I completely remove TFS Bindings

In visual studio 2015,

  1. Unbind the solution and project by File->Source Control->Advanced->Change Source Control
  2. Remove the cache in C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\6.0

How to efficiently count the number of keys/properties of an object in JavaScript?

You could use this code:

if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                keys.push(k);
            }
        }
        return keys;
    };
}

Then you can use this in older browsers as well:

var len = Object.keys(obj).length;

How do I change select2 box height

The selected answer is correct but you shouldn't have to edit the select2.css file. You can add the following to your own custom css file.

.select2-container .select2-choice {
    display: block!important;
    height: 36px!important;
    white-space: nowrap!important;
    line-height: 26px!important;
}

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

I'd like to add that for accessibility, I think you should add focus trigger :

i.e. $("#popover").popover({ trigger: "hover focus" });

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

Is HTML considered a programming language?

In recruitment terms, having been on both sides of the fence, definitely put HTML under 'programming languages', or perhaps more safely under 'technologies'

Yes, we all know that it is a Markup Language and not a Programming Language. but a) Recruitment Agencies don't know and don't care, and b) employers don't know and don't care. Really.

And pointing out their ignorance will only serve you ill. And the techies who eventually see your CV will be grateful for a candidate who has heard of HTML, and won't worry about the taxonomy.

Honestly, it isn't an issue.

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

How should I log while using multiprocessing in Python?

Simplest idea as mentioned:

  • Grab the filename and the process id of the current process.
  • Set up a [WatchedFileHandler][1]. The reasons for this handler are discussed in detail here, but in short there are certain worse race conditions with the other logging handlers. This one has the shortest window for the race condition.
    • Choose a path to save the logs to such as /var/log/...

Embedding Base64 Images

Update: 2017-01-10

Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.

http://caniuse.com/#feat=datauri


Data URIs are now supported by the following web browsers:

  • Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
  • Konqueror, via KDE's KIO slaves input/output system
  • Opera (including devices such as the Nintendo DSi or Wii)
  • WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
  • Trident
    • Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
    • Data URIs are supported only for the following elements and/or attributes[4]:
      • object (images only)
      • img
      • input type=image
      • link
    • CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
    • Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
    • TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme

http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

How to deploy a Java Web Application (.war) on tomcat?

  • copy the .war file in the webapps folder
  • upload the file using the manager application - http://host:port/manager. You will have to setup some users beforehand.
  • (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in webapps/webappname

Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:

After you have it deployed (check the /logs dir for any problems), it should be accessible via: http://host:port/yourwebappname/. So in your case, one of those:

http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/

If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)

How to pass table value parameters to stored procedure from .net code

DataTable, DbDataReader, or IEnumerable<SqlDataRecord> objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).

The following example illustrates using either a DataTable or an IEnumerable<SqlDataRecord>:

SQL Code:

CREATE TABLE dbo.PageView
(
    PageViewID BIGINT NOT NULL CONSTRAINT pkPageView PRIMARY KEY CLUSTERED,
    PageViewCount BIGINT NOT NULL
);
CREATE TYPE dbo.PageViewTableType AS TABLE
(
    PageViewID BIGINT NOT NULL
);
CREATE PROCEDURE dbo.procMergePageView
    @Display dbo.PageViewTableType READONLY
AS
BEGIN
    MERGE INTO dbo.PageView AS T
    USING @Display AS S
    ON T.PageViewID = S.PageViewID
    WHEN MATCHED THEN UPDATE SET T.PageViewCount = T.PageViewCount + 1
    WHEN NOT MATCHED THEN INSERT VALUES(S.PageViewID, 1);
END

C# Code:

private static void ExecuteProcedure(bool useDataTable, 
                                     string connectionString, 
                                     IEnumerable<long> ids) 
{
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    {
        connection.Open();
        using (SqlCommand command = connection.CreateCommand()) 
        {
            command.CommandText = "dbo.procMergePageView";
            command.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter;
            if (useDataTable) {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateDataTable(ids));
            }
            else 
            {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateSqlDataRecords(ids));
            }
            parameter.SqlDbType = SqlDbType.Structured;
            parameter.TypeName = "dbo.PageViewTableType";

            command.ExecuteNonQuery();
        }
    }
}

private static DataTable CreateDataTable(IEnumerable<long> ids) 
{
    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(long));
    foreach (long id in ids) 
    {
        table.Rows.Add(id);
    }
    return table;
}

private static IEnumerable<SqlDataRecord> CreateSqlDataRecords(IEnumerable<long> ids) 
{
    SqlMetaData[] metaData = new SqlMetaData[1];
    metaData[0] = new SqlMetaData("ID", SqlDbType.BigInt);
    SqlDataRecord record = new SqlDataRecord(metaData);
    foreach (long id in ids) 
    {
        record.SetInt64(0, id);
        yield return record;
    }
}

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

Changing the color of an hr element

Some browsers use the color attribute and some use the background-color attribute. To be safe:

hr{
    color: #color;
    background-color: #color;
}

How to access JSON Object name/value?

You should do

alert(data[0].name); //Take the property name of the first array

and not

 alert(data.myName)

jQuery should be able to sniff the dataType for you even if you don't set it so no need for JSON.parse.

fiddle here

http://jsfiddle.net/H2yN6/

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

How do you rotate a two dimensional array?

Ruby-way: .transpose.map &:reverse

How to programmatically set cell value in DataGridView?

I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:

dataGridView1.ReadOnly = false; //Before modifying, it is required.
dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!

Note:

  1. Previously I have designed the columns in design mode.
  2. I have set the row header visibility to false from property of the datagridview.
  3. The last line is important to understand: When yoou directly giving index of datagridview, the first number is cell number, second one is row number! Remember it!

Hope this might help you.

Get the index of the object inside an array, matching a condition

How can I get the index of the object tha match a condition (without iterate along the array)?

You cannot, something has to iterate through the array (at least once).

If the condition changes a lot, then you'll have to loop through and look at the objects therein to see if they match the condition. However, on a system with ES5 features (or if you install a shim), that iteration can be done fairly concisely:

var index;
yourArray.some(function(entry, i) {
    if (entry.prop2 == "yutu") {
        index = i;
        return true;
    }
});

That uses the new(ish) Array#some function, which loops through the entries in the array until the function you give it returns true. The function I've given it saves the index of the matching entry, then returns true to stop the iteration.

Or of course, just use a for loop. Your various iteration options are covered in this other answer.

But if you're always going to be using the same property for this lookup, and if the property values are unique, you can loop just once and create an object to map them:

var prop2map = {};
yourArray.forEach(function(entry) {
    prop2map[entry.prop2] = entry;
});

(Or, again, you could use a for loop or any of your other options.)

Then if you need to find the entry with prop2 = "yutu", you can do this:

var entry = prop2map["yutu"];

I call this "cross-indexing" the array. Naturally, if you remove or add entries (or change their prop2 values), you need to update your mapping object as well.

What is the difference between Swing and AWT?

Several consequences result from this difference between AWT and Swing.

AWT is a thin layer of code on top of the OS, whereas Swing is much larger. Swing also has very much richer functionality. Using AWT, you have to implement a lot of things yourself, while Swing has them built in. For GUI-intensive work, AWT feels very primitive to work with compared to Swing. Because Swing implements GUI functionality itself rather than relying on the host OS, it can offer a richer environment on all platforms Java runs on. AWT is more limited in supplying the same functionality on all platforms because not all platforms implement the same-looking controls in the same ways.

Swing components are called "lightweight" because they do not require a native OS object to implement their functionality. JDialog and JFrame are heavyweight, because they do have a peer. So components like JButton, JTextArea, etc., are lightweight because they do not have an OS peer.

A peer is a widget provided by the operating system, such as a button object or an entry field object.

How to make an HTTP request + basic auth in Swift

You provide credentials in a URLRequest instance, like this in Swift 3:

let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

Or in an NSMutableURLRequest in Swift 2:

// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])

// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

Selector on background color of TextView

The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/selected_state" />
</selector>

You would also need to move that resource to the drawable directory where it would make more sense since it's not a color selector per se.

Then you would have to create the res/drawable/selected_state.xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid android:color="@color/semitransparent_white" />
</shape>

and finally, you would use it like this:

android:background="@drawable/selector"

Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference his resource that was still in the color directory but using @drawable so he ended up with an ID collision, selecting the wrong resource.

Hope this can still help someone even if the OP probably has, I hope, solved his problem by now.

jquery find closest previous sibling with class

Try:

$('li.current_sub').prevAll("li.par_cat:first");

Tested it with your markup:

$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");

will fill up the closest previous li.par_cat with "woohoo".

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

#include <string.h>
#include <stdio.h>

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Find all paths between two graph nodes

The following functions (modified BFS with a recursive path-finding function between two nodes) will do the job for an acyclic graph:

from collections import defaultdict

# modified BFS
def find_all_parents(G, s):
    Q = [s]
    parents = defaultdict(set)
    while len(Q) != 0:
        v = Q[0]
        Q.pop(0)
        for w in G.get(v, []):
            parents[w].add(v)
            Q.append(w) 
    return parents

# recursive path-finding function (assumes that there exists a path in G from a to b)   
def find_all_paths(parents, a, b): 
    return [a] if a == b else [y + b for x in list(parents[b]) for y in find_all_paths(parents, a, x)]

For example, with the following graph (DAG) G given by

G = {'A':['B','C'], 'B':['D'], 'C':['D', 'F'], 'D':['E', 'F'], 'E':['F']}

if we want to find all paths between the nodes 'A' and 'F' (using the above-defined functions as find_all_paths(find_all_parents(G, 'A'), 'A', 'F')), it will return the following paths:

enter image description here

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

I've been to this post about 10 times now and I just wanted to leave my two cents here. You can just unmount it conditionally.

if (renderMyComponent) {
  <MyComponent props={...} />
}

All you have to do is remove it from the DOM in order to unmount it.

As long as renderMyComponent = true, the component will render. If you set renderMyComponent = false, it will unmount from the DOM.

How to upgrade docker-compose to latest version

I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

I was getting:

-bash: /usr/local/bin/docker-compose: Permission denied

and while I was using it with sudo I was getting:

sudo: docker-compose: command not found

So here's the steps that I took and solved my problem:

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

Batch files: How to read a file?

You can use the for command:

FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k

Type

for /?

at the command prompt. Also, you can parse ini files!

ValueError: object too deep for desired array while using convolution

np.convolve() takes one dimension array. You need to check the input and convert it into 1D.

You can use the np.ravel(), to convert the array to one dimension.

ReactJS call parent method

Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

 const handleParentFun = (value) =>{
   console.log("Call to Parent Component!",value);
 }
 return (<>
           This is Parent Component
           <ChildComponent 
             handleParentFun={(value)=>{
               console.log("your value -->",value);
               handleParentFun(value);
             }}
           />
        </>);
}

Child Component

import React from "react";


export default function ChildComponent(props){
  return(
         <> This is Child Component 
          <button onClick={props.handleParentFun("YoureValue")}>
            Call to Parent Component Function
          </button>
         </>
        );
}

how to define ssh private key for servers fetched by dynamic inventory in files

You can simply define the key to use directly when running the command:

ansible-playbook \
        \ # Super verbose output incl. SSH-Details:
    -vvvv \
        \ # The Server to target: (Keep the trailing comma!)
    -i "000.000.0.000," \
        \ # Define the key to use:
    --private-key=~/.ssh/id_rsa_ansible \
        \ # The `env` var is needed if `python` is not available:
    -e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
        \ # Dry–Run:
    --check \
    deploy.yml

Copy/ Paste:

ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml

How to handle click event in Button Column in Datagridview?

A bit late to the table here, but in c# (vs2013) you don't need to use column names either, in fact a lot of the extra work that some people propose is completely unnecessary.

The column is actually created as an member of the container (the form, or usercontrol that you've put the DataGridView into). From the designer code (the stuff you're not supposed to edit except when the designer breaks something), you'd see something like:

this.curvesList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.enablePlot,
        this.desc,
        this.unit,
        this.min,
        this.max,
        this.color});

...

//
// color
// 
this.color.HeaderText = "Colour";
this.color.MinimumWidth = 40;
this.color.Name = "color";
this.color.ReadOnly = true;
this.color.Width = 40;

...

private System.Windows.Forms.DataGridViewButtonColumn color;

So in the CellContentClick handler, apart from ensuring that the row index is not 0, you just need to check whether the clicked column is in fact the one you want by comparing object references:

private void curvesList_CellContentClick(object sender, 
    DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;
    var column = senderGrid.Columns[e.ColumnIndex];
    if (e.RowIndex >= 0)
    {
        if ((object)column == (object)color)
        {
            colorDialog.Color = Color.Blue;
                colorDialog.ShowDialog();
        }
    }
}

Note that the beauty of this is that any name changes will be caught by the compiler. If you index with a text name that changes, or that you capitalize incorrectly, you're bound for runtime issues. Here you actually use the name of an object, that the designer creates based on the name you supplied. But any mismatch will be brought to your attention by the compiler.

Regex for Comma delimited list

This regex extracts an element from a comma separated list, regardless of contents:

(.+?)(?:,|$)

If you just replace the comma with something else, it should work for any delimiter.

SQL Server 2000: How to exit a stored procedure?

Put it in a TRY/CATCH.

When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block

Reference: MSDN.

EDIT: This works for MSSQL 2005+, but I see that you now have clarified that you are working on MSSQL 2000. I'll leave this here for reference.

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

Python: BeautifulSoup - get an attribute value based on the name attribute

theharshest answered the question but here is another way to do the same thing. Also, In your example you have NAME in caps and in your code you have name in lowercase.

s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)

attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}

print attributes_dictionary['class'][0]
# prints: question

print soup.find('div').get_text()
# prints: Hello World

How do you set a default value for a MySQL Datetime column?

You can use now() to set the value of a datetime column, but keep in mind that you can't use that as a default value.

JavaScript closures vs. anonymous functions

Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.

A simple explanation for closures:

  1. Take a function. Let's call it F.
  2. List all the variables of F.
  3. The variables may be of two types:
    1. Local variables (bound variables)
    2. Non-local variables (free variables)
  4. If F has no free variables then it cannot be a closure.
  5. If F has any free variables (which are defined in a parent scope of F) then:
    1. There must be only one parent scope of F to which a free variable is bound.
    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.
    3. That free variable is called an upvalue of the closure F.

Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):

Case 1: Your Friend's Program

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. i is a free variable.
    3. setTimeout is a free variable.
    4. g is a local variable.
    5. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. i is bound to the global scope.
    2. setTimeout is bound to the global scope.
    3. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence i is not closed over by f.
    2. Hence setTimeout is not closed over by f.
    3. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Bad for you: Your friend is using a closure. The inner function is a closure.

Case 2: Your Program

for (var i = 0; i < 10; i++) {
    setTimeout((function f(i2) {
        return function g() {
            console.log(i2);
        };
    })(i), 1000);
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. g is a local variable.
    3. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Good for you: You are using a closure. The inner function is a closure.

So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.

Edit: A simple explanation as to why are all functions closures (credits @Peter):

First let's consider the following program (it's the control):

_x000D_
_x000D_
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
    regularFunction();_x000D_
_x000D_
    function regularFunction() {_x000D_
        alert(eval("message"));_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.
  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).
  3. When we execute the program we observe that message is indeed alerted.

Next let's consider the following program (it's the alternative):

_x000D_
_x000D_
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
    return function closureFunction() {_x000D_
        alert(eval("message"));_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that only closureFunction is a closure from the above definition.
  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).
  3. When we execute the program we observe that message is actually being alerted.

What do we infer from this?

  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.
  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.
  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.

Is there a command for formatting HTML in the Atom editor?

  1. Go to "Packages" in atom editor.
  2. Then in "Packages" view choose "Settings View".
  3. Choose "Install Packages/Themes".
  4. Search for "Atom Beautify" and install it.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

MySQL: @variable vs. variable. What's the difference?

MySQL has a concept of user-defined variables.

They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.

They are prepended with an @ sign, like this: @var

You can initialize this variable with a SET statement or inside a query:

SET @var = 1

SELECT @var2 := 2

When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:

DELIMITER //

CREATE PROCEDURE prc_test (var INT)
BEGIN
    DECLARE  var2 INT;
    SET var2 = 1;
    SELECT  var2;
END;
//

DELIMITER ;

These variables are not prepended with any prefixes.

The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to NULL each time the procedure is called, while the session-specific variable is not:

CREATE PROCEDURE prc_test ()
BEGIN
    DECLARE var2 INT DEFAULT 1;
    SET var2 = var2 + 1;
    SET @var2 = @var2 + 1;
    SELECT  var2, @var2;
END;

SET @var2 = 1;

CALL prc_test();

var2  @var2
---   ---
2     2


CALL prc_test();

var2  @var2
---   ---
2     3


CALL prc_test();

var2  @var2
---   ---
2     4

As you can see, var2 (procedure variable) is reinitialized each time the procedure is called, while @var2 (session-specific variable) is not.

(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port or "session variables" such as @@session.sql_mode; these "session variables" are unrelated to session-specific user-defined variables.)

How to use youtube-dl from a python program?

It's not difficult and actually documented:

import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

How do I collapse a table row in Bootstrap?


problem is that the collapse item (div) is nested in the table elements. The div is hidden, the tr and td of the table are still visible and some css-styles are applied to them (border and padding).
Why are you using tables? Is there a reason for? When you dont´t have to use them, dont´use them :-)

How to return data from PHP to a jQuery ajax call

based on accepted answer

$output = some_function();
  echo $output;

if it results array then use json_encode it will result json array which is supportable by javascript

$output = some_function();
  echo json_encode($output);

If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword

$output = some_function();
  echo $output;
exit;

Class type check in TypeScript

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.

So you could use

mySprite instanceof Sprite;

Note that this operator is also in ActionScript but it shouldn't be used there anymore:

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript's instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

See also:

Is there a pure CSS way to make an input transparent?

input[type="text"]
{
    background: transparent;
    border: none;
}

Nobody will even know it's there.

Apache VirtualHost 403 Forbidden

This may be a permissions problem.

every single parent path to the virtual document root must be Readable, Writable, and Executable by the web server httpd user

according to this page about Apache 403 errors.

Since you're using Allow from all, your order shouldn't matter, but you might try switching it to Deny,Allow to set the default behavior to "allowing."

Escape string Python for MySQL

One other way to work around this is using something like this when using mysqlclient in python.

suppose the data you want to enter is like this <ol><li><strong style="background-color: rgb(255, 255, 0);">Saurav\'s List</strong></li></ol>. It contains both double qoute and single quote.

You can use the following method to escape the quotes:

statement = """ Update chats set html='{}' """.format(html_string.replace("'","\\\'"))

Note: three \ characters are needed to escape the single quote which is there in unformatted python string.

cmake and libpthread

The following should be clean (using find_package) and work (the find module is called FindThreads):

cmake_minimum_required (VERSION 2.6) 
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
        {
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Sunken);
            }
            else
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Raised);
            }
        }

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.

Counting number of characters in a file through shell script

This will do it:

wc -c filename

If you want only the count without the filename being repeated in the output:

wc -c < filename

Edit:

Use -m to count character instead of bytes (as shown in Sébastien's answer).

Add shadow to custom shape on Android

This is my version of a drop shadow. I was going for a hazy shadow all around the shape and used this answer by Joakim Lundborg as my starting point. What I changed is to add corners to all the shadow items and to increase the radius of the corner for each subsequent shadow item. So here is the xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#02000000" />
            <corners android:radius="8dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#05000000" />
            <corners android:radius="7dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10000000" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#15000000" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20000000" />
            <corners android:radius="4dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#25000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>

    <!-- Background -->
    <item>
    <shape>
            <solid android:color="#0099CC" />
        <corners android:radius="3dp" />
    </shape>
   </item>
</layer-list>

How to add message box with 'OK' button?

Since in your situation you only want to notify the user with a short and simple message, a Toast would make for a better user experience.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();

Update: A Snackbar is recommended now instead of a Toast for Material Design apps.

If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment. (The documentation currently recommends wrapping your AlertDialog in a fragment rather than calling it directly.)

Make a class that extends DialogFragment:

public class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("App Title");
        builder.setMessage("This is an alert with no consequence");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // You don't have to do anything here if you just 
                // want it dismissed when clicked
            }
        });

        // Create the AlertDialog object and return it
        return builder.create();
    }
}

Then call it when you need it in your activity:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");

See also

enter image description here

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

How to display a "busy" indicator with jQuery?

The jQuery documentation recommends doing something like the following:

$( document ).ajaxStart(function() {
  $( "#loading" ).show();
}).ajaxStop(function() {
  $( "#loading" ).hide();
});

Where #loading is the element with your busy indicator in it.

References:

Java system properties and environment variables

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);

Can we add div inside table above every <tr>?

"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page

For example:

<table>
    <tbody class="green">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
    <tbody class="blue">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
</table>

secondly, you can put "div" tag inside "td" tag.

<table>
    <tr>
        <td>
            <div></div>
        </td>
    </tr>
</table>

Further questions are always welcome.

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This works for me on a similar issue where I failed to delete the user due to the reference. Thank you

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})

Do I cast the result of malloc?

It depends on the programming language and compiler. If you use malloc in C, there is no need to type cast it, as it will automatically type cast. However, if you are using C++, then you should type cast because malloc will return a void* type.

Factory Pattern. When to use factory methods?

Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.

class Foo{
  public Foo(bool withBar);
}

is not as expressive as:

class Foo{
  public static Foo withBar();
  public static Foo withoutBar();
}

Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc.

Does the join order matter in SQL?

Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).

The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.

The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.

When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order

What is a plain English explanation of "Big O" notation?

Big O describes an upper limit on the growth behaviour of a function, for example the runtime of a program, when inputs become large.

Examples:

  • O(n): If I double the input size the runtime doubles

  • O(n2): If the input size doubles the runtime quadruples

  • O(log n): If the input size doubles the runtime increases by one

  • O(2n): If the input size increases by one, the runtime doubles

The input size is usually the space in bits needed to represent the input.

Store output of subprocess.Popen call in a string

This was perfect for me. You will get the return code, stdout and stderr in a tuple.

from subprocess import Popen, PIPE

def console(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    out, err = p.communicate()
    return (p.returncode, out, err)

For Example:

result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]

How do you move a file?

Since you're using Tortoise you may want to check out this link on LosTechies. It should be almost exactly what you are looking for.

http://www.lostechies.com/blogs/joshua_lockwood/archive/2007/09/12/subversion-tip-of-the-day-moving-files.aspx

How to set the JSTL variable value in javascript?

As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself. Best ways are here. To display user name, if u have html like

<div id="uName"></div>

You can display user name as follows.

var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;

To get data from jstl to your javascript :

var userName = '<c:out value="${user}"/>';

here ${user} is the data you get as response(from backend).

Asigning number/array length

var arrayLength = <c:out value="${details.size()}"/>;

Advanced

function advanced(){
    var values = new Array();
    <c:if test="${empty details.users}">
       values.push("No user found"); 
    </c:if>         

    <c:if test="${!empty details.users}">
        <c:forEach var="user" items="${details.users}" varStatus="stat">
            values.push("${user.name}");   
        </c:forEach>
    </:c:if>
    alert("values[0] "+values[0]);

}); 

Bootstrap Datepicker - Months and Years Only

Why not call the $('.input-group.date').datepicker("remove"); when the select statement is changed then set your datepicker view then call the $('.input-group.date').datepicker("update");

1 = false and 0 = true?

It may very well be a mistake on the original author, however the notion that 1 is true and 0 is false is not a universal concept. In shell scripting 0 is returned for success, and any other number for failure. In other languages such as Ruby, only nil and false are considered false, and any other value is considered true, so in Ruby both 1 and 0 would be considered true.

PHP cURL error code 60

@Overflowh I tried the above answer also with no luck. I changed php version from 5.3.24 to 5.5.8 as this setting will only work in php 5.3.7 and above. I then found this http://flwebsites.biz/posts/how-fix-curl-error-60-ssl-issue I downloaded the cacert.pem from there and replaced the one I had download/made from curl.hxxx.se linked above and it all started working. I was trying to get paypal sandbox IPN to verify. Happy to say after the .pem swap all is ok using curl.cainfo setting in php.ini which still was not in 5.3.24.

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

Z=np.array([1.0,1.0,1.0,1.0])  

def func(TempLake,Z):
    A=TempLake
    B=Z
    return A*B
Nlayers=Z.size
N=3
TempLake=np.zeros((N+1,Nlayers))
kOUT=np.vectorize(func)(TempLake,Z)

This works too , instead of looping , just vectorize however read below notes from the scipy documentation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.

Github permission denied: ssh add agent has no identities

For my mac Big Sur, with gist from answers above, following steps work for me.

$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa

And added ssh public key to git hub by following instruction;

https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

If all gone well, you should be able to get the following result;

$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

My solution is a mix of several answers here.

I checked the build server, and Windows7/NET4.0 SDK was already installed, so I did find the path:

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets`

However, on this line:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" />

$(MSBuildExtensionsPath) expands to C:\Program Files\MSBuild which does not have the path.

Therefore what I did was to create a symlink, using this command:

mklink /J "C:\Program Files\MSBuild\Microsoft\VisualStudio" "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio"

This way the $(MSBuildExtensionsPath) expands to a valid path, and no changes are needed in the app itself, only in the build server (perhaps one could create the symlink every build, to make sure this step is not lost and is "documented").

Using Java 8's Optional with Stream::flatMap

As my previous answer appeared not to be very popular, I will give this another go.

A short answer:

You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:

things.stream()
      .map(this::resolve)
      .filter(Optional::isPresent)
      .findFirst()
      .flatMap( Function.identity() );

This will fit all your requirements:

  1. It will find first response that resolves to a nonempty Optional<Result>
  2. It calls this::resolve lazily as needed
  3. this::resolve will not be called after first non-empty result
  4. It will return Optional<Result>

Longer answer

The only modification compared to OP initial version was that I removed .map(Optional::get) before call to .findFirst() and added .flatMap(o -> o) as the last call in the chain.

This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.

You can't really go any shorter than this in Java.

The alternative snippet of code using the more conventional for loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:

  1. Calling this.resolve,
  2. filtering based on Optional.isPresent
  3. returning the result and
  4. some way of dealing with negative result (when nothing was found)

Just to prove that my solution works as advertised, I wrote a small test program:

public class StackOverflow {

    public static void main( String... args ) {
        try {
            final int integer = Stream.of( args )
                    .peek( s -> System.out.println( "Looking at " + s ) )
                    .map( StackOverflow::resolve )
                    .filter( Optional::isPresent )
                    .findFirst()
                    .flatMap( o -> o )
                    .orElseThrow( NoSuchElementException::new )
                    .intValue();

            System.out.println( "First integer found is " + integer );
        }
        catch ( NoSuchElementException e ) {
            System.out.println( "No integers provided!" );
        }
    }

    private static Optional<Integer> resolve( String string ) {
        try {
            return Optional.of( Integer.valueOf( string ) );
        }
        catch ( NumberFormatException e )
        {
            System.out.println( '"' + string + '"' + " is not an integer");
            return Optional.empty();
        }
    }

}

(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)

Executing this on a command line, I got the following results:

$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3

Creating Threads in python

You can use the target argument in the Thread constructor to directly pass in a function that gets called instead of run.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

Convert a timedelta to days, hours and minutes

If you have a datetime.timedelta value td, td.days already gives you the "days" you want. timedelta values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60

Version vs build in Xcode

Apple sort of rearranged/repurposed the fields.

Going forward, if you look on the Info tab for your Application Target, you should use the "Bundle versions string, short" as your Version (e.g., 3.4.0) and "Bundle version" as your Build (e.g., 500 or 1A500). If you don't see them both, you can add them. Those will map to the proper Version and Build textboxes on the Summary tab; they are the same values.

When viewing the Info tab, if you right-click and select Show Raw Keys/Values, you'll see the actual names are CFBundleShortVersionString (Version) and CFBundleVersion (Build).

The Version is usually used how you appear to have been using it with Xcode 3. I'm not sure on what level you're asking about the Version/Build difference, so I'll answer it philosophically.

There are all sorts of schemes, but a popular one is:

{MajorVersion}.{MinorVersion}.{Revision}

  • Major version - Major changes, redesigns, and functionality changes
  • Minor version - Minor improvements, additions to functionality
  • Revision - A patch number for bug-fixes

Then the Build is used separately to indicate the total number of builds for a release or for the entire product lifetime.

Many developers start the Build number at 0, and every time they build they increase the number by one, increasing forever. In my projects, I have a script that automatically increases the build number every time I build. See instructions for that below.

  • Release 1.0.0 might be build 542. It took 542 builds to get to a 1.0.0 release.
  • Release 1.0.1 might be build 578.
  • Release 1.1.0 might be build 694.
  • Release 2.0.0 might be build 949.

Other developers, including Apple, have a Build number comprised of a major version + minor version + number of builds for the release. These are the actual software version numbers, as opposed to the values used for marketing.

If you go to Xcode menu > About Xcode, you'll see the Version and Build numbers. If you hit the More Info... button you'll see a bunch of different versions. Since the More Info... button was removed in Xcode 5, this information is also available from the Software > Developer section of the System Information app, available by opening Apple menu > About This Mac > System Report....

For example, Xcode 4.2 (4C139). Marketing version 4.2 is Build major version 4, Build minor version C, and Build number 139. The next release (presumably 4.3) will likely be Build release 4D, and the Build number will start over at 0 and increment from there.

The iPhone Simulator Version/Build numbers are the same way, as are iPhones, Macs, etc.

  • 3.2: (7W367a)
  • 4.0: (8A400)
  • 4.1: (8B117)
  • 4.2: (8C134)
  • 4.3: (8H7)

Update: By request, here are the steps to create a script that runs each time you build your app in Xcode to read the Build number, increment it, and write it back to the app's {App}-Info.plist file. There are optional, additional steps if you want to write your version/build numbers to your Settings.bundle/Root*.plist file(s).

This is extended from the how-to article here.

In Xcode 4.2 - 5.0:

  1. Load your Xcode project.
  2. In the left hand pane, click on your project at the very top of the hierarchy. This will load the project settings editor.
  3. On the left-hand side of the center window pane, click on your app under the TARGETS heading. You will need to configure this setup for each project target.
  4. Select the Build Phases tab.
    • In Xcode 4, at the bottom right, click the Add Build Phase button and select Add Run Script.
    • In Xcode 5, select Editor menu > Add Build Phase > Add Run Script Build Phase.
  5. Drag-and-drop the new Run Script phase to move it to just before the Copy Bundle Resources phase (when the app-info.plist file will be bundled with your app).
  6. In the new Run Script phase, set Shell: /bin/bash.
  7. Copy and paste the following into the script area for integer build numbers:

    buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
    buildNumber=$(($buildNumber + 1))
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
    

    As @Bdebeez pointed out, the Apple Generic Versioning Tool (agvtool) is also available. If you prefer to use it instead, then there are a couple things to change first:

    • Select the Build Settings tab.
    • Under the Versioning section, set the Current Project Version to the initial build number you want to use, e.g., 1.
    • Back on the Build Phases tab, drag-and-drop your Run Script phase after the Copy Bundle Resources phase to avoid a race condition when trying to both build and update the source file that includes your build number.

    Note that with the agvtool method you may still periodically get failed/canceled builds with no errors. For this reason, I don't recommend using agvtool with this script.

    Nevertheless, in your Run Script phase, you can use the following script:

    "${DEVELOPER_BIN_DIR}/agvtool" next-version -all
    

    The next-version argument increments the build number (bump is also an alias for the same thing), and -all updates Info.plist with the new build number.

  8. And if you have a Settings bundle where you show the Version and Build, you can add the following to the end of the script to update the version and build. Note: Change the PreferenceSpecifiers values to match your settings. PreferenceSpecifiers:2 means look at the item at index 2 under the PreferenceSpecifiers array in your plist file, so for a 0-based index, that's the 3rd preference setting in the array.

    productVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
    

    If you're using agvtool instead of reading the Info.plist directly, you can add the following to your script instead:

    buildNumber=$("${DEVELOPER_BIN_DIR}/agvtool" what-version -terse)
    productVersion=$("${DEVELOPER_BIN_DIR}/agvtool" what-marketing-version -terse1)
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
    
  9. And if you have a universal app for iPad & iPhone, then you can also set the settings for the iPhone file:

    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root~iphone.plist    
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root~iphone.plist
    

Add space between HTML elements only using CSS

add these rules to the parent container:

display: grid
grid-auto-flow: column
grid-column-gap: 10px

Good reference: https://cssreference.io/

Browser compatibility: https://gridbyexample.com/browsers/

Expanding a parent <div> to the height of its children

Where We’re Starting From

Here’s some boilerplate HTML and CSS. In our example, we have a parent element with two floated child elements.

_x000D_
_x000D_
/* The CSS you're starting with may look similar to this._x000D_
 * This doesn't solve our problem yet, but we'll get there shortly._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
<!-- The HTML you're starting with might look similar to this -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Solution #1: overflow: auto

A solution that works in all modern browsers and in Internet Explorer back to IE8 is to add overflow: auto to the parent element. This also works in IE7, with scrollbars added.

_x000D_
_x000D_
/* Our Modified CSS._x000D_
 * This is one way we can solve our problem._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
  overflow: auto;_x000D_
  /*This is what we added!*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Solution #2: Float Parent Container

Another solution that works in all modern browsers and back to IE7 is to float the parent container.

This may not always be practical, because floating your parent div may affect other parts of your page layout.

_x000D_
_x000D_
/* Modified CSS #2._x000D_
 * Floating parent div._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  float: left;_x000D_
  /*Added*/_x000D_
  height: auto;_x000D_
  width: 100%;_x000D_
  /*Added*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Method #3: Add Clearing Div Below Floated Elements

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #3._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clear {_x000D_
  clear: both;_x000D_
}
_x000D_
<!-- Solution 3, Add a clearing div to bottom of parent element -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Method #4: Add Clearing Div To The Parent Element This solution is pretty bulletproof for older browsers and newer browsers alike.

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #4._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clearfix {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.clearfix:after {_x000D_
  clear: both;_x000D_
  content: "";_x000D_
  display: table;_x000D_
}
_x000D_
<!-- Solution 4, make parent element self-clearing -->_x000D_
<div class="containing-div clearfix">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

from https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/

milliseconds to time in javascript

var secondsToTime = function(duration) {
  var date = new Date(duration);

  return "%hours:%minutes:%seconds:%milliseconds"
    .replace('%hours', date.getHours())
    .replace('%minutes', date.getMinutes())
    .replace('%seconds', date.getSeconds())
    .replace('%milliseconds', date.getMilliseconds());
}

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Paste text on Android Emulator

On Linux this will paste text directly from the clipboard

adb shell input text "'$(xclip -selection c -o)'"

Also it very useful to create global keyboard shortkey with this command for example Ctrl+Shift+Super+V

How to get an enum value from a string value in Java?

Another utility capturing in reverse way. Using a value which identify that Enum, not from its name.

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.EnumSet;

public class EnumUtil {

    /**
     * Returns the <code>Enum</code> of type <code>enumType</code> whose a 
     * public method return value of this Enum is 
     * equal to <code>valor</code>.<br/>
     * Such method should be unique public, not final and static method 
     * declared in Enum.
     * In case of more than one method in match those conditions
     * its first one will be chosen.
     * 
     * @param enumType
     * @param value
     * @return 
     */
    public static <E extends Enum<E>> E from(Class<E> enumType, Object value) {
        String methodName = getMethodIdentifier(enumType);
        return from(enumType, value, methodName);
    }

    /**
     * Returns the <code>Enum</code> of type <code>enumType</code> whose  
     * public method <code>methodName</code> return is 
     * equal to <code>value</code>.<br/>
     *
     * @param enumType
     * @param value
     * @param methodName
     * @return
     */
    public static <E extends Enum<E>> E from(Class<E> enumType, Object value, String methodName) {
        EnumSet<E> enumSet = EnumSet.allOf(enumType);
        for (E en : enumSet) {
            try {
                String invoke = enumType.getMethod(methodName).invoke(en).toString();
                if (invoke.equals(value.toString())) {
                    return en;
                }
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    private static String getMethodIdentifier(Class<?> enumType) {
        Method[] methods = enumType.getDeclaredMethods();
        String name = null;
        for (Method method : methods) {
            int mod = method.getModifiers();
            if (Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
                name = method.getName();
                break;
            }
        }
        return name;
    }
}

Example:

public enum Foo {
    ONE("eins"), TWO("zwei"), THREE("drei");

    private String value;

    private Foo(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

EnumUtil.from(Foo.class, "drei") returns Foo.THREE, because it will use getValue to match "drei", which is unique public, not final and not static method in Foo. In case Foo has more than on public, not final and not static method, for example, getTranslate which returns "drei", the other method can be used: EnumUtil.from(Foo.class, "drei", "getTranslate").

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I had a similar problem, you gotta make sure you have:

  1. oracle instant client
  2. cx_Oracle binary( from SourceForge )
  3. Python IMPORTANT: Make sure they are ALL either 64-bit or 32-bit, mixing is gonna cause problems

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

What are the differences between char literals '\n' and '\r' in Java?

On the command line, \r will move the cursor back to the beginning of the current line. To see the difference you must run your code from a command prompt. Eclipse's console show similar output for both the expression. For complete list of escape sequences, click here https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6

Node / Express: EADDRINUSE, Address already in use - Kill server

delete undefined file in your project root directory (which created on app crash)

How to logout and redirect to login page using Laravel 5.4?

if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:

$auth = new LoginController();
$auth->logout($request);

Complete File:

namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
    public function handle($request, Closure $next){
        $user = Auth::guard()->user();
        if( $user->role == 3 ) {
            $auth = new LoginController();
            $auth->logout($request);
            header("Location: https://google.com");
            die();
        } 
        return $next($request);
    }
}

What are the best practices for using a GUID as a primary key, specifically regarding performance?

GUIDs may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.

You really need to keep two issues apart:

  1. the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.

  2. the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option.

By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! I've personally seen massive performance gains when breaking up the previous GUID-based Primary / Clustered Key into two separate key - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1) column.

As Kimberly Tripp - the Queen of Indexing - and others have stated a great many times - a GUID as the clustering key isn't optimal, since due to its randomness, it will lead to massive page and index fragmentation and to generally bad performance.

Yes, I know - there's newsequentialid() in SQL Server 2005 and up - but even that is not truly and fully sequential and thus also suffers from the same problems as the GUID - just a bit less prominently so.

Then there's another issue to consider: the clustering key on a table will be added to each and every entry on each and every non-clustered index on your table as well - thus you really want to make sure it's as small as possible. Typically, an INT with 2+ billion rows should be sufficient for the vast majority of tables - and compared to a GUID as the clustering key, you can save yourself hundreds of megabytes of storage on disk and in server memory.

Quick calculation - using INT vs. GUID as Primary and Clustering Key:

  • Base Table with 1'000'000 rows (3.8 MB vs. 15.26 MB)
  • 6 nonclustered indexes (22.89 MB vs. 91.55 MB)

TOTAL: 25 MB vs. 106 MB - and that's just on a single table!

Some more food for thought - excellent stuff by Kimberly Tripp - read it, read it again, digest it! It's the SQL Server indexing gospel, really.

PS: of course, if you're dealing with just a few hundred or a few thousand rows - most of these arguments won't really have much of an impact on you. However: if you get into the tens or hundreds of thousands of rows, or you start counting in millions - then those points become very crucial and very important to understand.

Update: if you want to have your PKGUID column as your primary key (but not your clustering key), and another column MYINT (INT IDENTITY) as your clustering key - use this:

CREATE TABLE dbo.MyTable
(PKGUID UNIQUEIDENTIFIER NOT NULL,
 MyINT INT IDENTITY(1,1) NOT NULL,
 .... add more columns as needed ...... )

ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY NONCLUSTERED (PKGUID)

CREATE UNIQUE CLUSTERED INDEX CIX_MyTable ON dbo.MyTable(MyINT)

Basically: you just have to explicitly tell the PRIMARY KEY constraint that it's NONCLUSTERED (otherwise it's created as your clustered index, by default) - and then you create a second index that's defined as CLUSTERED

This will work - and it's a valid option if you have an existing system that needs to be "re-engineered" for performance. For a new system, if you start from scratch, and you're not in a replication scenario, then I'd always pick ID INT IDENTITY(1,1) as my clustered primary key - much more efficient than anything else!

How to print table using Javascript?

You can also use a jQuery plugin to do that

jQuery PrintPage plugin

Demo

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

How to select a CRAN mirror in R

I had, on macOS, the exact thing that you say: A 'please select' prompt and then nothing more.

After I opened (and updated; don't know if that was relevant) X-Quartz, and then restarted R and tried again, I got an X-window list of mirrors to choose from after a few seconds. It was faster the third time onwards.

$("#form1").validate is not a function

youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.

Regex to validate JSON

A trailing comma in a JSON array caused my Perl 5.16 to hang, possibly because it kept backtracking. I had to add a backtrack-terminating directive:

(?<json>   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) )(*PRUNE) \s* )
                                                                                   ^^^^^^^^

This way, once it identifies a construct that is not 'optional' (* or ?), it shouldn't try backtracking over it to try to identify it as something else.

How do you use window.postMessage across domains?

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'A');
        </script>
    </body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
    <iframe src="B"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

A and B must be something like http://domain.com

EDIT:

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

How do I encode/decode HTML entities in Ruby?

You can use htmlascii gem:

Htmlascii.convert string

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

Programmatically check Play Store for app updates

enter image description here

Google has introduced in-app updates API

The API currently supports two flows:

  • The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.
  • The “flexible flow” allows users to download the update while continuing to use your app.

Execute command without keeping it in history

This command might come in handy. This will not record the command that is executed

history -d $((HISTCMD-1)) && <Your Command Here>

How to kill/stop a long SQL query immediately?

  1. First, you need to display/check all running queries using below query-

    SELECT text, GETDATE(), *
    FROM sys.dm_exec_requests
    CROSS APPLY sys.dm_exec_sql_text(sql_handle)
    
  2. Find Session-Id and Description for respective all running queries and then copy specific query's Session-Id which you want to kill/stop immediately.

  3. Kill/stop specific query using Session-Id using this query:

    Kill Session-id
    

    Example:

    kill 125 --125 is my Session-Id
    

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

if condition in sql server update query

Since you're using SQL 2008:

UPDATE
    table_Name

SET
    column_A  
     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

    column_B  
     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
WHERE
    ID = @ID

If you were using SQL 2012:

UPDATE
    table_Name
SET
    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
    ID = @ID

Google Maps API v3 adding an InfoWindow to each marker

Hey everyone. I don't know if this is the optimal solution but I figured I'd post it here to hopefully help people out in the future. Please comment if you see anything that should be changed.

My for loops is now:

for (var i in tracks[racer_id].data.points) {
    values = tracks[racer_id].data.points[i];                
    point = new google.maps.LatLng(values.lat, values.lng);
    if (values.qst) {
        tracks[racer_id].markers[i] = add_marker(racer_id, point, '<b>Speed:</b> ' + values.inst + ' knots<br /><b>Invalid:</b> <input type="button" value="Yes" /> <input type="button" value="No" />');
    }
    track_coordinates.push(point);
    bd.extend(point);
}

And add_marker is defined as:

var info_window = new google.maps.InfoWindow({content: ''});

function add_marker(racer_id, point, note) {
    var marker = new google.maps.Marker({map: map, position: point, clickable: true});
    marker.note = note;
    google.maps.event.addListener(marker, 'click', function() {
        info_window.content = marker.note;
        info_window.open(map, marker);
    });
    return marker;
}

You can use info_window.close() to turn off the info_window at any time. Hope this helps someone.

Wrap a text within only two lines inside div

I believe the CSS-only solution text-overflow: ellipsis applies to one line only, so you won't be able to go this route:

.yourdiv {

    line-height: 1.5em; /* Sets line height to 1.5 times text size */
    height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
    width: 100%; /* Use whatever width you want */
    white-space: normal; /* Wrap lines of text */
    overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
    text-overflow: ellipsis; /* Ellipses (cross-browser) */
    -o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}

Have you tried http://tpgblog.com/threedots/ for jQuery?

TypeError: ObjectId('') is not JSON serializable

You should define you own JSONEncoder and using it:

import json
from bson import ObjectId

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)

JSONEncoder().encode(analytics)

It's also possible to use it in the following way.

json.encode(analytics, cls=JSONEncoder)

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

Best way to remove from NSMutableArray while iterating?

In a more declarative way, depending on the criteria matching the items to remove you could use:

[theArray filterUsingPredicate:aPredicate]

@Nathan should be very efficient

addClass and removeClass in jQuery - not removing class

What happens is that your close button is placed inside your .clickable div, so the click event will be triggered in both elements.

The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button callback will be executed first, and when .clickable is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.

                    / \
--------------------| |-----------------
| .clickable        | |                |
|   ----------------| |-----------     |
|   | .close_button | |          |     |
|   ------------------------------     |
|             event bubbling           |
----------------------------------------

To prevent your event from reaching .clickable, you need to add the event parameter to your callback function and then call the stopPropagation method on it.

$(".close_button").click(function (e) { 
    $("#spot1").addClass("spot");
    $("#spot1").removeClass("grown");
    e.stopPropagation();
});

Fiddle: http://jsfiddle.net/u4GCk/1/

More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])

How to get file name from file path in android

Old thread but thought I would update;

 File theFile = .......
 String theName = theFile.getName();  // Get the file name
 String thePath = theFile.getAbsolutePath(); // Get the full

More info can be found here; Android File Class

How to check that a string is parseable to a double?

You can always wrap Double.parseDouble() in a try catch block.

try
{
  Double.parseDouble(number);
}
catch(NumberFormatException e)
{
  //not a double
}

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

Angular2 Material Dialog css, dialog size

I think you need to use /deep/, because your CSS may not see your modal class. For example, if you want to customize .modal-dialog

/deep/.modal-dialog {
  width: 75% !important;
}

But this code will modify all your modal-windows, better solution will be

:host {
  /deep/.modal-dialog {
  width: 75% !important;
  }
}

MongoDB vs Firebase

Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.

What's the advantage of using Firebase over MongoDB?

You can take advantage of all built-in features of Firebase over MongoDB.

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

How to make the checkbox unchecked by default always

No, there is no way in simple HTML. Javascript might be your only solution at this time..

Loop through all checkboxes in javascript and set them to unchecked:

var checkboxes = document.getElementsByTagName('input');

for (var i=0; i<checkboxes.length; i++)  {
  if (checkboxes[i].type == 'checkbox')   {
    checkboxes[i].checked = false;
  }
}

wrap it up in a onload listener and you should be fine then :)

Best way to reset an Oracle sequence to the next value in an existing column?

In my case I have a sequence called PS_LOG_SEQ which had a LAST_NUMBER = 3920.

I then imported some data from PROD to my local machine and inserted into the PS_LOG table. Production data had more than 20000 rows with the latest LOG_ID (primary key) being 20070. After importing I tried to insert new rows in this table but when saving I got an exception like this one:

ORA-00001: unique constraint (LOG.PS_LOG_PK) violated

Surely this has to do with the Sequence PS_LOG_SEQ associated with the PS_LOG table. The LAST_NUMBER was colliding with data I imported which had already used the next ID value from the PS_LOG_SEQ.

To solve that I used this command to update the sequence to the latest \ max(LOG_ID) + 1:

alter sequence PS_LOG_SEQ restart start with 20071;

This command reset the LAST_NUMBER value and I could then insert new rows into the table. No more collision. :)

Note: this alter sequence command is new in Oracle 12c.

Note: this blog post documents the ALTER SEQUENCE RESTART option does exist, but as of 18c, is not documented. Its apparently intended for internal Oracle use.

Swing vs JavaFx for desktop applications

What will be cleaner and easier to maintain?

All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on how the code is written rather than what library is used to write it.

And what will be faster to build from scratch?

Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.

One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.

Personally, I see JavaFX as the "up and coming" UI library that's not quite there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)

Can't clone a github repo on Linux via HTTPS

I was able to get a git 1.7.1 to work after quite some time.

First, I had to do disable SSL just so I could pull:

git config --global http.sslverify false

Then I could clone

git clone https://github.com/USERNAME/PROJECTNAME.git

Then after adding and committing i was UNABLE to push back. So i did

git remote -v

origin  https://github.com/USERNAME/PROJECTNAME.git (fetch)
origin  https://github.com/USERNAME/PROJECTNAME.git (push)

to see the pull and push adresses:

These must be modified with USERNAME@

git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

It will still prompt you for a password, which you could add with

USERNAME:PASSWORD@github.....

But dont do that, as you save your password in cleartext for easy theft.

I had to do this combination since I could not get SSH to work due to firewall limitations.

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Can I open a dropdownlist using jQuery

It is not possible for javascript to "click" on an element (u can trigger the attached onclick event, but you can't literally click it)

To view all the items in the list, make the list a multiple list and increase its size, like such:

<select id="countries" multiple="multiple" size="10">
<option value="1">Country</option>
</select>

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

No content to map due to end-of-input jackson parser

The problem for me was that I read the response twice as follows:

System.out.println(response.body().string());
getSucherResponse = objectMapper.readValue(response.body().string(), GetSucherResponse.class);

However, the response can only be read once as it is a stream.

jQuery Datepicker onchange event issue

Manual says:

apply.daterangepicker: Triggered when the apply button is clicked, or when a predefined range is clicked

So:

$('#daterange').daterangepicker({
  locale: { cancelLabel: 'Clear' }  
});

$('#daterange').on('apply.daterangepicker', function() {
  alert('worked!');
});

Works for me.

How to parseInt in Angular.js

This are to way to bind add too numbers

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
  return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Download files from SFTP with SSH.NET library

My version of @Merak Marey's Code. I am checking if files exist already and different download directories for .txt and other files

        static void DownloadAll()
    {
        string host = "xxx.xxx.xxx.xxx";
        string username = "@@@";
        string password = "123";string remoteDirectory = "/IN/";
        string finalDir = "";
        string localDirectory = @"C:\filesDN\";
        string localDirectoryZip = @"C:\filesDN\ZIP\";
        using (var sftp = new SftpClient(host, username, password))
        {
            Console.WriteLine("Connecting to " + host + " as " + username);
            sftp.Connect();
            Console.WriteLine("Connected!");
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {

                string remoteFileName = file.Name;

                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today)))
                { 

                    if (!file.Name.Contains(".TXT"))
                    {
                        finalDir = localDirectoryZip;
                    } 
                    else 
                    {
                        finalDir = localDirectory;
                    }


                    if (File.Exists(finalDir  + file.Name))
                    {
                        Console.WriteLine("File " + file.Name + " Exists");
                    }else{
                        Console.WriteLine("Downloading file: " + file.Name);
                          using (Stream file1 = File.OpenWrite(finalDir + remoteFileName))
                    {
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
                    }
                }
            }



            Console.ReadLine();

        }

Python def function: How do you specify the end of the function?

In my opinion, it's better to explicitly mark the end of the function by comment

def func():
     # funcbody
     ## end of subroutine func ##

The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Git push error: "origin does not appear to be a git repository"

To resolving this problem.I just create a new folder and put some new files.Then use these commond.

* git add .
* git commit 
* git remote add master `your address`

then it tells me to login in. To input your username and password. after that

git pull 
git push origin master

finished you have pushed your code to your github

Changes in import statement python3

Relative import happens whenever you are importing a package relative to the current script/package.

Consider the following tree for example:

mypkg
+-- base.py
+-- derived.py

Now, your derived.py requires something from base.py. In Python 2, you could do it like this (in derived.py):

from base import BaseThing

Python 3 no longer supports that since it's not explicit whether you want the 'relative' or 'absolute' base. In other words, if there was a Python package named base installed in the system, you'd get the wrong one.

Instead it requires you to use explicit imports which explicitly specify location of a module on a path-alike basis. Your derived.py would look like:

from .base import BaseThing

The leading . says 'import base from module directory'; in other words, .base maps to ./base.py.

Similarly, there is .. prefix which goes up the directory hierarchy like ../ (with ..mod mapping to ../mod.py), and then ... which goes two levels up (../../mod.py) and so on.

Please however note that the relative paths listed above were relative to directory where current module (derived.py) resides in, not the current working directory.


@BrenBarn has already explained the star import case. For completeness, I will have to say the same ;).

For example, you need to use a few math functions but you use them only in a single function. In Python 2 you were permitted to be semi-lazy:

def sin_degrees(x):
    from math import *
    return sin(degrees(x))

Note that it already triggers a warning in Python 2:

a.py:1: SyntaxWarning: import * only allowed at module level
  def sin_degrees(x):

In modern Python 2 code you should and in Python 3 you have to do either:

def sin_degrees(x):
    from math import sin, degrees
    return sin(degrees(x))

or:

from math import *

def sin_degrees(x):
    return sin(degrees(x))

Change the maximum upload file size

I had the same problem. I have tried three ways that were usually suggested:

  1. functions.php
  2. php.ini
  3. .htaccess

none if which solved my problem. I am using godaddy and came across a suggested solution which was:

  1. got to Web Hosting, then Manage
  2. Under Software select Select PHP version
  3. Select Switch to PHP Options found on the top right corner of the table in font color: blue
  4. On the bottom most part, you'll probably have upload_max_filesize = 2M
  5. Now, feel free to change it
  6. Be sure to click the Save button!
  7. Now go to your wp-admin panel, select Media then Add

Voila! Now you have a different max upload file size :)

How to count certain elements in array?

Here is an ES2017+ way to get the counts for all array items in O(N):

const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};

arr.forEach((el) => {
  counts[el] = counts[el] ? (counts[el] += 1) : 1;
});

You can also optionally sort the output:

const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);

console.log(countsSorted) for your example array:

[
  [ '2', 3 ],
  [ '1', 1 ],
  [ '3', 1 ],
  [ '5', 1 ],
  [ '8', 1 ],
  [ '9', 1 ]
]

How To Get Selected Value From UIPickerView

You can get it in the following manner:

NSInteger row;
NSArray *repeatPickerData;
UIPickerView *repeatPickerView;

row = [repeatPickerView selectedRowInComponent:0];
self.strPrintRepeat = [repeatPickerData objectAtIndex:row];

How do I convert Long to byte[] and back in java

Here's another way to convert byte[] to long using Java 8 or newer:

private static int bytesToInt(final byte[] bytes, final int offset) {
    assert offset + Integer.BYTES <= bytes.length;

    return (bytes[offset + Integer.BYTES - 1] & 0xFF) |
            (bytes[offset + Integer.BYTES - 2] & 0xFF) << Byte.SIZE |
            (bytes[offset + Integer.BYTES - 3] & 0xFF) << Byte.SIZE * 2 |
            (bytes[offset + Integer.BYTES - 4] & 0xFF) << Byte.SIZE * 3;
}

private static long bytesToLong(final byte[] bytes, final int offset) {
    return toUnsignedLong(bytesToInt(bytes, offset)) << Integer.SIZE |
            toUnsignedLong(bytesToInt(bytes, offset + Integer.BYTES));
}

Converting a long can be expressed as the high- and low-order bits of two integer values subject to a bitwise-OR. Note that the toUnsignedLong is from the Integer class and the first call to toUnsignedLong may be superfluous.

The opposite conversion can be unrolled as well, as others have mentioned.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

To follow up, I just ran into this as well. When I installed Node.js there was an option that said Add to PATH (Available After Restart). Seems like Windows just needs a restart to make things work.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

One option is to declare a default value for 'new_field':

new_field = models.CharField(max_length=140, default='DEFAULT VALUE')

another option is to declare 'new_field' as a nullable field:

new_field = models.CharField(max_length=140, null=True)

If you decide to accept 'new_field' as a nullable field you may want to accept 'no input' as valid input for 'new_field'. Then you have to add the blank=True statement as well:

new_field = models.CharField(max_length=140, blank=True, null=True)

Even with null=True and/or blank=True you can add a default value if necessary:

new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)

Error: EACCES: permission denied

A related issue:

Wasted 3 hours spanning several days.

On a AWS EC2 machine, below worked:

sudo chown -R $(whoami) /home/ubuntu/.cache
sudo chown -R $(whoami) /home/ubuntu/.config
sudo chown -R $(whoami) /home/ubuntu/.local
sudo chown -R $(whoami) /home/ubuntu/.npm
sudo chown -R $(whoami) /home/ubuntu/.pm2

Hope that helps.

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

break statement in "if else" - java

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

What are the differences between struct and class in C++?

There are 3 basic difference between structure and class

1St- memory are reserved for structure in stack memory (which is near to programming language )whether for class in stack memory are reserved for only reffrence and actual memory are reserved in heap memory.

2Nd - By default structure treat as a public whether class treat as a private .

3Rd- can't re -use code in structure but in class we can re-use same code in many time called inhertence

Warning: Cannot modify header information - headers already sent by ERROR

You are trying to send headers information after outputing content.

If you want to do this, look for output buffering.

Therefore, look to use ob_start();

How can I convert an HTML table to CSV?

Here's a ruby script that uses nokogiri -- http://nokogiri.rubyforge.org/nokogiri/

require 'nokogiri'

doc = Nokogiri::HTML(table_string)

doc.xpath('//table//tr').each do |row|
  row.xpath('td').each do |cell|
    print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
  end
  print "\n"
end

Worked for my basic test case.

MVC4 HTTP Error 403.14 - Forbidden

You can also get a 403 if when testing with dev server you are using integrated pipeline and then install as classic pipeline mode on your live IIS 7.5 web server, also I was missing my app_data folder which also was required

JavaFX Panel inside Panel auto resizing

Also see here

@FXML
private void mnuUserLevel_onClick(ActionEvent event) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("DBedit.fxml"));
    loader.setController(new DBeditEntityUserlevel());

    try {
           Node n = (Node)loader.load();
           AnchorPane.setTopAnchor(n, 0.0);
           AnchorPane.setRightAnchor(n, 0.0);
           AnchorPane.setLeftAnchor(n, 0.0);
           AnchorPane.setBottomAnchor(n, 0.0);
           mainContent.getChildren().setAll(n);
    } catch (IOException e){
           System.out.println(e.getMessage());
    }
}

The scenario is to load a child fxml into parent AnchorPane. To make the child to stretch in accords to its parent use AnChorPane.setxxxAnchor command.

Illegal mix of collations MySQL Error

SET collation_connection = 'utf8_general_ci';

then for your databases

ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci;

ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

MySQL sneaks swedish in there sometimes for no sensible reason.

Something like 'contains any' for Java set?

Use retainAll() in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

You could easily do this by using 4 easy steps

  1. backup your database, just incase
  2. change database collation: right click database, select properties, go to the options and change the collation to the required collation.
  3. Generate a script to Drop and Recreate all your database objects: right click your database, select tasks, select generate script... ( make sure you select Drop & Create on the Advanced options of the Wizard, Also select Schema & Data )
  4. Run the Script Generated above

Why is __dirname not defined in node REPL?

As @qiao said, you can't use __dirname in the node repl. However, if you need need this value in the console, you can use path.resolve() or path.dirname(). Although, path.dirname() will just give you a "." so, probably not that helpful. Be sure to require('path').

An example of how to use getopts in bash

I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.

Updated answer:

Save the file as getopt.sh:

#!/bin/bash

function get_variable_name_for_option {
    local OPT_DESC=${1}
    local OPTION=${2}
    local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")

    if [[ "${VAR}" == "${1}" ]]; then
        echo ""
    else
        echo ${VAR}
    fi
}

function parse_options {
    local OPT_DESC=${1}
    local INPUT=$(get_input_for_getopts "${OPT_DESC}")

    shift
    while getopts ${INPUT} OPTION ${@};
    do
        [ ${OPTION} == "?" ] && usage
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
            [ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
    done

    check_for_required "${OPT_DESC}"

}

function check_for_required {
    local OPT_DESC=${1}
    local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
    while test -n "${REQUIRED}"; do
        OPTION=${REQUIRED:0:1}
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
                [ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
        REQUIRED=${REQUIRED:1}
    done
}

function get_input_for_getopts {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}

function get_optional {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}

function get_required {
    local OPT_DESC=${1}
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}

function usage {
    printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
    exit 10
}

Then you can use it like this:

#!/bin/bash
#
# [ and ] defines optional arguments
#

# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}

echo ${USER}
echo ${START_DATE_TIME}

Old answer:

I recently needed to use a generic approach. I came across with this solution:

#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
#   OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
#   ~$ echo get_options ${OPT_DESC}
#   a:b:c
#   ~$
#


# Required options 
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"

# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"

function usage {
    IFS="|"
    printf "%s" ${0}
    for i in ${REQUIRED_DESC};
    do
        VARNAME=$(echo $i | sed -e "s/.*=>//g")
    printf " %s" "-${i:0:1} $VARNAME"
    done

    for i in ${OPTIONAL_DESC};
    do
        VARNAME=$(echo $i | sed -e "s/.*=>//g")
        printf " %s" "[-${i:0:1} $VARNAME]"
    done
    printf "\n"
    unset IFS
    exit
}

# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
#   $1: The options description (SEE TOP)
#
# Example:
#   OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#   OPTIONS=$(get_options ${OPT_DESC})
#   echo "${OPTIONS}"
#
# Output:
#   "h:f:PW"
function get_options {
    echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}

# Auxiliary function that returns all variable names separated by '|'
# Arguments:
#       $1: The options description (SEE TOP)
#
# Example:
#       OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#       VARNAMES=$(get_values ${OPT_DESC})
#       echo "${VARNAMES}"
#
# Output:
#       "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
    echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}

# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
#   $1: The options description (SEE TOP)
#   $2: The option which the variable name wants to be retrieved
#
# Example:
#   OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
#   H_VAR=$(get_variable_name ${OPT_DESC} "h")
#   echo "${H_VAR}"
#
# Output:
#   "H_VAR"
function get_variable_name {
    VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
    if [[ ${VAR} == ${1} ]]; then
        echo ""
    else
        echo ${VAR}
    fi
}

# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})

# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})

# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")

# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
    [[ ${OPTION} == ":" ]] && usage
    VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
    [[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done

shift $(($OPTIND - 1))

# Checks for required options. Report an error and exits if
# required options are missing.

# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
    [[ -v ${VARNAME} ]] || usage
done
unset IFS

# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
    VARNAME=$(echo $i | sed -e "s/.*=>//g")
    [[ -v ${VARNAME} ]] || usage
    printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}

I didn't test this roughly, so I could have some bugs in there.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

How to fix Error: laravel.log could not be opened?

In my particular case I had a config file generated and cached into the bootstrap/cache/ directory so my steps where:

  1. Remove all generated cached files: rm bootstrap/cache/*.php
  2. Create a new laravel.log file and apply the update of the permissions on the file using:

    • chmod -R 775 storage

How do servlets work? Instantiation, sessions, shared variables and multithreading

When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).

During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information

Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.

Q) In the lifetime of servlet how many times instantiation and initialization happens ??

A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).

Q)How session concept works?

A)whenever getSession() is called on HttpServletRequest object

Step 1: request object is evaluated for incoming session ID.

Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).

Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.

Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.

Note:

1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine

2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code

Inshort form:

A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.