Programs & Examples On #Fileopendialog

A User Interface (UI) that provides a dialog box, to open file(s). Also known as `OpenFileDialog`.

Angular 2 http post params and body

Yes the problem is here. It's related to your syntax.

Try using this

return this.http.post(this.BASE_URL, params, options)
  .map(data => this.handleData(data))
  .catch(this.handleError);

instead of

return this.http.post(this.BASE_URL, params, options)
  .map(this.handleData)
  .catch(this.handleError);

Also, the second parameter is supposed to be the body, not the url params.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

What is the { get; set; } syntax in C#?

Get set are access modifiers to property. Get reads the property field. Set sets the property value. Get is like Read-only access. Set is like Write-only access. To use the property as read write both get and set must be used.

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

How to use source: function()... and AJAX in JQuery UI autocomplete

On the .ASPX page:

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head id="Head1" runat="server">
        <title>AutoComplete Box with jQuery</title>
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
        <script type="text/javascript">
            $(document).ready(function() {
                SearchText();
            });
            function SearchText() {
                $(".autosuggest").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "Default.aspx/GetAutoCompleteData",
                            data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {

                                    response(data.d);
                                }
                            },
                            error: function(result) {
                                alert("Error");
                            }
                        });
                    }
                });
            }
        </script>
  </head>
  <body>
      <form id="form1" runat="server">
          <div class="demo">
           <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
       <input type="text" id="txtSearch" class="autosuggest" />
    </div>
        </form>
    </body>
    </html>    

In your .ASPX.CS code-behind file:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
            SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");

            SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
            con.Open();
                cmd.Parameters.AddWithValue("@Name", username);
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    result.Add(dr["Name"].ToString());
                }
                return result;
        }
}

How to get Toolbar from fragment?

In XML

 <androidx.appcompat.widget.Toolbar
  android:id="@+id/main_toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:layout_scrollFlags="scroll|enterAlways">
 </androidx.appcompat.widget.Toolbar>

Kotlin: In fragment.kt -> onCreateView()

setHasOptionsMenu(true)

val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)

(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)

(activity as? AppCompatActivity)?.supportActionBar?.show()

-> onCreateOptionsMenu()

   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.app_main_menu,menu)
       super.onCreateOptionsMenu(menu, inflater)
   }

->onOptionsItemSelected()

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.selected_id->{//to_do}
             else -> super.onOptionsItemSelected(item)
        }
    }

How to split page into 4 equal parts?

Some good answers here but just adding an approach that won't be affected by borders and padding:

<style type="text/css">
html, body{width: 100%; height: 100%; padding: 0; margin: 0}
div{position: absolute; padding: 1em; border: 1px solid #000}
#nw{background: #f09; top: 0; left: 0; right: 50%; bottom: 50%}
#ne{background: #f90; top: 0; left: 50%; right: 0; bottom: 50%}
#sw{background: #009; top: 50%; left: 0; right: 50%; bottom: 0}
#se{background: #090; top: 50%; left: 50%; right: 0; bottom: 0}
</style>

<div id="nw">test</div>
<div id="ne">test</div>
<div id="sw">test</div>
<div id="se">test</div>

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How can I connect to Android with ADB over TCP?

Use the adbwireless app to enable the phone, then use adb connect from the Windows machine to talk to it. The adbwireless app on the phone tells you how to connect to it, giving the IP address and everything.

The much less fun alternative is to connect via USB, tell the phone to use TCPIP via adb tcpip 5555, then disconnect USB, then use adb connect. This is much harder because this way you have to figure out the IP address of the phone yourself (adbwireless tells you the IP), you have to connect via USB, and you have to run adb tcpip (adbwireless takes care of that too).

So: install adbwireless on your phone. Use it. It is possible, I do it routinely on Linux and on Windows.

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Heres an example using: getDisplayMedia

document.body.innerHTML = '<video style="width: 100%; height: 100%; border: 1px black solid;"/>';

navigator.mediaDevices.getDisplayMedia()
.then( mediaStream => {
  const video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = e => {
    video.play();
    video.pause();
  };
})
.catch( err => console.log(`${err.name}: ${err.message}`));

Also worth checking out is the Screen Capture API docs.

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

Android: how to convert whole ImageView to Bitmap?

This is a working code

imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());

Name does not exist in the current context

"The project works on the laptop, but now having copied the updated source code onto the desktop ..."

I did something similar, creating two versions of a project and copying files between them. It gave me the same error.

My solution was to go into the project file, where I discovered that what had looked like this:

<Compile Include="App_Code\Common\Pair.cs" />
<Compile Include="App_Code\Common\QueryCommand.cs" />

Now looked like this:

<Content Include="App_Code\Common\Pair.cs">
  <SubType>Code</SubType>
</Content>
<Content Include="App_Code\Common\QueryCommand.cs">
  <SubType>Code</SubType>
</Content>

When I changed them back, Visual Studio was happy again.

How to get EditText value and display it on screen through TextView?

First get the text from edit text view

edittext.getText().toString()

and Store the obtained text in a string, say value.

value = edittext.getText().toString()

Then set value as the text for textview.

textview.setText(value)

Finding all possible combinations of numbers to reach a given sum

The solution of this problem has been given a million times on the Internet. The problem is called The coin changing problem. One can find solutions at http://rosettacode.org/wiki/Count_the_coins and mathematical model of it at http://jaqm.ro/issues/volume-5,issue-2/pdfs/patterson_harmel.pdf (or Google coin change problem).

By the way, the Scala solution by Tsagadai, is interesting. This example produces either 1 or 0. As a side effect, it lists on the console all possible solutions. It displays the solution, but fails making it usable in any way.

To be as useful as possible, the code should return a List[List[Int]]in order to allow getting the number of solution (length of the list of lists), the "best" solution (the shortest list), or all the possible solutions.

Here is an example. It is very inefficient, but it is easy to understand.

object Sum extends App {

  def sumCombinations(total: Int, numbers: List[Int]): List[List[Int]] = {

    def add(x: (Int, List[List[Int]]), y: (Int, List[List[Int]])): (Int, List[List[Int]]) = {
      (x._1 + y._1, x._2 ::: y._2)
    }

    def sumCombinations(resultAcc: List[List[Int]], sumAcc: List[Int], total: Int, numbers: List[Int]): (Int, List[List[Int]]) = {
      if (numbers.isEmpty || total < 0) {
        (0, resultAcc)
      } else if (total == 0) {
        (1, sumAcc :: resultAcc)
      } else {
        add(sumCombinations(resultAcc, sumAcc, total, numbers.tail), sumCombinations(resultAcc, numbers.head :: sumAcc, total - numbers.head, numbers))
      }
    }

    sumCombinations(Nil, Nil, total, numbers.sortWith(_ > _))._2
  }

  println(sumCombinations(15, List(1, 2, 5, 10)) mkString "\n")
}

When run, it displays:

List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2)
List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2)
List(1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2)
List(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2)
List(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)
List(1, 1, 1, 2, 2, 2, 2, 2, 2)
List(1, 2, 2, 2, 2, 2, 2, 2)
List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5)
List(1, 1, 1, 1, 1, 1, 1, 1, 2, 5)
List(1, 1, 1, 1, 1, 1, 2, 2, 5)
List(1, 1, 1, 1, 2, 2, 2, 5)
List(1, 1, 2, 2, 2, 2, 5)
List(2, 2, 2, 2, 2, 5)
List(1, 1, 1, 1, 1, 5, 5)
List(1, 1, 1, 2, 5, 5)
List(1, 2, 2, 5, 5)
List(5, 5, 5)
List(1, 1, 1, 1, 1, 10)
List(1, 1, 1, 2, 10)
List(1, 2, 2, 10)
List(5, 10)

