Programs & Examples On #Two connection limit

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

What's the best way to use R scripts on the command line (terminal)?

You might want to use python's rpy2 module. However, the "right" way to do this is with R CMD BATCH. You can modify this to write to STDOUT, but the default is to write to a .Rout file. See example below:

[ramanujan:~]$cat foo.R
print(rnorm(10))
[ramanujan:~]$R CMD BATCH foo.R
[ramanujan:~]$cat foo.Rout

R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]


 ~/.Rprofile loaded.
Welcome at  Fri Apr 17 13:33:17 2009
> print(rnorm(10))
 [1]  1.5891276  1.1219071 -0.6110963  0.1579430 -0.3104579  1.0072677 -0.1303165  0.6998849  1.9918643 -1.2390156
>

Goodbye at  Fri Apr 17 13:33:17 2009
> proc.time()
   user  system elapsed
  0.614   0.050   0.721

Note: you'll want to try out the --vanilla and other options to remove all the startup cruft.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

Another way to solve this problem is to install the missing libs that you need.

You can download the libs and see how to install here.

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

Get week of year in JavaScript like in PHP

You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.

A better link on the same site is: Working with weeks.

Edit

Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.

Edit 2017

There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.

_x000D_
_x000D_
/* For a given date, get the ISO week number_x000D_
 *_x000D_
 * Based on information at:_x000D_
 *_x000D_
 *    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR_x000D_
 *_x000D_
 * Algorithm is to find nearest thursday, it's year_x000D_
 * is the year of the week number. Then get weeks_x000D_
 * between that date and the first day of that year._x000D_
 *_x000D_
 * Note that dates in one year can be weeks of previous_x000D_
 * or next year, overlap is up to 3 days._x000D_
 *_x000D_
 * e.g. 2014/12/29 is Monday in week  1 of 2015_x000D_
 *      2012/1/1   is Sunday in week 52 of 2011_x000D_
 */_x000D_
function getWeekNumber(d) {_x000D_
    // Copy date so don't modify original_x000D_
    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));_x000D_
    // Set to nearest Thursday: current date + 4 - current day number_x000D_
    // Make Sunday's day number 7_x000D_
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));_x000D_
    // Get first day of year_x000D_
    var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
    // Calculate full weeks to nearest Thursday_x000D_
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);_x000D_
    // Return array of year and week number_x000D_
    return [d.getUTCFullYear(), weekNo];_x000D_
}_x000D_
_x000D_
var result = getWeekNumber(new Date());_x000D_
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
_x000D_
_x000D_
_x000D_

Hours are zeroed when creating the "UTC" date.

Minimized, prototype version (returns only week-number):

_x000D_
_x000D_
Date.prototype.getWeekNumber = function(){_x000D_
  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));_x000D_
  var dayNum = d.getUTCDay() || 7;_x000D_
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);_x000D_
  var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
  return Math.ceil((((d - yearStart) / 86400000) + 1)/7)_x000D_
};_x000D_
_x000D_
document.write('The current ISO week number is ' + new Date().getWeekNumber());
_x000D_
_x000D_
_x000D_

Test section

In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).

_x000D_
_x000D_
Date.prototype.getWeekNumber = function(){_x000D_
  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));_x000D_
  var dayNum = d.getUTCDay() || 7;_x000D_
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);_x000D_
  var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));_x000D_
  return Math.ceil((((d - yearStart) / 86400000) + 1)/7)_x000D_
};_x000D_
_x000D_
function checkWeek() {_x000D_
  var s = document.getElementById('dString').value;_x000D_
  var m = moment(s, 'YYYY-MM-DD');_x000D_
  document.getElementById('momentWeek').value = m.format('W');_x000D_
  document.getElementById('answerWeek').value = m.toDate().getWeekNumber();      _x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>_x000D_
_x000D_
Enter date  YYYY-MM-DD: <input id="dString" value="2021-02-22">_x000D_
<button onclick="checkWeek(this)">Check week number</button><br>_x000D_
Moment: <input id="momentWeek" readonly><br>_x000D_
Answer: <input id="answerWeek" readonly>
_x000D_
_x000D_
_x000D_

The create-react-app imports restriction outside of src directory

I have had to overcome this same issue in Truffle. The solution was as follows:

ince Create-React-App's default behavior disallows importing files from outside of the src folder, we need to bring the contracts in our build folder inside src. We can copy and paste them every time we compile our contracts, but a better way is to simply configure Truffle to put the files there.

In the truffle-config.js file, replace the contents with the following:

const path = require("path");

module.exports = {
  contracts_build_directory: path.join(__dirname, "client/src/contracts")
};

I don't know if this helps you, but I know I found your question when I had the same issue in Truffle, and this might help someone else.

pandas: to_numeric for multiple columns

UPDATE: you don't need to convert your values afterwards, you can do it on-the-fly when reading your CSV:

In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)

In [166]: df.dtypes
Out[166]:
GeoName                    object
ComponentName              object
IndustryId                  int64
IndustryClassification     object
Description                object
2004                        int64
2005                        int64
2006                        int64
2007                        int64
2008                        int64
2009                        int64
2010                        int64
2011                        int64
2012                        int64
2013                        int64
2014                      float64
dtype: object

If you need to convert multiple columns to numeric dtypes - use the following technique:

Sample source DF:

In [271]: df
Out[271]:
     id    a  b  c  d  e    f
0  id_3  AAA  6  3  5  8    1
1  id_9    3  7  5  7  3  BBB
2  id_7    4  2  3  5  4    2
3  id_0    7  3  5  7  9    4
4  id_0    2  4  6  4  0    2

In [272]: df.dtypes
Out[272]:
id    object
a     object
b      int64
c      int64
d      int64
e      int64
f     object
dtype: object

Converting selected columns to numeric dtypes:

In [273]: cols = df.columns.drop('id')

In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

In [275]: df
Out[275]:
     id    a  b  c  d  e    f
0  id_3  NaN  6  3  5  8  1.0
1  id_9  3.0  7  5  7  3  NaN
2  id_7  4.0  2  3  5  4  2.0
3  id_0  7.0  3  5  7  9  4.0
4  id_0  2.0  4  6  4  0  2.0

In [276]: df.dtypes
Out[276]:
id     object
a     float64
b       int64
c       int64
d       int64
e       int64
f     float64
dtype: object

PS if you want to select all string (object) columns use the following simple trick:

cols = df.columns[df.dtypes.eq('object')]

How can you export the Visual Studio Code extension list?

Open the Visual Studio Code console and write:

code --list-extensions (or code-insiders --list-extensions if Visual Studio Code insider is installed)

Then share the command line with colleagues:

code --install-extension {ext1} --install-extension {ext2} --install-extension {extN} replacing {ext1}, {ext2}, ... , {extN} with the extension you listed

For Visual Studio Code insider: code-insiders --install-extension {ext1} ...

If they copy/paste it in Visual Studio Code command-line terminal, they'll install the shared extensions.

More information on command-line-extension-management.

Java: How to convert a File object to a String object in java?

You can copy all contents of myhtml to String as follows:

Scanner myScanner = null;
try
{
    myScanner = new Scanner(myhtml);
    String contents = myScanner.useDelimiter("\\Z").next(); 
}
finally
{
    if(myScanner != null)
    {
        myScanner.close(); 
    }
}

Ofcourse, you can add a catch block to handle exceptions properly.

SDK Manager.exe doesn't work

I solved my problem opening android.bat inside sdk/tools and setting the java_exe property, which was empty.

set java_exe="C:\Program Files\Java\jre6\bin\java"

Print string and variable contents on the same line in R

Or using message

message("Current working dir: ", wd)

@agstudy's answer is the more suitable here

Slack clean all messages (~8K) in a channel

For anyone else who doesn't need to do it programmatic, here's a quick way:

(probably for paid users only)

  1. Open the channel in web or the desktop app, and click the cog (top right).
  2. Choose "Additional options..." to bring up the archival menu. notes
  3. Select "Set the channel message retention policy".
  4. Set "Retain all messages for a specific number of days".
  5. All messages older than this time are deleted permanently!

I usually set this option to "1 day" to leave the channel with some context, then I go back into the above settings, and set it's retention policy back to "default" to go continue storing them from now-on.

Notes:
Luke points out: If the option is hidden: you have to go to global workspace Admin settings, Message Retention & Deletion, and check "Let workspace members override these settings"

Exit while loop by user hitting ENTER key

Here's a solution (resembling the original) that works:

User = raw_input('Enter <Carriage return> only to exit: ')
while True:
    #Run my program
    print 'In the loop, User=%r' % (User, )

    # Check if the user asked to terminate the loop.
    if User == '':
        break

    # Give the user another chance to exit.
    User = raw_input('Enter <Carriage return> only to exit: ')

Note that the code in the original question has several issues:

  1. The if/else is outside the while loop, so the loop will run forever.
  2. The else is missing a colon.
  3. In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
  4. It doesn't need the running variable, since the if clause performs a break.

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

Mysql 1050 Error "Table already exists" when in fact, it does not

