Programs & Examples On #Alter

'alter' is a SQL keyword used to change or modify the table structure or the records in a table.

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

How to add new column to MYSQL table?

for WORDPRESS:

global $wpdb;


$your_table  = $wpdb->prefix. 'My_Table_Name';
$your_column =                'My_Column_Name'; 

if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
    "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"
);}

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

create table test (a int, b int , c int, d int);
alter table test drop column b, d;

Be aware that DROP COLUMN does not physically remove the data, and for fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD.

How to change column datatype in SQL database without losing data

for me , in sql server 2016, I do it like this

*To rename column Column1 to column2

EXEC sp_rename 'dbo.T_Table1.Column1', 'Column2', 'COLUMN'

*To modify column Type from string to int:( Please be sure that data are in the correct format)

ALTER TABLE dbo.T_Table1 ALTER COLUMN Column2  int; 

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

How to remove constraints from my MySQL table?

Also nice, you can temporarily disable all foreign key checks from a mysql database: SET FOREIGN_KEY_CHECKS=0; And to enable it again: SET FOREIGN_KEY_CHECKS=1;

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

How can I get column names from a table in SQL Server?

Just run this command

EXEC sp_columns 'Your Table Name'

Trying to SSH into an Amazon Ec2 instance - permission error

I have seen two reasons behind this issue

1) access key does not have the right permission. pem keys with default permission are not allowed to make a secure connection. You just have to change the permission:

chmod 400 xyz.pem

2) Also check whether you have logged-in with proper user credentials. Otherwise, use sudo while connecting

sudo ssh -i {keyfile} ec2-user@{ip address of remote host}

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

uncaught syntaxerror unexpected token U JSON

I was getting this message while validating (in MVC project). For me, adding ValidationMessageFor element fixed the issue.

To be precise, line number 43 in jquery.validate.unobtrusive.js caused the issue:

  replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

Sprint == Iteration.

The lengths can vary, but it's a bad planning precedent to let them vary too much.

Keep them consistent in duration and you will get better at planning and delivering. Everything will be measured by how many 10-day sprints it takes to finish a series of use cases.

Keep them consistent in length and you can plan your deliveries, end-user testing, etc., with more accuracy.

The point is to release on time at a consistent pace. A regular schedule makes management slightly simpler and more predictable.

IPC performance: Named Pipe vs Socket

For two way communication with named pipes:

  • If you have few processes, you can open two pipes for two directions (processA2ProcessB and processB2ProcessA)
  • If you have many processes, you can open in and out pipes for every process (processAin, processAout, processBin, processBout, processCin, processCout etc)
  • Or you can go hybrid as always :)

Named pipes are quite easy to implement.

E.g. I implemented a project in C with named pipes, thanks to standart file input-output based communication (fopen, fprintf, fscanf ...) it was so easy and clean (if that is also a consideration).

I even coded them with java (I was serializing and sending objects over them!)

Named pipes has one disadvantage:

  • they do not scale on multiple computers like sockets since they rely on filesystem (assuming shared filesystem is not an option)

How can I show a combobox in Android?

Here is an example of custom combobox in android:

package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

public class ComboBox extends LinearLayout {

   private AutoCompleteTextView _text;
   private ImageButton _button;

   public ComboBox(Context context) {
       super(context);
       this.createChildControls(context);
   }

   public ComboBox(Context context, AttributeSet attrs) {
       super(context, attrs);
       this.createChildControls(context);
}

 private void createChildControls(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

   _text = new AutoCompleteTextView(context);
   _text.setSingleLine();
   _text.setInputType(InputType.TYPE_CLASS_TEXT
                   | InputType.TYPE_TEXT_VARIATION_NORMAL
                   | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                   | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                   | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
   _text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
   this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT, 1));

   _button = new ImageButton(context);
   _button.setImageResource(android.R.drawable.arrow_down_float);
   _button.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                   _text.showDropDown();
           }
   });
   this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));
 }

/**
    * Sets the source for DDLB suggestions.
    * Cursor MUST be managed by supplier!!
    * @param source Source of suggestions.
    * @param column Which column from source to show.
    */
 public void setSuggestionSource(Cursor source, String column) {
    String[] from = new String[] { column };
    int[] to = new int[] { android.R.id.text1 };
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
                   android.R.layout.simple_dropdown_item_1line, source, from, to);
    // this is to ensure that when suggestion is selected
    // it provides the value to the textbox
    cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
    _text.setAdapter(cursorAdapter);
 }

/**
    * Gets the text in the combo box.
    *
    * @return Text.
    */
public String getText() {
    return _text.getText().toString();
 }

/**
    * Sets the text in combo box.
    */
public void setText(String text) {
    _text.setText(text);
   }
}

Hope it helps!!

Thread Safe C# Singleton Pattern

Reflection resistant Singleton pattern:

public sealed class Singleton
{
    public static Singleton Instance => _lazy.Value;
    private static Lazy<Singleton, Func<int>> _lazy { get; }

    static Singleton()
    {
        var i = 0;
        _lazy = new Lazy<Singleton, Func<int>>(() =>
        {
            i++;
            return new Singleton();
        }, () => i);
    }

    private Singleton()
    {
        if (_lazy.Metadata() == 0 || _lazy.IsValueCreated)
            throw new Exception("Singleton creation exception");
    }

    public void Run()
    {
        Console.WriteLine("Singleton called");
    }
}

How to change date format in JavaScript

You can certainly format the date yourself..

var mydate = new Date(form.startDate.value);
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"][mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();

You can also use an external library, such as DateJS.

Here's a DateJS example:

<script src="http://www.datejs.com/build/date.js" type="text/javascript"></script>
<script>
   var mydate = new Date(form.startDate.value);
   var str = mydate.toString("MMMM yyyy");
   window.alert(str);
</script>

C# Numeric Only TextBox Control

this way is right with me:

private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
     const char Delete = (char)8;
     e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

Opacity of background-color, but not the text

Relaxing your requirement to work on IE6 and legacy browsers you can use ::before and display: inline-block

div
{
  display: inline-block;
  position: relative;    
}
div::before
{
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background:red;
  opacity: .2;
}

Demo at http://jsfiddle.net/KVyFH/172/ ?

It will work on any modern browser

Rotation of 3D vector?

Using pyquaternion is extremely simple; to install it (while still in python), run in your console:

import pip;
pip.main(['install','pyquaternion'])

Once installed:

  from pyquaternion import Quaternion
  v = [3,5,0]
  axis = [4,4,1]
  theta = 1.2 #radian
  rotated_v = Quaternion(axis=axis,angle=theta).rotate(v)

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

Reading a text file with SQL Server

Just discovered this:

SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents

It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB with:

SINGLE_NCLOB for nvarchar(max) SINGLE_BLOB for varbinary(max)

Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!

How to return the current timestamp with Moment.js?

Current date using momment.js in DD-MM-YYYY format

const currentdate=moment().format("DD-MM-YYYY"); 
console.log(currentdate)

How to open a link in new tab using angular?

In the app-routing.modules.ts file:

{
    path: 'hero/:id', component: HeroComponent
}

In the component.html file:

target="_blank" [routerLink]="['/hero', '/sachin']"

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

.col-xs-$   Extra Small     Phones Less than 768px 
.col-sm-$   Small Devices   Tablets 768px and Up 
.col-md-$   Medium Devices  Desktops 992px and Up 
.col-lg-$   Large Devices   Large Desktops 1200px and Up 

iPad WebApp Full Screen in Safari

  1. First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.

  2. After locating the webpage, tap on the arrow icon at the top of your screen.

  3. In the drop-down menu, tap on the Add to Home Screen option.

  4. The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.

  5. A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.

Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:

<meta name="apple-mobile-web-app-capable" content="yes">

You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.

Maven version with a property

If you're using Maven 3, one option to work around this problem is to use the versions plugin http://www.mojohaus.org/versions-maven-plugin/

Specifically the commands,

mvn versions:set -DnewVersion=2.0-RELEASE
mvn versions:commit

This will update the parent and child poms to 2.0-RELEASE. You can run this as a build step before.

Unlike the release plugin, it doesn't try to talk to your source control

How to pass the button value into my onclick event function?

You can pass the value to the function using this.value, where this points to the button

<input type="button" value="mybutton1" onclick="dosomething(this.value)">

And then access that value in the function

function dosomething(val){
  console.log(val);
}

How do I restart my C# WinForm Application?

Take for instance an application that:

  1. While application is not registered; (upon start) the application should prompt the user to register the application and create a login account.

  2. Once registration is submitted and login credentials are created; the application should restart, check for registration and prompt the user to login with the inserted credentials (so the user can access to all the application features).

Problem: By building and launching the application from Visual Studio; any of the 4 alternatives bellow will fail to accomplish the tasks required.

/*
 * Note(s):
 * Take into consideration that the lines bellow don't represent a code block.
 * They are just a representation of possibilities,
 * that can be used to restart the application.
 */

Application.Restart();
Application.Exit();
Environment.Exit(int errorCode);
Process.GetCurrentProcess().Kill();

What happens is: After creating the Registration, Login and calling Application.Restart(); the application will (strangely) reopen the Registration Form and skip data in a Database (even though the resource is set to "Copy if Newer").

Solution: Batch Building the application was (for me) a proof that any of the lines above were actually working as expected. Just not when building and running the application with Visual Studio.

In first place I'd try batch building the application; run it outside Visual Studio and check if Application.Restart() actually works as expected.

Also Check further Info regarding this thread subject: How do I restart my C# WinForm Application?

generate days from date range

improved with weekday an joining a custom holiday table microsoft MSSQL 2012 for powerpivot date table https://gist.github.com/josy1024/cb1487d66d9e0ccbd420bc4a23b6e90e

with [dates] as (
    select convert(datetime, '2016-01-01') as [date] --start
    union all
    select dateadd(day, 1, [date])
    from [dates]
    where [date] < '2018-01-01' --end
)
select [date]
, DATEPART (dw,[date]) as Wochentag
, (select holidayname from holidaytable 
where holidaytable.hdate = [date]) 
as Feiertag
from [dates]
where [date] between '2016-01-01' and '2016-31-12'
option (maxrecursion 0)

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

In the hopes it might narrow things down/help someone, I did an investigatory approach. For me, I initially moved the folder at C:\Users\{user}\AppData\Local\Microsoft\VisualStudio to My Documents and allowed Visual Studio to re-create it by re-launching it. This removed the errors. So I moved everything back, one-by-one, and restarted Visual Studio each time until I discovered the culprits. These folders were fine to move back in:

  • 1033 (overwrote the auto-generated copy with old)
  • Designer (was in my old copy, not initially re-created when I re-launched VS, copied it back in)
  • Extensions (overwrote the auto-generated copy with old)
  • ImageLibrary (overwrote the auto-generated copy with old)
  • Notifications (overwrote the auto-generated copy with old)
  • STemplate (was in my old copy, not initially re-created when I re-launched VS, copied it back in)
  • VTC (was in my old copy, not initially re-created when I re-launched VS, copied it back in)