The sumCombinations() function may be used by itself, and the result may be further analyzed to display the "best" solution (the shortest list), or the number of solutions (the number of lists).

Note that even like this, the requirements may not be fully satisfied. It might happen that the order of each list in the solution be significant. In such a case, each list would have to be duplicated as many time as there are combination of its elements. Or we might be interested only in the combinations that are different.

For example, we might consider that List(5, 10) should give two combinations: List(5, 10) and List(10, 5). For List(5, 5, 5) it could give three combinations or one only, depending on the requirements. For integers, the three permutations are equivalent, but if we are dealing with coins, like in the "coin changing problem", they are not.

Also not stated in the requirements is the question of whether each number (or coin) may be used only once or many times. We could (and we should!) generalize the problem to a list of lists of occurrences of each number. This translates in real life into "what are the possible ways to make an certain amount of money with a set of coins (and not a set of coin values)". The original problem is just a particular case of this one, where we have as many occurrences of each coin as needed to make the total amount with each single coin value.

What is the significance of 1/1/1753 in SQL Server?

1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.

An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)

How to convert string to binary?

a = list(input("Enter a string\t: "))
def fun(a):
    c =' '.join(['0'*(8-len(bin(ord(i))[2:]))+(bin(ord(i))[2:]) for i in a])
    return c
print(fun(a))

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

Using "super" in C++

I don't know whether it's rare or not, but I've certainly done the same thing.

As has been pointed out, the difficulty with making this part of the language itself is when a class makes use of multiple inheritance.

How to convert Nvarchar column to INT

I know its Too late But I hope it will work new comers Try This Its Working ... :D

select 
  case 
      when isnumeric(my_NvarcharColumn) = 1 then 
              cast(my_NvarcharColumn AS int)
      else
              NULL
 end

AS 'my_NvarcharColumnmitter'
from A

Angularjs dynamic ng-pattern validation

Used pattern :

 ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"

Used reference file:

 '<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>'

Example for Input:

 <input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">

Lollipop : draw behind statusBar with its color set to transparent

I will be adding some more information here. The latest Android developments have made it pretty easy to handle a lot of cases in status bar. Following are my observations from the styles.xml

  1. Background color: for SDK 21+, as a lot of answers mentioned,<item name="android:windowTranslucentStatus">true</item> will make the status bar transparent and show in front of UI. Your Activity will take the whole space of the top.
  2. Background color: again,for SDK 21+, <item name="android:statusBarColor">@color/your_color</item> will simply give a color to your status bar, without affecting anything else.

  3. However, in later devices (Android M/+), the icons started coming in different shades. The OS can give a darker shade of gray to the icons for SDK 23/+ , if you override your styles.xml file in values-23 folder and add <item name="android:windowLightStatusBar">true</item>.
    This way, you will be providing your user with a more visible status bar, if your status bar has a light color( think of how a lot of google apps have light background yet the icons are visible there in a greyish color).
    I would suggest you to use this, if you are giving color to your status bar via point #2

  4. In the most recent devices, SDK 29/+ comes with a system wide light and dark theme, controllable by the user. As devs, we are also supposed to override our style file in a new values-night folder, to give user 2 different experiences.
    Here again, I have found the point #2 to be effective in providing the "background color to status bar". But system was not changing the color of status bar icons for my app. since my day version of style consisted of lighter theme, this means that users will suffer from low visibility ( white icons on lighter background)
    This problem can be solved by using the point #3 approach or by overriding style file in values-29 folder and using a newer api <item name="android:enforceStatusBarContrast">true</item> . This will automatically enforce the grayish tint to icons, if your background color is too light.

Javamail Could not convert socket to TLS GMail

I got similar problem when default SSL protocol for sending emails was set to TLSv1 and smtp server was not supporting this protocol anymore. Trick was to use newer protocol:

mail.smtp.ssl.protocols=TLSv1.2

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

How can I "disable" zoom on a mobile web page?

Possible Solution for Web Apps: While zooming can not be disabled in iOS Safari anymore, it will be disabled when opening the site from a home screen shortcut.

Add these meta tags to declare your App as "Web App capable":

    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" >
    <meta name="apple-mobile-web-app-capable" content="yes" >

However only use this feature if your app is self sustaining, as the forward/backward buttons and URL bar as well as the sharing options are disabled. (You can still swipe left and right though) This approach however enables quite the app like ux. The fullscreen browser only starts when the site is loaded from the homescreen. I also only got it to work after I included an apple-touch-icon-180x180.png in my root folder.

As a bonus, you probably also want to include a variant of this as well:

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

HTML5 phone number validation with pattern

How about this? /(7|8|9)\d{9}/

It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.

C++ delete vector, objects, free memory

You can free memory used by vector by this way:

//Removes all elements in vector
v.clear()

//Frees the memory which is not used by the vector
v.shrink_to_fit();

How do I redirect output to a variable in shell?

You can do:

hash=$(genhash --use-ssl -s $IP -p 443 --url $URL)

or

hash=`genhash --use-ssl -s $IP -p 443 --url $URL`

If you want to result of the entire pipe to be assigned to the variable, you can use the entire pipeline in the above assignments.

What is the best way to initialize a JavaScript Date to midnight?

Just wanted to clarify that the snippet from accepted answer gives the nearest midnight in the past:

var d = new Date();
d.setHours(0,0,0,0); // last midnight

If you want to get the nearest midnight in future, use the following code:

var d = new Date();
d.setHours(24,0,0,0); // next midnight

How to get the last characters in a String in Java, regardless of String size

How about:

String numbers = text.substring(text.length() - 7);

That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:

String numbers = text.substring(Math.max(0, text.length() - 7));

or

String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7);

Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text is null.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I have a project that does this whenever I build with the View open. As soon as I closed the view, the error goes away and the build succeeds. Very strange.

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

You can give https://github.com/ersiner/osx-env-sync a try. It handles both command line and GUI apps from a single source and works withe the latest version of OS X (Yosemite).