I had this problem on Win7 in Sql Maestro for MySql 12.3. Enormously irritating, a show stopper in fact. Nothing helped, not even dropping and recreating the database. I have this same setup on XP and it works there, so after reading your answers about permissions I realized that it must be Win7 permissions related. So I ran MySql as administrator and even though Sql Maestro was run normally, the error disappeared. So it must have been a permissions issue between Win7 and MySql.

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

What are the differences between a multidimensional array and an array of arrays in C#?

This might have been mentioned in the above answers but not explicitly: with jagged array you can use array[row] to refer a whole row of data, but this is not allowed for multi-d arrays.

How can I search an array in VB.NET?

If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.

The representation of if-elseif-else in EL using JSF

One possible solution is:

<h:panelGroup rendered="#{bean.row == 10}">
    <div class="text-success">
        <h:outputText value="#{bean.row}"/>
    </div>
</h:panelGroup>

Apply jQuery datepicker to multiple instances

I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js

// this.element.on('click', $.proxy(this.show, this));

org.xml.sax.SAXParseException: Content is not allowed in prolog

I encountered similar problem with jenkins junit report plugin. It turns out you have to specify *.xml, even if you create junit xml in home directory. (So Test report XMLs: .xml ..(or targeted_directory/.xml).

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

If tdd='<td class="abc"> 75</td>'
In Beautifulsoup 

if(tdd.has_attr('class')):
   print(tdd.attrs['class'][0])


Result:  abc

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Match whitespace but not newlines

The below regex would match white spaces but not of a new line character.

(?:(?!\n)\s)

DEMO

If you want to add carriage return also then add \r with the | operator inside the negative lookahead.

(?:(?![\n\r])\s)

DEMO

Add + after the non-capturing group to match one or more white spaces.

(?:(?![\n\r])\s)+

DEMO

I don't know why you people failed to mention the POSIX character class [[:blank:]] which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).

DEMO

how to add or embed CKEditor in php page

If you have downloaded the latest Version 4.3.4 then just follow these steps.

  • Download the package, unzip and place in your web directory or root folder.
  • Provide the read write permissions to that folder (preferably Ubuntu machines )
  • Create view page test.php
  • Paste the below mentioned code it should work fine.

Load the mentioned js file

<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<textarea class="ckeditor" name="editor"></textarea>

How to change the text of a button in jQuery?

$("#btnAddProfile").html('Save').button('refresh');

Create WordPress Page that redirects to another URL

(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)

I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php all the time, or fiddle around with your server settings on each addition (I do not like both).

TLTR

You can add a filter on the actual WP permalink function you need (for me it was post_link, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.

This is ok, because the post is an alias, so you won't need the content anyways.

First step is to open the alias post and put the ID of the referenced post as content (and nothing else):

enter image description here

Next, open your functions.php and add:

function prefix_filter_post_permalink($url, $post) {
    // if the content of the post to get the permalink for is just a number...
    if (is_numeric($post->post_content)) {
        // instead, return the permalink for the post that has this ID
        return get_the_permalink((int)$post->post_content);
    }
    return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );

That's it

Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.

This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP code is far from ideal, but like this for making the point readable.

How can I make XSLT work in chrome?

What Eric says is correct.

In the xsl, for the xsl:stylesheet tag have the following attributes

version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"

It works fine in chrome.

After installing with pip, "jupyter: command not found"

Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:

First verify this is a PATH issue:

Check if the path returned by which jupyter is covered by the sudo user:

sudo env | grep ^PATH

(As opposed to the current user: env | grep ^PATH)

If its not covered - add a soft link from it to one of the covered paths. For ex:

sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin

Now you sould be able to run:

sudo jupyter notebook

How to add element into ArrayList in HashMap

Typical code is to create an explicit method to add to the list, and create the ArrayList on the fly when adding. Note the synchronization so the list only gets created once!

@Override
public synchronized boolean addToList(String key, Item item) {
   Collection<Item> list = theMap.get(key);
   if (list == null)  {
      list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
      theMap.put(key, list );
   }

   return list.add(item);
}

Android SDK installation doesn't find JDK

WORKING SOLUTION AND NO REGISTRY MODIFY NEEDED

Simply put your java bin path in front of your PATH environment.

PATH before

C:\Windows\system32;C:\Windows\%^^&^&^............(old path setting)

PATH after

C:\Program Files\Java\jdk1.6.0_18\bin;C:\Windows\system32;C:\Windows\%^^&^&^............(old path setting)

And now the Android SDK installer is working.

BTW, I'm running Win7 x64.

Jquery: How to check if the element has certain css class/style

i've found one solution:

$("#someElement")[0].className.match("test")

but somehow i believe that there's a better way!

Android - save/restore fragment state

You can get current Fragment from fragmentManager. And if there are non of them in fragment manager you can create Fragment_1

public class MainActivity extends FragmentActivity {


    public static Fragment_1 fragment_1;
    public static Fragment_2 fragment_2;
    public static Fragment_3 fragment_3;
    public static FragmentManager fragmentManager;


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.main);

        fragment_1 = (Fragment_1) fragmentManager.findFragmentByTag("fragment1");

        fragment_2  =(Fragment_2) fragmentManager.findFragmentByTag("fragment2");

        fragment_3 = (Fragment_3) fragmentManager.findFragmentByTag("fragment3");


        if(fragment_1==null && fragment_2==null && fragment_3==null){           
            fragment_1 = new Fragment_1();          
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment_1, "fragment1").commit();
        }


    }


}

also you can use setRetainInstance to true what it will do it ignore onDestroy() method in fragment and your application going to back ground and os kill your application to allocate more memory you will need to save all data you need in onSaveInstanceState bundle

public class Fragment_1 extends Fragment {


    private EditText title;
    private Button go_next;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true); //Will ignore onDestroy Method (Nested Fragments no need this if parent have it)
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        onRestoreInstanceStae(savedInstanceState);
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    //Here you can restore saved data in onSaveInstanceState Bundle
    private void onRestoreInstanceState(Bundle savedInstanceState){
        if(savedInstanceState!=null){
            String SomeText = savedInstanceState.getString("title");            
        }
    }

    //Here you Save your data
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("title", "Some Text");
    }

}

Set keyboard caret position in html textbox

The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

In case the code gets lost again, here are the two main functions:

function doGetCaretPosition(ctrl)
{
 var CaretPos = 0;

 if (ctrl.selectionStart || ctrl.selectionStart == 0)
 {// Standard.
  CaretPos = ctrl.selectionStart;
 }
 else if (document.selection)
 {// Legacy IE
  ctrl.focus ();
  var Sel = document.selection.createRange ();
  Sel.moveStart ('character', -ctrl.value.length);
  CaretPos = Sel.text.length;
 }

 return (CaretPos);
}


function setCaretPosition(ctrl,pos)
{
 if (ctrl.setSelectionRange)
 {
  ctrl.focus();
  ctrl.setSelectionRange(pos,pos);
 }
 else if (ctrl.createTextRange)
 {
  var range = ctrl.createTextRange();
  range.collapse(true);
  range.moveEnd('character', pos);
  range.moveStart('character', pos);
  range.select();
 }
}

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

Multiple Java versions running concurrently under Windows

Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)

If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

How to get StackPanel's children to fill maximum space downward?

You can use SpicyTaco.AutoGrid - a modified version of StackPanel:

<st:StackPanel Orientation="Horizontal" MarginBetweenChildren="10" Margin="10">
   <Button Content="Info" HorizontalAlignment="Left" st:StackPanel.Fill="Fill"/>
   <Button Content="Cancel"/>
   <Button Content="Save"/>
</st:StackPanel>

First button will be fill.

You can install it via NuGet:

Install-Package SpicyTaco.AutoGrid

I recommend taking a look at SpicyTaco.AutoGrid. It's very useful for forms in WPF instead of DockPanel, StackPanel and Grid and solve problem with stretching very easy and gracefully. Just look at readme on GitHub.

<st:AutoGrid Columns="160,*" ChildMargin="3">
    <Label Content="Name:"/>
    <TextBox/>

    <Label Content="E-Mail:"/>
    <TextBox/>

    <Label Content="Comment:"/>
    <TextBox/>
</st:AutoGrid>

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

In .NET, which loop runs faster, 'for' or 'foreach'?

It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ, etc. In general, stick with foreach.

Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.

Swift: How to get substring from start to last index of character

Here's an easy and short way to get a substring if you know the index:

let s = "www.stackoverflow.com"
let result = String(s.characters.prefix(17)) // "www.stackoverflow"

It won't crash the app if your index exceeds string's length:

let s = "short"
let result = String(s.characters.prefix(17)) // "short"

Both examples are Swift 3 ready.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

For the first error you can simply clear your local repository cache to force it download from main repository rather than checking the local one.

For second error, if you are behind proxy you should configure it this way Configuring a proxy otherwise you have a network problem now.

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

SQL Server : SUM() of multiple rows including where clauses

This will bring back totals per property and type

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
GROUP BY    PropertyID,
            TYPE

This will bring back only active values

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID,
            TYPE

and this will bring back totals for properties

SELECT  PropertyID,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID

......

Private pages for a private Github repo

