Programs & Examples On #Penetration testing

This tag is for questions that involve black box security testing of applications and/or networks. Questions that involve vulnerability scanning, offensive security, exploit development, etc., might fall under this tag.

What is "X-Content-Type-Options=nosniff"?

Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

However, this is not a valid method for w3c compliant websites, the validator will raise an error:

Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.

And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.

To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:

Visualization of enabled no-sniff option

Is there a way to view past mysql queries with phpmyadmin?

There is a Console tab at the bottom of the SQL (query) screen. By default it is not expanded, but once clicked on it should expose tabs for Options, History and Clear. Click on history.

The Query history length is set from within Page Related Settings which found by clicking on the gear wheel at the top right of screen.

This is correct for PHP version 4.5.1-1

How to find the size of a table in SQL?

I know that in SQL 2012 (may work in other versions) you can do the following:

  1. Right click on the database name in the Object Explorer.
  2. Select Reports > Standard Reports > Disk Usage by Top Tables.

That will give you a list of the top 1000 tables and then you can order it by data size etc.

How to dismiss ViewController in Swift?

For reference, be aware that you might be dismissing the wrong view controller. For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.

How do I get next month date from today's date and insert it in my database?

The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.

If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.

$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;

This way, you will be able to get the month and year of the next month without having a month skipped.

Javascript + Regex = Nothing to repeat error?

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

How can I copy columns from one sheet to another with VBA in Excel?

The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):

Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)

"Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.

As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.

Why can't C# interfaces contain fields?

For this you can have a Car base class that implement the year field, and all other implementations can inheritance from it.

Kafka consumer list

you can use this for 0.9.0.0. version kafka

./kafka-consumer-groups.sh --list --zookeeper hostname:potnumber

to view the groups you have created. This will display all the consumer group names.

 ./kafka-consumer-groups.sh --describe --zookeeper hostname:potnumber  --describe  --group consumer_group_name

To view the details

GROUP, TOPIC, PARTITION, CURRENT OFFSET, LOG END OFFSET, LAG, OWNER

phpmyadmin logs out after 1440 secs

To set permanently cookie you need to follow some steps

Goto->/etc/phpmyadmin/config.inc.php file

add this code

$cfg['LoginCookieValidity'] = <cookie expiration time in seconds > 

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Update the tensorflow binary for your CPU & OS using this command

pip install --ignore-installed --upgrade "Download URL"

The download url of the whl file can be found here

https://github.com/lakshayg/tensorflow-build

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException compared with many other exception types, and that is:

Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.

IndexOutOfRangeException is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.

Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException more often than not is simply just pilot (programmer) error.

How to add app icon within phonegap projects?

FAQ: ICON / SPLASH SCREEN (Cordova 5.x / 2015)

I present my answer as a general FAQ that may help you to solve many problems I've encountered while dealing with icons/splash screens. You may find out like me that the documentation is not always very clear nor up to date. This will probably go to StackOverflow documentation when available.

First: answering the question

How can I add custom app icons for iOS and Android with phonegap?

In your version of Cordova the icon tag is useless. It is not even documented in Cordova 3.0.0. You should use the documentation version that fits the cli you are using and not the latest one!

The icon tag does not work for Android at all before the version 3.5.0 according to what I can see in the different versions of the documentation. In 3.4.0 they still advice to manually copy the files

In newer versions: your config.xml looks better for newer Cordova versions. However there are still many things you may want to know. If you decide to upgrade here are some useful things to modify:

  • You don't need the gap: namespace
  • You need <preference name="SplashScreen" value="screen" /> for Android

Here are more details of the questions you might ask yourself when trying to deal with icons and splash screen:

Can I use an old version of Cordova / Phonegap

No, the icon/splashscreen feature was not in former versions of Cordova so you must use a recent version. In former versions, only Phonegap Build did handle the icons/splash screen so building locally and handling icons was only possible with a hook. I don't know the minimum version to use this feature but with 5.1.1 it works fine in both Cordova/Phonegap cli. With Cordova 3.5 it didn't work for me.

Edit: for Android you must use at least 3.5.0

How can I debug the build process about icons?

The cli use a CP command. If you provide an invalid icon path, it will show a cp error:

sebastien@sebastien-xps:cordova (dev *+$%)$ cordova run android --device
cp: no such file or directory: /home/sebastien/Desktop/Stample-react/cordova/res/www/stample_splash.png

Edit: you have use cordova build <platform> --verbose to get logs of cp command usage to see where your icons gets copied

The icons should go in a folder according to the config. For me it goes in many subfolders in : platforms/android/build/intermediates/res/armv7/debug/drawable-hdpi-v4/icon.png

Then you can find the APK, and open it as a zip archive to check the icons are present. They must be in a res/drawable* folder because it's a special folder for Android.

Where should I put the icons/splash screens in my project?

In many examples you will find the icons/splash screens are declared inside a res folder. This res is a special Android folder in the output APK, but it does not mean you have to use a res folder in your project.

You can put your icon anywhere, but the path you use must be relative to the root of the project, and not www so take care! This is documented, but not clearly because all the examples are using res and you don't know where this folder is :(

I mean if you put the icon in www/icon.png you absolutly must include www in your path.

Edit Mars 2016: after upgrading my versions, now it seems that icons are relative to www folder but documentation has not been changed (issue)

Does <icon src="icon.png"/> work?

No it does not!.

On Android, it seems it used to work before (when the density attribute was not supported yet?) but not anymore. See this Cordova issue

On iOS, it seems using this global declaration may override more specific declarations so take care and build with --verbose to ensure everything works as expected.

Can I use the same icon/splash screen file for all the densities.

Yes you can. You can even use the same file for both the icon, and splash screen (just to test!). I have used a "big" icon file of 65kb without any problem.

What's the difference when using the platform tag vs the platform attribute

<icon src="icon.png" platform="android" density="ldpi" />

is the same as

<platform name="android">
    <icon src="www/stample_icon.png" density="ldpi" />
</platform>

Should I use the gap: namespace if using Phonegap?

In my experience new versions of Phonegap or Cordova are both able to understand icon declarations without using any gap: xml namespace.

However I'm still waiting for a valid answer here: cordova/phonegap plugin add VS config.xml

As far as I understand, some features with the gap: namespace may be available earlier in PhonegapBuild, then in Phonegap and then being ported to Cordova (?)

Is <preference name="SplashScreen" value="screen" /> required?

At least for Android yes it is. I opened an issue with additional explainations.

Does icon declaration order matters?

Yes it does! It may not have any impact on Android but it has on iOS according to my tests. This is unexpected and undocumented behavior so I opened another issue.

Do I need cordova-plugin-splashscreen?

Yes this is absolutly required if you want the splash screen to work. The documentation is not clear (issue) and let us think that the plugin is required only to offer a splash screen javascript API.

How can I resize the images for all width/height/densities fastly

There are tools to help you do that. The best one for me is http://makeappicon.com/ but it requires to provide an email address.

Other possible solutions are:

Can you give me an example config?

Yes. Here's my real config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="co.x" version="0.2.6" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>x</name>
    <description>
        x
    </description>
    <author email="[email protected]" href="https://x.co">
        x
    </author>
    <content src="index.html" />
    <preference name="permissions"                  value="none" />
    <preference name="webviewbounce"                value="false" />
    <preference name="StatusBarOverlaysWebView"     value="false" />
    <preference name="StatusBarBackgroundColor"     value="#0177C6" />
    <preference name="detect-data-types"            value="true" />
    <preference name="stay-in-webview"              value="false" />
    <preference name="android-minSdkVersion"        value="14" />
    <preference name="android-targetSdkVersion"     value="22" />
    <preference name="phonegap-version"             value="cli-5.1.1" />

    <preference name="SplashScreenDelay"            value="10000" />
    <preference name="SplashScreen"                 value="screen" />


    <plugin name="cordova-plugin-device"                spec="1.0.1" />
    <plugin name="cordova-plugin-console"               spec="1.0.1" />
    <plugin name="cordova-plugin-whitelist"             spec="1.1.0" />
    <plugin name="cordova-plugin-crosswalk-webview"     spec="1.2.0" />
    <plugin name="cordova-plugin-statusbar"             spec="1.0.1" />
    <plugin name="cordova-plugin-screen-orientation"    spec="1.3.6" />
    <plugin name="cordova-plugin-splashscreen"          spec="2.1.0" />

    <access origin="http://*" />
    <access origin="https://*" />

    <access launch-external="yes" origin="tel:*" />
    <access launch-external="yes" origin="geo:*" />
    <access launch-external="yes" origin="mailto:*" />
    <access launch-external="yes" origin="sms:*" />
    <access launch-external="yes" origin="market:*" />

    <platform name="android">
        <icon src="www/stample_icon.png" density="ldpi" />
        <icon src="www/stample_icon.png" density="mdpi" />
        <icon src="www/stample_icon.png" density="hdpi" />
        <icon src="www/stample_icon.png" density="xhdpi" />
        <icon src="www/stample_icon.png" density="xxhdpi" />
        <icon src="www/stample_icon.png" density="xxxhdpi" />
        <splash src="www/stample_splash.png" density="land-hdpi"/>
        <splash src="www/stample_splash.png" density="land-ldpi"/>
        <splash src="www/stample_splash.png" density="land-mdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-hdpi"/>
        <splash src="www/stample_splash.png" density="port-ldpi"/>
        <splash src="www/stample_splash.png" density="port-mdpi"/>
        <splash src="www/stample_splash.png" density="port-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxxhdpi"/>
    </platform>

    <platform name="ios">
        <icon src="www/stample_icon.png" width="180" height="180" />
        <icon src="www/stample_icon.png" width="60" height="60" />
        <icon src="www/stample_icon.png" width="120" height="120" />
        <icon src="www/stample_icon.png" width="76" height="76" />
        <icon src="www/stample_icon.png" width="152" height="152" />
        <icon src="www/stample_icon.png" width="40" height="40" />
        <icon src="www/stample_icon.png" width="80" height="80" />
        <icon src="www/stample_icon.png" width="57" height="57" />
        <icon src="www/stample_icon.png" width="114" height="114" />
        <icon src="www/stample_icon.png" width="72" height="72" />
        <icon src="www/stample_icon.png" width="144" height="144" />
        <icon src="www/stample_icon.png" width="29" height="29" />
        <icon src="www/stample_icon.png" width="58" height="58" />
        <icon src="www/stample_icon.png" width="50" height="50" />
        <icon src="www/stample_icon.png" width="100" height="100" />
        <splash src="www/stample_splash.png" width="320" height="480"/>
        <splash src="www/stample_splash.png" width="640" height="960"/>
        <splash src="www/stample_splash.png" width="768" height="1024"/>
        <splash src="www/stample_splash.png" width="1536" height="2048"/>
        <splash src="www/stample_splash.png" width="1024" height="768"/>
        <splash src="www/stample_splash.png" width="2048" height="1536"/>
        <splash src="www/stample_splash.png" width="640" height="1136"/>
        <splash src="www/stample_splash.png" width="750" height="1334"/>
        <splash src="www/stample_splash.png" width="1242" height="2208"/>
        <splash src="www/stample_splash.png" width="2208" height="1242"/>
    </platform>

    <allow-intent href="*" />
    <engine name="browser" spec="^3.6.0" />
    <engine name="android" spec="^4.0.2" />