You can use path substitutions and other shell tricks since what you write is regular bash script to be sourced by bash in the first place. No restrictions.. (Check osx-env-sync documentation and you'll understand how it achieves this.)

I answered a similar question here where you'll find more.

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

Preventing SQL injection in Node.js

The node-mysql library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values

How can I disable mod_security in .htaccess file?

It is possible to do this, but most likely your host implemented mod_security for a reason. Be sure they approve of you disabling it for your own site.

That said, this should do it;

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

How to randomize (or permute) a dataframe rowwise and columnwise?

Of course you can sample each row:

sapply (1:4, function (row) df1[row,]<<-sample(df1[row,]))

will shuffle the rows itself, so the number of 1's in each row doesn't change. Small changes and it also works great with columns, but this is a exercise for the reader :-P

.NET obfuscation tools/strategy

I've been obfuscating code in the same application since .Net 1, and it's been a major headache from a maintenance perspective. As you've mentioned, the serialization problem can be avoided, but it's really easy to make a mistake and obfuscate something you didn't want obfuscated. It's easy to break the build, or to change the obfuscation pattern and not be able to open old files. Plus it can be difficult to find out what went wrong and where.

Our choice was Xenocode, and were I to make the choice again today I would prefer to not obfuscate the code, or use Dotfuscator.

multiple conditions for JavaScript .includes() method

Here's a controversial option:

String.prototype.includesOneOf = function(arrayOfStrings) {
  if(!Array.isArray(arrayOfStrings)) {
    throw new Error('includesOneOf only accepts an array')
  }
  return arrayOfStrings.some(str => this.includes(str))
}

Allowing you to do things like:

'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True

Link to "pin it" on pinterest without generating a button

I Found some code for wordpress:

 <script type="text/javascript">

    function insert_pinterest($content) {
        global $post;
        $posturl = urlencode(get_permalink()); //Get the post URL
        $pinspan = '<span class="pinterest-button">';
     $pinurl = '';
     $pinend = '</span>';
        $pattern = '//i';
        $replacement = $pinspan.$pinurl.'$2.$3'.$pindescription.$pinfinish.''.$pinend;
        $content = preg_replace( $pattern, $replacement, $content );
        //Fix the link problem
        $newpattern = '/<span class="pinterest-button"><\/a><\/span><\/a>/i';
     $replacement = '';
     $content = preg_replace( $newpattern, $replacement, $content );
     return $content;
    }
    add_filter( 'the_content', 'insert_pinterest' );

    </script>

Then you put the following in your PHP:

<?php $pinterestimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $pinterestimage[0]; ?>&description=<?php the_title(); ?>">Pin It</a>

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

Float right and position absolute doesn't work together

Perhaps you should divide your content like such using floats:

<div style="overflow: auto;">
    <div style="float: left; width: 600px;">
        Here is my content!
    </div>
    <div style="float: right; width: 300px;">
        Here is my sidebar!
    </div>
</div>

Notice the overflow: auto;, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div to have an overflow: auto (or overflow: hidden) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.

How to get all groups that a user is a member of?

Almost all above solutions used the ActiveDirecotry module which might not be available by default in most cases.

I used below method. A bit indirect, but served my purpose.

List all available groups

Get-WmiObject -Class Win32_Group

And then list the groups the user belongs to

[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups

Comparison can then be done via checking through the SIDs. This works for the logged in user. Please correct me if I am wrong. Completely new to PowerShell, but had to get this done for a work commitment.

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

ImportError: No module named pip

After installing ez_setup, you should have easy_install available. To install pip just do:

easy_install pip

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

What order are the Junit @Before/@After called?

This isn't an answer to the tagline question, but it is an answer to the problems mentioned in the body of the question. Instead of using @Before or @After, look into using @org.junit.Rule because it gives you more flexibility. ExternalResource (as of 4.7) is the rule you will be most interested in if you are managing connections. Also, If you want guaranteed execution order of your rules use a RuleChain (as of 4.10). I believe all of these were available when this question was asked. Code example below is copied from ExternalResource's javadocs.

 public static class UsesExternalResource {
  Server myServer= new Server();

  @Rule
  public ExternalResource resource= new ExternalResource() {
      @Override
      protected void before() throws Throwable {
          myServer.connect();
         };

      @Override
      protected void after() {
          myServer.disconnect();
         };
     };

  @Test
  public void testFoo() {
      new Client().run(myServer);
     }
 }

Possible heap pollution via varargs parameter

@SafeVarargs does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.

http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.

Heap pollution is when you get a ClassCastException when doing an operation on a generic interface and it contains another type than declared.

How do I convert an integer to binary in JavaScript?

we can also calculate the binary for positive or negative numbers as below:

_x000D_
_x000D_
function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = n >>> 0;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
_x000D_
_x000D_

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Where is Ubuntu storing installed programs?

for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.

hope it helps

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

What is a unix command for deleting the first N characters of a line?

You can use cut:

cut -c N- file.txt > new_file.txt

-c: characters

file.txt: input file

new_file.txt: output file

N-: Characters from N to end to be cut and output to the new file.

Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.

This will perform the operation to each line of the input file.

Java: How to check if object is null?

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
    drawable = getRandomDrawable();
}

The equals() method checks for value equality, which means that it compares the contents of two objects. Since null is not an object, this crashes when trying to compare the contents of your object to the contents of null.

The == operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null references) are also equal.

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Recently I had same problem, but on Linux Server. Database was crashed, and I recovered it from backup, based on simply copying /var/lib/mysql/* (analog mysql DATA folder in wamp). After recovery I had to create new table and got mysql error #1146. I tried to restart mysql, and it said it could not start. I checked mysql logs, and found that mysql simply had no access rigths to its DB files. I checked owner info of /var/lib/mysql/*, and got 'myuser:myuser' (myuser is me). But it should be 'mysql:adm' (so is own developer machine), so I changed owner to 'mysql:adm'. And after this mysql started normally, and I could create tables, or do any other operations.

So after moving database files or restoring from backups check access rigths for mysql.

Hope this helps...

Angular CLI SASS options

For Angular 9.0 and above, update the "schematics":{} object in angular.json file like this:

"schematics": {
  "@schematics/angular:component": {
    "style": "scss"
  }
}

Valid to use <a> (anchor tag) without href attribute?

I think you can find your answer here : Is an anchor tag without the href attribute safe?

Also if you want to no link operation with href , you can use it like :

<a href="javascript:void(0);">something</a>

Access nested dictionary items via a list of keys?

You can make use of the eval function in python.

def nested_parse(nest, map_list):
    nestq = "nest['" + "']['".join(map_list) + "']"
    return eval(nestq, {'__builtins__':None}, {'nest':nest})

Explanation

For your example query: maplist = ["b", "v", "y"]

nestq will be "nest['b']['v']['y']" where nest is the nested dictionary.

The eval builtin function executes the given string. However, it is important to be careful about possible vulnerabilities that arise from use of eval function. Discussion can be found here:

  1. https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
  2. https://www.journaldev.com/22504/python-eval-function

In the nested_parse() function, I have made sure that no __builtins__ globals are available and only local variable that is available is the nest dictionary.

How to get folder path from file path with CMD

For the folder name and drive, you can use:

echo %~dp0

You can get a lot more information using different modifiers:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file

The modifiers can be combined to get compound results:
%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only

This is a copy paste from the "for /?" command on the prompt. Hope it helps.

Related

Top 10 DOS Batch tips (Yes, DOS Batch...) shows batchparams.bat (link to source as a gist):

C:\Temp>batchparams.bat c:\windows\notepad.exe
%~1     =      c:\windows\notepad.exe
%~f1     =      c:\WINDOWS\NOTEPAD.EXE
%~d1     =      c:
%~p1     =      \WINDOWS\
%~n1     =      NOTEPAD
%~x1     =      .EXE
%~s1     =      c:\WINDOWS\NOTEPAD.EXE
%~a1     =      --a------
%~t1     =      08/25/2005 01:50 AM
%~z1     =      17920
%~$PATHATH:1     =
%~dp1     =      c:\WINDOWS\
%~nx1     =      NOTEPAD.EXE
%~dp$PATH:1     =      c:\WINDOWS\
%~ftza1     =      --a------ 08/25/2005 01:50 AM 17920 c:\WINDOWS\NOTEPAD.EXE

Insert line break inside placeholder attribute of a textarea?

I don't like hiding the placeholder when you focus the textarea. So I made a constructor function Placeholder that looks exactly like the built-in placeholder and works also in other browsers than Google Chrome. It's very convenient because you can use the Placeholder function as often as you want and it doesn't even need jQuery.

EDIT:

It now also handles special cases, like inserting the placeholder, correctly.

_x000D_
_x000D_
var textarea = document.getElementById("textarea");_x000D_
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");_x000D_
_x000D_
function Placeholder(el, placeholder) {_x000D_
    if (el.value == "" || el.value == placeholder) {_x000D_
        el.style.color = "gray";_x000D_
        el.value = placeholder;_x000D_
        el._plc = true;_x000D_
        el.className += " unselectable";_x000D_
    }_x000D_
    function keyPress(e) {_x000D_
        window.setTimeout(function() {_x000D_
            var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");_x000D_
            _x000D_
            if (el.value == "") {_x000D_
                el.value = placeholder;_x000D_
                el.style.color = "gray";_x000D_
                cursorToStart(el);_x000D_
                el._plc = true;_x000D_
                el.className += " unselectable";_x000D_
            } else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {_x000D_
                el.value = reverseStr(replaced);_x000D_
                el.style.color = "black";_x000D_
                el._plc = false;_x000D_
                el.readOnly = false;_x000D_
                el.className = el.className.replace("unselectable", "");_x000D_
            } else if (el._plc && el.readOnly) {_x000D_
                var ch = String.fromCharCode(e.charCode);_x000D_
                if (e.keyCode == 13) ch = "\n";     // ENTER_x000D_
                else if (e.charCode == 0) return;   // non-character keys_x000D_
                _x000D_
                el.value = ch;_x000D_
                el.style.color = "black";_x000D_
                el._plc = false;_x000D_
                el.readOnly = false;_x000D_
                el.className = el.className.replace("unselectable", "");_x000D_
            }_x000D_
        }, 10);_x000D_
    }_x000D_
    el.addEventListener("keypress", keyPress, false);_x000D_
    el.addEventListener("paste", keyPress, false);_x000D_
    el.addEventListener("cut", keyPress, false);_x000D_
    el.addEventListener("mousedown", function() {_x000D_
        if (el._plc) el.readOnly = true;_x000D_
    }, false);_x000D_
    el.addEventListener("mouseup", function() {_x000D_
        el.readOnly = false;_x000D_
        if (el._plc) cursorToStart(el);_x000D_
    }, false);_x000D_
  _x000D_
    function cursorToStart(input) {_x000D_
        if (input.createTextRange) {_x000D_
            var part = input.createTextRange();_x000D_
            part.move("character", 0);_x000D_
            part.select();_x000D_
        } else if (input.setSelectionRange){_x000D_
            input.setSelectionRange(0, 0);_x000D_
        } input.focus();_x000D_
    }_x000D_
    function reverseStr(str) {_x000D_
        if (!str) return "";_x000D_
        return str.split("").reverse().join("");_x000D_
    }_x000D_
}
_x000D_
textarea {_x000D_
    border: 1px solid gray;_x000D_
    padding: 3px 6px;_x000D_
    font-family: Arial;_x000D_
    font-size: 13px;_x000D_
    transition: .2s;_x000D_
}_x000D_
textarea:hover, textarea:focus {_x000D_
    border-color: #2277cc;_x000D_
}_x000D_
textarea:focus {_x000D_
    box-shadow: inset 0 0 5px #85B7E9;_x000D_
}_x000D_
*.unselectable {_x000D_
    -webkit-user-select: none;_x000D_
    -webkit-touch-callout: none;_x000D_
    -khtml-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    -o-user-select: none;_x000D_
}
_x000D_
<textarea id="textarea"></textarea>
_x000D_
_x000D_
_x000D_

For loop in multidimensional javascript array

Or you can do this alternatively with "forEach()":

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
  } else {
    console.log(item);
  }
});

If you need array's index, please try this code:

var i = 0; j = 0;

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
    i++;
    j = 0;
  } else {
    console.log("[" + i + "][" + j + "] = " + item);
    j++;
  }
});

And the result will look like this:

[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 4
[1][1] = 5
[1][2] = 6
[2][0] = 7
[2][1] = 8
[2][2] = 9

How to wait until an element is present in Selenium?

public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {

    FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
        .pollingEvery(pollingSec, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);

    for (int i = 0; i < 2; i++) {
        try {
            //fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
        fWait.until(ExpectedConditions.visibilityOf(element));
        fWait.until(ExpectedConditions.elementToBeClickable(element));
        } catch (Exception e) {

        System.out.println("Element Not found trying again - " + element.toString().substring(70));
        e.printStackTrace();

        }
    }

    return element;

    }

PHP - Check if the page run on Mobile or Desktop browser

You can do it manually if you want.

Reference: http://php.net/manual/en/function.get-browser.php

preg_match('/windows|win32/i', $_SERVER['HTTP_USER_AGENT'])

preg_match('/iPhone|iPod|iPad/', $_SERVER['HTTP_USER_AGENT'])

You can even make it a script

$device = 'Blackberry'

preg_match("/$device/", $_SERVER['HTTP_USER_AGENT'])

Here is somewhat of a small list

                        '/windows nt 6.2/i'     =>  'Windows 8',
                        '/windows nt 6.1/i'     =>  'Windows 7',
                        '/windows nt 6.0/i'     =>  'Windows Vista',
                        '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                        '/windows nt 5.1/i'     =>  'Windows XP',
                        '/windows xp/i'         =>  'Windows XP',
                        '/windows nt 5.0/i'     =>  'Windows 2000',
                        '/windows me/i'         =>  'Windows ME',
                        '/win98/i'              =>  'Windows 98',
                        '/win95/i'              =>  'Windows 95',
                        '/win16/i'              =>  'Windows 3.11',
                        '/macintosh|mac os x/i' =>  'Mac OS X',
                        '/mac_powerpc/i'        =>  'Mac OS 9',
                        '/linux/i'              =>  'Linux',
                        '/ubuntu/i'             =>  'Ubuntu',
                        '/iphone/i'             =>  'iPhone',
                        '/ipod/i'               =>  'iPod',
                        '/ipad/i'               =>  'iPad',
                        '/android/i'            =>  'Android',
                        '/blackberry/i'         =>  'BlackBerry',
                        '/webos/i'              =>  'Mobile'

Browsers

                        '/msie/i'       =>  'Internet Explorer',
                        '/firefox/i'    =>  'Firefox',
                        '/safari/i'     =>  'Safari',
                        '/chrome/i'     =>  'Chrome',
                        '/opera/i'      =>  'Opera',
                        '/netscape/i'   =>  'Netscape',
                        '/maxthon/i'    =>  'Maxthon',
                        '/konqueror/i'  =>  'Konqueror',
                        '/mobile/i'     =>  'Handheld Browser'

How do I convert an NSString value to NSData?

In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

Control cannot fall through from one case label

You missed break statements. Don't forget to use break-statements even in the default case.

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
        break;
    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
        break;
    default:
        Console.WriteLine("Default case handling");
        break;
}

How to Determine the Screen Height and Width in Flutter

You can use:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.of(context).padding;
  • double newheight = height - padding.top - padding.bottom;

How to convert a string of bytes into an int?

You can also use the struct module to do this:

>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L

How to overwrite the output directory in spark

If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.

Have a look at the following classes: FileOutputFormat, FileOutputCommitter

In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.

I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.

The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.

Mailx send html message

If you use AIX try this This will attach a text file and include a HTML body If this does not work catch the output in the /var/spool/mqueue

#!/usr/bin/kWh
if (( $# < 1 ))
 then
  echo "\n\tSyntax: $(basename) MAILTO SUBJECT BODY.html ATTACH.txt "
  echo "\tmailzatt"
  exit
fi
export MAILTO=${[email protected]}
MAILFROM=$(whoami)
SUBJECT=${2-"mailzatt"}
export BODY=${3-/apps/bin/attch.txt}
export ATTACH=${4-/apps/bin/attch.txt}
export HST=$(hostname)
#export BODY="/wrk/stocksum/report.html"
#export ATTACH="/wrk/stocksum/Report.txt"
#export MAILPART=`uuidgen` ## Generates Unique ID
#export MAILPART_BODY=`uuidgen` ## Generates Unique ID
export MAILPART="==".$(date +%d%S)."===" ## Generates Unique ID
export MAILPART_BODY="==".$(date +%d%Sbody)."===" ## Generates Unique ID
(
echo "To: $MAILTO"
 echo "From: mailmate@$HST "
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
 echo ""
 echo ""
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/html"
 echo "Content-Disposition: inline"
 cat $BODY
 echo ""
 echo "--$MAILPART_BODY--"
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: text/plain"
 echo "Content-Disposition: attachment; filename=\"$(basename $ATTACH)\""
 echo ""
 cat $ATTACH
 echo ""
 echo "--${MAILPART}--"
  ) | /usr/sbin/sendmail -t

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Reflection: How to Invoke Method with parameters

I'am posting this answer because many visitors enter here from google for this problem.


string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );

when external .dll -instead of this.GetType(), you might use typeof(YourClass).

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

for me, that's caused by the SSL certificate not enabled in the K8S ingress. hope this helps someone

Ignore files that have already been committed to a Git repository

i followed these steps

git rm -r --cached .
git add .
git reset HEAD

after that, git delete all files (*.swp in my case) that should be ignoring.

The controller for path was not found or does not implement IController

Or maybe you missed keyword "Controller" at the end of controller name ;)

npm install hangs

I had the same issue on macOS, after some time struggling and searching around, this answer actually solved the issue for me:

npm config rm proxy
npm config rm https-proxy
npm config set registry http://registry.npmjs.org/

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

How do I center an anchor element in CSS?

Just put it between center tags:

<center>><Your text here>></center>

The project cannot be built until the build path errors are resolved.

Go to > Right CLick on your project folder > Build Path > Configure Build Path > Libraries Tab > remove project and external dependencies > apply & close

Now, Gradle refresh your project.

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

In addition to bvamos's answer, according to the documentation the use of sem is deprecated :

NAME ipcrm - remove a message queue, semaphore set or shared memory id SYNOPSIS ipcrm [ -M key | -m id | -Q key | -q id | -S key | -s id ] ... deprecated usage

ipcrm [ shm | msg | sem ] id ...

remove shared memory

us ipcrm -m to remove a shared memory segment by the id

#!/bin/bash

set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_M; do
  ipcrm -m $id;
done

or ipcrm -M to remove a shared memory segment by the key

#!/bin/bash

set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_M; do
  ipcrm -M $id;
done

remove message queues

us ipcrm -q to remove a shared memory segment by the id

#!/bin/bash

set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_Q; do
  ipcrm -q $id;
done

or ipcrm -Q to remove a shared memory segment by the key

#!/bin/bash

set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_Q; do
  ipcrm -Q $id;
done

remove semaphores

us ipcrm -s to remove a semaphore segment by the id

#!/bin/bash

set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_S; do
  ipcrm -s $id;
done

or ipcrm -S to remove a semaphore segment by the key

#!/bin/bash

set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_S; do
  ipcrm -S $id;
done

How to kill zombie process

A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by pid 1, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and wait on them to determine their exit status.

An example of how you might send a signal to every process that is the parent of a zombie (note that this is extremely crude and might kill processes that you do not intend. I do not recommend using this sort of sledge hammer):

# Don't do this.  Incredibly risky sledge hammer!
kill $(ps -A -ostat,ppid | awk '/[zZ]/ && !a[$2]++ {print $2}')

How can I get a list of all classes within current module in Python?

This is the line that I use to get all of the classes that have been defined in the current module (ie not imported). It's a little long according to PEP-8 but you can change it as you see fit.

import sys
import inspect

classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) 
          if obj.__module__ is __name__]

This gives you a list of the class names. If you want the class objects themselves just keep obj instead.

classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
          if obj.__module__ is __name__]

This is has been more useful in my experience.

What is the best way to implement constants in Java?

In Effective Java (2nd edition), it's recommended that you use enums instead of static ints for constants.

There's a good writeup on enums in Java here: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

Note that at the end of that article the question posed is:

So when should you use enums?

With an answer of:

Any time you need a fixed set of constants

Disable a link in Bootstrap

You cant set links to "disabled" just system elements like input, textfield etc.

But you can disable links with jQuery/JavaScript

$('.disabled').click(function(e){
    e.preventDefault();
});

Just wrap the above code in whatever event you want to disable the links.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

sql like operator to get the numbers only

what might get you where you want in plain SQL92:

select * from tbl where lower(answer) = upper(answer)

or, if you also want to be robust for leading/trailing spaces:

select * from tbl where lower(answer) = trim(upper(answer))

Crop image in PHP

You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)

Example:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:

split -l 100000 database.sql database-

It will give files like:

database-aaa
database-aab
database-aac
...

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.

    private static Field PC_VERSION_INIT = null;
    static {
        try {
            PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
            PC_VERSION_INIT.setAccessible(true);
        } catch (NoSuchFieldException | SecurityException e) {
        }
    }

    public T call(final EntityManager em) {
                if (PC_VERSION_INIT != null && isDetached(entity)) {
                    try {
                        PC_VERSION_INIT.set(entity, false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                    }
                }
                em.persist(entity);
                return entity;
            }

            /**
             * @param entity
             * @param detached
             * @return
             */
            private boolean isDetached(final Object entity) {
                if (entity instanceof PersistenceCapable) {
                    PersistenceCapable pc = (PersistenceCapable) entity;
                    if (pc.pcIsDetached() == Boolean.TRUE) {
                        return true;
                    }
                }
                return false;
            }

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