As outlined above, Github pages do not support that functionality. I had the same issue when our team decided to host project documentation (static HTML) internally and privately.

I ended up creating a service https://www.privatehub.cloud It is basically a simple proxy server with Github OAuth authentication, so it merely returns your GitHub repository content with a proper MIME type. By design, only who have access to foo will be able to see foo content at https://bar-foo.privatehub.cloud. From functional point of view, you can think about it as a simplified GitHub pages with built-in authentication.

Unfortunately, Github OAuth does not allow to request read-only access to private repos, so the server needs the full access (obviously, it does not write anything to your repo). As GitHub API allows to retrieve files under 1 Mb only, the service cannot return larger files. Yet, I found the service is quite suitable for small projects for internal documentation or staging version of a website.

Best way to convert strings to symbols in hash

This is my one liner for nested hashes

def symbolize_keys(hash)
  hash.each_with_object({}) { |(k, v), h| h[k.to_sym] = v.is_a?(Hash) ? symbolize_keys(v) : v }
end

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Apparently this issue caused by Android Studio on the various situation but the reason is build error When importing an existing project into android studio.

In my case, I've imported my exist project where I was supposed to install few build tools then finally build configuration was done with error. In this case, just do the following things

  1. Close the current project
  2. File>New>Import Project (Don't use the open recent project)

    Note: I'm sure this kind of error is not on source code when this happened on Import project.

Iterate over the lines of a string

Here are three possibilities:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

Measuring gives:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

But the split-based approach still rules.

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

at least, it's a bit less verbose. The need to strip trailing \ns unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('\n'), stri)

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

How do I execute a string containing Python code in Python?

eval() is just for expressions, while eval('x+1') works, eval('x=1') won't work for example. In that case, it's better to use exec, or even better: try to find a better solution :)

Calculating bits required to store decimal number

The simplest answer would be to convert the required values to binary, and see how many bits are required for that value. However, the question asks how many bits for a decimal number of X digits. In this case, it seems like you have to choose the highest value with X digits, and then convert that number to binary.

As a basic example, Let's assume we wanted to store a 1 digit base ten number, and wanted to know how many bits that would require. The largest 1 digit base ten number is 9, so we need to convert it to binary. This yields 1001, which has a total of 4 bits. This same example can be applied to a two digit number (with the max value being 99, which converts to 1100011). To solve for n digits, you probably need to solve the others and search for a pattern.

To convert values to binary, you repeatedly divide by two until you get a quotient of 0 (and all of your remainders will be 0 or 1). You then reverse the orders of your remainders to get the number in binary.

Exampe: 13 to binary.

  • 13/2 = 6 r 1
  • 6/2 = 3 r 0
  • 3/2 = 1 r 1
  • 1/2 = 0 r 1
  • = 1101 ((8*1) + (4*1) + (2*0) + (1*1))

Hope this helps out.

How to make a window always stay on top in .Net?

Why not making your form a dialogue box:

myForm.ShowDialog();

What is the difference between AF_INET and PF_INET in socket programming?

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

Regex to check whether a string contains only numbers

^[0-9]$ 

...is a regular expression matching any single digit, so 1 will return true but 123 will return false.

If you add the * quantifier,

^[0-9]*$

the expression will match arbitrary length strings of digits and 123 will return true. (123f will still return false).

Be aware that technically an empty string is a 0-length string of digits, and so it will return true using ^[0-9]*$ If you want to only accept strings containing 1 or more digits, use + instead of *

^[0-9]+$

As the many others have pointed out, there are more than a few ways to achieve this, but I felt like it was appropriate to point out that the code in the original question only requires a single additional character to work as intended.

How can I disable ARC for a single file in a project?

Please Just follow the screenshot and enter -fno-objc-arc .

enter image description here

Performance of Java matrix math libraries?

You may want to check out the jblas project. It's a relatively new Java library that uses BLAS, LAPACK and ATLAS for high-performance matrix operations.

The developer has posted some benchmarks in which jblas comes off favourably against MTJ and Colt.

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

I faced the same issue. Tried adding the US_export_policy.jar and local_policy.jar in the java security folder first but the issue persisted. Then added the below in java_opts inside tomcat setenv.shfile and it worked.

-Djdk.tls.ephemeralDHKeySize=2048

Please check this link for further info

Class constructor type in typescript?

Solution from typescript interfaces reference:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {
    new (): Animal;
}

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'

    constructor(AnimalClass: AnimalConstructor) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

How do I edit an incorrect commit message in git ( that I've pushed )?

(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)

How to change commits deeper in history

Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.

You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.

Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .

Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...

I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.

Converting String to Cstring in C++

vector<char> toVector( const std::string& s ) {
  string s = "apple";  
  vector<char> v(s.size()+1);
  memcpy( &v.front(), s.c_str(), s.size() + 1 );
  return v;
}
vector<char> v = toVector(std::string("apple"));

// what you were looking for (mutable)
char* c = v.data();

.c_str() works for immutable. The vector will manage the memory for you.

PHP "php://input" vs $_POST

So I wrote a function that would get the POST data from the php://input stream.

So the challenge here was switching to PUT, DELETE OR PATCH request method, and still obtain the post data that was sent with that request.

I'm sharing this maybe for someone with a similar challenge. The function below is what I came up with and it works. I hope it helps!

    /**
     * @method Post getPostData
     * @return array
     * 
     * Convert Content-Disposition to a post data
     */
    function getPostData() : array
    {
        // @var string $input
        $input = file_get_contents('php://input');

        // continue if $_POST is empty
        if (strlen($input) > 0 && count($_POST) == 0 || count($_POST) > 0) :

            $postsize = "---".sha1(strlen($input))."---";

            preg_match_all('/([-]{2,})([^\s]+)[\n|\s]{0,}/', $input, $match);

            // update input
            if (count($match) > 0) $input = preg_replace('/([-]{2,})([^\s]+)[\n|\s]{0,}/', '', $input);

            // extract the content-disposition
            preg_match_all("/(Content-Disposition: form-data; name=)+(.*)/m", $input, $matches);

            // let's get the keys
            if (count($matches) > 0 && count($matches[0]) > 0)
            {
                $keys = $matches[2];

                foreach ($keys as $index => $key) :
                    $key = trim($key);
                    $key = preg_replace('/^["]/','',$key);
                    $key = preg_replace('/["]$/','',$key);
                    $key = preg_replace('/[\s]/','',$key);
                    $keys[$index] = $key;
                endforeach;

                $input = preg_replace("/(Content-Disposition: form-data; name=)+(.*)/m", $postsize, $input);

                $input = preg_replace("/(Content-Length: )+([^\n]+)/im", '', $input);

                // now let's get key value
                $inputArr = explode($postsize, $input);

                // @var array $values
                $values = [];

                foreach ($inputArr as $index => $val) :
                    $val = preg_replace('/[\n]/','',$val);

                    if (preg_match('/[\S]/', $val)) $values[$index] = trim($val);

                endforeach;

                // now combine the key to the values
                $post = [];

                // @var array $value
                $value = [];

                // update value
                foreach ($values as $i => $val) $value[] = $val;

                // push to post
                foreach ($keys as $x => $key) $post[$key] = isset($value[$x]) ? $value[$x] : '';

                if (is_array($post)) :

                    $newPost = [];

                    foreach ($post as $key => $val) :

                        if (preg_match('/[\[]/', $key)) :

                            $k = substr($key, 0, strpos($key, '['));
                            $child = substr($key, strpos($key, '['));
                            $child = preg_replace('/[\[|\]]/','', $child);
                            $newPost[$k][$child] = $val;

                        else:

                            $newPost[$key] = $val;

                        endif;

                    endforeach;

                    $_POST = count($newPost) > 0 ? $newPost : $post;

                endif;
            }

        endif;

        // return post array
        return $_POST;
    }

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

Why should I use a pointer rather than the object itself?

"Necessity is the mother of invention." The most of important difference that I would like to point out is the outcome of my own experience of coding. Sometimes you need to pass objects to functions. In that case, if your object is of a very big class then passing it as an object will copy its state (which you might not want ..AND CAN BE BIG OVERHEAD) thus resulting in an overhead of copying object .while pointer is fixed 4-byte size (assuming 32 bit). Other reasons are already mentioned above...

jQuery Force set src attribute for iframe

Use attr

$('#abc_frame').attr('src', url)

This way you can get and set every HTML tag attribute. Note that there is also .prop(). See .prop() vs .attr() about the differences. Short version: .attr() is used for attributes as they are written in HTML source code and .prop() is for all that JavaScript attached to the DOM element.

Chrome: console.log, console.debug are not working

In my case it was just an old cached Javascript file. After clearing the cache I saw my logs.

How to convert a string to utf-8 in Python

Translate with ord() and unichar(). Every unicode char have a number asociated, something like an index. So Python have a few methods to translate between a char and his number. Downside is a ñ example. Hope it can help.

>>> C = 'ñ'
>>> U = C.decode('utf8')
>>> U
u'\xf1'
>>> ord(U)
241
>>> unichr(241)
u'\xf1'
>>> print unichr(241).encode('utf8')
ñ

How do I sort a list of dictionaries by a value of the dictionary?

import operator

To sort the list of dictionaries by key='name':

list_of_dicts.sort(key=operator.itemgetter('name'))

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age'))

How do I inject a controller into another controller in AngularJS

There is no need to import/Inject your controller in JS. You can just inject your controller/nested controller through your HTML.It's worked for me. Like :

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

Show div when radio button selected

var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});