</widget>

A good source of examples are starter kits. Like phonegap-start or Ionic starter

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

For the records I had this issue and was a stupid mistake on my end. My issue was data type mismatch. Data type in database table and C# classes should be same......

How to "add existing frameworks" in Xcode 4?

I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.

How to clear an EditText on click?

Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..

Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.

pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png

How to set the authorization header using curl

Just adding so you don't have to click-through:

curl --user name:password http://www.example.com

or if you're trying to do send authentication for OAuth 2:

curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com

#if DEBUG vs. Conditional("DEBUG")

Let's presume your code also had an #else statement which defined a null stub function, addressing one of Jon Skeet's points. There's a second important distinction between the two.

Suppose the #if DEBUG or Conditional function exists in a DLL which is referenced by your main project executable. Using the #if, the evaluation of the conditional will be performed with regard to the library's compilation settings. Using the Conditional attribute, the evaluation of the conditional will be performed with regard to the compilation settings of the invoker.

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Crystal Reports 13 And Asp.Net 3.5

I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:

  1. Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.

  2. You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS

  3. Make sure you setup FULL TRUST permission on your root folder

  4. The LOCAL SERVICE permission must be setup on your application pool

  5. Make sure the aspnet_client folder exists on your root folder.

If you can make sure all the 5 points above, your Crystal Report should work without any fuss.

Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.

Good luck!

@synthesize vs @dynamic, what are the differences?

One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.

Get size of folder or file

I've tested du -c <folderpath> and is 2x faster than nio.Files or recursion

private static long getFolderSize(File folder){
  if (folder != null && folder.exists() && folder.canRead()){
    try {
      Process p = new ProcessBuilder("du","-c",folder.getAbsolutePath()).start();
      BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String total = "";
      for (String line; null != (line = r.readLine());)
        total = line;
      r.close();
      p.waitFor();
      if (total.length() > 0 && total.endsWith("total"))
        return Long.parseLong(total.split("\\s+")[0]) * 1024;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  return -1;
}

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Getting first and last day of the current month

An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

var now = DateTime.Now; // get the current DateTime 

//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
    
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1); 
    
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);

//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay; 

JSON.parse unexpected character error

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

Change icon on click (toggle)

Try this:

$('#click_advance').click(function(){
  $('#display_advance').toggle('1000');
  icon = $(this).find("i");
  icon.hasClass("icon-circle-arrow-down"){
    icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
  }else{
    icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
  }
})

or even better, as Kevin said:

$('#click_advance').click(function(){
  $('#display_advance').toggle('1000');
  icon = $(this).find("i");
  icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})

PHP display current server path

You can also use the following alternative realpath.

Create a file called path.php

Put the following code inside by specifying the name of the created file.

<?php 
    echo realpath('path.php'); 
?>

A php file that you can move to all your folders to always have the absolute path from where the executed file is located.

;-)

Java error: Comparison method violates its general contract

It might also be an OpenJDK bug... (not in this case but it is the same error)

If somebody like me stumbles upon this answer regarding the

java.lang.IllegalArgumentException: Comparison method violates its general contract!

then it might also be a bug in the Java-Version. I have a compareTo running since several years now in some applications. But suddenly it stopped working and throws the error after all compares were done (i compare 6 Attributes before returning "0").

Now I just found this Bugreport of OpenJDK:

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

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.

<PropertyGroup>
  <Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>

<ItemGroup>
  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>

<Target Name="GenerateNetcoreExe"
        AfterTargets="Build"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
  <Exec
    ConsoleToMSBuild="true"
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
  </Exec>
  <Copy
    SourceFiles="@(BootStrapFiles)"
    DestinationFolder="$(OutputPath)"
  />

</Target>

I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

How to convert an array to object in PHP?

Actually if you want to use this with multi-dimensional arrays you would want to use some recursion.

static public function array_to_object(array $array)
{
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $array[$key] = self::array_to_object($value);
        }
    }
    return (object)$array;
}

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

Parse an HTML string with JS

var doc = new DOMParser().parseFromString(html, "text/html");
var links = doc.querySelectorAll("a");

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

Python List & for-each access (Find/Replace in built-in list)

You could replace something in there by getting the index along with the item.

>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
...     print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
...     if item in ('a', 'A'):
...         foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']

Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.

Wrong:

>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
...     if isinstance(item, int):
...         foo.remove(item)
...
>>> foo 
['a', 'b', 'c', 2]

The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:

>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
...     if isinstance(item, int):
...         foo.remove(item)
...
>>> foo 
['a', 'b', 'c']

Find all zero-byte files in directory and subdirectories

Bash 4+ tested - This is the correct way to search for size 0:

find /path/to/dir -size 0 -type f -name "*.xml"

Search for multiple file extensions of size 0:

find /path/to/dir -size 0 -type f \( -iname \*.css -o -iname \*.js \)

Note: If you removed the \( ... \) the results would be all of the files that meet this requirement hence ignoring the size 0.

Jquery function BEFORE form submission

You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});

Returning a value from callback function in Node.js

Example code for node.js - async function to sync function:

var deasync = require('deasync');

function syncFunc()
{
    var ret = null;
    asyncFunc(function(err, result){
        ret = {err : err, result : result}
    });

    while((ret == null))
    {
         deasync.runLoopOnce();
    }

    return (ret.err || ret.result);
}

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

Connecting to SQL Server with Visual Studio Express Editions

The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.

SQL 'LIKE' query using '%' where the search criteria contains '%'

The easiest solution is to dispense with "like" altogether:

Select * 
from table
where charindex(search_criteria, name) > 0

I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.

Unable to install Android Studio in Ubuntu

None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

How to resume Fragment from BackStack if exists

I think this method my solve your problem:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

which was originally posted in This Question

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

even i faced the same problem. The possibility of this could be usage of same port by two or more application/process. In Some cases you can use different port number which will avoid this problem, but in other case you have to manually kill the process with help of command prompt.

The command to kill is, In your command prompt first enter this command

C:\Users\A611003>tasklist

After this you can able to see list of process running with process ID. For example, enter image description here

From this select the process you want to stop, for example consider the process id 304 is your server and you have problem with that. Then enter this command.

C:\Users\A611003>Taskkill /PID 304 /F

This will kill that process now you can clean, publish your server and start it.

Note: If you fail to add /F in the above command it does nothing. It is the force kill. you can also try/? for list of available options.

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

MAX function in where clause mysql

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT.

The normative pattern for solving this type of problem is to use an inline view, something like this:

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
  JOIN ( SELECT MAX(mx.id) AS max_id
           FROM mytable mx
       ) m
    ON m.max_id = t.id

This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:

 WHERE t.id = (SELECT MAX(id) FROM ... )

Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
 ORDER BY t.id DESC
 LIMIT 1

Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)

This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5.

Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

How to connect to LocalDB in Visual Studio Server Explorer?

Visual Studio 2015 RC, has LocalDb 12 installed, similar instructions to before but still shouldn't be required to know 'magic', before hand to use this, the default instance should have been turned on ... Rant complete, no for solution:

cmd> sqllocaldb start

Which will display

LocalDB instance "MSSQLLocalDB" started.