These files were fine to move back in/overwrite the auto-generated ones:

  • ApplicationPrivateSettings (was in my old copy, not initially re-created when I re-launched VS)
  • ApplicationPrivateSettings.lock (overwrote the auto-generated copy with old)
  • vspdmc.lock (overwrote the auto-generated copy with old)

These files were fine to move back in. Each was in my old copy, and not initially re-created when I re-launched VS:

  • .NETFramework,Version=v4.0,Set=Framework,Hash=C958D412.dat
  • .NETFramework,Version=v4.0,Set=RecentAssemblies,Hash=0.dat
  • .NETFramework,Version=v4.5,Set=Extensions,Hash=75EAE334.dat
  • .NETFramework,Version=v4.5,Set=Extensions,Hash=497525A2.dat
  • .NETFramework,Version=v4.5,Set=Framework,Hash=5AE9A175.dat
  • .NETFramework,Version=v4.5.2,Set=Extensions,Hash=24CEEB0D.dat
  • .NETFramework,Version=v4.5.2,Set=Extensions,Hash=72AE305.dat
  • .NETFramework,Version=v4.5.2,Set=Extensions,Hash=ADF899D7.dat
  • .NETFramework,Version=v4.5.2,Set=Framework,Hash=D8E943A2.dat

These caused problems - delete these files and re-launch VS to allow it to re-create them:

  • ComponentModelCache - When I overwrote this folder's contents with my old ones (4 files: MS.VS.Default.cache, .catalogs, .err, .external), this gave me all of the errors I had gotten before about not being able to load packages when loading my project, and the "object reference not set to an instance of an object" error when trying to close VS.
  • devenv.exe.config - same as ComponentModelCache
  • .NETFramework,Version=v4.0,Set=Extensions,Hash=6D09DECC.dat - causes error output from the JavaScript Language Service, complaining of missing js files
  • .NETFramework,Version=v4.0,Set=Extensions,Hash=9951BC03.dat - causes error output from the JavaScript Language Service, complaining of missing js files
  • .NETFramework,Version=v4.5.2,Set=RecentAssemblies,Hash=0.dat - causes error output from the JavaScript Language Service, complaining of missing js files

These are the errors from those last .NETFramework files (which I do not get if I do not add them back in):

01:10:11.7550: Referenced file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\libhelp.js' not found.
01:10:11.7550: Referenced file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\sitetypesWeb.js' not found.
01:10:11.7550: Referenced file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\domWeb.js' not found.
01:10:11.7550: Referenced file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\underscorefilter.js' not found.
01:10:11.7550: Referenced file 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\showPlainComments.js' not found.

I might just need to re-install/repair the JavaScript Language Service plug-in, so it might be un-related. But definitely devenv.exe.config and ComponentModelCache need to go to correct the "object reference not set to an instance of an object" error.

Linux find file names with given string recursively

A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.

man -k <your search term>

What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)

That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:

man -k find | egrep '\(1\)'

or, if you also want to look for commands that require higher privilege levels, like this:

man -k find | egrep '\([18]\)'

bash script read all the files in directory

A simple loop should be working:

for file in /var/*
do
    #whatever you need with "$file"
done

See bash filename expansion

How to use Git for Unity3D source control?

The following is an excerpt from my personal blog .

Using Git with 3D Games

Update Oct 2015: GitHub has since released a plugin for Git called Git LFS that directly deals with the below problem. You can now easily and efficiently version large binary files!

Git can work fine with 3D games out of the box. However the main caveat here is that versioning large (>5 MB) media files can be a problem over the long term as your commit history bloats. We have solved this potential issue in our projects by only versioning the binary asset when it is considered final. Our 3D artists use Dropbox to work on WIP assets, both for the reason above and because it's much faster and simpler (not many artists will actively want to use Git!).

Git Workflow

Your Git workflow is very much something you need to decide for yourself given your own experiences as a team and how you work together. However. I would strongly recommend the appropriately named Git Flow methodology as described by the original author here.

I won't go into too much depth here on how the methodology works as the author describes it perfectly and in quite few words too so it's easy to get through. I have been using with my team for awhile now, and it's the best workflow we've tried so far.

Git GUI Client Application

This is really a personal preference here as there are quite a few options in terms of Git GUI or whether to use a GUI at all. But I would like to suggest the free SourceTree application as it plugs in perfectly with the Git Flow extension. Read the SourceTree tutorial here on implementing the Git Flow methodology in their application.

Unity3D Ignore Folders

For an up to date version checkout Github maintained Unity.gitignore file without OS specifics.

# =============== #
# Unity generated #
# =============== #
Temp/
Library/

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
obj/
*.svd
*.userprefs
/*.csproj
*.pidb
*.suo
/*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

Unity3D Settings

For versions of Unity 3D v4.3 and up:

  1. (Skip this step in v4.5 and up) Enable External option in Unity ? Preferences ? Packages ? Repository.
  2. Open the Edit menu and pick Project Settings ? Editor:
    1. Switch Version Control Mode to Visible Meta Files.
    2. Switch Asset Serialization Mode to Force Text.
  3. Save the scene and project from File menu.

Want you migrate your existing repo to LFS?

Check out my blog post for steps on how to do it here.

Additional Configuration

One of the few major annoyances one has with using Git with Unity3D projects is that Git doesn't care about directories and will happily leave empty directories around after removing files from them. Unity3D will make *.meta files for these directories and can cause a bit of a battle between team members when Git commits keep adding and removing these meta files.

Add this Git post-merge hook to the /.git/hooks/ folder for repositories with Unity3D projects in them. After any Git pull/merge, it will look at what files have been removed, check if the directory it existed in is empty, and if so delete it.

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

How do I efficiently iterate over each entry in a Java Map?

package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}

Plotting a fast Fourier transform in Python

The important thing about fft is that it can only be applied to data in which the timestamp is uniform (i.e. uniform sampling in time, like what you have shown above).

In case of non-uniform sampling, please use a function for fitting the data. There are several tutorials and functions to choose from:

https://github.com/tiagopereira/python_tips/wiki/Scipy%3A-curve-fitting http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

If fitting is not an option, you can directly use some form of interpolation to interpolate data to a uniform sampling:

https://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html

When you have uniform samples, you will only have to wory about the time delta (t[1] - t[0]) of your samples. In this case, you can directly use the fft functions

Y    = numpy.fft.fft(y)
freq = numpy.fft.fftfreq(len(y), t[1] - t[0])

pylab.figure()
pylab.plot( freq, numpy.abs(Y) )
pylab.figure()
pylab.plot(freq, numpy.angle(Y) )
pylab.show()

This should solve your problem.

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

ERROR! MySQL manager or server PID file could not be found! QNAP

screenshot

If you're using MySQL Workbench, the mysql.server stop/restart/start will not work.

You will need to login into the workbench and then click "shutdown server". See image attached.

Simulating a click in jQuery/JavaScript on a link

Why not just the good ol' javascript?

$('#element')[0].click()

How to get ° character in a string in python?

This is the most coder-friendly version of specifying a unicode character:

degree_sign= u'\N{DEGREE SIGN}'

Note: must be a capital N in the \N construct to avoid confusion with the '\n' newline character. The character name inside the curly braces can be any case.

It's easier to remember the name of a character than its unicode index. It's also more readable, ergo debugging-friendly. The character substitution happens at compile time: the .py[co] file will contain a constant for u'°':

>>> import dis
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval')
>>> dis.dis(c)
  1           0 LOAD_CONST               0 (u'\xb0')
              3 RETURN_VALUE
>>> c.co_consts
(u'\xb0',)
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval')
>>> c.co_consts
(u'\xb0-\u2205',)
>>> print c.co_consts[0]
°-Ø

How do I print the content of a .txt file in Python?

How to read and print the content of a txt file

Assume you got a file called file.txt that you want to read in a program and the content is this:

this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line

You can read this content: write the following script in notepad:

with open("file.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

save it as readfile.py for example, in the same folder of the txt file.

Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:

C:\examples> python readfile.py

You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).

output

this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line

ImportError: No module named xlsxwriter

Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:

sudo pip install xlsxwriter

Note

Windows users can omit sudo at the start of the command.

Running a Python script from PHP

If you want to know the return status of the command and get the entire stdout output you can actually use exec:

$command = 'ls';
exec($command, $out, $status);

$out is an array of all lines. $status is the return status. Very useful for debugging.

If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to "implement".

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

Get google map link with latitude/longitude

Use View mode returns a map with no markers or directions.

The example below uses the optional maptype parameter to display a satellite view of the map.

https://www.google.com/maps/embed/v1/view
  ?key=YOUR_API_KEY
  &center=-33.8569,151.2152
  &zoom=18
  &maptype=satellite

Google MAP API v3: Center & Zoom on displayed markers

Try this function....it works...

$(function() {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var latlng_pos=[];
        var j=0;
         $(".property_item").each(function(){
            latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
            j++;
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                // position: new google.maps.LatLng(-35.397, 150.640),
                map: map
            });
        }
        );
        // map: an instance of google.maps.Map object
        // latlng: an array of google.maps.LatLng objects
        var latlngbounds = new google.maps.LatLngBounds( );
        for ( var i = 0; i < latlng_pos.length; i++ ) {
            latlngbounds.extend( latlng_pos[ i ] );
        }
        map.fitBounds( latlngbounds );



    });

Use of PUT vs PATCH methods in REST API real life scenarios

TLDR - Dumbed Down Version

PUT => Set all new attributes for an existing resource.

PATCH => Partially update an existing resource (not all attributes required).

Turn off auto formatting in Visual Studio

VS2015 settings that helped me prevent auto formatting:

(and Tools > Options > Text Editor > Basic > Advanced, just like Tango91 suggested)

enter image description here

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Simply delete the tables that are dragged into your .dbml file and re-drag them again. Then Clean solution>Rebuild solution> Build solution.

Thats what worked for me.

I didnt made the table on my own, I was using VS and SSMS, I followed this link for ASP.NET Identity:https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

Firebase Storage How to store and Retrieve images

You can also use a service called Filepicker which will store your image to their servers and Filepicker which is now called Filestack, will provide you with a url to the image. You can than store the url to Firebase.

How to make function decorators and chain them together?

#decorator.py
def makeHtmlTag(tag, *args, **kwds):
    def real_decorator(fn):
        css_class = " class='{0}'".format(kwds["css_class"]) \
                                 if "css_class" in kwds else ""
        def wrapped(*args, **kwds):
            return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
        return wrapped
    # return decorator dont call it
    return real_decorator

@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
    return "hello world"

print hello()

You can also write decorator in Class

#class.py
class makeHtmlTagClass(object):
    def __init__(self, tag, css_class=""):
        self._tag = tag
        self._css_class = " class='{0}'".format(css_class) \
                                       if css_class != "" else ""

    def __call__(self, fn):
        def wrapped(*args, **kwargs):
            return "<" + self._tag + self._css_class+">"  \
                       + fn(*args, **kwargs) + "</" + self._tag + ">"
        return wrapped

@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
    return "Hello, {}".format(name)

print hello("Your name")

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

Getting a slice of keys from a map

You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

package main

import (
    "fmt"
    "reflect"
)

func main() {
    abc := map[string]int{
        "a": 1,
        "b": 2,
        "c": 3,
    }

    keys := reflect.ValueOf(abc).MapKeys()

    fmt.Println(keys) // [a b c]
}

Text in HTML Field to disappear when clicked?

What you want to do is use the HTML5 attribute placeholder which lets you set a default value for your input box:

<input type="text" name="inputBox" placeholder="enter your text here">

This should achieve what you're looking for. However, be careful because the placeholder attribute is not supported in Internet Explorer 9 and earlier versions.

setTimeout or setInterval?

setInterval()

setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

If you want to loop code for animations or on a clock tick, then use setInterval().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

Converting a string to int in Groovy

Several ways to achieve this. Examples are as below

a. return "22".toInteger()
b. if("22".isInteger()) return "22".toInteger()
c. return "22" as Integer()
d. return Integer.parseInt("22")

Hope this helps

Regular expression for decimal number

I just found TryParse() has an issue that it accounts for thousands seperator. Example in En-US, 10,36.00 is ok. I had a specific scenario where the thousands seperator should not be considered and hence regex \d(\.\d) turned out to be the best bet. Of course had to keep the decimal char variable for different locales.

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

Output data with no column headings using PowerShell

The -expandproperty does not work with more than 1 object. You can use this one :

Select-Object Name | ForEach-Object {$_.Name}

If there is more than one value then :

Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}

Connect Java to a MySQL database

MySql JDBC Connection:

Class.forName("com.mysql.jdbc.Driver");     

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");         
Statement stmt=con.createStatement();            
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");  

Java Immutable Collections

Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.

Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.

Here's a quote from guava's ImmutableList

Unlike Collections.unmodifiableList(java.util.List<? extends T>), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.

So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.

Cannot assign requested address - possible causes?

this is just a shot in the dark : when you call connect without a bind first, the system allocates your local port, and if you have multiple threads connecting and disconnecting it could possibly try to allocate a port already in use. the kernel source file inet_connection_sock.c hints at this condition. just as an experiment try doing a bind to a local port first, making sure each bind/connect uses a different local port number.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

How to debug heap corruption errors?

One quick tip, that I got from Detecting access to freed memory is this:

If you want to locate the error quickly, without checking every statement that accesses the memory block, you can set the memory pointer to an invalid value after freeing the block:

#ifdef _DEBUG // detect the access to freed memory
#undef free
#define free(p) _free_dbg(p, _NORMAL_BLOCK); *(int*)&p = 0x666;
#endif

How to define a circle shape in an Android XML drawable file?

<?xml version="1.0" encoding="utf-8"?>
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <!-- fill color -->
    <solid android:color="@color/white" />

    <!-- radius -->
    <stroke
        android:width="1dp"
        android:color="@color/white" />

    <!-- corners -->
    <corners
        android:radius="2dp"/>
</shape>

TypeError: p.easing[this.easing] is not a function

Jquery easing plugin renamed their effect function names from version 1.2 on. If you have some javascript depending on easing and it is not calling the right effect name it will throw this error.

Why do I need to explicitly push a new branch?

Output of git push when pushing a new branch

> git checkout -b new_branch
Switched to a new branch 'new_branch'
> git push
fatal: The current branch new_branch has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin new_branch

A simple git push assumes that there already exists a remote branch that the current local branch is tracking. If no such remote branch exists, and you want to create it, you must specify that using the -u (short form of --set-upstream) flag.

Why this is so? I guess the implementers felt that creating a branch on the remote is such a major action that it should be hard to do it by mistake. git push is something you do all the time.

"Isn't a branch a new change to be pushed by default?" I would say that "a change" in Git is a commit. A branch is a pointer to a commit. To me it makes more sense to think of a push as something that pushes commits over to the other repositories. Which commits are pushed is determined by what branch you are on and the tracking relationship of that branch to branches on the remote.

You can read more about tracking branches in the Remote Branches chapter of the Pro Git book.

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

Permission denied at hdfs

Start a shell as hduser (from root) and run your command

sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input

[update] Also note that the hdfs user is the super user and has all r/w privileges.

Get AVG ignoring Null or Zero values

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don't need DISTINCT and your WHERE on ActualTime is not sargable.

SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
       AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
       AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT))    AS Average3
FROM   Table1 a
WHERE  a.ActualTime >= '20130401'
       AND a.ActualTime < '20130501' 

PS I have no idea what Table2 b is in the original query for as there is no join condition for it so have omitted it from my answer.

Clearing content of text file using php

This would truncate the file:

$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);

In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.

Convert all strings in a list to int

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

e.g.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

Need to combine lots of files in a directory

Use the Windows 'copy' command.

C:\Users\dan>help copy
    Copies one or more files to another location.

    COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] source [/A | /B]
         [+ source [/A | /B] [+ ...]] [destination [/A | /B]]

      source       Specifies the file or files to be copied.
      /A           Indicates an ASCII text file.
      /B           Indicates a binary file.
      /D           Allow the destination file to be created decrypted
      destination  Specifies the directory and/or filename for the new file(s).
      /V           Verifies that new files are written correctly.
      /N           Uses short filename, if available, when copying a file with 
                   a non-8dot3 name.
      /Y           Suppresses prompting to confirm you want to overwrite an
                   existing destination file.
      /-Y          Causes prompting to confirm you want to overwrite an
                   existing destination file.
      /Z           Copies networked files in restartable mode.
      /L           If the source is a symbolic link, copy the link to the 
                   target
                   instead of the actual file the source link points to.

    The switch /Y may be preset in the COPYCMD environment variable.
    This may be overridden with /-Y on the command line.  Default is
    to prompt on overwrites unless COPY command is being executed from
    within a batch script.

    **To append files, specify a single file for destination, but 
    multiple files for source (using wildcards or file1+file2+file3 
    format).**

So in your case:

copy *.txt destination.txt

Will concatenate all .txt files in alphabetical order into destination.txt

Thanks for asking, I learned something new!

WCF ServiceHost access rights

Open Visual Studio as an Administrator.. It will run.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

The same problem when I used 'org.springframework.android:spring-android-rest-template:2.0.0.M1' in Android Studio 1.0.1. I need include this in build.gradle

android{
...
    packagingOptions{
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
    }
...
}

How does the stack work in assembly language?

(I've made a gist of all the code in this answer in case you want to play with it)

I have only ever did most basic things in asm during my CS101 course back in 2003. And I had never really "got it" how asm and stack work until I've realized that it's all basicaly like programming in C or C++ ... but without local variables, parameters and functions. Probably doesn't sound easy yet :) Let me show you (for x86 asm with Intel syntax).


1. What is the stack

Stack is usually a contiguous chunk of memory allocated for every thread before they start. You can store there whatever you want. In C++ terms (code snippet #1):

const int STACK_CAPACITY = 1000;
thread_local int stack[STACK_CAPACITY];

2. Stack's top and bottom

In principle, you could store values in random cells of stack array (snippet #2.1):

stack[333] = 123;
stack[517] = 456;
stack[555] = stack[333] + stack[517];

But imagine how hard would it be to remember which cells of stack are already in use and wich ones are "free". That's why we store new values on the stack next to each other.

One weird thing about (x86) asm's stack is that you add things there starting with the last index and move to lower indexes: stack[999], then stack[998] and so on (snippet #2.2):

stack[999] = 123;
stack[998] = 456;
stack[997] = stack[999] + stack[998];

And still (caution, you're gonna be confused now) the "official" name for stack[999] is bottom of the stack.
The last used cell (stack[997] in the example above) is called top of the stack (see Where the top of the stack is on x86).


3. Stack pointer (SP)

For the purpose of this discussion let's assume CPU registers are represented as global variables (see General-Purpose Registers).

int AX, BX, SP, BP, ...;
int main(){...}

There is special CPU register (SP) that tracks the top of the stack. SP is a pointer (holds a memory address like 0xAAAABBCC). But for the purposes of this post I'll use it as an array index (0, 1, 2, ...).

When a thread starts, SP == STACK_CAPACITY and then the program and OS modify it as needed. The rule is you can't write to stack cells beyond stack's top and any index less then SP is invalid and unsafe (because of system interrupts), so you first decrement SP and then write a value to the newly allocated cell.

When you want to push several values in the stack in a row, you can reserve space for all of them upfront (snippet #3):

SP -= 3;
stack[999] = 12;
stack[998] = 34;
stack[997] = stack[999] + stack[998];

Note. Now you can see why allocation on the stack is so fast - it's just a single register decrement.


4. Local variables

Let's take a look at this simplistic function (snippet #4.1):

int triple(int a) {
    int result = a * 3;
    return result;
}

and rewrite it without using of local variable (snippet #4.2):

int triple_noLocals(int a) {
    SP -= 1; // move pointer to unused cell, where we can store what we need
    stack[SP] = a * 3;
    return stack[SP];
}

and see how it is being called (snippet #4.3):

// SP == 1000
someVar = triple_noLocals(11);
// now SP == 999, but we don't need the value at stack[999] anymore
// and we will move the stack index back, so we can reuse this cell later
SP += 1; // SP == 1000 again

5. Push / pop

Addition of a new element on the top of the stack is such a frequent operation, that CPUs have a special instruction for that, push. We'll implent it like this (snippet 5.1):

void push(int value) {
    --SP;
    stack[SP] = value;
}

Likewise, taking the top element of the stack (snippet 5.2):

void pop(int& result) {
    result = stack[SP];
    ++SP; // note that `pop` decreases stack's size
}

Common usage pattern for push/pop is temporarily saving some value. Say, we have something useful in variable myVar and for some reason we need to do calculations which will overwrite it (snippet 5.3):

int myVar = ...;
push(myVar); // SP == 999
myVar += 10;
... // do something with new value in myVar
pop(myVar); // restore original value, SP == 1000

6. Function parameters

Now let's pass parameters using stack (snippet #6):

int triple_noL_noParams() { // `a` is at index 999, SP == 999
    SP -= 1; // SP == 998, stack[SP + 1] == a
    stack[SP] = stack[SP + 1] * 3;
    return stack[SP];
}

int main(){
    push(11); // SP == 999
    assert(triple(11) == triple_noL_noParams());
    SP += 2; // cleanup 1 local and 1 parameter
}

7. return statement

Let's return value in AX register (snippet #7):

void triple_noL_noP_noReturn() { // `a` at 998, SP == 998
    SP -= 1; // SP == 997

    stack[SP] = stack[SP + 1] * 3;
    AX = stack[SP];

    SP += 1; // finally we can cleanup locals right in the function body, SP == 998
}

void main(){
    ... // some code
    push(AX); // save AX in case there is something useful there, SP == 999
    push(11); // SP == 998
    triple_noL_noP_noReturn();
    assert(triple(11) == AX);
    SP += 1; // cleanup param
             // locals were cleaned up in the function body, so we don't need to do it here
    pop(AX); // restore AX
    ...
}

8. Stack base pointer (BP) (also known as frame pointer) and stack frame

Lets take more "advanced" function and rewrite it in our asm-like C++ (snippet #8.1):

int myAlgo(int a, int b) {
    int t1 = a * 3;
    int t2 = b * 3;
    return t1 - t2;
}

void myAlgo_noLPR() { // `a` at 997, `b` at 998, old AX at 999, SP == 997
    SP -= 2; // SP == 995

    stack[SP + 1] = stack[SP + 2] * 3; 
    stack[SP]     = stack[SP + 3] * 3;
    AX = stack[SP + 1] - stack[SP];

    SP += 2; // cleanup locals, SP == 997
}

int main(){
    push(AX); // SP == 999
    push(22); // SP == 998
    push(11); // SP == 997
    myAlgo_noLPR();
    assert(myAlgo(11, 22) == AX);
    SP += 2;
    pop(AX);
}

Now imagine we decided to introduce new local variable to store result there before returning, as we do in tripple (snippet #4.1). The body of the function will be (snippet #8.2):

SP -= 3; // SP == 994
stack[SP + 2] = stack[SP + 3] * 3; 
stack[SP + 1] = stack[SP + 4] * 3;
stack[SP]     = stack[SP + 2] - stack[SP + 1];
AX = stack[SP];
SP += 3;

You see, we had to update every single reference to function parameters and local variables. To avoid that, we need an anchor index, which doesn't change when the stack grows.

We will create the anchor right upon function entry (before we allocate space for locals) by saving current top (value of SP) into BP register. Snippet #8.3:

void myAlgo_noLPR_withAnchor() { // `a` at 997, `b` at 998, SP == 997
    push(BP);   // save old BP, SP == 996
    BP = SP;    // create anchor, stack[BP] == old value of BP, now BP == 996
    SP -= 2;    // SP == 994

    stack[BP - 1] = stack[BP + 1] * 3;
    stack[BP - 2] = stack[BP + 2] * 3;
    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP;    // cleanup locals, SP == 996
    pop(BP);    // SP == 997
}

The slice of stack, wich belongs to and is in full control of the function is called function's stack frame. E.g. myAlgo_noLPR_withAnchor's stack frame is stack[996 .. 994] (both idexes inclusive).
Frame starts at function's BP (after we've updated it inside function) and lasts until the next stack frame. So the parameters on the stack are part of the caller's stack frame (see note 8a).

Notes:
8a. Wikipedia says otherwise about parameters, but here I adhere to Intel software developer's manual, see vol. 1, section 6.2.4.1 Stack-Frame Base Pointer and Figure 6-2 in section 6.3.2 Far CALL and RET Operation. Function's parameters and stack frame are part of function's activation record (see The gen on function perilogues).
8b. positive offsets from BP point to function parameters and negative offsets point to local variables. That's pretty handy for debugging
8c. stack[BP] stores the address of the previous stack frame, stack[stack[BP]] stores pre-previous stack frame and so on. Following this chain, you can discover frames of all the functions in the programm, which didn't return yet. This is how debuggers show you call stack
8d. the first 3 instructions of myAlgo_noLPR_withAnchor, where we setup the frame (save old BP, update BP, reserve space for locals) are called function prologue


9. Calling conventions

In snippet 8.1 we've pushed parameters for myAlgo from right to left and returned result in AX. We could as well pass params left to right and return in BX. Or pass params in BX and CX and return in AX. Obviously, caller (main()) and called function must agree where and in which order all this stuff is stored.

Calling convention is a set of rules on how parameters are passed and result is returned.

In the code above we've used cdecl calling convention:

  • Parameters are passed on the stack, with the first argument at the lowest address on the stack at the time of the call (pushed last <...>). The caller is responsible for popping parameters back off the stack after the call.
  • the return value is placed in AX
  • EBP and ESP must be preserved by the callee (myAlgo_noLPR_withAnchor function in our case), such that the caller (main function) can rely on those registers not having been changed by a call.
  • All other registers (EAX, <...>) may be freely modified by the callee; if a caller wishes to preserve a value before and after the function call, it must save the value elsewhere (we do this with AX)

(Source: example "32-bit cdecl" from Stack Overflow Documentation; copyright 2016 by icktoofay and Peter Cordes ; licensed under CC BY-SA 3.0. An archive of the full Stack Overflow Documentation content can be found at archive.org, in which this example is indexed by topic ID 3261 and example ID 11196.)


10. Function calls

Now the most interesting part. Just like data, executable code is also stored in memory (completely unrelated to memory for stack) and every instruction has an address.
When not commanded otherwise, CPU executes instructions one after another, in the order they are stored in memory. But we can command CPU to "jump" to another location in memory and execute instructions from there on. In asm it can be any address, and in more high-level languages like C++ you can only jump to addresses marked by labels (there are workarounds but they are not pretty, to say the least).

Let's take this function (snippet #10.1):

int myAlgo_withCalls(int a, int b) {
    int t1 = triple(a);
    int t2 = triple(b);
    return t1 - t2;
}

And instead of calling tripple C++ way, do the following:

  1. copy tripple's code to the beginning of myAlgo body
  2. at myAlgo entry jump over tripple's code with goto
  3. when we need to execute tripple's code, save on the stack address of the code line just after tripple call, so we can return here later and continue execution (PUSH_ADDRESS macro below)
  4. jump to the address of the 1st line (tripple function) and execute it to the end (3. and 4. together are CALL macro)
  5. at the end of the tripple (after we've cleaned up locals), take return address from the top of the stack and jump there (RET macro)

Because there is no easy way to jump to particular code address in C++, we will use labels to mark places of jumps. I won't go into detail how macros below work, just believe me they do what I say they do (snippet #10.2):

// pushes the address of the code at label's location on the stack
// NOTE1: this gonna work only with 32-bit compiler (so that pointer is 32-bit and fits in int)
// NOTE2: __asm block is specific for Visual C++. In GCC use https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
#define PUSH_ADDRESS(labelName) {               \
    void* tmpPointer;                           \
    __asm{ mov [tmpPointer], offset labelName } \
    push(reinterpret_cast<int>(tmpPointer));    \
}

// why we need indirection, read https://stackoverflow.com/a/13301627/264047
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)

// generates token (not a string) we will use as label name. 
// Example: LABEL_NAME(155) will generate token `lbl_155`
#define LABEL_NAME(num) TOKENPASTE2(lbl_, num)

#define CALL_IMPL(funcLabelName, callId)    \
    PUSH_ADDRESS(LABEL_NAME(callId));       \
    goto funcLabelName;                     \
    LABEL_NAME(callId) :

// saves return address on the stack and jumps to label `funcLabelName`
#define CALL(funcLabelName) CALL_IMPL(funcLabelName, __LINE__)

// takes address at the top of stack and jump there
#define RET() {                                         \
    int tmpInt;                                         \
    pop(tmpInt);                                        \
    void* tmpPointer = reinterpret_cast<void*>(tmpInt); \
    __asm{ jmp tmpPointer }                             \
}

void myAlgo_asm() {
    goto my_algo_start;

triple_label:
    push(BP);
    BP = SP;
    SP -= 1;

    // stack[BP] == old BP, stack[BP + 1] == return address
    stack[BP - 1] = stack[BP + 2] * 3;
    AX = stack[BP - 1];

    SP = BP;     
    pop(BP);
    RET();

my_algo_start:
    push(BP);   // SP == 995
    BP = SP;    // BP == 995; stack[BP] == old BP, 
                // stack[BP + 1] == dummy return address, 
                // `a` at [BP + 2], `b` at [BP + 3]
    SP -= 2;    // SP == 993

    push(AX);
    push(stack[BP + 2]);
    CALL(triple_label);
    stack[BP - 1] = AX;
    SP -= 1;
    pop(AX);

    push(AX);
    push(stack[BP + 3]);
    CALL(triple_label);
    stack[BP - 2] = AX;
    SP -= 1;
    pop(AX);

    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP; // cleanup locals, SP == 997
    pop(BP);
}

int main() {
    push(AX);
    push(22);
    push(11);
    push(7777); // dummy value, so that offsets inside function are like we've pushed return address
    myAlgo_asm();
    assert(myAlgo_withCalls(11, 22) == AX);
    SP += 1; // pop dummy "return address"
    SP += 2;
    pop(AX);
}

Notes:
10a. because return address is stored on the stack, in principle we can change it. This is how stack smashing attack works
10b. the last 3 instructions at the "end" of triple_label (cleanup locals, restore old BP, return) are called function's epilogue


11. Assembly

Now let's look at real asm for myAlgo_withCalls. To do that in Visual Studio:

  • set build platform to x86 (not x86_64)
  • build type: Debug
  • set break point somewhere inside myAlgo_withCalls
  • run, and when execution stops at break point press Ctrl + Alt + D

One difference with our asm-like C++ is that asm's stack operate on bytes instead of ints. So to reserve space for one int, SP will be decremented by 4 bytes.
Here we go (snippet #11.1, line numbers in comments are from the gist):

;   114: int myAlgo_withCalls(int a, int b) {
 push        ebp        ; create stack frame 
 mov         ebp,esp  
; return address at (ebp + 4), `a` at (ebp + 8), `b` at (ebp + 12)
 
 sub         esp,0D8h   ; reserve space for locals. Compiler can reserve more bytes then needed. 0D8h is hexadecimal == 216 decimal 
 
 push        ebx        ; cdecl requires to save all these registers
 push        esi  
 push        edi  
 
 ; fill all the space for local variables (from (ebp-0D8h) to (ebp)) with value 0CCCCCCCCh repeated 36h times (36h * 4 == 0D8h)
 ; see https://stackoverflow.com/q/3818856/264047
 ; I guess that's for ease of debugging, so that stack is filled with recognizable values
 ; 0CCCCCCCCh in binary is 110011001100...
 lea         edi,[ebp-0D8h]     
 mov         ecx,36h    
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 
;   115:    int t1 = triple(a);
 mov         eax,dword ptr [ebp+8]   ; push parameter `a` on the stack
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4                   ; clean up param 
 mov         dword ptr [ebp-8],eax   ; copy result from eax to `t1`
 
;   116:    int t2 = triple(b);
 mov         eax,dword ptr [ebp+0Ch] ; push `b` (0Ch == 12)
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4  
 mov         dword ptr [ebp-14h],eax ; t2 = eax
 
 mov         eax,dword ptr [ebp-8]   ; calculate and store result in eax
 sub         eax,dword ptr [ebp-14h]  

 pop         edi  ; restore registers
 pop         esi  
 pop         ebx  
 
 add         esp,0D8h  ; check we didn't mess up esp or ebp. this is only for debug builds
 cmp         ebp,esp  
 call        __RTC_CheckEsp (01A116Dh)  
 
 mov         esp,ebp  ; destroy frame
 pop         ebp  
 ret  

And asm for tripple (snippet #11.2):

 push        ebp  
 mov         ebp,esp  
 sub         esp,0CCh  
 push        ebx  
 push        esi  
 push        edi  
 lea         edi,[ebp-0CCh]  
 mov         ecx,33h  
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 imul        eax,dword ptr [ebp+8],3  
 mov         dword ptr [ebp-8],eax  
 mov         eax,dword ptr [ebp-8]  
 pop         edi  
 pop         esi  
 pop         ebx  
 mov         esp,ebp  
 pop         ebp  
 ret  

Hope, after reading this post, assembly doesn't look as cryptic as before :)


Here are links from the post's body and some further reading:

Javadoc link to method in other class

So the solution to the original problem is that you don't need both the "@see" and the "{@link...}" references on the same line. The "@link" tag is self-sufficient and, as noted, you can put it anywhere in the javadoc block. So you can mix the two approaches:

/**
 * some javadoc stuff
 * {@link com.my.package.Class#method()}
 * more stuff
 * @see com.my.package.AnotherClass
 */