JSFIDDLE

How do I set up access control in SVN?

@Stephen Bailey

To complete your answer, you can also delegate the user rights to the project manager, through a plain text file in your repository.

To do that, you set up your SVN database with a default authz file containing the following:

###########################################################################
# The content of this file always precedes the content of the
# $REPOS/admin/acl_descriptions.txt file.
# It describes the immutable permissions on main folders.
###########################################################################
[groups]
svnadmins = xxx,yyy,....

[/]
@svnadmins = rw
* = r
[/admin]
@svnadmins = rw
@projadmins = r
* =

[/admin/acl_descriptions.txt]
@projadmins = rw

This default authz file authorizes the SVN administrators to modify a visible plain text file within your SVN repository, called '/admin/acl_descriptions.txt', in which the SVN administrators or project managers will modify and register the users.

Then you set up a pre-commit hook which will detect if the revision is composed of that file (and only that file).

If it is, this hook's script will validate the content of your plain text file and check if each line is compliant with the SVN syntax.

Then a post-commit hook will update the \conf\authz file with the concatenation of:

  • the TEMPLATE authz file presented above
  • the plain text file /admin/acl_descriptions.txt

The first iteration is done by the SVN administrator, who adds:

[groups]
projadmins = zzzz

He commits his modification, and that updates the authz file.

Then the project manager 'zzzz' can add, remove or declare any group of users and any users he wants. He commits the file and the authz file is updated.

That way, the SVN administrator does not have to individually manage any and all users for all SVN repositories.

Spark - Error "A master URL must be set in your configuration" when submitting an app

just add .setMaster("local") to your code as shown below:

val conf = new SparkConf().setAppName("Second").setMaster("local") 

It worked for me ! Happy coding !

Sequel Pro Alternative for Windows

I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.

You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.

How to get value of selected radio button?

This works in IE9 and above and all other browsers.

document.querySelector('input[name="rate"]:checked').value;

Autoplay audio files on an iPad with HTML5

This seems to work:

<html>
<title>
iPad Sound Test  - Auto Play
</title>
</head>
<body>
<audio id="audio" src="mp3test.mp3" controls="controls" loop="loop">
</audio>
<script type="text/javascript"> 
    window.onload = function() {
        var audioPlayer = document.getElementById("audio");
        audioPlayer.load();
        audioPlayer.play();
    };
    </script> 

</body>
</html>

See it in action here: http://www.johncoles.co.uk/ipad/test/1.html (Archived)

As of iOS 4.2 this no-longer works. Sorry.

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

What does the arrow operator, '->', do in Java?

I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.

Appending to an existing string

you can also use the following:

s.concat("world")

Getting Chrome to accept self-signed localhost certificate

If you're on a mac and not seeing the export tab or how to get the certificate this worked for me:

  1. Click the lock before the https://
  2. Go to the "Connection" tab
  3. Click "Certificate Information"

    Now you should see this: Different information of course and yours should be marked as trusted yet (otherwise      you probably wouldn't be here)

  4. Drag that little certificate icon do your desktop (or anywhere).

  5. Double click the .cer file that was downloaded, this should import it into your keychain and open Keychain Access to your list of certificates.

    In some cases, this is enough and you can now refresh the page.

    Otherwise:

  6. Double click the newly added certificate.
  7. Under the trust drop down change the "When using this certificate" option to "Always Trust"

Now reload the page in question and it should be problem solved! Hope this helps.


Edit from Wolph

To make this a little easier you can use the following script (source):

  1. Save the following script as whitelist_ssl_certificate.ssh:

    #!/usr/bin/env bash -e
    
    SERVERNAME=$(echo "$1" | sed -E -e 's/https?:\/\///' -e 's/\/.*//')
    echo "$SERVERNAME"
    
    if [[ "$SERVERNAME" =~ .*\..* ]]; then
        echo "Adding certificate for $SERVERNAME"
        echo -n | openssl s_client -connect $SERVERNAME:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee /tmp/$SERVERNAME.cert
        sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" /tmp/$SERVERNAME.cert
    else
        echo "Usage: $0 www.site.name"
        echo "http:// and such will be stripped automatically"
    fi
    
  2. Make the script executable (from the shell):

    chmod +x whitelist_ssl_certificate.ssh
    
  3. Run the script for the domain you want (simply copy/pasting the full url works):

    ./whitelist_ssl_certificate.ssh https://your_website/whatever
    

How do I debug Windows services in Visual Studio?

In the OnStart method, do the following.

protected override void OnStart(string[] args)
{
    try
    {
        RequestAdditionalTime(600000);
        System.Diagnostics.Debugger.Launch(); // Put breakpoint here.

        .... Your code
    }
    catch (Exception ex)
    {
        .... Your exception code
    }
}

Then run a command prompt as administrator and put in the following:

c:\> sc create test-xyzService binPath= <ProjectPath>\bin\debug\service.exe type= own start= demand

The above line will create test-xyzService in the service list.

To start the service, this will prompt you to attach to debut in Visual Studio or not.

c:\> sc start text-xyzService

To stop the service:

c:\> sc stop test-xyzService

To delete or uninstall:

c:\> sc delete text-xyzService

How to loop over a Class attributes in Java?

Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.

MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
    String propertyName = propertyDesc.getName();
    Object value = propertyDesc.getReadMethod().invoke(bean);
}

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Execute a large SQL script (with GO commands)

I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.

String pattern = "\\bGO\\b|\\bgo\\b";

String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
  getJdbcTemplate().update(chunk);
}

This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use the directions API.

Make an ajax call i.e.

https://maps.googleapis.com/maps/api/directions/json?parameters

and then parse the responce

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}

//navigation 
link.this.router.navigateByUrl('/home');

How to make a JTable non-editable

You can use a TableModel.

Define a class like this:

public class MyModel extends AbstractTableModel{
    //not necessary
}

actually isCellEditable() is false by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)

Then use the setModel() method of your JTable.

JTable myTable = new JTable();
myTable.setModel(new MyModel());

Multi-threading in VBA

I was looking for something similar and the official answer is no. However, I was able to find an interesting concept by Daniel at ExcelHero.com.

Basically, you need to create worker vbscripts to execute the various things you want and have it report back to excel. For what I am doing, retrieving HTML data from various website, it works great!

Take a look:

http://www.excelhero.com/blog/2010/05/multi-threaded-vba.html

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

Detecting value change of input[type=text] in jQuery

DON'T FORGET THE cut or select EVENTS!

The accepted answer is almost perfect, but it forgets about the cut and select events.

cut is fired when the user cuts text (CTRL + X or via right click)

select is fired when the user selects a browser-suggested option

You should add them too, as such:

$("#myTextBox").on("change paste keyup cut select", function() {
   //Do your function 
});

Java ArrayList copy

Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:

ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);

This is actual copying of values and not just copying of reference.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Just run it without options.

P:\>cl.exe
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How to determine if a number is positive or negative?

This will only works for everything except [0..2]

boolean isPositive = (n % (n - 1)) * n == n;

You can make a better solution like this (works except for [0..1])

boolean isPositive = ((n % (n - 0.5)) * n) / 0.5 == n;

You can get better precision by changing the 0.5 part with something like 2^m (m integer):

boolean isPositive = ((n % (n - 0.03125)) * n) / 0.03125 == n;

Drop rows with all zeros in pandas data frame

Replace the zeros with nan and then drop the rows with all entries as nan. After that replace nan with zeros.

import numpy as np
df = df.replace(0, np.nan)
df = df.dropna(how='all', axis=0)
df = df.replace(np.nan, 0)

Which sort algorithm works best on mostly sorted data?

Based on the highly scientific method of watching animated gifs I would say Insertion and Bubble sorts are good candidates.

Project vs Repository in GitHub

GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:

Project

A Repository as documented on GitHub:

A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.

A Project as documented on GitHub:

Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.

Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.

QUERY syntax using cell reference

I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:

=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)

if variable contains

if (code.indexOf("ST1")>=0) { location = "stoke central"; }

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

For everyone coming here for having similar question, the following works great and I have it in my library the last years:

(function(g3, $, window, document, undefined){
   g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's 
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
   if(obj === null)
      return 'null';
   else if(typeof obj === 'undefined')
      return 'undefined';
   return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Android Studio cannot find the svn command because it's not on PATH, and it doesn't know where svn is installed.

One way to fix is to edit the PATH environment variable: add the directory that contains svn.exe. You will need to restart Android Studio to make it re-read the PATH variable.

Another way is to set the absolute path of svn.exe in the Use command client box in the settings screen that you included in your post.

UPDATE

According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe to PATH, and Android Studio will correctly pick it up.

Find Number of CPUs and Cores per CPU using Command Prompt

In order to check the absence of physical sockets run:

wmic cpu get SocketDesignation

Is there a way to get the git root directory in one command?

Short solutions that work with submodules, in hooks, and inside the .git directory

Here's the short answer that most will want:

r=$(git rev-parse --git-dir) && r=$(cd "$r" && pwd)/ && echo "${r%%/.git/*}"

This will work anywhere in a git working tree (including inside the .git directory), but assumes that repository directory(s) are called .git (which is the default). With submodules, this will go to the root of the outermost containing repository.

If you want to get to the root of the current submodule use:

echo $(r=$(git rev-parse --show-toplevel) && ([[ -n $r ]] && echo "$r" || (cd $(git rev-parse --git-dir)/.. && pwd) ))

To easily execute a command in your submodule root, under [alias] in your .gitconfig, add:

sh = "!f() { root=$(pwd)/ && cd ${root%%/.git/*} && git rev-parse && exec \"$@\"; }; f"

This allows you to easily do things like git sh ag <string>

Robust solution that supports differently named or external .git or $GIT_DIR directories.

Note that $GIT_DIR may point somewhere external (and not be called .git), hence the need for further checking.

Put this in your .bashrc:

# Print the name of the git working tree's root directory
function git_root() {
  local root first_commit
  # git displays its own error if not in a repository
  root=$(git rev-parse --show-toplevel) || return
  if [[ -n $root ]]; then
    echo $root
    return
  elif [[ $(git rev-parse --is-inside-git-dir) = true ]]; then
    # We're inside the .git directory
    # Store the commit id of the first commit to compare later
    # It's possible that $GIT_DIR points somewhere not inside the repo
    first_commit=$(git rev-list --parents HEAD | tail -1) ||
      echo "$0: Can't get initial commit" 2>&1 && false && return
    root=$(git rev-parse --git-dir)/.. &&
      # subshell so we don't change the user's working directory
    ( cd "$root" &&
      if [[ $(git rev-list --parents HEAD | tail -1) = $first_commit ]]; then
        pwd
      else
        echo "$FUNCNAME: git directory is not inside its repository" 2>&1
        false
      fi
    )
  else
    echo "$FUNCNAME: Can't determine repository root" 2>&1
    false
  fi
}

# Change working directory to git repository root
function cd_git_root() {
  local root
  root=$(git_root) || return 1  # git_root will print any errors
  cd "$root"
}

Execute it by typing git_root (after restarting your shell: exec bash)

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I am surprised that there isn't more information posted about Solr. Solr is quite similar to Sphinx but has more advanced features (AFAIK as I haven't used Sphinx -- only read about it).

The answer at the link below details a few things about Sphinx which also applies to Solr. Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Solr also provides the following additional features:

  1. Supports replication
  2. Multiple cores (think of these as separate databases with their own configuration and own indexes)
  3. Boolean searches
  4. Highlighting of keywords (fairly easy to do in application code if you have regex-fu; however, why not let a specialized tool do a better job for you)
  5. Update index via XML or delimited file
  6. Communicate with the search server via HTTP (it can even return Json, Native PHP/Ruby/Python)
  7. PDF, Word document indexing
  8. Dynamic fields
  9. Facets
  10. Aggregate fields
  11. Stop words, synonyms, etc.
  12. More Like this...
  13. Index directly from the database with custom queries
  14. Auto-suggest
  15. Cache Autowarming
  16. Fast indexing (compare to MySQL full-text search indexing times) -- Lucene uses a binary inverted index format.
  17. Boosting (custom rules for increasing relevance of a particular keyword or phrase, etc.)
  18. Fielded searches (if a search user knows the field he/she wants to search, they narrow down their search by typing the field, then the value, and ONLY that field is searched rather than everything -- much better user experience)

BTW, there are tons more features; however, I've listed just the features that I have actually used in production. BTW, out of the box, MySQL supports #1, #3, and #11 (limited) on the list above. For the features you are looking for, a relational database isn't going to cut it. I'd eliminate those straight away.

Also, another benefit is that Solr (well, Lucene actually) is a document database (e.g. NoSQL) so many of the benefits of any other document database can be realized with Solr. In other words, you can use it for more than just search (i.e. Performance). Get creative with it :)

Scrollview vertical and horizontal in android

My solution based on Mahdi Hijazi answer, but without any custom views:

Layout:

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/scrollHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ScrollView 
        android:id="@+id/scrollVertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <WateverViewYouWant/>

    </ScrollView>
</HorizontalScrollView>

Code (onCreate/onCreateView):

    final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
    final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
    vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener         
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    });
    hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener         
        private float mx, my, curX, curY;
        private boolean started = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            curX = event.getX();
            curY = event.getY();
            int dx = (int) (mx - curX);
            int dy = (int) (my - curY);
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    if (started) {
                        vScroll.scrollBy(0, dy);
                        hScroll.scrollBy(dx, 0);
                    } else {
                        started = true;
                    }
                    mx = curX;
                    my = curY;
                    break;
                case MotionEvent.ACTION_UP: 
                    vScroll.scrollBy(0, dy);
                    hScroll.scrollBy(dx, 0);
                    started = false;
                    break;
            }
            return true;
        }
    });

You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.

Position buttons next to each other in the center of page

your code will look something like this ...

<!doctype html>
<html lang="en">

<head>
<style>
#button1{
width: 300px;
height: 40px;

}
#button2{
width: 300px;
height: 40px;
}
display:inline-block;
</style>

<meta charset="utf-8">
<meta name="Homepage" content="Starting page for the survey website ">

 <title> Survey HomePage</title>
</head>
<body>
<center>
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
 <button type="button home-button" id="button1" >Home</button>
 <button type="button contact-button" id="button2">Contact Us</button>
</center>
</body>
 </html>

Traverse all the Nodes of a JSON Object Tree with JavaScript

_x000D_
_x000D_
var test = {_x000D_
    depth00: {_x000D_
        depth10: 'string'_x000D_
        , depth11: 11_x000D_
        , depth12: {_x000D_
            depth20:'string'_x000D_
            , depth21:21_x000D_
        }_x000D_
        , depth13: [_x000D_
            {_x000D_
                depth22:'2201'_x000D_
                , depth23:'2301'_x000D_
            }_x000D_
            , {_x000D_
                depth22:'2202'_x000D_
                , depth23:'2302'_x000D_
            }_x000D_
        ]_x000D_
    }_x000D_
    ,depth01: {_x000D_
        depth10: 'string'_x000D_
        , depth11: 11_x000D_
        , depth12: {_x000D_
            depth20:'string'_x000D_
            , depth21:21_x000D_
        }_x000D_
        , depth13: [_x000D_
            {_x000D_
                depth22:'2201'_x000D_
                , depth23:'2301'_x000D_
            }_x000D_
            , {_x000D_
                depth22:'2202'_x000D_
                , depth23:'2302'_x000D_
            }_x000D_
        ]_x000D_
    }_x000D_
    , depth02: 'string'_x000D_
    , dpeth03: 3_x000D_
};_x000D_
_x000D_
_x000D_
function traverse(result, obj, preKey) {_x000D_
    if(!obj) return [];_x000D_
    if (typeof obj == 'object') {_x000D_
        for(var key in obj) {_x000D_
            traverse(result, obj[key], (preKey || '') + (preKey ? '[' +  key + ']' : key))_x000D_
        }_x000D_
    } else {_x000D_
        result.push({_x000D_
            key: (preKey || '')_x000D_
            , val: obj_x000D_
        });_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
document.getElementById('textarea').value = JSON.stringify(traverse([], test), null, 2);
_x000D_
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
_x000D_
_x000D_
_x000D_

How to run the sftp command with a password from Bash script?

You can use a Python script with scp and os library to make a system call.

  1. ssh-keygen -t rsa -b 2048 (local machine)
  2. ssh-copy-id user@remote_server_address
  3. create a Python script like:
    import os
    cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
    os.system(cmd)
  1. create a rule in crontab to automate your script
  2. done

jQuery input button click event listener

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Java Could not reserve enough space for object heap error

to make sure it runs the 64 bit version of java have it like this:

"c:\Program Files\Java\jre7\bin\java.exe" -Xmx1536M -Xms1536M -XX:MaxPermSize=256M -jar forge-1.6.4-9.11.1.965-universal.jar

take a look at what jre version you have installed just in case.. x64 should be in program files while x32 resides in Program Files (x86)

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

How can I parse a time string containing milliseconds in it with python?

For python 2 i did this

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"

hope that makes sense :) Example output:

13:31:21.72 Blink 01


13:31:21.81 END OF BLINK 01


13:31:26.3 Blink 01


13:31:26.39 END OF BLINK 01


13:31:34.65 Starting Lane 01


Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

How do I add multiple conditions to "ng-disabled"?

You should be able to && the conditions:

ng-disabled="condition1 && condition2"

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

Here is a solution that throws away staged changes:

git reset file/to/overwrite
git checkout file/to/overwrite

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

Embed image in a <button> element

If the image is a piece of semantic data (like a profile picture, for example), then use an <img> element inside your <button> and use CSS to resize the <img>. If the image is just a way to make a button visually pleasing, use CSS background-image to style the <button> (and don't use an <img>).

Demo: http://jsfiddle.net/ThinkingStiff/V5Xqr/

HTML:

<button id="close-image"><img src="http://thinkingstiff.com/images/matt.jpg"></button>
<button id="close-CSS"></button>

CSS:

button {
    display: inline-block;
    height: 134px;
    padding: 0;
    margin: 0;
    vertical-align: top;
    width: 104px;
}

#close-image img {
    display: block;
    height: 130px;  
    width: 100px;
}

#close-CSS {
    background-image: url( 'http://thinkingstiff.com/images/matt.jpg' );
    background-size: 100px 130px;
    height: 134px;  
    width: 104px;
}