Your instance name might differ. Either way pop over to VS and open Server Explorer, right click Data Connections, choose Add, choose SQL Server, in the server name type:

(localdb)\MSSQLLocalDB

Without entering in a DB name, click 'Test Connection'.

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

How to delete duplicate lines in a file without sorting it in Unix?

This can be achieved using awk
Below Line will display unique Values

awk file_name | uniq

You can output these unique values to a new file

awk file_name | uniq > uniq_file_name

new file uniq_file_name will contain only Unique values, no duplicates

Immutable vs Mutable types

A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed

In another word change the entire value of that variable (name) or leave it alone.

Example:

my_string = "Hello world" 
my_string[0] = "h"
print my_string 

you expected this to work and print hello world but this will throw the following error:

Traceback (most recent call last):
File "test.py", line 4, in <module>
my_string[0] = "h"
TypeError: 'str' object does not support item assignment

The interpreter is saying : i can't change the first character of this string

you will have to change the whole string in order to make it works:

my_string = "Hello World" 
my_string = "hello world"
print my_string #hello world

check this table:

enter image description here

source

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

How to remove decimal values from a value of type 'double' in Java

I did this to remove the decimal places from the double value

new DecimalFormat("#").format(100.0);

The output of the above is

100

What does "O(1) access time" mean?

O(1) always execute in the same time regardless of dataset n. An example of O(1) would be an ArrayList accessing its element with index.

O(n) also known as Linear Order, the performance will grow linearly and in direct proportion to the size of the input data. An example of O(n) would be an ArrayList insertion and deletion at random position. As each subsequent insertion/deletion at random position will cause the elements in the ArrayList to shift left right of its internal array in order to maintain its linear structure, not to mention about the creation of a new arrays and the copying of elements from the old to new array which takes up expensive processing time hence, detriment the performance.

Delayed function calls

It sounds like the control of the creation of both these objects and their interdependence needs to controlled externally, rather than between the classes themselves.

Does "display:none" prevent an image from loading?

The trick to using display:none with images is to assign them an id. This was there is not a lot of code needed to make it work. Here is an example using media queries and 3 stylesheets. One for phone, one for tablet, and one for desktop. I have 3 images, image of a phone, a tablet, and a desktop. On a phone screen only an image of the phone will display, a tablet will display only the tablet image, a desktop displays on the desktop computer image. Here is a code example to make it work:

Source code:

<div id="content">
<img id="phone" src="images/phone.png" />
<img id="tablet" src="images/tablet.png" />
<img id="desktop" src="images/desktop.png" />
</div>

The phone CSS which doesn't need a media query. Its the img#phone that makes it work:

img#phone {
    display: block;
    margin: 6em auto 0 auto;
    width: 70%;
    }

img#tablet {display: none;}
img#desktop {display: none;}

The tablet css:

@media only screen and (min-width: 641px) {
img#phone {display: none;}

img#tablet {
    display: block;
    margin: 6em auto 0 auto;
    width: 70%;
    }
}

And the desktop css:

@media only screen and (min-width: 1141px) {
img#tablet {display: none;}

img#desktop {
    display: block;
    margin: 6em auto 0 auto;
    width: 80%;
    }
}

Good luck and let me know how it works for you.

What does "export default" do in JSX?

Export like export default HelloWorld; and import, such as import React from 'react' are part of the ES6 modules system.

A module is a self contained unit that can expose assets to other modules using export, and acquire assets from other modules using import.

In your code:

import React from 'react'; // get the React object from the react module

class HelloWorld extends React.Component {
  render() {
    return <p>Hello, world!</p>;
  }
}

export default HelloWorld; // expose the HelloWorld component to other modules

In ES6 there are two kinds of exports:

Named exports - for example export function func() {} is a named export with the name of func. Named modules can be imported using import { exportName } from 'module';. In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';. There can be multiple named exports in one module.

Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.

A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';.

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;
}

.min-100 {
    min-height: 100%;
}

https://codeply.com/go/dTaVyMah1U

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;
}

https://codeply.com/go/kMahVdZyGj

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

ASP.NET 2.0 - How to use app_offline.htm

Note that this behaves the same on IIS 6 and 7.x, and .NET 2, 3, and 4.x.

Also note that when app_offline.htm is present, IIS will return this http status code:

HTTP/1.1 503 Service Unavailable

This is all by design. This allows your load balancer (or whatever) to see that the server is off line.

Formatting "yesterday's" date in python

all answers are correct, but I want to mention that time delta accepts negative arguments.

>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

Reset select value to default

For those who are working with Bootstrap-select, you might want to use this:

$('#mySelect').selectpicker('render');

Group a list of objects by an attribute

Implement SQL GROUP BY Feature in Java using Comparator, comparator will compare your column data, and sort it. Basically if you keep sorted data that looks as grouped data, for example if you have same repeated column data then sort mechanism sort them keeping same data one side and then look for other data which is dissimilar data. This indirectly viewed as GROUPING of same data.

public class GroupByFeatureInJava {

    public static void main(String[] args) {
        ProductBean p1 = new ProductBean("P1", 20, new Date());
        ProductBean p2 = new ProductBean("P1", 30, new Date());
        ProductBean p3 = new ProductBean("P2", 20, new Date());
        ProductBean p4 = new ProductBean("P1", 20, new Date());
        ProductBean p5 = new ProductBean("P3", 60, new Date());
        ProductBean p6 = new ProductBean("P1", 20, new Date());

        List<ProductBean> list = new ArrayList<ProductBean>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        list.add(p5);
        list.add(p6);

        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
        System.out.println("******** AFTER GROUP BY PRODUCT_ID ******");
        Collections.sort(list, new ProductBean().new CompareByProductID());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }

        System.out.println("******** AFTER GROUP BY PRICE ******");
        Collections.sort(list, new ProductBean().new CompareByProductPrice());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
    }
}

class ProductBean {
    String productId;
    int price;
    Date date;

    @Override
    public String toString() {
        return "ProductBean [" + productId + " " + price + " " + date + "]";
    }
    ProductBean() {
    }
    ProductBean(String productId, int price, Date date) {
        this.productId = productId;
        this.price = price;
        this.date = date;
    }
    class CompareByProductID implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.productId.compareTo(p2.productId) > 0) {
                return 1;
            }
            if (p1.productId.compareTo(p2.productId) < 0) {
                return -1;
            }
            // at this point all a.b,c,d are equal... so return "equal"
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByProductPrice implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            // this mean the first column is tied in thee two rows
            if (p1.price > p2.price) {
                return 1;
            }
            if (p1.price < p2.price) {
                return -1;
            }
            return 0;
        }
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByCreateDate implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.date.after(p2.date)) {
                return 1;
            }
            if (p1.date.before(p2.date)) {
                return -1;
            }
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }
}

Output is here for the above ProductBean list is done GROUP BY criteria, here if you see the input data that is given list of ProductBean to Collections.sort(list, object of Comparator for your required column) This will sort based on your comparator implementation and you will be able to see the GROUPED data in below output. Hope this helps...

    ******** BEFORE GROUPING INPUT DATA LOOKS THIS WAY ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ******** AFTER GROUP BY PRODUCT_ID ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

    ******** AFTER GROUP BY PRICE ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

Center Contents of Bootstrap row container

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</p>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The answer is misleading because it attempts to fix a problem that is not a problem. You actually CAN have a WHERE CLAUSE in each segment of a UNION. You cannot have an ORDER BY except in the last segment. Therefore, this should work...

select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
-----remove this-- order by ReceivedDate desc
union
select top 2 t2.ID,  t2.ReceivedDate --- add second column
  from Table t2
 where t2.Type = 'TYPE_2'
order by ReceivedDate desc

JQuery Redirect to URL after specified time

Yes, the solution is to use setTimeout, like this:

var delay = 10000;
var url = "https://stackoverflow.com";
var timeoutID = setTimeout(function() {
    window.location.href = url;
}, delay);

note that the result was stored into timeoutID. If, for whatever reason you need to cancel the order, you just need to call

clearTimeout(timeoutID);

How to check if curl is enabled or disabled

you can check by putting these code in php file.

<?php
if(in_array  ('curl', get_loaded_extensions())) {
    echo "CURL is available on your web server";
}
else{
    echo "CURL is not available on your web server";
}

OR

var_dump(extension_loaded('curl'));

SHA-1 fingerprint of keystore certificate

Open Command Prompt in Windows and go to the following folder .

C:\Program Files\Java\jdk1.7.0_05\bin

Use commands cd <next directory name> to change directory to next. Use command cd .. to change directory to the Prev

Now type the following command as it is :

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

BackgroundWorker vs background Thread

If it ain't broke - fix it till it is...just kidding :)

But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.

Set a path variable with spaces in the path in a Windows .cmd file or batch file

also just try adding double slashes like this works for me only

set dir="C:\\1. Some Folder\\Some Other Folder\\Just Because"

@echo on MKDIR %dir%

OMG after posting they removed the second \ in my post so if you open my comment and it shows three you should read them as two......

How to remove duplicate values from an array in PHP

Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.

$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
    if(!in_array($a[$i], $b)){
        array_push($b, $a[$i]);
    }
}
print_r ($b);

Get installed applications in a system