What's the best practice using a settings file in Python?

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print(config.truck['color'])  

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How to load a tsv file into a Pandas DataFrame?

open file, save as .csv and then apply

df = pd.read_csv('apps.csv', sep='\t')

for any other format also, just change the sep tag

PDO error message?

Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:

 print_r($this->pdo->errorInfo());

Use PHP implode() function:

 echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());

This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.

Hope it helps

How does Facebook Sharer select Images and other metadata when sharing my URL?

Use facebook feed dialog instead of share dialog to show custom Images

Example:

https://www.facebook.com/dialog/feed?app_id=1389892087910588
&redirect_uri=https://scotch.io
&link=https://scotch.io
&picture=http://placekitten.com/500/500
&caption=This%20is%20the%20caption
&description=This%20is%20the%20description

Java logical operator short-circuiting

Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.

Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.

It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:

 if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since the Beta, Razor uses a different config section for globally defining namespace imports. In your Views\Web.config file you should add the following:

<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  </sectionGroup>
</configSections>

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <!-- Your namespace here -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

Note that you might need to close and reopen the file for the changes to be picked up by the editor.

.gitignore after commit

However, will it automatically remove these committed files from the repository?

No. Even with an existing .gitignore you are able to stage "ignored" files with the -f (force) flag. If they files are already commited, they don't get removed automatically.