Run php function on button click

I tried the code of William, Thanks brother.

but it's not working as a simple button I have to add form with method="post". Also I have to write submit instead of button.

here is my code below..

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" /><br/>
</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(array_key_exists('test',$_POST)){
   testfun();
}

?>

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

Creating a simple XML file using python

Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).

It's using context manager and with keyword.

from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag('root'):
    with tag('doc'):
        with tag('field1', name='blah'):
            text('some value1')
        with tag('field2', name='asdfasd'):
            text('some value2')

result = indent(
    doc.getvalue(),
    indentation = ' '*4,
    newline = '\r\n'
)

print(result)

so you will get:

<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some value2</field2>
    </doc>
</root>

cast a List to a Collection

There have multiple solusions to convert list to a collection

Solution 1

List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;

Solution 2

private static final Collection<String> c = new ArrayList<String>(
                                                Arrays.asList("a", "b", "c"));

Solution 3

private static final Collection<Contact> = new ArrayList<Contact>(
                       Arrays.asList(new Contact("text1", "name1")
                                     new Contact("text2", "name2")));

Solution 4

List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);

Easiest way to flip a boolean value?

If you know the values are 0 or 1, you could do flipval ^= 1.

How to fix .pch file missing on build?

If everything is right, but this mistake is present, it need check next section in ****.vcxproj file:

<ClCompile Include="stdafx.cpp">
  <PrecompiledHeader Condition=

In my case it there was an incorrect name of a configuration: only first word.

How to embed images in html email

I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.

Regarding displaying embedded (inline) images, here's what's on their documentation:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

To give you a more complete example of how it would work:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

Edit:

Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.

One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.

For example:

You can replace the line that send the email:

$mail->Send();

With this:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

Hope that helps. Let me know if you run into trouble using it.

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

There is a lot of way to solve this...

One way is set the TrustStore certificates in a keystore file and put it in the path of the application, and set these system properties in the main method:

public static void main(String[] args) {
  System.setProperty("javax.net.ssl.trustStore", "trust-store.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "TrustStore");
  ...
}

Other way is place the keystore as resource file inside the project jar file and load it:

public static SSLContext createSSLContext(String resourcePath, String pass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
  // initialise the keystore
  final char[] password = pass.toCharArray();
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(ThisClass.class.getResourceAsStream(resourcePath
  ), password);

  // Setup the key manager factory.
  KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
  kmf.init(ks, password);

  // Setup the trust manager factory.
  TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
  tmf.init(ks);

  SSLContext sslc = SSLContext.getInstance("TLS");
  sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
  return sslc;
}

public static void main(String[] args) {
  SSLContext.setDefault(
    createSSLContext("/trust-store.jks", "TrustStore"));
  ...
}

In windows you can try this solution too: https://stackoverflow.com/a/59056537/980442


I created the keystore file from a Certificate authority CA .crt file in this way:

keytool -import -alias ca -keystore trust-store.jks -storepass TrustStore -trustcacerts -file ca.crt

FYI: https://docs.oracle.com/javadb/10.8.3.0/adminguide/cadminsslclient.html

How to paste into a terminal?

In Konsole (KDE terminal) is the same, Ctrl + Shift + V

Extracting Nupkg files using command line

This worked for me:

Rename-Item -Path A_Package.nupkg -NewName A_Package.zip

Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference

Validating a Textbox field for only numeric input.

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}

How can I create a link to a local file on a locally-run web page?

back to 2017:

use URL.createObjectURL( file ) to create local link to file system that user select;

don't forgot to free memory by using URL.revokeObjectURL()

How to watch and reload ts-node when TypeScript files change

I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev https://github.com/whitecolor/ts-node-dev

Just run ts-node-dev src/index.ts

Split string by single spaces

If you are averse to boost, you can use regular old operator>>, along with std::noskipws:

EDIT: updates after testing.

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>

void split(const std::string& str, std::vector<std::string>& v) {
  std::stringstream ss(str);
  ss >> std::noskipws;
  std::string field;
  char ws_delim;
  while(1) {
    if( ss >> field )
      v.push_back(field);
    else if (ss.eof())
      break;
    else
      v.push_back(std::string());
    ss.clear();
    ss >> ws_delim;
  }
}

int main() {
  std::vector<std::string> v;
  split("hello world  how are   you", v);
  std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
  std::cout << "\n";
}

http://ideone.com/62McC

Android: why is there no maxHeight for a View?

My MaxHeightScrollView custom view

public class MaxHeightScrollView extends ScrollView {
    private int maxHeight;

    public MaxHeightScrollView(Context context) {
        this(context, null);
    }