You can take a look at this article. It makes use of registry to read the list of installed applications.

public void GetInstalledApps()
{
    string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
    using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
    {
        foreach (string skName in rk.GetSubKeyNames())
        {
            using (RegistryKey sk = rk.OpenSubKey(skName))
            {
                try
                {
                    lstInstalled.Items.Add(sk.GetValue("DisplayName"));
                }
                catch (Exception ex)
                { }
            }
        }
    }
}

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

How to show math equations in general github's markdown(not github's blog)

One other work-around is to use jupyter notebooks and use the markdown mode in cells to render equations.

Basic stuff seems to work perfectly, like centered equations

\begin{equation}
...
\end{equation}

or inline equations

$ \sum_{\forall i}{x_i^{2}} $

Although, one of the functions that I really wanted did not render at all in github was \mbox{}, which was a bummer. But, all in all this has been the most successful way of rendering equations on github.

Fixed width buttons with Bootstrap

Best way to the solution of your problem is to use button block btn-block with desired column width.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
    <div class="col-md-12">_x000D_
      <button class="btn btn-primary btn-block">Save</button>_x000D_
    </div>_x000D_
    <div class="col-md-12">_x000D_
        <button class="btn btn-success btn-block">Download</button>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

How to split a string in shell and get the last field

There are many good answers here, but still I want to share this one using basename :

 basename $(echo "a:b:c:d:e" | tr ':' '/')

However it will fail if there are already some '/' in your string. If slash / is your delimiter then you just have to (and should) use basename.

It's not the best answer but it just shows how you can be creative using bash commands.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Try to login via the terminal using the following command:

mysql -u root -p

It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:

database_password: "0000"

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

How to restore default perspective settings in Eclipse IDE

There is no keyboard shortcut for restoring the perspective directly AFAIK. To open the Window menu (where Reset Perspective resides), try Alt-W. If that does not work, I guess your Eclipse has hung for some reason. Another shortcut you might want to try is F10 (should open the main menu).

Convert Dictionary to JSON in Swift

You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.

Here is example code that will convert a dictionary of strings to JSON:

Swift 3 version:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: dictionary,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    print("JSON string = \(theJSONText!)")
}

To display the above in "pretty printed" format you'd change the options line to:

    options: [.prettyPrinted]

Or in Swift 2 syntax:

import Foundation
 
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)
let theJSONText = NSString(data: theJSONData!,
  encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")

The output of that is

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"

Or in pretty format:

{
  "anotherKey" : "anotherValue",
  "aKey" : "aValue"
}

The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.

EDIT:

In Swift 3/4 syntax, the code above looks like this:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
  }

How do I validate a date in rails?

A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:

Inside your model.rb

validate :date_field_must_be_a_date_or_blank

# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
  date_field_before_type_cast.to_date
rescue ArgumentError
  errors.add(:birthday, :invalid)
end

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

Get bitcoin historical data

In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.

The script uses python websocket-client and pusher_client_python libraries, so install them.

#!/usr/bin/python

import pusherclient
import time
import logging
import sys
import datetime
import signal
import os

logging.basicConfig()
log_file_fd = None

def sigint_and_sigterm_handler(signal, frame):
    global log_file_fd
    log_file_fd.close()
    sys.exit(0)


class BitstampLogger:

    def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
        self.channel = channel
        self.event = event
        self.log_file_fd = open(log_file_path, "a")
        self.log_file_reload_path = log_file_reload_path
        self.pusher = pusherclient.Pusher(pusher_key)
        self.pusher.connection.logger.setLevel(logging.WARNING)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()

    def callback(self, data):
        utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
        line = str(utc_timestamp) + " " + data + "\n"
        if os.path.exists(self.log_file_reload_path):
            os.remove(self.log_file_reload_path)
            self.log_file_fd.close()
            self.log_file_fd = open(log_file_path, "a")
        self.log_file_fd.write(line)

    def connect_handler(self, data):
        channel = self.pusher.subscribe(self.channel)
        channel.bind(self.event, self.callback)


def main(log_file_path, log_file_reload_path):
    global log_file_fd
    bitstamp_logger = BitstampLogger(
        log_file_path,
        log_file_reload_path,
        "de504dc5763aeef9ff52",
        "live_trades",
        "trade")
    log_file_fd = bitstamp_logger.log_file_fd
    signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
    signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
    while True:
        time.sleep(1)