git rm --cached path/to/ignored.exe

Enable binary mode while restoring a Database from an SQL dump

If you don't have enough space or don't want to waste time in decompressing it, Try this command.

gunzip < compressed-sqlfile.gz | mysql -u root -p

Don't forget to replace compressed-sqlfile.gz with your compressed file name.

.gz restore will not work without command I provided above.

Python equivalent of D3.js

Check out python-nvd3. It is a python wrapper for nvd3. Looks cooler than d3.py and also has more chart options.

Move an item inside a list?

A solution very simple, but you have to know the index of the original position and the index of the new position:

list1[index1],list1[index2]=list1[index2],list1[index1]

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

It's actually quite easy to implement as a helper:

Handlebars.registerHelper('eachProperty', function(context, options) {
    var ret = "";
    for(var prop in context)
    {
        ret = ret + options.fn({property:prop,value:context[prop]});
    }
    return ret;
});

Then using it like so:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

Use grep to report back only line numbers

To count the number of lines matched the pattern:

grep -n "Pattern" in_file.ext | wc -l 

To extract matched pattern

sed -n '/pattern/p' file.est

To display line numbers on which pattern was matched

grep -n "pattern" file.ext | cut -f1 -d:

How do I instantiate a JAXBElement<String> object?

I don't know why you think there's no constructor. See the API.