Output:

enter image description here

IIS Config Error - This configuration section cannot be used at this path

Below is what worked for me:

  1. In IIS Click on root note "LAPTOP ____**".
  2. From option being shown in middle tray, Click on Configuration editor at bottom.
  3. In Top Drop Down select "system.webServer/handlers".
  4. At right window in Section Unlock Section.

JavaScript property access: dot notation vs. brackets?

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.

In case of Arrays

The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length because that is easier to write than array["length"].

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

ITextSharp insert text to an existing pdf

This worked for me and includes using OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    using (Stream outStream = Response.OutputStream)
    {
        Document document = new Document(size);
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

        document.Open();
        try
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(110, 110);
                cb.ShowText("aaa");
            }
            finally
            {
                cb.EndText();
            }

                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 0, 0);

        }
        finally
        {
            document.Close();
            writer.Close();
            reader.Close();
        }
    }

Bash command line and input limit

Ok, Denizens. So I have accepted the command line length limits as gospel for quite some time. So, what to do with one's assumptions? Naturally- check them.

I have a Fedora 22 machine at my disposal (meaning: Linux with bash4). I have created a directory with 500,000 inodes (files) in it each of 18 characters long. The command line length is 9,500,000 characters. Created thus:

seq 1 500000 | while read digit; do
    touch $(printf "abigfilename%06d\n" $digit);
done

And we note:

$ getconf ARG_MAX
2097152

Note however I can do this:

$ echo * > /dev/null

But this fails:

$ /bin/echo * > /dev/null
bash: /bin/echo: Argument list too long

I can run a for loop:

$ for f in *; do :; done

which is another shell builtin.

Careful reading of the documentation for ARG_MAX states, Maximum length of argument to the exec functions. This means: Without calling exec, there is no ARG_MAX limitation. So it would explain why shell builtins are not restricted by ARG_MAX.

And indeed, I can ls my directory if my argument list is 109948 files long, or about 2,089,000 characters (give or take). Once I add one more 18-character filename file, though, then I get an Argument list too long error. So ARG_MAX is working as advertised: the exec is failing with more than ARG_MAX characters on the argument list- including, it should be noted, the environment data.

How do you make div elements display inline?

An inline div is a freak of the web & should be beaten until it becomes a span (at least 9 times out of 10)...

<span>foo</span>
<span>bar</span>
<span>baz</span>

...answers the original question...

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() method etc. use the code below:

getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);

To hide softkeyboard at the time of Button is click in activity:

View view = this.getCurrentFocus();

    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

How to select only the first rows for each unique value of a column?

In SQL 2k5+, you can do something like:

;with cte as (
  select CName, AddressLine,
  rank() over (partition by CName order by AddressLine) as [r]
  from MyTable
)
select CName, AddressLine
from cte
where [r] = 1

Is there a vr (vertical rule) in html?

Too many overly-complicated answers. Just make a TableData tag that spans how many rows you want it to using rowspan. Then use the right-border for the actual bar.

Example:

<td rowspan="5" style="border-right-color: #000000; border-right-width: thin; border-right-style: solid">&nbsp;</td>
<td rowspan="5">&nbsp;</td>

Ensure that the "&nbsp" in the second line runs the same amount of lines as the first. so that there's proper spacing between both.

This technique has served me rather well with my time in HTML5.

use std::fill to populate vector with increasing numbers

There is another option - without using iota. For_each + lambda expression can be used:

vector<int> ivec(10); // the vector of size 10
int i = 0;            // incrementor
for_each(ivec.begin(), ivec.end(), [&](int& item) { ++i; item += i;});

Two important things why it's working:

  1. Lambda captures outer scope [&] which means that i will be available inside expression
  2. item passed as a reference, therefore, it is mutable inside the vector

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

jQuery: how to scroll to certain anchor/div on page load?

Just append #[id of the div you want to scroll to] to your page url. For example, if I wanted to scroll to the copyright section of this stackoverflow question, the URL would change from

http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load

to

http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright

notice the #copyright at the end of the URL.

CSS text-overflow in a table cell?

I solved this using an absolutely positioned div inside the cell (relative).

td {
    position: relative;
}
td > div {
    position: absolute;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;        
}

That's it. Then you can either add a top: value to the div or vertically center it:

td > div {      
    top: 0;
    bottom: 0;
    margin: auto 0;
    height: 1.5em; // = line height 
}

To get some space on the right side, you can reduce the max-width a little.

Remove a file from the list that will be committed

if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.

git reset HEAD <file>

Print: Entry, ":CFBundleIdentifier", Does Not Exist

If you're using Xcode 10, it may be due to an incompatibility with the latest build system of Xcode. Try switching to the legacy build system.

Open Xcode 10, File > Project Settings > Build System > switch dropdown to Legacy Build System.

Screenshot

Is there a "null coalescing" operator in JavaScript?

Note that React's create-react-app tool-chain supports the null-coalescing since version 3.3.0 (released 5.12.2019). From the release notes:

Optional Chaining and Nullish Coalescing Operators

We now support the optional chaining and nullish coalescing operators!

// Optional chaining
a?.(); // undefined if `a` is null/undefined
b?.c; // undefined if `b` is null/undefined

// Nullish coalescing
undefined ?? 'some other default'; // result: 'some other default'
null ?? 'some other default'; // result: 'some other default'
'' ?? 'some other default'; // result: ''
0 ?? 300; // result: 0
false ?? true; // result: false

This said, in case you use create-react-app 3.3.0+ you can start using the null-coalesce operator already today in your React apps.

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

`getchar()` gives the same output as the input string

There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.

If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.

As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).

main() {
    int c;
    do {
        c = getchar();
        if (c == EOF && ferror()) {
            perror("getchar");
        }
        else {
            putchar(c);
        }
    }
    while(c != EOF);
}

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

scp from Linux to Windows

Windows doesn't support SSH/SCP/SFTP natively. Are you running an SSH server application on that Windows server? If so, one of the configuration options is probably where the root is, and you would specify paths relative to that root. In any case, check the documentation for the SSH server application you are running in Windows.

Alternatively, use smbclient to push the file to a Windows share.

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.

Parse an URL in JavaScript

Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...

What's the difference between JavaScript and Java?

Everything. They're unrelated languages.

How do I check if a column is empty or null in MySQL?

You can test whether a column is null or is not null using WHERE col IS NULL or WHERE col IS NOT NULL e.g.

SELECT myCol 
FROM MyTable 
WHERE MyCol IS NULL 