if __name__ == '__main__':
    log_file_path = sys.argv[1]
    log_file_reload_path = sys.argv[2]
    main(log_file_path, log_file_reload_path

and logrotate file config

/mnt/data/bitstamp_logs/bitstamp-trade.log
{
    rotate 10000000000
    minsize 10M
    copytruncate
    missingok
    compress
    postrotate
        touch /mnt/data/bitstamp_logs/reload_log > /dev/null
    endscript
}

then you can run it on background

nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &

Best way to create a simple python web service

If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy

What are the differences between a program and an application?

My understanding is this:

  • A computer program is a set of instructions that can be executed on a computer.
  • An application is software that directly helps a user perform tasks.
  • The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications.

How to get the text node of an element?

Pure JavaScript: Minimalist

First off, always keep this in mind when looking for text in the DOM.

MDN - Whitespace in the DOM

This issue will make you pay attention to the structure of your XML / HTML.

In this pure JavaScript example, I account for the possibility of multiple text nodes that could be interleaved with other kinds of nodes. However, initially, I do not pass judgment on whitespace, leaving that filtering task to other code.

In this version, I pass a NodeList in from the calling / client code.

/**
* Gets strings from text nodes. Minimalist. Non-robust. Pre-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
    var trueTarget = target - 1,
        length = nodeList.length; // Because you may have many child nodes.

    for (var i = 0; i < length; i++) {
        if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
            return nodeList[i].nodeValue;  // Done! No need to keep going.
        }
    }

    return null;
}

Of course, by testing node.hasChildNodes() first, there would be no need to use a pre-test for loop.

/**
* Gets strings from text nodes. Minimalist. Non-robust. Post-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
    var trueTarget = target - 1,
        length = nodeList.length,
        i = 0;

    do {
        if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
            return nodeList[i].nodeValue;  // Done! No need to keep going.
         }

        i++;
    } while (i < length);

    return null;
}

Pure JavaScript: Robust

Here the function getTextById() uses two helper functions: getStringsFromChildren() and filterWhitespaceLines().


getStringsFromChildren()

/**
* Collects strings from child text nodes.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @version 7.0
* @param parentNode An instance of the Node interface, such as an Element. object.
* @return Array of strings, or null.
* @throws TypeError if the parentNode is not a Node object.
*/
function getStringsFromChildren(parentNode)
{
    var strings = [],
        nodeList,
        length,
        i = 0;

    if (!parentNode instanceof Node) {
        throw new TypeError("The parentNode parameter expects an instance of a Node.");
    }

    if (!parentNode.hasChildNodes()) {
        return null; // We are done. Node may resemble <element></element>
    }

    nodeList = parentNode.childNodes;
    length = nodeList.length;

    do {
        if ((nodeList[i].nodeType === Node.TEXT_NODE)) {
            strings.push(nodeList[i].nodeValue);
         }

        i++;
    } while (i < length);

    if (strings.length > 0) {
        return strings;
    }

    return null;
}

filterWhitespaceLines()

/**
* Filters an array of strings to remove whitespace lines.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param textArray a String associated with the id attribute of an Element.
* @return Array of strings that are not lines of whitespace, or null.
* @throws TypeError if the textArray param is not of type Array.
*/
function filterWhitespaceLines(textArray) 
{
    var filteredArray = [],
        whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.

    if (!textArray instanceof Array) {
        throw new TypeError("The textArray parameter expects an instance of a Array.");
    }

    for (var i = 0; i < textArray.length; i++) {
        if (!whitespaceLine.test(textArray[i])) {  // If it is not a line of whitespace.
            filteredArray.push(textArray[i].trim());  // Trimming here is fine. 
        }
    }

    if (filteredArray.length > 0) {
        return filteredArray ; // Leave selecting and joining strings for a specific implementation. 
    }

    return null; // No text to return.
}

getTextById()

/**
* Gets strings from text nodes. Robust.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param id A String associated with the id property of an Element.
* @return Array of strings, or null.
* @throws TypeError if the id param is not of type String.
* @throws TypeError if the id param cannot be used to find a node by id.
*/
function getTextById(id) 
{
    var textArray = null;             // The hopeful output.
    var idDatatype = typeof id;       // Only used in an TypeError message.
    var node;                         // The parent node being examined.

    try {
        if (idDatatype !== "string") {
            throw new TypeError("The id argument must be of type String! Got " + idDatatype);
        }

        node = document.getElementById(id);

        if (node === null) {
            throw new TypeError("No element found with the id: " + id);
        }

        textArray = getStringsFromChildren(node);

        if (textArray === null) {
            return null; // No text nodes found. Example: <element></element>
        }

        textArray = filterWhitespaceLines(textArray);

        if (textArray.length > 0) {
            return textArray; // Leave selecting and joining strings for a specific implementation. 
        }
    } catch (e) {
        console.log(e.message);
    }

    return null; // No text to return.
}

Next, the return value (Array, or null) is sent to the client code where it should be handled. Hopefully, the array should have string elements of real text, not lines of whitespace.

Empty strings ("") are not returned because you need a text node to properly indicate the presence of valid text. Returning ("") may give the false impression that a text node exists, leading someone to assume that they can alter the text by changing the value of .nodeValue. This is false, because a text node does not exist in the case of an empty string.

Example 1:

<p id="bio"></p> <!-- There is no text node here. Return null. -->

Example 2:

<p id="bio">

</p> <!-- There are at least two text nodes ("\n"), here. -->

The problem comes in when you want to make your HTML easy to read by spacing it out. Now, even though there is no human readable valid text, there are still text nodes with newline ("\n") characters in their .nodeValue properties.

Humans see examples one and two as functionally equivalent--empty elements waiting to be filled. The DOM is different than human reasoning. This is why the getStringsFromChildren() function must determine if text nodes exist and gather the .nodeValue values into an array.

for (var i = 0; i < length; i++) {
    if (nodeList[i].nodeType === Node.TEXT_NODE) {
            textNodes.push(nodeList[i].nodeValue);
    }
}

In example two, two text nodes do exist and getStringFromChildren() will return the .nodeValue of both of them ("\n"). However, filterWhitespaceLines() uses a regular expression to filter out lines of pure whitespace characters.

Is returning null instead of newline ("\n") characters a form of lying to the client / calling code? In human terms, no. In DOM terms, yes. However, the issue here is getting text, not editing it. There is no human text to return to the calling code.

One can never know how many newline characters might appear in someone's HTML. Creating a counter that looks for the "second" newline character is unreliable. It might not exist.

Of course, further down the line, the issue of editing text in an empty <p></p> element with extra whitespace (example 2) might mean destroying (maybe, skipping) all but one text node between a paragraph's tags to ensure the element contains precisely what it is supposed to display.

Regardless, except for cases where you are doing something extraordinary, you will need a way to determine which text node's .nodeValue property has the true, human readable text that you want to edit. filterWhitespaceLines gets us half way there.

var whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.

for (var i = 0; i < filteredTextArray.length; i++) {
    if (!whitespaceLine.test(textArray[i])) {  // If it is not a line of whitespace.
        filteredTextArray.push(textArray[i].trim());  // Trimming here is fine. 
    }
}

At this point you may have output that looks like this:

["Dealing with text nodes is fun.", "Some people just use jQuery."]

There is no guarantee that these two strings are adjacent to each other in the DOM, so joining them with .join() might make an unnatural composite. Instead, in the code that calls getTextById(), you need to chose which string you want to work with.

Test the output.

try {
    var strings = getTextById("bio");

    if (strings === null) {
        // Do something.
    } else if (strings.length === 1) {
        // Do something with strings[0]
    } else { // Could be another else if
        // Do something. It all depends on the context.
    }
} catch (e) {
    console.log(e.message);
}

One could add .trim() inside of getStringsFromChildren() to get rid of leading and trailing whitespace (or to turn a bunch of spaces into a zero length string (""), but how can you know a priori what every application may need to have happen to the text (string) once it is found? You don't, so leave that to a specific implementation, and let getStringsFromChildren() be generic.

There may be times when this level of specificity (the target and such) is not required. That is great. Use a simple solution in those cases. However, a generalized algorithm enables you to accommodate simple and complex situations.

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal can have better performance if the edges can be sorted in linear time, or are already sorted.

Prim's better if the number of edges to vertices is high.

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

GCM with PHP (Google Cloud Messaging)

A lot of the tutorials are outdated, and even the current code doesn't account for when device registration_ids are updated or devices unregister. If those items go unchecked, it will eventually cause issues that prevent messages from being received. http://forum.loungekatt.com/viewtopic.php?t=63#p181

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

Sort array of objects by string property value

function compare(propName) {
    return function(a,b) {
        if (a[propName] < b[propName])
            return -1;
        if (a[propName] > b[propName])
            return 1;
        return 0;
    };
}

objs.sort(compare("last_nom"));

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

Apache won't follow symlinks (403 Forbidden)

Related to this question, I just figured out why my vhost was giving me that 403.

I had tested ALL possibilities on this question and others without luck. It almost drives me mad.

I am setting up a server with releases deployment similar to Capistrano way through symlinks and when I tried to access the DocRoot folder (which is now a symlink to current release folder) it gave me the 403.

My vhost is:

DocumentRoot /var/www/site.com/html
<Directory /var/www/site.com/html>
        AllowOverride All
        Options +FollowSymLinks
        Require all granted
</Directory>

and my main httpd.conf file was (default Apache 2.4 install):

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes -FollowSymLinks -Includes
(...)

It turns out that the main Options definition was taking precedence over my vhosts fiel (for me that is counter intuitive). So I've changed it to:

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes +FollowSymLinks -Includes
(...)

and Eureka! (note the plus sign before FollowSymLinks in MAIN httpd.conf file. Hope this help some other lost soul.

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

Constructor of an abstract class in C#

I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents

abstract classes are normal classes with A few exceptions

  1. You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
  2. It may has abstract function.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Just create the database using createdb CLI tool:

PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

Eventviewer eventid for lock and unlock

For Windows 10 the event ID for lock=4800 and unlock=4801.

As it says in the answer provided by Mario and User 00000, you will need to enable logging of lock and unlock events by using their method described above by running gpedit.msc and navigating to the branch they indicated:

Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies - Local Group Policy Object -> Logon/Logoff -> Audit Other Login/Logoff

Enable for both success and failure events.

After enabling logging of those events you can filter for Event ID 4800 and 4801 directly.

This method works for Windows 10 as I just used it to filter my security logs after locking and unlocking my computer.

How to add bootstrap to an angular-cli project

Open Terminal/command prompt in the respective project directory and type following command.

npm install --save bootstrap

Then open .angular-cli.json file, Look for

"styles": [ "styles.css" ],

change that to

 "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
  ],

All done.

Twitter Bootstrap dropdown menu

You must include jQuery in the project.

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

I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php

Hope this helps someone else.

Laravel 5 How to switch from Production mode

Do not forget to run the command php artisan config:clear after you have made the changes to the .env file. Done this again php artisan env, which will return the correct version.

How to return Json object from MVC controller to view

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

Generic information about tables and columns can be found in these tables:

select * from INFORMATION_SCHEMA.TABLES
select * from INFORMATION_SCHEMA.COLUMNS

The table description is an extended property, you can query them from sys.extended_properties:

select 
    TableName = tbl.table_schema + '.' + tbl.table_name, 
    TableDescription = prop.value,
    ColumnName = col.column_name, 
    ColumnDataType = col.data_type
FROM information_schema.tables tbl
INNER JOIN information_schema.columns col 
    ON col.table_name = tbl.table_name
    AND col.table_schema = tbl.table_schema
LEFT JOIN sys.extended_properties prop 
    ON prop.major_id = object_id(tbl.table_schema + '.' + tbl.table_name) 
    AND prop.minor_id = 0
    AND prop.name = 'MS_Description' 
WHERE tbl.table_type = 'base table'

How to disable EditText in Android

Write this in parent:

android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

Example:

<RelativeLayout 
android:id="@+id/menu_2_zawezanie_rl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/menu_2_horizontalScrollView"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="horizontal"
android:background="@drawable/rame">

<EditText
    android:id="@+id/menu2_et"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/menu2_ibtn"
    android:gravity="center"
    android:hint="@string/filtruj" >
</EditText>
<ImageButton
    android:id="@+id/menu2_ibtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:background="@null"
    android:src="@drawable/selector_btn" />

how to remove the first two columns in a file using shell (awk, sed, whatever)

You can use sed:

sed 's/^[^ ][^ ]* [^ ][^ ]* //'

This looks for lines starting with one-or-more non-blanks, a blank, another set of one-or-more non-blanks and another blank, and deletes the matched material, aka the first two fields. The [^ ][^ ]* is marginally shorter than the equivalent but more explicit [^ ]\{1,\} notation, and the second might run into issues with GNU sed (though if you use --posix as an option, even GNU sed can't screw it up). OTOH, if the character class to be repeated was more complex, the numbered notation wins for brevity. It is easy to extend this to handle 'blank or tab' as separator, or 'multiple blanks' or 'multiple blanks or tabs'. It could also be modified to handle optional leading blanks (or tabs) before the first field, etc.

For awk and cut, see Sampson-Chen's answer. There are other ways to write the awk script, but they're not materially better than the answer given. Note that you might need to set the field separator explicitly (-F" ") in awk if you do not want tabs treated as separators, or you might have multiple blanks between fields. The POSIX standard cut does not support multiple separators between fields; GNU cut has the useful but non-standard -i option to allow for multiple separators between fields.

You can also do it in pure shell:

while read junk1 junk2 residue
do echo "$residue"
done < in-file > out-file

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Ignore outliers in ggplot2 boxplot

The "coef" option of the geom_boxplot function allows to change the outlier cutoff in terms of interquartile ranges. This option is documented for the function stat_boxplot. To deactivate outliers (in other words they are treated as regular data), one can instead of using the default value of 1.5 specify a very high cutoff value:

library(ggplot2)
# generate data with outliers:
df = data.frame(x=1, y = c(-10, rnorm(100), 10)) 
# generate plot with increased cutoff for outliers:
ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl

to new : jdbc:oracle:thin:@//localhost:1521/orcl

and it worked for me.....hurrah!! image

Convert a list to a string in C#

If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList). Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().

Return Boolean Value on SQL Select Statement

What you have there will return no row at all if the user doesn't exist. Here's what you need:

SELECT CASE WHEN EXISTS (
    SELECT *
    FROM [User]
    WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

How do I use a file grep comparison inside a bash if/else statement?

just use bash

while read -r line
do
  case "$line" in
    *MYSQL_ROLE=master*)
       echo "do your stuff";;
    *) echo "doesn't exist";;      
  esac
done <"/etc/aws/hosts.conf"

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

Google Maps JavaScript API RefererNotAllowedMapError

The Problem
Google suggestions the format *.example.com/*
This format does not work.

The Solution
Check the browser console for the Google Maps JavaScript API error: RefererNotAllowedMapError
Underneath the error it should have: "Your site URL to be authorized: https://example.com/".
Use that url for the referrer and add a wildcard * to the end of it (https://example.com/*, in this case).

Arrays.asList() of an array

Use java.utils.Arrays:

public int getTheNumber(int[] factors) {
    int[] f = (int[])factors.clone();
    Arrays.sort(f);
    return f[0]*f[(f.length-1];
}

Or if you want to be efficient avoid all the object allocation just actually do the work:

public static int getTheNumber(int[] array) {
    if (array.length == 0)
        throw new IllegalArgumentException();
    int min = array[0];
    int max = array[0];
    for (int i = 1; i< array.length;++i) {
        int v = array[i];
        if (v < min) {
            min = v;
        } else if (v > max) {
            max = v;
        }
    }
    return min * max;
}

PHPExcel auto size column width

$col = 'A';
while(true){
    $tempCol = $col++;
    $objPHPExcel->getActiveSheet()->getColumnDimension($tempCol)->setAutoSize(true);
    if($tempCol == $objPHPExcel->getActiveSheet()->getHighestDataColumn()){
        break;
    }
}

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

Determining image file size + dimensions via Javascript?

var img = new Image();
img.src = sYourFilePath;
var iSize = img.fileSize;

How to open a different activity on recyclerView item onclick

Simply you can do it easy... You just need to get the context of your activity, here, from your View.

//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion

Remember that you need to modify AndroidManifest.xml and place the activity...

<activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>

target input by type and name (selector)

You can combine attribute selectors this way:

$("[attr1=val][attr2=val]")...

so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]. jQuery has a selector for that, namely :checkbox so the end result is:

$("input:checkbox[name=ProductCode]")...

Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:

<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">

allowing you to use the much faster selector of:

$("input.ProductCode")...

How do I conditionally add attributes to React components?

Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...( condition && { disabled: true } )
};

var component = <div { ...props } />;

Or its inline version

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);

Execute a stored procedure in another stored procedure in SQL server

Your sp_test: Return fullname

USE [MY_DB]
GO

IF (OBJECT_ID('[dbo].[sp_test]', 'P') IS NOT NULL)
DROP PROCEDURE [dbo].sp_test;
GO

CREATE PROCEDURE [dbo].sp_test 
@name VARCHAR(20),
@last_name VARCHAR(30),
@full_name VARCHAR(50) OUTPUT
AS

SET @full_name = @name + @last_name;

GO

In your sp_main

...
DECLARE @my_name VARCHAR(20);
DECLARE @my_last_name VARCHAR(30);
DECLARE @my_full_name VARCHAR(50);
...

EXEC sp_test @my_name, @my_last_name, @my_full_name OUTPUT;
...

psql: server closed the connection unexepectedly

Solved by setting a password for the user first.

In terminal

sudo -u <username> psql

ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE

\q

In pgAdmin

**Connection**

Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX

How to do the equivalent of pass by reference for primitives in Java

You have several choices. The one that makes the most sense really depends on what you're trying to do.

Choice 1: make toyNumber a public member variable in a class

class MyToy {
  public int toyNumber;
}

then pass a reference to a MyToy to your method.

void play(MyToy toy){  
    System.out.println("Toy number in play " + toy.toyNumber);   
    toy.toyNumber++;  
    System.out.println("Toy number in play after increement " + toy.toyNumber);   
}

Choice 2: return the value instead of pass by reference

int play(int toyNumber){  
    System.out.println("Toy number in play " + toyNumber);   
    toyNumber++;  
    System.out.println("Toy number in play after increement " + toyNumber);   
    return toyNumber
}

This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.

Choice 3: make it a class or static variable

If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.

Choice 4: Create a single element array of type int and pass that

This is considered a hack, but is sometimes employed to return values from inline class invocations.

void play(int [] toyNumber){  
    System.out.println("Toy number in play " + toyNumber[0]);   
    toyNumber[0]++;  
    System.out.println("Toy number in play after increement " + toyNumber[0]);   
}

Converting std::__cxx11::string to std::string

I got this, the only way I found to fix this was to update all of mingw-64 (I did this using pacman on msys2 for your information).

Spring @ContextConfiguration how to put the right location for the xml

Our Tests look like this (using Maven and Spring 3.1):

@ContextConfiguration
(
  {
   "classpath:beans.xml",
   "file:src/main/webapp/WEB-INF/spring/applicationContext.xml",
   "file:src/main/webapp/WEB-INF/spring/dispatcher-data-servlet.xml",
   "file:src/main/webapp/WEB-INF/spring/dispatcher-servlet.xml"
  }
)
@RunWith(SpringJUnit4ClassRunner.class)
public class CCustomerCtrlTest
{
  @Resource private ApplicationContext m_oApplicationContext;
  @Autowired private RequestMappingHandlerAdapter m_oHandlerAdapter;
  @Autowired private RequestMappingHandlerMapping m_oHandlerMapping;
  private MockHttpServletRequest m_oRequest;
  private MockHttpServletResponse m_oResp;
  private CCustomerCtrl m_oCtrl;

// more code ....
}

Remove blank attributes from an Object in Javascript

ES10/ES2019 examples

A simple one-liner (returning a new object).

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

Same as above but written as a function.

function removeEmpty(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}

This function uses recursion to remove items from nested objects.

function removeEmpty(obj) {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
  );
}

ES6/ES2015 examples

A simple one-liner. Warning: This mutates the given object instead of returning a new one.

Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);

A single declaration (not mutating the given object).

let o = Object.keys(obj)
  .filter((k) => obj[k] != null)
  .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});

Same as above but written as a function.

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
}

This function uses recursion to remove items from nested objects.

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce(
      (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),
      {}
    );
}

Same as the function above, but written in an imperative (non-functional) style.

function removeEmpty(obj) {
  const newObj = {};
  Object.entries(obj).forEach(([k, v]) => {
    if (v === Object(v)) {
      newObj[k] = removeEmpty(v);
    } else if (v != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

ES5/ES2009 examples

In the old days things were a lot more verbose.

This is a non recursive version written in a functional style.

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = obj[k];
      return acc;
    }, {});
}

This is a non recursive version written in an imperative style.

function removeEmpty(obj) {
  const newObj = {};
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      newObj[k] = removeEmpty(obj[k]);
    } else if (obj[k] != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

And a recursive version written in a functional style.

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k];
      return acc;
    }, {});
}

How do I declare and initialize an array in Java?

package com.examplehub.basics;

import java.util.Arrays;

public class Array {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        System.out.println("numbers[0] = " + numbers[0]);
        System.out.println("numbers[1] = " + numbers[1]);
        System.out.println("numbers[2] = " + numbers[2]);
        System.out.println("numbers[3] = " + numbers[3]);
        System.out.println("numbers[4] = " + numbers[4]);

        /*
         * Array index is out of bounds
         */
        //System.out.println(numbers[-1]);
        //System.out.println(numbers[5]);


        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        for (int i = 0; i < 5; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * Length of numbers = 5
         */
        System.out.println("length of numbers = " + numbers.length);

        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * numbers[4] = 5
         * numbers[3] = 4
         * numbers[2] = 3
         * numbers[1] = 2
         * numbers[0] = 1
         */
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * 12345
         */
        for (int number : numbers) {
            System.out.print(number);
        }
        System.out.println();

        /*
         * [1, 2, 3, 4, 5]
         */
        System.out.println(Arrays.toString(numbers));



        String[] company = {"Google", "Facebook", "Amazon", "Microsoft"};

        /*
         * company[0] = Google
         * company[1] = Facebook
         * company[2] = Amazon
         * company[3] = Microsoft
         */
        for (int i = 0; i < company.length; i++) {
            System.out.println("company[" + i + "] = " + company[i]);
        }

        /*
         * Google
         * Facebook
         * Amazon
         * Microsoft
         */
        for (String c : company) {
            System.out.println(c);
        }

        /*
         * [Google, Facebook, Amazon, Microsoft]
         */
        System.out.println(Arrays.toString(company));

        int[][] twoDimensionalNumbers = {
                {1, 2, 3},
                {4, 5, 6, 7},
                {8, 9},
                {10, 11, 12, 13, 14, 15}
        };

        /*
         * total rows  = 4
         */
        System.out.println("total rows  = " + twoDimensionalNumbers.length);

        /*
         * row 0 length = 3
         * row 1 length = 4
         * row 2 length = 2
         * row 3 length = 6
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.println("row " + i + " length = " + twoDimensionalNumbers[i].length);
        }

        /*
         * row 0 = 1 2 3
         * row 1 = 4 5 6 7
         * row 2 = 8 9
         * row 3 = 10 11 12 13 14 15
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.print("row " + i + " = ");
            for (int j = 0; j < twoDimensionalNumbers[i].length; j++) {
                System.out.print(twoDimensionalNumbers[i][j] + " ");
            }
            System.out.println();
        }

        /*
         * row 0 = [1, 2, 3]
         * row 1 = [4, 5, 6, 7]
         * row 2 = [8, 9]
         * row 3 = [10, 11, 12, 13, 14, 15]
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.println("row " + i + " = " + Arrays.toString(twoDimensionalNumbers[i]));
        }

        /*
         * 1 2 3
         * 4 5 6 7
         * 8 9
         * 10 11 12 13 14 15
         */
        for (int[] ints : twoDimensionalNumbers) {
            for (int num : ints) {
                System.out.print(num + " ");
            }
            System.out.println();
        }

        /*
         * [1, 2, 3]
         * [4, 5, 6, 7]
         * [8, 9]
         * [10, 11, 12, 13, 14, 15]
         */
        for (int[] ints : twoDimensionalNumbers) {
            System.out.println(Arrays.toString(ints));
        }


        int length = 5;
        int[] array = new int[length];
        for (int i = 0; i < 5; i++) {
            array[i] = i + 1;
        }

        /*
         * [1, 2, 3, 4, 5]
         */
        System.out.println(Arrays.toString(array));

    }
}