    public MaxHeightScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray styledAttrs =
                context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
        try {
            maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_mhs_maxHeight, 0);
        } finally {
            styledAttrs.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

style.xml

<declare-styleable name="MaxHeightScrollView">
    <attr name="mhs_maxHeight" format="dimension" />
</declare-styleable>

Using

<....MaxHeightScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:mhs_maxHeight="100dp"
    >

    ...

</....MaxHeightScrollView>

What is the difference between sscanf or atoi to convert a string to an integer?

If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:

echojson_encode($row);

form with no action and where enter does not reload page

an idea:

<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
    <input id="pwset" type="text" size="20" name='pwuser'><br><br>
    <button type="button" onclick="CheckPassword()">Next</button>
</form>

and

<script type="text/javascript">
    $("#pwset").focus();
    function CheckPassword()
    {
        inputtxt = $("#pwset").val();
        //and now your code
        $("#div1").load("next.php #div2");
        return false;
    }
</script>

SQL Server - Adding a string to a text column (concat equivalent)

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table 
create table test (
    a text
) 
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works: 
update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added

hope that helps

Get current controller in view

I have put this in my partial view:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()

in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.

So use this alert instead:

alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I've been fighting with this issue for a long time, and just y'day I figure out how to make it gone and today I can run a 50 threads process calling selenium without seen this issue anymore and also stop crashing my machine with outofmemory issue with too many open chromedriver processes.

  1. I am using selenium 3.7.1, chromedrive 2.33, java.version: '1.8.0', redhat ver '3.10.0-693.5.2.el7.x86_64', chrome browser version: 60.0.3112.90;
  2. running an open session with screen, to be sure my session never dies,
  3. running Xvfb : nohup Xvfb -ac :15 -screen 0 1280x1024x16 &
  4. export DISPLAY:15 from .bashsh/.profile

these 4 items are the basic setting everyone would already know, now comes the code, where all made a lot of difference to achieve the success:

public class HttpWebClient {
    public static ChromeDriverService service;
    public ThreadLocal<WebDriver> threadWebDriver = new ThreadLocal<WebDriver>(){
    @Override
    protected WebDriver initialValue() {
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("permissions.default.stylesheet", 2);
        profile.setPreference("permissions.default.image", 2);
        profile.setPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
        profile.setPreference(FirefoxProfile.ALLOWED_HOSTS_PREFERENCE, "localhost");
        WebDriver driver = new FirefoxDriver(profile);
        return driver;
    };
};

public HttpWebClient(){
    // fix for headless systems:
    // start service first, this will create an instance at system and every time you call the 
    // browser will be used
    // be sure you start the service only if there are no alive instances, that will prevent you to have 
    // multiples chromedrive instances causing it to crash
    try{
        if (service==null){
            service = new ChromeDriverService.Builder()
            .usingDriverExecutable(new File(conf.get("webdriver.chrome.driver"))) // set the chromedriver path at your system
            .usingAnyFreePort()
            .withEnvironment(ImmutableMap.of("DISPLAY", ":15"))
            .withSilent(true)
            .build();
            service.start();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

// my Configuration class is for good and easy setting, you can replace it by using values instead.
public WebDriver getDriverForPage(String url, Configuration conf) {
    WebDriver driver = null;
    DesiredCapabilities capabilities = null;
    long pageLoadWait = conf.getLong("page.load.delay", 60);

    try {
            System.setProperty("webdriver.chrome.driver", conf.get("webdriver.chrome.driver"));
            String driverType = conf.get("selenium.driver", "chrome");

        capabilities = DesiredCapabilities.chrome();
        String[] options = new String[] { "--start-maximized", "--headless" };
        capabilities.setCapability("chrome.switches", options);

                    // here is where your chromedriver will call the browser
                    // I used to call the class ChromeDriver directly, which was causing too much problems 
                    // when you have multiple calls
        driver = new RemoteWebDriver(service.getUrl(), capabilities);

        driver.manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.SECONDS);
        driver.get(url);

                    // never look back

    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.debug("Crawling URL : "+url);
            LOG.debug("Selenium WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }
    return driver;
}

public void cleanUpDriver(WebDriver driver) {
    if (driver != null) {
        try {
                            // be sure to close every driver you opened
            driver.close();
            driver.quit();
            //service.stop(); do not stop the service, bcz it is needed
            TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

}

Good luck and I hope you don't see that crash issue anymore

Please comment your success

Best regards,

How to suppress warnings globally in an R Script

Have a look at ?options and use warn:

options( warn = -1 )

How to export specific request to file using postman?

There is no direct option to export a single request from Postman.

You can create and export collections. Here is a link to help with that.

Regarding the single request thing, you can try a workaround. I tried with the RAW body parameters and it worked.

What you can do is,

  1. In your request tab, click on the 3 dots in the top right corner of your request panel/box. enter image description here

  2. Select Code. This will open Generate Code Snippents window. enter image description here

  3. Copy the cURL code and save it in a text file. Share this with who you want to. enter image description here

  4. They can then import the request from the text file. enter image description here

Setting PayPal return URL and making it auto return?

on the checkout page, look for the 'cancel_return' hidden form element:

set the value of the cancel_return form element to the URL you wish to return to:

When should we use intern method of String on String literals

you should make out two period time which are compile time and runtime time.for example:

//example 1 
"test" == "test" // --> true 
"test" == "te" + "st" // --> true

//example 2 
"test" == "!test".substring(1) // --> false
"test" == "!test".substring(1).intern() // --> true

in the one hand,in the example 1,we find the results are all return true,because in the compile time,the jvm will put the "test" to the pool of literal strings,if the jvm find "test" exists,then it will use the exists one,in example 1,the "test" strings are all point to the same memory address,so the example 1 will return true. in the other hand,in the example 2,the method of substring() execute in the runtime time, in the case of "test" == "!test".substring(1),the pool will create two string object,"test" and "!test",so they are different reference objects,so this case will return false,in the case of "test" == "!test".substring(1).intern(),the method of intern() will put the ""!test".substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.

Mac install and open mysql using terminal

In the terminal, I typed:

/usr/local/mysql/bin/mysql -u root -p

I was then prompted to enter the temporary password that was given to me upon completion of the installation.

How can I convert a Word document to PDF?

I agree with posters listing OpenOffice as a high-fidelity import/export facility of word / pdf docs with a Java API and it also works across platforms. OpenOffice import/export filters are pretty powerful and preserve most formatting during conversion to various formats including PDF. Docmosis and JODReports value-add to make life easier than learning the OpenOffice API directly which can be challenging because of the style of the UNO api and the crash-related bugs.

Get to UIViewController from UIView?

There is no way.

What I do is pass the UIViewController pointer to the UIView (or an appropriate inheritance). I'm sorry I can't help with the IB approach to the problem because I don't believe in IB.

To answer the first commenter: sometimes you do need to know who called you because it determines what you can do. For example with a database you might have read access only or read/write ...

How can I get the current stack trace in Java?

This is an old post, but here is my solution :

Thread.currentThread().dumpStack();

More info and more methods there : http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

Django - Reverse for '' not found. '' is not a valid view function or pattern name

The common error that I have find is when you forget to define your url in yourapp/urls.py

we don't want any suggetion!! solution plz..

Replacing few values in a pandas dataframe column with another value

This solution will change the existing dataframe itself:

mydf = pd.DataFrame({"BrandName":["A", "B", "ABC", "D", "AB"], "Speciality":["H", "I", "J", "K", "L"]})
mydf["BrandName"].replace(["ABC", "AB"], "A", inplace=True)

How do I perform an IF...THEN in an SQL SELECT?

If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in Oracle 11.2g:

INSERT INTO customers (last_name, first_name, city)
    SELECT 'Doe', 'John', 'Chicago' FROM dual
    WHERE NOT EXISTS 
        (SELECT '1' from customers 
            where last_name = 'Doe' 
            and first_name = 'John'
            and city = 'Chicago');

How to uninstall pip on OSX?

The first thing you should try is:

sudo pip uninstall pip

On many environments that doesn't work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

How can I style an Android Switch?

You can customize material styles by setting different color properties. For example custom application theme

<style name="CustomAppTheme" parent="Theme.AppCompat">
    <item name="android:textColorPrimaryDisableOnly">#00838f</item>
    <item name="colorAccent">#e91e63</item>
</style>

Custom switch theme

<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
    <item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
    <item name="android:colorControlActivated">#1b5e20</item>
    <item name="android:colorForeground">#f57f17</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>

You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples

custom switch track and thumb

'sudo gem install' or 'gem install' and gem locations

sudo gem install --no-user-install <gem-name>

will install your gem globally, i.e. it will be available to all user's contexts.

Find object by id in an array of JavaScript objects

Use Array.prototype.filter() function.

DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[
 {
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  }
 },
 {
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  }
 },
{
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false
  }
 }
];

FILTER

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}

Hive insert query like SQL

There are few properties to set to make a Hive table support ACID properties and to insert the values into tables as like in SQL .

Conditions to create a ACID table in Hive.

  1. The table should be stored as ORC file. Only ORC format can support ACID prpoperties for now.
  2. The table must be bucketed

Properties to set to create ACID table:

set hive.support.concurrency =true;
set hive.enforce.bucketing =true;
set hive.exec.dynamic.partition.mode =nonstrict
set hive.compactor.initiator.on = true;
set hive.compactor.worker.threads= 1;
set hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;

set the property hive.in.test to true in hive.site.xml

After setting all these properties , the table should be created with tblproperty 'transactional' ='true'. The table should be bucketed and saved as orc

CREATE TABLE table_name (col1 int,col2 string, col3 int) CLUSTERED BY col1 INTO 4 

BUCKETS STORED AS orc tblproperties('transactional' ='true');

Now its possible to inserte values into the table like SQL query.

INSERT INTO TABLE table_name VALUES (1,'a',100),(2,'b',200),(3,'c',300);

How to convert an object to JSON correctly in Angular 2 with TypeScript

Tested and working in Angular 9.0

If you're getting the data using API

array: [];

ngOnInit()    {
this.service.method()
.subscribe(
    data=>
  {
    this.array = JSON.parse(JSON.stringify(data.object));
  }
)

}

You can use that array to print your results from API data in html template.

Like

<p>{{array['something']}}</p>

How to pass multiple parameters in json format to a web service using jquery?

This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:

data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"

Make sure your JSON is properly formed?

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

SQL Column definition : default value and not null redundant?

In case of Oracle since 12c you have DEFAULT ON NULL which implies a NOT NULL constraint.

ALTER TABLE tbl ADD (col VARCHAR(20) DEFAULT ON NULL 'MyDefault');

ALTER TABLE

ON NULL

If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.

When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified. If you specify an inline constraint that conflicts with NOT NULL and NOT DEFERRABLE, then an error is raised.

docker unauthorized: authentication required - upon push with successful login

The solution you posted is not working for me...

This is what works for me:

  1. Create the repository with the desired name.

  2. When committing the image, name the image like the repository, including the username <dockerusername>/desired-name. For example, radu/desired-name.

remove borders around html input

your code is look like this jsfiddle.net/NTkGZ/

try

border:none;

Customize Bootstrap checkboxes

Here you have an example styling checkboxes and radios using Font Awesome 5 free[

_x000D_
_x000D_
  /*General style*/_x000D_
  .custom-checkbox label, .custom-radio label {_x000D_
    position: relative;_x000D_
    cursor: pointer;_x000D_
    color: #666;_x000D_
    font-size: 30px;_x000D_
  }_x000D_
 .custom-checkbox input[type="checkbox"] ,.custom-radio input[type="radio"] {_x000D_
    position: absolute;_x000D_
    right: 9000px;_x000D_
  }_x000D_
   /*Custom checkboxes style*/_x000D_
  .custom-checkbox input[type="checkbox"]+.label-text:before {_x000D_
    content: "\f0c8";_x000D_
    font-family: "Font Awesome 5 Pro";_x000D_
    speak: none;_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    font-variant: normal;_x000D_
    text-transform: none;_x000D_
    line-height: 1;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    width: 1em;_x000D_
    display: inline-block;_x000D_
    margin-right: 5px;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:checked+.label-text:before {_x000D_
    content: "\f14a";_x000D_
    color: #2980b9;_x000D_
    animation: effect 250ms ease-in;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:disabled+.label-text {_x000D_
    color: #aaa;_x000D_
  }_x000D_
  .custom-checkbox input[type="checkbox"]:disabled+.label-text:before {_x000D_
    content: "\f0c8";_x000D_
    color: #ccc;_x000D_
  }_x000D_
_x000D_
   /*Custom checkboxes style*/_x000D_
  .custom-radio input[type="radio"]+.label-text:before {_x000D_
    content: "\f111";_x000D_
    font-family: "Font Awesome 5 Pro";_x000D_
    speak: none;_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    font-variant: normal;_x000D_
    text-transform: none;_x000D_
    line-height: 1;_x000D_
    -webkit-font-smoothing: antialiased;_x000D_
    width: 1em;_x000D_
    display: inline-block;_x000D_
    margin-right: 5px;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:checked+.label-text:before {_x000D_
    content: "\f192";_x000D_
    color: #8e44ad;_x000D_
    animation: effect 250ms ease-in;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:disabled+.label-text {_x000D_
    color: #aaa;_x000D_
  }_x000D_
_x000D_
  .custom-radio input[type="radio"]:disabled+.label-text:before {_x000D_
    content: "\f111";_x000D_
    color: #ccc;_x000D_
  }_x000D_
_x000D_
  @keyframes effect {_x000D_
    0% {_x000D_
      transform: scale(0);_x000D_
    }_x000D_
    25% {_x000D_
      transform: scale(1.3);_x000D_
    }_x000D_
    75% {_x000D_
      transform: scale(1.4);_x000D_
    }_x000D_
    100% {_x000D_
      transform: scale(1);_x000D_
    }_x000D_
  }
_x000D_
<script src="https://kit.fontawesome.com/2a10ab39d6.js"></script>_x000D_
<div class="col-md-4">_x000D_
  <form>_x000D_
    <h2>1. Customs Checkboxes</h2>_x000D_
    <div class="custom-checkbox">_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check" checked> <span class="label-text">Option 01</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check"> <span class="label-text">Option 02</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check"> <span class="label-text">Option 03</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="checkbox" name="check" disabled> <span class="label-text">Option 04</span>_x000D_
                </label>_x000D_
      </div>_x000D_
    </div>_x000D_
  </form>_x000D_
</div>_x000D_
<div class="col-md-4">_x000D_
  <form>_x000D_
    <h2>2. Customs Radios</h2>_x000D_
    <div class="custom-radio">_x000D_
_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio" checked> <span class="label-text">Option 01</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio"> <span class="label-text">Option 02</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio"> <span class="label-text">Option 03</span>_x000D_
                </label>_x000D_
      </div>_x000D_
      <div class="form-check">_x000D_
        <label>_x000D_
                    <input type="radio" name="radio" disabled> <span class="label-text">Option 04</span>_x000D_
                </label>_x000D_
      </div>_x000D_
    </div>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Writing to an Excel spreadsheet

  • xlrd/xlwt (standard): Python does not have this functionality in it's standard library, but I think of xlrd/xlwt as the "standard" way to read and write excel files. It is fairly easy to make a workbook, add sheets, write data/formulas, and format cells. If you need all of these things, you may have the most success with this library. I think you could choose openpyxl instead and it would be quite similar, but I have not used it.

    To format cells with xlwt, define a XFStyle and include the style when you write to a sheet. Here is an example with many number formats. See example code below.

  • Tablib (powerful, intuitive): Tablib is a more powerful yet intuitive library for working with tabular data. It can write excel workbooks with multiple sheets as well as other formats, such as csv, json, and yaml. If you don't need formatted cells (like background color), you will do yourself a favor to use this library, which will get you farther in the long run.

  • csv (easy): Files on your computer are either text or binary. Text files are just characters, including special ones like newlines and tabs, and can be easily opened anywhere (e.g. notepad, your web browser, or Office products). A csv file is a text file that is formatted in a certain way: each line is a list of values, separated by commas. Python programs can easily read and write text, so a csv file is the easiest and fastest way to export data from your python program into excel (or another python program).

    Excel files are binary and require special libraries that know the file format, which is why you need an additional library for python, or a special program like Microsoft Excel, Gnumeric, or LibreOffice, to read/write them.


import xlwt

style = xlwt.XFStyle()
style.num_format_str = '0.00E+00'

...

for i,n in enumerate(list1):
    sheet1.write(i, 0, n, fmt)

Difference between adjustResize and adjustPan in android?

adjustResize = resize the page content

adjustPan = move page content without resizing page content

Determine the type of an object?

be careful using isinstance

isinstance(True, bool)
True
>>> isinstance(True, int)
True

but type

type(True) == bool
True
>>> type(True) == int
False

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Python: Append item to list N times

l = []
x = 0
l.extend([x]*100)

Java Minimum and Maximum values in Array

You just throw away Min/Max values:

  // get biggest number
  getMaxValue(array); // <- getMaxValue returns value, which is ignored
  // get smallest number
  getMinValue(array); // <- getMinValue returns value, which is ignored as well

You can do something like

  ... 
  array[i] = next;

  System.out.print("Max value = ");
  System.out.println(getMaxValue(array)); // <- Print out getMaxValue value

  System.out.print("Min value = ");
  System.out.println(getMinValue(array)); // <- Print out getMinValue value

  ...  

What is the difference between <p> and <div>?

<p> represents a paragraph and <div> represents a 'division', I suppose the main difference is that divs are semantically 'meaningless', where as a <p> is supposed to represent something relating to the text itself.

You wouldn't want to have nested <p>s for example, since that wouldn't make much semantic sense (except in the sense of quotations) Whereas people use nested <div>s for page layout.

According to Wikipedia

In HTML, the span and div elements are used where parts of a document cannot be semantically described by other HTML elements.

Angular window resize event

Here is an update to @GiridharKamik answer above with the latest version of Rxjs.

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, fromEvent } from 'rxjs';
import { pluck, distinctUntilChanged, map } from 'rxjs/operators';

@Injectable()
export class WindowService {
    height$: Observable<number>;
    constructor() {
        const windowSize$ = new BehaviorSubject(getWindowSize());

        this.height$ = windowSize$.pipe(pluck('height'), distinctUntilChanged());

        fromEvent(window, 'resize').pipe(map(getWindowSize))
            .subscribe(windowSize$);
    }

}

function getWindowSize() {
    return {
        height: window.innerHeight
        //you can sense other parameters here
    };
};

Executing command line programs from within python

This whole setup seems a little unstable to me.

Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.

Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.

Is it possible to send a variable number of arguments to a JavaScript function?

Do you want your function to react to an array argument or variable arguments? If the latter, try:

var func = function(...rest) {
  alert(rest.length);

  // In JS, don't use for..in with arrays
  // use for..of that consumes array's pre-defined iterator
  // or a more functional approach
  rest.forEach((v) => console.log(v));
};

But if you wish to handle an array argument

var fn = function(arr) {
  alert(arr.length);

  for(var i of arr) {
    console.log(i);
  }
};

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.

In Jelly Bean it is: Settings > Data Usage > mobile data

Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.

For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.

It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

if you use spring boot check in application.propertiese this property is commented or remove it if exist.

server.tomcat.additional-tld-skip-patterns=*.jar

text flowing out of div

If this helps. Add the following property with value to your selector:

white-space: pre-wrap;

How to redirect verbose garbage collection output to a file?

Java 9 & Unified JVM Logging

JEP 158 introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM:

-Xlog

For example, the following option:

-Xlog:gc

will log messages tagged with gc tag using info level to stdout. Or this one:

-Xlog:gc=debug:file=gc.txt:none

would log messages tagged with gc tag using debug level to a file called gc.txt with no decorations. For more detailed discussion, you can checkout the examples in the JEP page.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

What is a Python egg?

"Egg" is a single-file importable distribution format for Python-related projects.

"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."

Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.

Purge or recreate a Ruby on Rails database

Simply you can run

rake db:setup

It will drop database, create new database and populate db from seed if you created seed file with some data.

Try catch statements in C

Perhaps not a major language (unfortunately), but in APL, theres the ?EA operation (stand for Execute Alternate).

Usage: 'Y' ?EA 'X' where X and Y are either code snippets supplied as strings or function names.

If X runs into an error, Y (usually error-handling) will be executed instead.

Force re-download of release dependency using Maven

If you know the group id of X, you can use this command to redownload all of X and it's dependencies

mvn clean dependency:purge-local-repository -DresolutionFuzziness=org.id.of.x

It does the same thing as the other answers that propose using dependency:purge-local-repository, but it only deletes and redownloads everything related to X.

How to display binary data as image - extjs 4

Need to convert it in base64.

JS have btoa() function for it.

For example:

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);

But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.

Update:

Need to write simple hex to base64 converter:

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

And use it:

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');

See working example with your hex data on jsfiddle

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

jQuery - Redirect with post data

Similar to the above answer, but written differently.

$.extend(
{
    redirectPost: function (location, args) {
        var form = $('<form>', { action: location, method: 'post' });
        $.each(args,
            function (key, value) {
                $(form).append(
                    $('<input>', { type: 'hidden', name: key, value: value })
                );
            });
        $(form).appendTo('body').submit();
    }
});

Any way to exit bash script, but not quitting the terminal

This is just like you put a run function inside your script run2.sh. You use exit code inside run while source your run2.sh file in the bash tty. If the give the run function its power to exit your script and give the run2.sh its power to exit the terminator. Then of cuz the run function has power to exit your teminator.

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

Anyway, I approve with Kaz it's a design problem.

SQL Server: Null VS Empty String

There's a nice article here which discusses this point. Key things to take away are that there is no difference in table size, however some users prefer to use an empty string as it can make queries easier as there is not a NULL check to do. You just check if the string is empty. Another thing to note is what NULL means in the context of a relational database. It means that the pointer to the character field is set to 0x00 in the row's header, therefore no data to access.

Update There's a detailed article here which talks about what is actually happening on a row basis

Each row has a null bitmap for columns that allow nulls. If the row in that column is null then a bit in the bitmap is 1 else it's 0.

For variable size datatypes the acctual size is 0 bytes.

For fixed size datatype the acctual size is the default datatype size in bytes set to default value (0 for numbers, '' for chars).

the result of DBCC PAGE shows that both NULL and empty strings both take up zero bytes.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

Stored procedures:

(+)

  • Great flexibility
  • Full control over SQL
  • The highest performance available

(-)

  • Requires knowledge of SQL
  • Stored procedures are out of source control
  • Substantial amount of "repeating yourself" while specifying the same table and field names. The high chance of breaking the application after renaming a DB entity and missing some references to it somewhere.
  • Slow development

ORM:

(+)

  • Rapid development
  • Data access code now under source control
  • You're isolated from changes in DB. If that happens you only need to update your model/mappings in one place.

(-)

  • Performance may be worse
  • No or little control over SQL the ORM produces (could be inefficient or worse buggy). Might need to intervene and replace it with custom stored procedures. That will render your code messy (some LINQ in code, some SQL in code and/or in the DB out of source control).
  • As any abstraction can produce "high-level" developers having no idea how it works under the hood

The general tradeoff is between having a great flexibility and losing lots of time vs. being restricted in what you can do but having it done very quickly.

There is no general answer to this question. It's a matter of holy wars. Also depends on a project at hand and your needs. Pick up what works best for you.

How do you get a query string on Flask?

I came here looking for the query string, not how to get values from the query string.

request.query_string returns the URL parameters as raw byte string (Ref 1).

Example of using request.query_string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_query_string():
    return request.query_string

if __name__ == '__main__':
    app.run(debug=True)

Output:

query parameters in Flask route

References:

  1. Official API documentation on query_string

List method to delete last element in list as well as all elements

To delete the last element from the list just do this.

a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4] 

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Equals(=) vs. LIKE

This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='12345678'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Get current domain

The only secure way of doing this

The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.

Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:

Secure methods of storing the domain Used By
A config file Joomla, Drupal/Symfony
The database WordPress
An environmental variable Laravel
A service registry Kubernetes DNS

The following work... but they're not secure

Hackers can make the following variables output whatever domain they want. This can lead to cache poisoning and barely noticeable phishing attacks.

$_SERVER['HTTP_HOST']

This gets the domain from the request headers which are open to manipulation by hackers. Same with:

$_SERVER['SERVER_NAME']

This one can be made better if the Apache setting usecanonicalname is turned off; in which case $_SERVER['SERVER_NAME'] will no longer be allowed to be populated with arbitrary values and will be secure. This is, however, non-default and not as common of a setup.

In popular systems

Below is how you can get the current domain in the following frameworks/systems:

WordPress

$urlparts = parse_url(home_url());
$domain = $urlparts['host'];

If you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.

Laravel

request()->getHost()

The request()->getHost function is inherited from Symfony, and has been secure since the 2013 CVE-2013-4752 was patched.

Drupal

The installer does not yet take care of making this secure (issue #2404259). But in Drupal 8 there is documentation you can you can follow at Trusted Host Settings to secure your Drupal installation after which the following can be used:

\Drupal::request()->getHost();

Other frameworks

Feel free to edit this answer to include how to get the current domain in your favorite framework. When doing so, please include a link to the relevant source code or to anything else that would help me verify that the framework is doing things securely.


Addendum

Exploitation examples:

  1. Cache poisoning can happen if a botnet continuously requests a page using the wrong hosts header. The resulting HTML will then include links to the attackers website where they can phish your users. At first the malicious links will only be sent back to the hacker, but if the hacker does enough requests, the malicious version of the page will end up in your cache where it will be distributed to other users.

  2. A phishing attack can happen if you store links in the database based on the hosts header. For example, let say you store the absolute URL to a user's profiles on a forum. By using the wrong header, a hacker could get anyone who clicks on their profile link to be sent a phishing site.

  3. Password reset poisoning can happen if a hacker uses a malicious hosts header when filling out the password reset form for a different user. That user will then get an email containing a password reset link that leads to a phishing site. Another more complex form of this skips the user having to do anything by getting the email to bounce and resend to one of the hacker's SMTP servers (for example CVE-2017-8295.)

  4. Here are some more malicious examples

Additional Caveats and Notes:

  • When usecanonicalname is turned off the $_SERVER['SERVER_NAME'] is populated with the same header $_SERVER['HTTP_HOST'] would have used anyways (plus the port). This is Apache's default setup. If you or devops turns this on then you're okay -- ish -- but do you really want to rely on a separate team, or yourself three years in the future, to keep what would appear to be a minor configuration at a non-default value? Even though this makes things secure, I would caution against relying on this setup.
  • Redhat, however, does turn usecanonical on by default [source].
  • If serverAlias is used in the virtual hosts entry, and the aliased domain is requested, $_SERVER['SERVER_NAME'] will not return the current domain, but will return the value of the serverName directive.
  • If the serverName cannot be resolved, the operating system's hostname command is used in its place [source].
  • If the host header is left out, the server will behave as if usecanonical was on [source].
  • Lastly, I just tried exploiting this on my local server, and was unable to spoof the hosts header. I'm not sure if there was an update to Apache that addressed this, or if I was just doing something wrong. Regardless, this header would still be exploitable in environments where virtual hosts are not being used.

Little Rant:

     This question received hundreds of thousands of views without a single mention of the security problems at hand! It shouldn't be this way, but just because a Stack Overflow answer is popular, that doesn't mean it is secure.



Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

'cannot find or open the pdb file' Visual Studio C++ 2013

There are no problems here this is perfectly normal - it shows informational messages about what debug-info was loaded (and which wasn't) and also that your program executed and exited normally - a zero return code means success.

If you don't see anything on the screen thry running your program with CTRL-F5 instead of just F5.

Retrieve WordPress root directory path?

If you have WordPress bootstrap loaded you can use get_home_path() function to get path to the WordPress root directory.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

To get the behavior you want, simply have each consumer consume from its own queue. You'll have to use a non-direct exchange type (topic, header, fanout) in order to get the message to all of the queues at once.

Post-increment and pre-increment within a 'for' loop produce same output

The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.

However, under the hood there's a difference: The post-incrementation i++ needs to create a temporary variable to store the original value of i, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++.

Three reasons why you should pre-increment:

  1. You won't have to think about whether the variable/object might have an overloaded post-incrementation method (for example in a template function) and treat it differently (or forget to treat it differently).
  2. Consistent code looks better.
  3. When someone asks you "Why do you pre-increment?" you'll get the chance to teach them about the halting problem and theoretical limits of compiler optimization. :)

Java ArrayList Index

Using an Array:

String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element

Using a List

ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));

How to convert a string of bytes into an int?

In Python 3.2 and later, use

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
2043455163

or

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
3148270713

according to the endianness of your byte-string.

This also works for bytestring-integers of arbitrary length, and for two's-complement signed integers by specifying signed=True. See the docs for from_bytes.

How to make a smaller RatingBar?

The best answer I got

  <style name="MyRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:minHeight">15dp</item>
    <item name="android:maxHeight">15dp</item>
    <item name="colorControlNormal">@color/white</item>
    <item name="colorControlActivated">@color/home_add</item>
</style>

user like this

<RatingBar
                style="?android:attr/ratingBarStyleIndicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:isIndicator="false"
                android:max="5"
                android:rating="3"
                android:scaleX=".8"
                android:scaleY=".8"
                android:theme="@style/MyRatingBar" />

Increase/Decrease sizes by using scaleX and scaleY value

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

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

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Stop MySQL service windows

You can set its startup type to manual in services.msc. This way it will not start automatically unless required. Simply get the name of the service from services.msc as shown here:

enter image description here

You can create batch files to start and stop the service fairly easily as well. Now use this name in batch files.

Your start.bat:

net start "mysql"

And in your stop.bat:

net stop "mysql"

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

Object array initialization without default constructor

In C++11's std::vector you can instantiate elements in-place using emplace_back:

  std::vector<Car> mycars;

  for (int i = 0; i < userInput; ++i)
  {
      mycars.emplace_back(i + 1); // pass in Car() constructor arguments
  }

Voila!

Car() default constructor never invoked.

Deletion will happen automatically when mycars goes out of scope.

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

Error in plot.new() : figure margins too large in R

I found this error today. Initially, I was trying to output it to a .jpeg file with low width and height.

jpeg("method1_test.jpg", width=900, height=900, res=40)

Later I increased the width and height to:

jpeg("method1_test.jpg", width=1900, height=1900, res=40)

The error was not there. :)

You can also play with the resolution, if the resolution is high, you need more width and height.

Python JSON encoding

The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.

From www.json.org:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

Draw a connecting line between two elements

Cytoscape supports this with its Architecture example which supports dragging elements.

For creating connections, there is the edgehandles extension. It does not yet support editing existing connections. Question.

For editing connection shapes, there is the edge-editing extension. Demo.

The edit-editation extension seems promising, however there is no demo yet.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

Being new to this myself, here's what I did:

I'm using MS Visual Studio 2010 Pro.

  1. Download and install the OpenXML SDK
  2. Within my project in Visual Studio, select "Project" then "Add Reference"
  3. Select the "Browse" tab
  4. In the "Look in:" pull down, navigate to: C:\Program Files(x86)\Open XML SDK\V2.0\lib and select the "DocumentFormat.OpenXml.dll
  5. Hit OK
  6. In the "Solution Explorer" (on the right for me), the "References" folder now shows the DocumentFormat.OpenXML library.
  7. Right-click on it and select Properties
  8. In the Properties panel, change "Copy Local" to "True".

You should be off and running now using the DocumentFormat classes.

Create a Maven project in Eclipse complains "Could not resolve archetype"

I fixed this problem by following the solution to this other StackOverflow question

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below: (Please note the https protocol)

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

Quickest way to find missing number in an array of numbers

Here program take time complexity is O(logn) and space complexity O(logn)

public class helper1 {

public static void main(String[] args) {


    int a[] = {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12};


    int k = missing(a, 0, a.length);
    System.out.println(k);
}

public static int missing(int[] a, int f, int l) {


    int mid = (l + f) / 2;

    //if first index reached last then no element found 
    if (a.length - 1 == f) {
        System.out.println("missing not find ");
        return 0;
    }

    //if mid with first found 
    if (mid == f) {
        System.out.println(a[mid] + 1);
        return a[mid] + 1;
    }

    if ((mid + 1) == a[mid])
        return missing(a, mid, l);
    else
        return missing(a, f, mid);

  }
 }

How to call servlet through a JSP page

You can use RequestDispatcher as you usually use it in Servlet:

<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
     RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>

Always be aware that don't commit any response before you use forward, as it will lead to IllegalStateException.

How can I change cols of textarea in twitter-bootstrap?

I found the following in the site.css generated by VS2013

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

To override this behavior in a specific element, add the following...

 style="max-width: none;" 

For example:

 <div class="col-md-6">
      <textarea style="max-width: none;" 
                class="form-control" 
                placeholder="a col-md-6 multiline input box" />
 </div>

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

Visual Studio 2015 installer hangs during install?

I had the same problem on a different context. After trying to repair, uninstall, and reinstall with no solution, I decided to wipe out all Visual Studio remnant by using TotalUninstaller by follower the steps by steps on the link below:

https://github.com/Microsoft/VisualStudioUninstaller/releases

Once everything is removed, I was able to successfully install the software.

Be aware that TotalUninstaller will remove everything related to Visual Studio 2013 to 2015. Earlier version will still be preserved.

I added this solution in case someone has the exact same problem.

How do I access call log for android?

This post is a little bit old, but here is another easy solution for getting data related to Call logs content provider in Android:

Use this lib: https://github.com/EverythingMe/easy-content-providers

Get all calls:

CallsProvider callsProvider = new CallsProvider(context);
List<Call> calls = callsProvider.getCalls().getList();

Each Call has all fields, so you can get any info you need:
callDate, duration, number, type(INCOMING, OUTGOING, MISSED), isRead, ...

It works with List or Cursor and there is a sample app to see how it looks and works.

In fact, there is a support for all Android content providers like: Contacts, SMS, Calendar, ... Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers

Hope it also helped :)

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

AppSettings get value from .config file

Coming back to this one after a long time...

Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

Requires System.Configuration of course.

(Editted the code to something that actually works and is simpler to read)

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Differences between JDK and Java SDK

JDK is the SDK for Java.

SDK stands for 'Software Development Kit', a developers tools that enables one to write the code with more more ease, effectiveness and efficiency. SDKs come for various languages. They provide a lot of APIs (Application Programming Interfaces) that makes the programmer's work easy.

enter image description here

The SDK for Java is called as JDK, the Java Development Kit. So by saying SDK for Java you are actually referring to the JDK.

Assuming that you are new to Java, there is another term that you'll come across- JRE, the acronym for Java Runtime Environment. JRE is something that you need when you try to run software programs written in Java.

Java is a platform independent language. The JRE runs the JVM, the Java Virtual Machine, that enables you to run the software on any platform for which the JVM is available.

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

How do I find out what version of Sybase is running

Run this command:

select @@version

Seaborn plots not showing up

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

Please note: In Python 2, you can also use sns.plt.show(), but not in Python 3.

Complete Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

Gives

enter image description here

How to debug apk signed for release?

Besides Manuel's way, you can still use the Manifest.

In Android Studio stable, you have to add the following 2 lines to application in the AndroidManifest file:

    android:debuggable="true"
    tools:ignore="HardcodedDebugMode"

The first one will enable debugging of signed APK, and the second one will prevent compile-time error.

After this, you can attach to the process via "Attach debugger to Android process" button.

PHP Header redirect not working

Try This :

**ob_start();**

include('header.php');

$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];

$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query
$MyDB->run();

header('Location:index.php');

**ob_end_flush();**

    exit;

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

WPF button click in C# code

You should place below line

btn.Click = btn.Click + btn1_Click;

Jar mismatch! Fix your dependencies

I think you create a new workspace and import all project properly with his lib and also add external jar android-support-v4.jar in adb bundle in sdk extra files. I think its work for you. Hope all the best

And also use the android support lib it may be help you and also update your adt bundle

UINavigationBar Hide back Button Text

If you're targeting iOS 13 and later you can use this new API to hide the back button title globally.

let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.clear]

UINavigationBar.appearance().standardAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().compactAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().scrollEdgeAppearance.backButtonAppearance = backButtonAppearance

How to convert a List<String> into a comma separated string without iterating List explicitly

The following:

String joinedString = ids.toString()

will give you a comma delimited list. See docs for details.

You will need to do some post-processing to remove the square brackets, but nothing too tricky.

Log record changes in SQL server in an audit table

Hey It's very simple see this

@OLD_GUEST_NAME = d.GUEST_NAME from deleted d;

this variable will store your old deleted value and then you can insert it where you want.

for example-

Create trigger testupdate on test for update, delete
  as
declare @tableid varchar(50);
declare @testid varchar(50);
declare @newdata varchar(50);
declare @olddata varchar(50);


select @tableid = count(*)+1 from audit_test
select @testid=d.tableid from inserted d;
select @olddata = d.data from deleted d;
select @newdata = i.data from inserted i;

insert into audit_test (tableid, testid, olddata, newdata) values (@tableid, @testid, @olddata, @newdata)

go