Finding absolute value of a number without using Math.abs()

In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.

(int)(((long)x*x - 1)%(double)x + 1);

Because Java treats a%b as a - a/b * b, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x will equal abs(x)-1; type casting of "long" is to prevent overflow and double allows dividing by zero.

Again, x = Integer.MIN_VALUE will cause overflow due to subtracting 1.

Resizing an iframe based on content

The solution on http://www.phinesolutions.com/use-jquery-to-adjust-the-iframe-height.html works great (uses jQuery):

<script type=”text/javascript”>
  $(document).ready(function() {
    var theFrame = $(”#iFrameToAdjust”, parent.document.body);
    theFrame.height($(document.body).height() + 30);
  });
</script>

I don't know that you need to add 30 to the length... 1 worked for me.

FYI: If you already have a "height" attribute on your iFrame, this just adds style="height: xxx". This might not be what you want.

Get the string within brackets in Python

This should do the job:

re.match(r"[^[]*\[([^]]*)\]", yourstring).groups()[0]

In plain English, what does "git reset" do?

Checkout points the head at a specific commit.

Reset points a branch at a specific commit. (A branch is a pointer to a commit.)

Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)

How to shift a block of code left/right by one space in VSCode?

There was a feature request for that in vscode repo. But it was marked as extension-candidate and closed. So, here is the extension: Indent One space

Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.

enter image description here

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

How to define a preprocessor symbol in Xcode

In response to Kevin Laity's comment (see cdespinosa's answer), about the GCC Preprocessing section not showing in your build settings, make the Active SDK the one that says (Base SDK) after it and this section will appear. You can do this by choosing the menu Project > Set Active Target > XXX (Base SDK). In different versions of XCode (Base SDK) maybe different, like (Project Setting or Project Default).

After you get this section appears, you can add your definitions to Processor Macros rather than creating a user-defined setting.

How to make CREATE OR REPLACE VIEW work in SQL Server?

SQL Server 2016 Answer

With SQL Server 2016 you can now do (MSDN Source):

DROP VIEW IF EXISTS dbo.MyView

Comparing chars in Java

If your input is a character and the characters you are checking against are mostly consecutive you could try this:

if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
    // ...
}

However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:

if (symbol.matches("[A-Z?]")) {
    // ...
}

If you have a character you'll first need to convert it to a string before you can use a regular expression:

if (Character.toString(symbol).matches("[A-Z?]")) {
    // ...
}

android TextView: setting the background color dynamically doesn't work

two ways to do that:

1.create color in colors.xml file like:

<resources>
        <color name="white">#ffffff</color>
</resources>

and use it int activity java class as:

et.setBackgroundResource(R.color.white);

2.

et.setBackgroundColor(getResources().getColor(R.color.white));
                or
et.setBackgroundColor(Color.parseColor("#ffffff"));

How to read/write files in .Net Core?

Works in Net Core 2.1

    var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");

    string SendData = System.IO.File.ReadAllText(file);

can't access mysql from command line mac

On mac, open the terminal and type:

cd /usr/local/mysql/bin

then type:

./mysql -u root -p

It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.

How to determine if object is in array

You could use jQuery's grep method:

$.grep(carBrands, function(obj) { return obj.name == "ford"; });

But as you specify no jQuery, you could just make a derivative of the function. From the source code:

function grepArray( elems, callback, inv ) {  
    var ret = [];  

    // Go through the array, only saving the items  
    // that pass the validator function  
    for ( var i = 0, length = elems.length; i < length; i++ ) {  
        if ( !inv !== !callback( elems[ i ], i ) ) {  
            ret.push( elems[ i ] );  
        }  
    }  

    return ret;  
}  

grepArray(carBrands, function(obj) { return obj.name == "ford"; });

What is a good naming convention for vars, methods, etc in C++?

There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.

It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:

class cat_t {
  ...
};

cat_t myCat;

It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.

In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)

And if all else fails, google it.

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

Should black box or white box testing be the emphasis for testers?

Black Box Testing: Black Box testing is just observation no need Internal Knowledge or structure of software product. just putting valid and Invalid data input and expecting the correct result. here tester find the defect but unable to Find the Location of defect.black box testing done in all testing level.

Black box testing tecniques are: 1. Equivalance partition 2. Boundary Value Analysis 3. Decision table 4. State Transition Diagram 4. Use case diagram

White Box Testing: White box is testing it requires the knowledge of internal logic and structure of software product. here we will check the loop, condition and branch. here we find not only the defect but also and location of defect.

White box Testing Techniques: 1. Statement Coverage 2. Decision Coverage 3. Branch Coverage 4. Path Coverage.

converting Java bitmap to byte array

CompressFormat is too slow...

Try ByteBuffer.

???Bitmap to byte???

width = bitmap.getWidth();
height = bitmap.getHeight();

int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();

???byte to bitmap???

Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);

How to get current timestamp in milliseconds since 1970 just the way Java gets

use <sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

refer this.

Does Hive have a String split function?

There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:

split(string str, string pat)
   Split str around pat (pat is a regular expression) 

In your case, the delimiter "|" has a special meaning as a regular expression, so it should be referred to as "\\|".

Java: how to add image to Jlabel?

To get an image from a URL we can use the following code:

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

It totally works for me. The PicUrl is a string variable which strores the url of the picture.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

On OS X, it's necessary to make sure Sandbox capabilities are set-up properly in order to use WKWebView.

This link made this clear to me: https://forums.developer.apple.com/thread/92265

Sharing hoping that it will help someone.


Select the Project File in the Navigator, select Capabilities, then make sure that:
* App Sandbox is OFF,
OR
* App Sandbox is ON AND Outgoing Connections (Client) is checked.

PowerShell script to check the status of a URL

For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest:

$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}

Styling input buttons for iPad and iPhone

I recently came across this problem myself.

<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->

Hope that helps.

Property 'map' does not exist on type 'Observable<Response>'

The angular new version does not support .map you have to install this through cmd npm install --save rxjs-compat via this you can enjoy with old technique . note: don't forget to import these lines.

import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

How do I convert a Swift Array to a String?

If the array contains strings, you can use the String's join method:

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

In Swift 2:

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

This can be useful if you want to use a specific separator (hypen, blank, comma, etc).

Otherwise you can simply use the description property, which returns a string representation of the array:

let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"

Hint: any object implementing the Printable protocol has a description property. If you adopt that protocol in your own classes/structs, you make them print friendly as well

In Swift 3

  • join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

var array = ["1", "2", "3"]
array.joined(separator:"-")

Convert serial.read() into a useable string using Arduino?

Unlimited string readed:

String content = "";
char character;
    
while(Serial.available()) {
     character = Serial.read();
     content.concat(character);
}
      
if (content != "") {
     Serial.println(content);
}

Set a default parameter value for a JavaScript function

Yeah this is referred to as a default parameter

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Syntax:

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

Description:

Parameters of functions default to undefined However, in situations it might be useful to set a different default value. This is where default parameters can help.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If no value is provided in the call, its value would be undefined. You would have to set a conditional check to make sure the parameter is not undefined

With default parameters in ES2015, the check in the function body is no longer necessary. Now you can simply put a default value in the function head.

Example of the differences:

// OLD METHOD
function multiply(a, b) {
  b = (typeof b !== 'undefined') ?  b : 1;
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5


// NEW METHOD
function multiply(a, b = 1) {
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5

Different Syntax Examples:

Padding undefined vs other falsy values:

Even if the value is set explicitly when calling, the value of the num argument is the default one.

function test(num = 1) {
  console.log(typeof num);
}

test();          // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)

// test with other falsy values:
test('');        // 'string' (num is set to '')
test(null);      // 'object' (num is set to null)

Evaluated at call time:

The default argument gets evaluated at call time, so unlike some other languages, a new object is created each time the function is called.

function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); //[1]
append(2); //[2], not [1, 2]


// This even applies to functions and variables
function callSomething(thing = something()) {
 return thing;
}

function something() {
  return 'sth';
}

callSomething();  //sth

Default parameters are available to later default parameters:

Params already encountered are available to later default parameters

function singularAutoPlural(singular, plural = singular + 's',
                        rallyingCry = plural + ' ATTACK!!!') {
  return [singular, plural, rallyingCry];
}

//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural('Gecko');

//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural('Fox', 'Foxes');

//["Deer", "Deer", "Deer ... change."]
singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \ petition the government for positive change.')

Functions defined inside function body:

Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError (currently a TypeError in SpiderMonkey, see bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.

// Doesn't work! Throws ReferenceError.
function f(a = go()) {
  function go() { return ':P'; }
}

Parameters without defaults after default parameters:

Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError. This has been fixed in bug 777060 and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

function f(x = 1, y) {
  return [x, y];
}

f(); // [1, undefined]
f(2); // [2, undefined]

Destructured paramet with default value assignment:

You can use default value assignment with the destructuring assignment notation

function f([x, y] = [1, 2], {z: z} = {z: 3}) {
  return x + y + z;
}

f(); // 6

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

Sorting a vector in descending order

bool comp(int i, int j) { return i > j; }
sort(numbers.begin(), numbers.end(), comp);

Check if returned value is not null and if so assign it, in one line, with one method call

Since Java 9 you have Objects#requireNonNullElse which does:

public static <T> T requireNonNullElse(T obj, T defaultObj) {
    return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}

Your code would be

dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());

Which is 1 line and calls getChicken() only once, so both requirements are satisfied.

Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.

Consider also the alternative Objects#requireNonNullElseGet:

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

Count the number of occurrences of a character in a string in Javascript

And there is:

function character_count(string, char, ptr = 0, count = 0) {
    while (ptr = string.indexOf(char, ptr) + 1) {count ++}
    return count
}

Works with integers too!

Difference between Key, Primary Key, Unique Key and Index in MySQL

PRIMARY KEY AND UNIQUE KEY are similar except it has different functions. Primary key makes the table row unique (i.e, there cannot be 2 row with the exact same key). You can only have 1 primary key in a database table.

Unique key makes the table column in a table row unique (i.e., no 2 table row may have the same exact value). You can have more than 1 unique key table column (unlike primary key which means only 1 table column in the table is unique).

INDEX also creates uniqueness. MySQL (example) will create a indexing table for the column that is indexed. This way, it's easier to retrieve the table row value when the query is queried on that indexed table column. The disadvantage is that if you do many updating/deleting/create, MySQL has to manage the indexing tables (and that can be a performance bottleneck).

Hope this helps.

Best way to randomize an array with .NET

You don't need complicated algorithms.

Just one simple line:

Random random = new Random();
array.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();

Note that we need to convert the Array to a List first, if you don't use List in the first place.

Also, mind that this is not efficient for very large arrays! Otherwise it's clean & simple.

Adding value labels on a matplotlib bar chart

Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.

You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

This produces a labeled plot that looks like:

enter image description here

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

select2 changing items dynamically

I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/

In a bootstrap responsive page how to center a div

I think the simplest way to accomplish the layout with bootstrap is like this:

<section>
<div class="container">
    <div class="row">
        <div align="center">
            <div style="max-width: 200px; background-color: blueviolet;">
                <div>
                    <h1 style="color: white;">Content goes here</h1>
                </div>
            </div>
        </div>
    </div>
</div>

all I did was to add layers of divs that allowed me to center the div, but since I am not using percentages, you need to specify the max-width of the div to be center.

You can use this same method to center more than one column, you just need to add more div layers:

<div class="container">
    <div class="row">
        <div align="center">
            <div style="max-width: 400px; background-color: blueviolet;">
                <div class="col-md-12 col-sm-12 col-xs-12" style="background-color: blueviolet;">
                    <div class="col-md-8 col-sm-8 col-xs-12" style="background-color: darkcyan;">
                        <h1 style="color: white;">Some content</h1>
                    </div>
                    <div class="col-md-4 col-sm-4 col-xs-12" style="background-color: blue;">
                        <p style="color: white;">More content</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Note: that I added a div with column 12 for md, sm and xs, if you don't do this the first div with background color (in this case "blueviolet") will collapse, you will be able to see the child divs, but not the background color.

'react-scripts' is not recognized as an internal or external command

In my case, the problem had to do with not having enough file permissions for some files the react-scripts package installation was going to write to. What solved it was running git bash as an administrator and then running npm install --save react-scripts again.

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

call a function in success of datatable ajax call

The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.

$("#tableOfData").DataTable({
        "pageLength": 50,
        "ajax":{
            url: someurl,
            dataType : "json",
            type: "post",
            "data": {data to be sent}
        },
        "initComplete":function( settings, json){
            console.log(json);
            // call your function here
        }
    });

React Native Error: ENOSPC: System limit for number of file watchers reached

The meaning of this error is that the number of files monitored by the system has reached the limit!!

Result: The command executed failed! Or throw a warning (such as executing a react-native start VSCode)

Solution:

Modify the number of system monitoring files

Ubuntu

sudo gedit /etc/sysctl.conf

Add a line at the bottom

fs.inotify.max_user_watches=524288

Then save and exit!

sudo sysctl -p

to check it

Then it is solved!

Search all the occurrences of a string in the entire project in Android Studio

Press SHIFT 2 times and you can search Every-where , both Class and Method() in the project.

Ctrl + N for finding only Class name.

Ctrl + E for Recent Files.

How can I check if a jQuery plugin is loaded?

If we're talking about a proper jQuery plugin (one that extends the fn namespace), then the proper way to detect the plugin would be:

if(typeof $.fn.pluginname !== 'undefined') { ... }

Or because every plugin is pretty much guaranteed to have some value that equates to true, you can use the shorter

if ($.fn.pluginname) { ... }

BTW, the $ and jQuery are interchangable, as the odd-looking wrapper around a plugin demonstrates:

(function($) {
    //
})(jQuery))

the closure

(function($) {
    //
})

is followed immediately by a call to that closure 'passing' jQuery as the parameter

(jQuery)

the $ in the closure is set equal to jQuery

The property 'value' does not exist on value of type 'HTMLElement'

If you are using react you can use the as operator.

let inputValue = (document.getElementById(elementId) as HTMLInputElement).value;

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

How to remove commits from a pull request

So do the following ,