Source from examplehub/java

jQuery get the image src

src should be in quotes:

$('.img1 img').attr('src');

SharePoint 2013 get current user using JavaScript

U can use javascript to achive that like this:

function loadConstants() {

    this.clientContext = new SP.ClientContext.get_current();
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);
      completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));


}

//U must set a timeout to recivie the exactly user u want:

function onQuerySucceeded(sender, args) {

    window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {

    console.log(args.get_message());
}

//By using a proper timeout, u can get current user :

function ttt(){ 

    var clientContext = new SP.ClientContext.get_current();
    var groupCollection = clientContext.get_web().get_siteGroups();
    visitorsGroup = groupCollection.getByName('OLAP Portal Members');

    t=this.currentUser .get_loginName().toLowerCase();

    console.log ('this.currentUser .get_loginName() : '+ t);      

}

How can I parse String to Int in an Angular expression?

You can use javascript Number method to parse it to an number,

var num=Number (num_str);

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

Java JRE 64-bit download for Windows?

You can also just search on sites like Tucows and CNET, they have it there too.

Inheriting from a template class in c++

#include<iostream>

using namespace std;

template<class t> 
class base {
protected:
    t a;
public:
    base(t aa){
        a = aa;
        cout<<"base "<<a<<endl;
    }
};

template <class t> 
class derived: public base<t>{
    public:
        derived(t a): base<t>(a) {
        }
        //Here is the method in derived class 
    void sampleMethod() {
        cout<<"In sample Method"<<endl;
    }
};

int main() {
    derived<int> q(1);
    // calling the methods
    q.sampleMethod();
}

Split output of command by columns using Bash?

Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:

command|head -n 6|tail -n 1|awk '{print $4}'

How can one print a size_t variable portably using the printf family?

For those talking about doing this in C++ which doesn't necessarily support the C99 extensions, then I heartily recommend boost::format. This makes the size_t type size question moot:

std::cout << boost::format("Sizeof(Var) is %d\n") % sizeof(Var);

Since you don't need size specifiers in boost::format, you can just worry about how you want to display the value.

Find the min/max element of an array in JavaScript

Simple stuff, really.

var arr = [10,20,30,40];
arr.max = function() { return  Math.max.apply(Math, this); }; //attach max funct
arr.min = function() { return  Math.min.apply(Math, this); }; //attach min funct

alert("min: " + arr.min() + " max: " + arr.max());

Find largest and smallest number in an array

You assign to big and small before the array is initialized, i.e., big and small assume the value of whatever is on the stack at this point. As they are just plain value types and no references, they won't assume a new value once values[0] is written to via cin >>.

Just move the assignment after your first loop and it should be fine.

How to add an object to an ArrayList in Java

You have to use new operator here to instantiate. For example:

Contacts.add(new Data(name, address, contact));

How to download file in swift?

Swift 3

you want to download file bite by bite and show in progress view so you want to try this code

import UIKit

class ViewController: UIViewController,URLSessionDownloadDelegate,UIDocumentInteractionControllerDelegate {

    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var btndown: UIButton!
    var urlLink: URL!
    var defaultSession: URLSession!
    var downloadTask: URLSessionDownloadTask!
    //var backgroundSession: URLSession!
    @IBOutlet weak var progress: UIProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()

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

        let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
        defaultSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
        progress.setProgress(0.0, animated: false)
    }

    func startDownloading () {
        let url = URL(string: "http://publications.gbdirect.co.uk/c_book/thecbook.pdf")!
        downloadTask = defaultSession.downloadTask(with: url)
        downloadTask.resume()
    }

    @IBAction func btndown(_ sender: UIButton) {

        startDownloading()

    }

    func showFileWithPath(path: String){
        let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
        if isFileFound == true{
            let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
            viewer.delegate = self
            viewer.presentPreview(animated: true)
        }

    }


    // MARK:- URLSessionDownloadDelegate
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

        print(downloadTask)
        print("File download succesfully")

        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path[0]
        let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.pdf"))

        if fileManager.fileExists(atPath: destinationURLForFile.path){
            showFileWithPath(path: destinationURLForFile.path)
            print(destinationURLForFile.path)
        }
        else{
            do {
                try fileManager.moveItem(at: location, to: destinationURLForFile)
                // show file
                showFileWithPath(path: destinationURLForFile.path)
            }catch{
                print("An error occurred while moving file to destination url")
            }
        }



    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        progress.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        downloadTask = nil
        progress.setProgress(0.0, animated: true)
        if (error != nil) {
            print("didCompleteWithError \(error?.localizedDescription ?? "no value")")
        }
        else {
            print("The task finished successfully")
        }
    }

    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController
    {
        return self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

use of this code you want to download file store automatically in Document Directory in your application

this code 100% Working

how to include js file in php?

I tried this, I've got something like

script type="text/javascript" src="createDiv.php?id=" script

AND In createDiv.php I Have

document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';

And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld php variable was formatted cut and paste from the html page

But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.

How do I print a list of "Build Settings" in Xcode project?

In case you would like to read/check your Target Build Settings in runtime using code, here is the way:

1) Add a Run Script:

cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj 

It will copy the Target Build Settings file into your Main Bundle (will be called BuildSetting.pbxproj).

2) You can now check the contents of that file at any time in code:

NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];

What is the difference between linear regression and logistic regression?

Regression means continuous variable, Linear means there is linear relation between y and x. Ex= You are trying to predict salary from no of years of experience. So here salary is independent variable(y) and yrs of experience is dependent variable(x). y=b0+ b1*x1 Linear regression We are trying to find optimum value of constant b0 and b1 which will give us best fitting line for your observation data. It is a equation of line which gives continuous value from x=0 to very large value. This line is called Linear regression model.

Logistic regression is type of classification technique. Dnt be misled by term regression. Here we predict whether y=0 or 1.

Here we first need to find p(y=1) (wprobability of y=1) given x from formuale below.

prob

Probaibility p is related to y by below formuale

s

Ex=we can make classification of tumour having more than 50% chance of having cancer as 1 and tumour having less than 50% chance of having cancer as 0. 5

Here red point will be predicted as 0 whereas green point will be predicted as 1.

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

Retrieving the output of subprocess.call()

I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:

import shlex
from subprocess import Popen, PIPE

def get_exitcode_stdout_stderr(cmd):
    """
    Execute the external command and get its exitcode, stdout and stderr.
    """
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode
    #
    return exitcode, out, err

cmd = "..."  # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)

I also have a blog post on it here.

Edit: the solution was updated to a newer one that doesn't need to write to temp. files.

What is the difference between a function expression vs declaration in JavaScript?

Regarding 3rd definition:

var foo = function foo() { return 5; }

Heres an example which shows how to use possibility of recursive call:

a = function b(i) { 
  if (i>10) {
    return i;
  }
  else {
    return b(++i);
  }
}

console.log(a(5));  // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15

Edit: more interesting example with closures:

a = function(c) {
 return function b(i){
  if (i>c) {
   return i;
  }
  return b(++i);
 }
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8

How to put a jar in classpath in Eclipse?

Right click on the project in which you want to put jar file. A window will open like this

enter image description here

Click on the AddExternal Jars there you can give the path to that jar file

Strange "java.lang.NoClassDefFoundError" in Eclipse

I had a similar problem and it had to do with the libraries referenced by the java build path; I was referencing libraries that didn't exist anymore when I did an update. When I removed these references, by project started running again.

The libraries are listed under the Java Build Path in the project properties window.

Hope this helps.

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

How do I specify different layouts for portrait and landscape orientations?

  1. Right click res folder,
  2. New -> Android Resource File
  3. in Available qualifiers, select Orientation,
  4. add to Chosen qualifier
  5. in Screen orientation, select Landscape
  6. Press OK

Using Android Studio 3.4.1, it no longer creates layout-land folder. It will create a folder and put two layout files together.

enter image description here

How to convert characters to HTML entities using plain JavaScript

The he library is the only 100% reliable solution that I know of!

He is written by Mathias Bynens - one of the world's most renowned JavaScript gurus - and has the following features :


Example use

he.encode('foo © bar ? baz  qux'); 
// Output : 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'

he.decode('foo &copy; bar &ne; baz &#x1D306; qux');
// Output : 'foo © bar ? baz  qux'

CSS: Auto resize div to fit container width

You can overflow:hidden to your #content. Write like this:

#content
{
    min-width:700px;
    margin-left:10px;
    overflow:hidden;
    background-color:AppWorkspace;
}

Check this http://jsfiddle.net/Zvt2j/1/

How to run mvim (MacVim) from Terminal?

For Mac .app bundles, you should install them via cask, if available, as using symlinks can cause issues. You may even get the following warning if you brew linkapps:

Unfortunately brew linkapps cannot behave nicely with e.g. Spotlight using either aliases or symlinks and Homebrew formulae do not build "proper" .app bundles that can be relocated. Instead, please consider using brew cask and migrate formulae using .apps to casks.

For MacVim, you can install with:

brew cask install macvim

You should then be able to launch MacVim like you do any other macOS app, including mvim or open -a MacVim from a terminal session.

UPDATE: A bit of clarification about brew and brew cask. In a nutshell, brew handles software at the unix level, whereas brew cask extends the functionality of brew into the macOS domain for additional functionality such as handling the location of macOS app bundles. Remember that brew is also implemented on Linux so it makes sense to have this division. There are other resources that explain the difference in more detail, such as What is the difference between brew and brew cask? so I won't say much more here.

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You tried to do a.setText(a1). a1 is an int value, but setText() requires a string value. For this reason you need use String.valueOf(a1) to pass the value of a1 as a String and not as an int to a.setText(), like so:

a.setText(String.valueOf(a1))

that was the exact solution to the problem with my case.

Concatenate multiple node values in xpath

<xsl:template match="element3">
        <xsl:value-of select="element4,element5" separator="."/>
    </xsl:template>

How to calculate the number of occurrence of a given character in each row of a column of strings?

s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)

May not be the efficient one but solve my purpose.

Getting JSONObject from JSONArray

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

for(int i = 0; deletedtrs_array.length(); i++){

            JSONObject myObj = deletedtrs_array.getJSONObject(i);
}

Determine the path of the executing BASH script

Vlad's code is overquoted. Should be:

MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`

JQUERY ajax passing value from MVC View to Controller

I didn't want to open another threat so ill post my problem here

Ajax wont forward value to controller, and i just cant find an error :(

-JS

<script>
        $(document).ready(function () {
            $("#sMarka").change(function () {
                var markaId = $(this).val();
                alert(markaId);
                debugger
                $.ajax({
                    type:"POST",
                    url:"@Url.Action("VratiModele")",
                    dataType: "html",
                    data: { "markaId": markaId },
                    success: function (model) {
                        debugger
                        $("#sModel").empty();
                        $("#sModel").append(model);
                    }
                });
            });
        });
    </script>

--controller

public IActionResult VratiModele(int markaId = 0)
        {
            if (markaId != 0)
            {
                List<Model> listaModela = db.Modeli.Where(m => m.MarkaId == markaId).ToList();
                ViewBag.ModelVozila = new SelectList(listaModela, "ModelId", "Naziv");
            }
            else
            {
                ViewBag.Greska = markaId.ToString();
            }

            return PartialView();
        }

Getting Textarea Value with jQuery

By using new version of jquery (1.8.2), I amend the current code like in this links http://jsfiddle.net/q5EXG/97/

By using the same code, I just change from jQuery to '$'

<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>

$('#send-thoughts').click(function()
{ var thought = $('#message').val();
  alert(thought);
});

Convert a negative number to a positive one in JavaScript

The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).

var y = -100;
var x =- y;

How to get the day name from a selected date?

(DateTime.Parse((Eval("date").ToString()))).DayOfWeek.ToString()

at the place of Eval("date"),you can use any date...get name of day

Serializing and submitting a form with jQuery and PHP

 $("#contactForm").submit(function() {

    $.post(url, $.param($(this).serializeArray()), function(data) {

    });
 });

Ruby on Rails: Where to define global constants?

Use a class method:

def self.colours
  ['white', 'red', 'black']
end

Then Model.colours will return that array. Alternatively, create an initializer and wrap the constants in a module to avoid namespace conflicts.

How to disable Django's CSRF validation?

If you just need some views not to use CSRF, you can use @csrf_exempt:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

You can find more examples and other scenarios in the Django documentation:

How to change href attribute using JavaScript after opening the link in a new window?

You can delay your code using setTimeout to execute after click

function changeLink(){
    setTimeout(function() {
        var link = document.getElementById("mylink");
        link.setAttribute('href', "http://facebook.com");
        document.getElementById("mylink").innerHTML = "facebook";
    }, 100);
}

Access to ES6 array element index inside for-of loop

Use Array.prototype.keys:

_x000D_
_x000D_
for (const index of [1, 2, 3, 4, 5].keys()) {_x000D_
  console.log(index);_x000D_
}
_x000D_
_x000D_
_x000D_

If you want to access both the key and the value, you can use Array.prototype.entries() with destructuring:

_x000D_
_x000D_
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {_x000D_
  console.log(index, value);_x000D_
}
_x000D_
_x000D_
_x000D_

Print array without brackets and commas

I used join() function like:

i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");

Which Prints:
HiHelloCheersGreetings


See more: Javascript Join - Use Join to Make an Array into a String in Javascript

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

The column of the first matrix and the row of the second matrix should be equal and the order should be like this only

column of first matrix = row of second matrix

and do not follow the below step

row of first matrix  = column of second matrix

it will throw an error

Google Maps API v3: InfoWindow not sizing correctly

I was having the same problem with IE and tried many of the fixes detailed in these responses, but was unable to remove the vertical scrollbars in IE reliably.

What worked best for me was to switch to fixed font sizes inside the infowindow -- 'px'... I was using ems. By fixing the font size I no longer needed to explicitly declare the infowindow width or height and the scrollbars were gone for good.

A formula to copy the values from a formula to another column

What about trying with VLOOKUP? The syntax is:

=VLOOKUP(cell you want to copy, range you want to copy, 1, FALSE).

It should do the trick.

Bootstrap select dropdown list placeholder

Solution for Angular 2

Create a label on top of the select

<label class="hidden-label" for="IsActive"
    *ngIf="filterIsActive == undefined">Placeholder text</label>
<select class="form-control form-control-sm" type="text" name="filterIsActive"
    [(ngModel)]="filterIsActive" id="IsActive">
    <option value="true">true</option>
    <option value="false">false</option>
</select>

and apply CSS to place it on top

.hidden-label {
    position: absolute;
    margin-top: .34rem;
    margin-left: .56rem;
    font-style: italic;
    pointer-events: none;
}

pointer-events: none allows you to display the select when you click on the label, which is hidden when you select an option.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Trying to detect browser close event

Following script will give message on Chrome and IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome
enter image description here

IE
enter image description here

on Firefox you will get generic message

enter image description here

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.

How do I install cygwin components from the command line?

Usually before installing a package one has to know its exact name:

# define a string to search
export to_srch=perl

# get html output of search and pick only the cygwin package names
wget -qO- "https://cygwin.com/cgi-bin2/package-grep.cgi?grep=$to_srch&arch=x86_64" | \
perl -l -ne 'm!(.*?)<\/a>\s+\-(.*?)\:(.*?)<\/li>!;print $2'

# and install 
# install multiple packages at once, note the
setup-x86_64.exe -q -s http://cygwin.mirror.constant.com -P "<<chosen_package_name>>"

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

Asynchronous Requests with Python requests

You can use httpx for that.

import httpx

async def get_async(url):
    async with httpx.AsyncClient() as client:
        return await client.get(url)

urls = ["http://google.com", "http://wikipedia.org"]

# Note that you need an async context to use `await`.
await asyncio.gather(*map(get_async, urls))

if you want a functional syntax, the gamla lib wraps this into get_async.

Then you can do


await gamla.map(gamla.get_async(10))(["http://google.com", "http://wikipedia.org"])

The 10 is the timeout in seconds.

(disclaimer: I am its author)

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

How do I prompt a user for confirmation in bash script?

This way you get 'y' 'yes' or 'Enter'

 read -r -p "Are you sure? [Y/n]" response
 response=${response,,} # tolower
 if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
 fi

If you are using zsh try this:

read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
fi

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

How can I create tests in Android Studio?

I think this post by Rex St John is very useful for unit testing with android studio.


(source: rexstjohn.com)

How to urlencode a querystring in Python?

For use in scripts/programs which need to support both python 2 and 3, the six module provides quote and urlencode functions:

>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'

How I can check if an object is null in ruby on rails 2?

it's nilin Ruby, not null. And it's enough to say if @objectname to test whether it's not nil. And no then. You can find more on if syntax here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.