In your example you have various permutations of white space. You can strip white space using TRIM and you can use COALESCE to default a NULL value (COALESCE will return the first non-null value from the values you suppy.

e.g.

SELECT myCol
FROM MyTable
WHERE TRIM(COALESCE(MyCol, '')) = '' 

This final query will return rows where MyCol is null or is any length of whitespace.

If you can avoid it, it's better not to have a function on a column in the WHERE clause as it makes it difficult to use an index. If you simply want to check if a column is null or empty, you may be better off doing this:

SELECT myCol
FROM MyTable
WHERE MyCol IS NULL OR MyCol =  '' 

See TRIM COALESCE and IS NULL for more info.

Also Working with null values from the MySQL docs

Placing border inside of div and not on its edge

Use pseudo element:

_x000D_
_x000D_
.button {_x000D_
    background: #333;_x000D_
    color: #fff;_x000D_
    float: left;_x000D_
    padding: 20px;_x000D_
    margin: 20px;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.button::after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    border: 5px solid #f00;_x000D_
}
_x000D_
<div class='button'>Hello</div>
_x000D_
_x000D_
_x000D_

Using ::after you are styling the virtual last child of the selected element. content property creates an anonymous replaced element.

We are containing the pseudo element using absolute position relative to the parent. Then you have freedom to have whatever custom background and/or border in the background of your main element.

This approach does not affect placement of the contents of the main element, which is different from using box-sizing: border-box;.

Consider this example:

_x000D_
_x000D_
.parent {_x000D_
    width: 200px;_x000D_
}_x000D_
_x000D_
.button {_x000D_
    background: #333;_x000D_
    color: #fff;_x000D_
    padding: 20px;_x000D_
    border: 5px solid #f00;_x000D_
    border-left-width: 20px;_x000D_
    box-sizing: border-box;_x000D_
}
_x000D_
<div class='parent'>_x000D_
    <div class='button'>Hello</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here .button width is constrained using the parent element. Setting the border-left-width adjusts the content-box size and thus the position of the text.

_x000D_
_x000D_
.parent {_x000D_
    width: 200px;_x000D_
}_x000D_
_x000D_
.button {_x000D_
    background: #333;_x000D_
    color: #fff;_x000D_
    padding: 20px;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.button::after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    border: 5px solid #f00;_x000D_
    border-left-width: 20px;_x000D_
}
_x000D_
<div class='parent'>_x000D_
    <div class='button'>Hello</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using the pseudo-element approach does not affect the content-box size.

Depending on the application, approach using a pseudo-element might or might not be a desirable behaviour.

How to get an MD5 checksum in PowerShell

Here is a one-line-command example with both computing the proper checksum of the file, like you just downloaded, and comparing it with the published checksum of the original.

For instance, I wrote an example for downloadings from the Apache JMeter project. In this case you have:

  1. downloaded binary file
  2. checksum of the original which is published in file.md5 as one string in the format:

3a84491f10fb7b147101cf3926c4a855 *apache-jmeter-4.0.zip

Then using this PowerShell command, you can verify the integrity of the downloaded file:

PS C:\Distr> (Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash -eq (Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash")

Output:

True

Explanation:

The first operand of -eq operator is a result of computing the checksum for the file:

(Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash

The second operand is the published checksum value. We firstly get content of the file.md5 which is one string and then we extract the hash value based on the string format:

Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash"

Both file and file.md5 must be in the same folder for this command work.

Documentation for using JavaScript code inside a PDF file

I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.

My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

Is embedding background image data into CSS as Base64 good or bad practice?

Base64 adds about 10% to the image size after GZipped but that outweighs the benefits when it comes to mobile. Since there is a overall trend with responsive web design, it is highly recommended.

W3C also recommends this approach for mobile and if you use asset pipeline in rails, this is a default feature when compressing your css

http://www.w3.org/TR/mwabp/#bp-conserve-css-images

How to get an Array with jQuery, multiple <input> with the same name

Using map:

var values = $("input[id='task']")
              .map(function(){return $(this).val();}).get();

If you change or remove the id (which should be unique), you may also use the selector $("input[name='task\\[\\]']")

Working example: http://jsbin.com/ixeze3

Duplicate and rename Xcode project & associated folders

I using Xcode 6+ and I just do:

  • Copy all files in project folders to new Folders (with new name).
  • Open *.xcodeproj or *.xcworkspace
  • Change name of Project.
  • Click on schema and delete current chema and add new one.

Here is done, but name of window Xcode and *.xcodeproj or *.xcworkspace still <old-name>. Then I do:

  • pop install
  • Open <new name>.xcworkspace

How to loop through file names returned by find?

find . -name "*.txt"|while read fname; do
  echo "$fname"
done

Note: this method and the (second) method shown by bmargulies are safe to use with white space in the file/folder names.

In order to also have the - somewhat exotic - case of newlines in the file/folder names covered, you will have to resort to the -exec predicate of find like this:

find . -name '*.txt' -exec echo "{}" \;

The {} is the placeholder for the found item and the \; is used to terminate the -exec predicate.

And for the sake of completeness let me add another variant - you gotta love the *nix ways for their versatility:

find . -name '*.txt' -print0|xargs -0 -n 1 echo

This would separate the printed items with a \0 character that isn't allowed in any of the file systems in file or folder names, to my knowledge, and therefore should cover all bases. xargs picks them up one by one then ...

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Changed to:

SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......

Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Just use two Listboxes, one for header and other for data

  1. for headers - set RowSource property to top row e.g. Incidents!Q4:S4

  2. for data - set Row Source Property to Incidents!Q5:S10

SpecialEffects to "3-frmSpecialEffectsEtched" enter image description here

Difference between $(document.body) and $('body')

There should be no difference at all maybe the first is a little more performant but i think it's trivial ( you shouldn't worry about this, really ).

With both you wrap the <body> tag in a jQuery object

How to make a gap between two DIV within the same column

I'm assuming you want the two boxes in the sidebar to be next to each other horizontally, so something like this fiddle? That uses inline-block, or you could achieve the same thing by floating the boxes.

EDIT - I've amended the above fiddle to do what I think you want, though your question could really do with being clearer. Similar to @balexandre's answer, though I've used :nth-child(odd) instead. Both will work, or if support for older browsers is important you'll have to stick with another helper class.

Alternate output format for psql

One interesting thing is we can view the tables horizontally, without folding. we can use PAGER environment variable. psql makes use of it. you can set

export PAGER='/usr/bin/less -S'

or just less -S if its already availble in command line, if not with the proper location. -S to view unfolded lines. you can pass in any custom viewer or other options with it.

I've written more in Psql Horizontal Display

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

For Tomcat 8, I had to add the following line to catalina.properties for preventing jars scanned by Tomcat:

tomcat.util.scan.StandardJarScanFilter.jarsToSkip=jsp-api.jar,servlet-api.jar

C++ convert hex string to signed integer

just use stoi/stol/stoll for example:

std::cout << std::stol("fffefffe", nullptr, 16) << std::endl;

output: 4294901758

How do I add the contents of an iterable to a set?

Use list comprehension.

Short circuiting the creation of iterable using a list for example :)

>>> x = [1, 2, 3, 4]
>>> 
>>> k = x.__iter__()
>>> k
<listiterator object at 0x100517490>
>>> l = [y for y in k]
>>> l
[1, 2, 3, 4]
>>> 
>>> z = Set([1,2])
>>> z.update(l)
>>> z
set([1, 2, 3, 4])
>>> 

[Edit: missed the set part of question]

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

How to set top position using jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

We were using:

mongoose.connect("mongodb://localhost/mean-course").then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});

? This gives a URL parser error

The correct syntax is:

mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});

Move an array element from one array position to another

I used the nice answer of @Reid, but struggled with moving an element from the end of an array one step further - to the beginning (like in a loop). E.g. ['a', 'b', 'c'] should become ['c', 'a', 'b'] by calling .move(2,3)

I achieved this by changing the case for new_index >= this.length.

Array.prototype.move = function (old_index, new_index) {
        console.log(old_index + " " + new_index);
        while (old_index < 0) {
            old_index += this.length;
        }
        while (new_index < 0) {
            new_index += this.length;
        }
        if (new_index >= this.length) {
            new_index = new_index % this.length;
        }
        this.splice(new_index, 0, this.splice(old_index, 1)[0]);
        return this; // for testing purposes
    };

Jenkins "Console Output" log location in filesystem

Easy solution would be:

curl  http://jenkinsUrl/job/<Build_Name>/<Build_Number>/consoleText -OutFile <FilePathToLocalDisk>

or for the last successful build...

curl  http://jenkinsUrl/job/<Build_Name>/lastSuccessfulBuild/consoleText -OutFile <FilePathToLocalDisk>

JavaScript + Unicode regexes

In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.

For \d use \p{N} (numbers)

For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)

Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.

What's the difference between %s and %d in Python string formatting?

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

obviously

print('%d' % (name))

will generate an exception; you cannot convert string to number

Android - Pulling SQlite database android device

If your device is running Android v4 or above, you can pull app data, including it's database, without root by using adb backup command, then extract the backup file and access the sqlite database.

First backup app data to your PC via USB cable with the following command, replace app.package.name with the actual package name of the application.

adb backup -f ~/data.ab -noapk app.package.name

This will prompt you to "unlock your device and confirm the backup operation". Do not provide a password for backup encryption, so you can extract it later. Click on the "Back up my data" button on your device. The screen will display the name of the package you're backing up, then close by itself upon successful completion.

The resulting data.ab file in your home folder contains application data in android backup format. To extract it use the following command:

dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf -

If the above ended with openssl:Error: 'zlib' is an invalid command. error, try the below.

dd if=data.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" | tar -xvf -

The result is the apps/app.package.name/ folder containing application data, including sqlite database.

For more details you can check the original blog post.

How to make sure docker's time syncs with that of the host?

This will reset the time in the docker server:

docker run --rm --privileged alpine hwclock -s

Next time you create a container the clock should be correct.

Source: https://github.com/docker/for-mac/issues/2076#issuecomment-353749995

Bootstrap 3 select input form inline

I know this is a bit old, but I had the same problem and my search brought me here. I wanted two select elements and a button all inline, which worked in 2 but not 3. I ended up wrapping the three elements in <form class="form-inline">...</form>. This actually worked perfectly for me.

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

How to make a page redirect using JavaScript?

Use:

document.location.href = "http://yoursite.com" + document.getElementById('somefield');

That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.

Sending HTML Code Through JSON

In PHP:

$data = "<html>....";
exit(json_encode($data));

Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/

Google Maps API v3: How to remove all markers?

You mean remove as in hiding them or deleting them?

if hiding:

function clearMarkers() {
            setAllMap(null);
        }

if you wish to delete them:

 function deleteMarkers() {
            clearMarkers();
            markers = [];
        }

notice that I use an array markers to keep track of them and reset it manually.