Lets say your branch name is my_branch and this has the extra commits.

  1. git checkout -b my_branch_with_extra_commits (Keeping this branch saved under a different name)
  2. gitk (Opens git console)
  3. Look for the commit you want to keep. Copy the SHA of that commit to a notepad.
  4. git checkout my_branch
  5. gitk (This will open the git console )
  6. Right click on the commit you want to revert to (State before your changes) and click on "reset branch to here"
  7. Do a git pull --rebase origin branch_name_to _merge_to
  8. git cherry-pick <SHA you copied in step 3. >

Now look at the local branch commit history and make sure everything looks good.

How to add dividers and spaces between items in RecyclerView?

Might I direct your attention to this particular file on Github by Alex Fu: https://gist.github.com/alexfu/0f464fc3742f134ccd1e

It's the DividerItemDecoration.java example file "pulled straight from the support demos".(https://plus.google.com/103498612790395592106/posts/VVEB3m7NkSS)

I was able to get divider lines nicely after importing this file in my project and add it as an item decoration to the recycler view.

Here's how my onCreateView look like in my fragment containing the Recyclerview:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
    mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    return rootView;
}

I'm sure additional styling can be done, but it's a starting point. :)

How to pass arguments from command line to gradle

There's a great example here:

https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line

Which details that you can pass parameters and then provide a default in an ext variable like so:

gradle -Dmy_app.color=blue

and then reference in Gradle as:

ext {
   color = System.getProperty("my_app.color", "red");
}

And then anywhere in your build script you can reference it as course anywhere you can reference it as project.ext.color

More tips here: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

PHP - Extracting a property from an array of objects

CODE

<?php

# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);

function extract_ids($array = array())
{
    $ids = array();
    foreach ($array as $object) {
        $ids[] = $object->id;
    }
    return $ids;
}

$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);

?>

OUTPUT

# var_dump($cats);
array(3) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(15)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(18)
  }
  [2]=>
  object(stdClass)#3 (1) {
    ["id"]=>
    int(23)
  }
}

# var_dump($cat_ids);
array(3) {
  [0]=>
  int(15)
  [1]=>
  int(18)
  [2]=>
  int(23)
}

I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

How to perform a real time search and filter on a HTML table

If you can separate html and data, you can use external libraries like datatables or the one i created. https://github.com/thehitechpanky/js-bootstrap-tables

This library uses keyup function to reload tabledata and hence it appears to work like search.

function _addTableDataRows(paramObjectTDR) {
    let { filterNode, limitNode, bodyNode, countNode, paramObject } = paramObjectTDR;
    let { dataRows, functionArray } = paramObject;
    _clearNode(bodyNode);
    if (typeof dataRows === `string`) {
        bodyNode.insertAdjacentHTML(`beforeend`, dataRows);
    } else {
        let filterTerm;
        if (filterNode) {
            filterTerm = filterNode.value.toLowerCase();
        }
        let serialNumber = 0;
        let limitNumber = 0;
        let rowNode;
        dataRows.forEach(currentRow => {
            if (!filterNode || _filterData(filterTerm, currentRow)) {
                serialNumber++;
                if (!limitNode || limitNode.value === `all` || limitNode.value >= serialNumber) {
                    limitNumber++;
                    rowNode = _getNode(`tr`);
                    bodyNode.appendChild(rowNode);
                    _addData(rowNode, serialNumber, currentRow, `td`);
                }
            }
        });
        _clearNode(countNode);
        countNode.insertAdjacentText(`beforeend`, `Showing 1 to ${limitNumber} of ${serialNumber} entries`);
    }
    if (functionArray) {
        functionArray.forEach(currentObject => {
            let { className, eventName, functionName } = currentObject;
            _attachFunctionToClassNodes(className, eventName, functionName);
        });
    }
}

Display an image with Python

Using opencv-python is faster for more operation on image:

import cv2
import matplotlib.pyplot as plt

im = cv2.imread('image.jpg')
im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR)

plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB))
plt.show()

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

What character represents a new line in a text area

By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.

In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea element value exists in three variants:

  1. the raw value as entered by the user, unnormalized; it may contain CR, LF, or CR LF pair;
  2. the internal value, called “API value”, where line breaks are normalized to LF (only);
  3. the submission value, where line breaks are normalized to CR LF pairs, as per Internet conventions.

Calculating how many days are between two dates in DB2?

Wouldn't it just be:

SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';

That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.

If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

How to pass an ArrayList to a varargs method parameter?

Though it is marked as resolved here my KOTLIN RESOLUTION

fun log(properties: Map<String, Any>) {
    val propertyPairsList = properties.map { Pair(it.key, it.value) }
    val bundle = bundleOf(*propertyPairsList.toTypedArray())
}

bundleOf has vararg parameter

Does bootstrap 4 have a built in horizontal divider?

HTML already has a built-in horizontal divider called <hr/> (short for "horizontal rule"). Bootstrap styles it like this:

hr {
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />_x000D_
<p>_x000D_
   Some text_x000D_
   <hr/>_x000D_
   More text_x000D_
</p>
_x000D_
_x000D_
_x000D_

php hide ALL errors

Per the PHP documentation, put this at the top of your php scripts:

<?php error_reporting(0); ?>

http://php.net/manual/en/function.error-reporting.php

If you do hide your errors, which you should in a live environment, make sure that you are logging any errors somewhere. How to log errors and warnings into a file? Otherwise, things will go wrong and you will have no idea why.

File inside jar is not visible for spring

If your spring-context.xml and my.config files are in different jars then you will need to use classpath*:my.config?

More info here

Also, make sure you are using resource.getInputStream() not resource.getFile() when loading from inside a jar file.

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

Pylint "unresolved import" error in Visual Studio Code

This issue has already been opened on GitHub:

Python unresolved import issue #3840

There are two very useful answers, by MagnuesBrzenk and SpenHouet.

The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:

PYTHONPATH=YOUR/MODULES/PATH

And in your settings.json add:

"python.envFile": ".env"

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Simple pthread! C++

When compiling with G++, remember to put the -lpthread flag :)

Sorting arrays in javascript by object key value

Not spectacular different than the answers already given, but more generic is :

sortArrayOfObjects = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] - b[key];
    });
};

sortArrayOfObjects(yourArray, "distance");

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Add an extra attribute to that EditText programmatically and you are done:

password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

For numeric password (pin):

password.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Also, make sure that the cursor is at the end of the text in the EditText because when you change the input type the cursor will be automatically set to the starting point. So I suggest using the following code:

et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.setSelection(et_password.getText().length());

When using Data Binding, you can make use of the following code:

<data>
        <import type="android.text.InputType"/>
.
.
.
<EditText
android:inputType='@{someViewModel.isMasked ? 
(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) :
InputType.TYPE_CLASS_TEXT }'

If using Kotlin:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

Make element fixed on scroll

There are some problems implementing this which the original accepted answer does not answer:

  1. The onscroll event of the window is firing very often. This implies that you either have to use a very performant listener, or you have to delay the listener somehow. jQuery Creator John Resig states here how a delayed mechanism can be implemented, and the reasons why you should do it. In my opinion, given todays browsers and environments, a performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
  2. The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
  3. Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here

Here's the code:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

Read pdf files with php

your initial request is "I have a large PDF file that is a floor map for a building. "

I am afraid to tell you this might be harder than you guess.

Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.

Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).

see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

Can jQuery read/write cookies to a browser?

You can browse all the jQuery plugins tagged with "cookie" here:

http://plugins.jquery.com/plugin-tags/cookies

Plenty of options there.

Check out the one called jQuery Storage, which takes advantage of HTML5's localStorage. If localStorage isn't available, it defaults to cookies. However, it doesn't allow you to set expiration.