How to wait for a number of threads to complete?

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DoSomethingInAThread implements Runnable
{
   public static void main(String[] args) throws ExecutionException, InterruptedException
   {
      //limit the number of actual threads
      int poolSize = 10;
      ExecutorService service = Executors.newFixedThreadPool(poolSize);
      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();

      for (int n = 0; n < 1000; n++)
      {
         Future f = service.submit(new DoSomethingInAThread());
         futures.add(f);
      }

      // wait for all tasks to complete before continuing
      for (Future<Runnable> f : futures)
      {
         f.get();
      }

      //shut down the executor service so that this thread can exit
      service.shutdownNow();
   }

   public void run()
   {
      // do something here
   }
}

Opening port 80 EC2 Amazon web services

For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.

See here on how to completely disable it (for testing purposes only!). And here for specific rules

Python way to clone a git repository

My solution is very simple and straight forward. It doesn't even need the manual entry of passphrase/password.

Here is my complete code:

import sys
import os

path  = "/path/to/store/your/cloned/project" 
clone = "git clone gitolite@<server_ip>:/your/project/name.git" 

os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning

How to detect if user select cancel InputBox VBA Excel

The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.

For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:

Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then  'I also tried with sRange.address and vbNullString
    MsgBox ("Cancel pressed!")
    Exit Sub
End If
    MsgBox ("Your custom range is " & sRange.Address)
End Sub

The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:

Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
    MsgBox ("Cancel pressed")
End Sub

So, the question is how to detect either an error or StrPtr()=0 with an If statement?

Sieve of Eratosthenes - Finding Primes Python

I realise this isn't really answering the question of how to generate primes quickly, but perhaps some will find this alternative interesting: because python provides lazy evaluation via generators, eratosthenes' sieve can be implemented exactly as stated:

def intsfrom(n):
    while True:
        yield n
        n += 1

def sieve(ilist):
    p = next(ilist)
    yield p
    for q in sieve(n for n in ilist if n%p != 0):
        yield q


try:
    for p in sieve(intsfrom(2)):
        print p,

    print ''
except RuntimeError as e:
    print e

The try block is there because the algorithm runs until it blows the stack and without the try block the backtrace is displayed pushing the actual output you want to see off screen.

Append date to filename in linux

I use this script in bash:

#!/bin/bash

now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"

cp -v $FILE $name-$now.$ext

This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!

Call javascript from MVC controller action

The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).

Adding a column to an existing table in a Rails migration

You can also add column to a specific position using before column or after column like:

rails generate migration add_dob_to_customer dob:date

The migration file will generate the following code except after: :email. you need to add after: :email or before: :email

class AddDobToCustomer < ActiveRecord::Migration[5.2]
  def change
    add_column :customers, :dob, :date, after: :email
  end
end

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

I think this could be useful for you.

_x000D_
_x000D_
const myObject = {_x000D_
   "a":"a",_x000D_
   "b":{_x000D_
      "c":"c",_x000D_
      "d":{_x000D_
         "e":"e",_x000D_
         "f":{_x000D_
            "g":"g",_x000D_
            "h":{_x000D_
               "i":"i"_x000D_
            }_x000D_
         }_x000D_
      }_x000D_
   }_x000D_
};_x000D_
_x000D_
console.log(JSON.stringify(myObject, null, '\t'));
_x000D_
_x000D_
_x000D_

As mentioned in this answer:

JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces).

day of the week to day number (Monday = 1, Tuesday = 2)

$tm = localtime($timestamp, TRUE);
$dow = $tm['tm_wday'];

Where $dow is the day of (the) week. Be aware of the herectic approach of localtime, though (pun): Sunday is not the last day of the week, but the first (0).

WPF TemplateBinding vs RelativeSource TemplatedParent

TemplateBinding - More limiting than using regular Binding

  • More efficient than a Binding but it has less functionality
  • Only works inside a ControlTemplate's visual tree
  • Doesn't work with properties on Freezables
  • Doesn't work within a ControlTemplate's Trigger
  • Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}

Regular Binding - Does not have above limitations of TemplateBinding

  • Respects Parent Properties
  • Resets Target Values to clear out any explicitly set values
  • Example: <Ellipse Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"/>

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

Cannot find mysql.sock

To refresh the locate's database I ran

/usr/libexec/locate.updatedb

HTTP Request in Swift with POST method

All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

func postRequest() {
    // Create url object
    guard let url = URL(string: yourURL) else {return}

    // Create the session object
    let session = URLSession.shared

    // Create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // Set the request method. Important Do not set any other headers, like Content-Type
    request.httpMethod = "POST" //set http method as POST

    // Set parameters here. Replace with your own.
    let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
    request.httpBody = postData

    // Create a task using the session object, to run and return completion handler
    let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
    guard error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    guard let serverData = data else {
        print("server data error")
        return
    }
    do {
        if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
            print("Response: \(requestJson)")
        }
    } catch let responseError {
        print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
        let message = String(bytes: serverData, encoding: .ascii)
        print(message as Any)
    }

    // Run the task
    webTask.resume()
}

Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

Prevent double submission of forms in jQuery

Nathan's code but for jQuery Validate plugin

If you happen to use jQuery Validate plugin, they already have submit handler implemented, and in that case there is no reason to implement more than one. The code:

jQuery.validator.setDefaults({
  submitHandler: function(form){
    // Prevent double submit
    if($(form).data('submitted')===true){
      // Previously submitted - don't submit again
      return false;
    } else {
      // Mark form as 'submitted' so that the next submit can be ignored
      $(form).data('submitted', true);
      return true;
    }
  }
});

You can easily expand it within the } else {-block to disable inputs and/or submit button.

Cheers

$(this).serialize() -- How to add a value?

firstly shouldn't

data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

be

data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

and secondly you can use

url: this.action + '?NonFormValue=' + NonFormValue,

or if the action already contains any parameters

url: this.action + '&NonFormValue=' + NonFormValue,

Connecting to Postgresql in a docker container from outside

To connect from the localhost you need to add '--net host':

docker run --name some-postgres --net host -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

You can access the server directly without using exec from your localhost, by using:

psql -h localhost -p 5432 -U postgres

Search text in stored procedure in SQL Server

You can also use

CREATE PROCEDURE [Search](
    @Filter nvarchar(max)
)
AS
BEGIN

SELECT name
FROM   procedures
WHERE   definition LIKE '%'+@Filter+'%'

END

and then run

exec [Search] 'text'

How to set the height of table header in UITableView?

Just create Footer Wrapper View using constructor UIView(frame:_) then if you are using xib file for FooterView, create view from xib and add as subView to wrapper view. then assign wrapper to tableView.tableFooterView = fixWrapper .

    let fixWrapper = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 54)) // dont remove
    let footer = UIView.viewFromNib("YourViewXibFileName") as! YourViewClassName
    fixWrapper.addSubview(footer)
    tableView.tableFooterView = fixWrapper
    tableFootterCostView = footer

It works perfectly for me! the point is to create footer view with constructor (frame:_). Even though you create UIView() and assign frame property it may not work.

Stock ticker symbol lookup API

You can use yahoo's symbol lookup like so:

http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=yahoo&callback=YAHOO.Finance.SymbolSuggest.ssCallback

Where query is the company name.

You'll get something like this in return:

YAHOO.Finance.SymbolSuggest.ssCallback(
{
    "ResultSet": {
        "Query": "ya",
        "Result": [
            {
                "symbol": "YHOO",
                "name": "Yahoo! Inc.",
                "exch": "NMS",
                "type": "S",
                "exchDisp": "NASDAQ"
            },
            {
                "symbol": "AUY",
                "name": "Yamana Gold, Inc.",
                "exch": "NYQ",
                "type": "S",
                "exchDisp": "NYSE"
            },
            {
                "symbol": "YZC",
                "name": "Yanzhou Coal Mining Co. Ltd.",
                "exch": "NYQ",
                "type": "S",
                "exchDisp": "NYSE"
            },
            {
                "symbol": "YRI.TO",
                "name": "YAMANA GOLD INC COM NPV",
                "exch": "TOR",
                "type": "S",
                "exchDisp": "Toronto"
            },
            {
                "symbol": "8046.TW",
                "name": "NAN YA PRINTED CIR TWD10",
                "exch": "TAI",
                "type": "S",
                "exchDisp": "Taiwan"
            },
            {
                "symbol": "600319.SS",
                "name": "WEIFANG YAXING CHE 'A'CNY1",
                "exch": "SHH",
                "type": "S",
                "exchDisp": "Shanghai"
            },
            {
                "symbol": "1991.HK",
                "name": "TA YANG GROUP",
                "exch": "HKG",
                "type": "S",
                "exchDisp": "Hong Kong"
            },
            {
                "symbol": "1303.TW",
                "name": "NAN YA PLASTIC TWD10",
                "exch": "TAI",
                "type": "S",
                "exchDisp": "Taiwan"
            },
            {
                "symbol": "0294.HK",
                "name": "YANGTZEKIANG",
                "exch": "HKG",
                "type": "S",
                "exchDisp": "Hong Kong"
            },
            {
                "symbol": "YAVY",
                "name": "Yadkin Valley Financial Corp.",
                "exch": "NMS",
                "type": "S",
                "exchDisp": "NASDAQ"
            }
        ]
    }
}
)

Which is JSON and very easy to work with.

Hush... don't tell anybody.