Programs & Examples On #Jusb

This project provides a Free Software (and Open Source) Java API for USB, supporting applications using Java host-side software to drive USB devices.

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

How to bundle an Angular app for production

Angular CLI 1.x.x (Works with Angular 4.x.x, 5.x.x)

This supports:

  • Angular 2.x and 4.x
  • Latest Webpack 2.x
  • Angular AoT compiler
  • Routing (normal and lazy)
  • SCSS
  • Custom file bundling (assets)
  • Additional development tools (linter, unit & end-to-end test setups)

Initial Setup

ng new project-name --routing

You can add --style=scss for SASS .scss support.

You can add --ng4 for using Angular 4 instead of Angular 2.

After creating the project, the CLI will automatically run npm install for you. If you want to use Yarn instead, or just want to look at the project skeleton without install, check how to do it here.

Bundle Steps

Inside the project folder:

ng build -prod

At the current version you need to to specify --aot manually, because it can be used in development mode (although that's not practical due to slowness).

This also performs AoT compilation for even smaller bundles (no Angular compiler, instead, generated compiler output). The bundles are much smaller with AoT if you use Angular 4 as the generated code is smaller.
You can test your app with AoT in development mode (sourcemaps, no minification) and AoT by running ng build --aot.

Output

The default output dir is ./dist, although it can be changed in ./angular-cli.json.

Deployable Files

The result of build step is the following:

(Note: <content-hash> refers to hash / fingerprint of the contents of the file that's meant to be a cache busting way, this is possible since Webpack writes the script tags by itself)

  • ./dist/assets
    Files copied as-is from ./src/assets/**
  • ./dist/index.html
    From ./src/index.html, after adding webpack scripts to it
    Source template file is configurable in ./angular-cli.json
  • ./dist/inline.js
    Small webpack loader / polyfill
  • ./dist/main.<content-hash>.bundle.js
    The main .js file containing all the .js scripts generated / imported
  • ./dist/styles.<content-hash>.bundle.js
    When you use Webpack loaders for CSS, which is the CLI way, they are loaded via JS here

In older versions it also created gzipped versions for checking their size, and .map sourcemaps files, but this is no longer happening as people kept asking to remove these.

Other Files

In certain other occasions, you might find other unwanted files/folders:

  • ./out-tsc/
    From ./src/tsconfig.json's outDir
  • ./out-tsc-e2e/
    From ./e2e/tsconfig.json's outDir
  • ./dist/ngfactory/
    From AoT compiler (not configurable without forking the CLI as of beta 16)

Rounding a number to the nearest 5 or 10 or X

I cannot add comment so I will use this

in a vbs run that and have fun figuring out why the 2 give a result of 2

you can't trust round

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

milliseconds to time in javascript

try this function :-

_x000D_
_x000D_
function msToTime(ms) {_x000D_
  var d = new Date(null)_x000D_
  d.setMilliseconds(ms)_x000D_
  return d.toLocaleTimeString("en-US")_x000D_
}_x000D_
_x000D_
var ms = 4000000_x000D_
alert(msToTime(ms))
_x000D_
_x000D_
_x000D_

How to convert a string to lower case in Bash?

echo "Hi All" | tr "[:upper:]" "[:lower:]"

Converting PKCS#12 certificate into PEM using OpenSSL

Try:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes

After that you have:

  • certificate in newfile.crt.pem
  • private key in newfile.key.pem

To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:

openssl pkcs12 -in path.p12 -out newfile.pem -nodes

Or, if you want to provide a password for the private key, omit -nodes and input a password:

openssl pkcs12 -in path.p12 -out newfile.pem

If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Easy way to pull latest of all git submodules

Henrik is on the right track. The 'foreach' command can execute any arbitrary shell script. Two options to pull the very latest might be,

git submodule foreach git pull origin master

and,

git submodule foreach /path/to/some/cool/script.sh

That will iterate through all initialized submodules and run the given commands.

Applying a single font to an entire website with CSS

in Bootstrap, web inspector says the Headings are set to 'inherit'

all i needed to set my page to the new font was

div, p {font-family: Algerian}

that's in .scss

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

In my case, I tried to first use port 88 instead, and even then the httpd won't start.

I used the below command, i.e. modify instead of add, as suggested by one of users, and was able to run httpd.

semanage port -a -t http_port_t -p tcp 88

Adding a new value to an existing ENUM Type

Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.

How to restart counting from 1 after erasing table in MS Access?

In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

This will work if you are trying to Grant permission to Users or roles.

Using Microsoft SQL Server Management Studio:

  1. Go to: Databases
  2. Right click on dbo.my_database
  3. Choose: Properties
  4. On the left side panel, click on: Permissions
  5. Select the User or Role and in the Name Panel
  6. Find Execute in in permissions and checkmark: Grant,With Grant, or Deny

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

Writing handler for UIAlertAction

You can do it as simple as this using swift 2:

let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
        self.pressed()
}))

func pressed()
{
    print("you pressed")
}

    **or**


let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
      print("pressed")
 }))

All the answers above are correct i am just showing another way that can be done.

Type of expression is ambiguous without more context Swift

In my case it happened with NSFetchedResultsController and the reason was that I defined the NSFetchedResultsController for a different model than I created the request for the initialization (RemotePlaylist vs. Playlist):

  var fetchedPlaylistsController:NSFetchedResultsController<RemotePlaylist>!

but initiated it with a request for another Playlist:

let request = Playlist.createFetchRequest()
fetchedPlaylistsController = NSFetchedResultsController(fetchRequest: request, ...

Disable Copy or Paste action for text box?

you can try this:

   <input type="textbox" id="confirmEmail" onselectstart="return false" onpaste="return false;" oncopy="return false" oncut="return false" ondrag="return false" ondrop="return false" autocomplete="off">

How to format a URL to get a file from Amazon S3?

Documentation here, and I'll use the Frankfurt region as an example.

There are 2 different URL styles:

But this url does not work:

The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I may be talking about another problem because I'm not getting NoSuchKey error but I suspect the error message has been made clearer over time.

Download file inside WebView

    mwebView.setDownloadListener(new DownloadListener()
   {

  @Override  


   public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimeType,
        long contentLength) {

    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));


    request.setMimeType(mimeType);


    String cookies = CookieManager.getInstance().getCookie(url);


    request.addRequestHeader("cookie", cookies);


    request.addRequestHeader("User-Agent", userAgent);


    request.setDescription("Downloading file...");


    request.setTitle(URLUtil.guessFileName(url, contentDisposition,
            mimeType));


    request.allowScanningByMediaScanner();


    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                    url, contentDisposition, mimeType));
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);
    Toast.makeText(getApplicationContext(), "Downloading File",
            Toast.LENGTH_LONG).show();
}});

Sorting list based on values from another list

I actually came here looking to sort a list by a list where the values matched.

list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

How to time Java program execution speed

For simple stuff, System.currentTimeMillis() can work.

It's actually so common that my IDE is setup so that upon entering "t0" it generates me the following line:

final long t0 = System.currentTimeMillis()

But for more complicated things, you'll probably want to use statistical time measurements, like here (scroll down a bit and look at the time measurements expressed including standard deviations etc.):

http://perf4j.codehaus.org/devguide.html

The maximum value for an int type in Go

Quick summary:

import "math/bits"
const (
    MaxUint uint = (1 << bits.UintSize) - 1
    MaxInt int = (1 << bits.UintSize) / 2 - 1
    MinInt int = (1 << bits.UintSize) / -2
)

Background:

As I presume you know, the uint type is the same size as either uint32 or uint64, depending on the platform you're on. Usually, one would use the unsized version of these only when there is no risk of coming close to the maximum value, as the version without a size specification can use the "native" type, depending on platform, which tends to be faster.

Note that it tends to be "faster" because using a non-native type sometimes requires additional math and bounds-checking to be performed by the processor, in order to emulate the larger or smaller integer. With that in mind, be aware that the performance of the processor (or compiler's optimised code) is almost always going to be better than adding your own bounds-checking code, so if there is any risk of it coming into play, it may make sense to simply use the fixed-size version, and let the optimised emulation handle any fallout from that.

With that having been said, there are still some situations where it is useful to know what you're working with.

The package "math/bits" contains the size of uint, in bits. To determine the maximum value, shift 1 by that many bits, minus 1. ie: (1 << bits.UintSize) - 1

Note that when calculating the maximum value of uint, you'll generally need to put it explicitly into a uint (or larger) variable, otherwise the compiler may fail, as it will default to attempting to assign that calculation into a signed int (where, as should be obvious, it would not fit), so:

const MaxUint uint = (1 << bits.UintSize) - 1

That's the direct answer to your question, but there are also a couple of related calculations you may be interested in.

According to the spec, uint and int are always the same size.

uint either 32 or 64 bits

int same size as uint

So we can also use this constant to determine the maximum value of int, by taking that same answer and dividing by 2 then subtracting 1. ie: (1 << bits.UintSize) / 2 - 1

And the minimum value of int, by shifting 1 by that many bits and dividing the result by -2. ie: (1 << bits.UintSize) / -2

In summary:

MaxUint: (1 << bits.UintSize) - 1

MaxInt: (1 << bits.UintSize) / 2 - 1

MinInt: (1 << bits.UintSize) / -2

full example (should be the same as below)

package main

import "fmt"
import "math"
import "math/bits"

func main() {
    var mi32 int64 = math.MinInt32
    var mi64 int64 = math.MinInt64

    var i32 uint64 = math.MaxInt32
    var ui32 uint64 = math.MaxUint32
    var i64 uint64 = math.MaxInt64
    var ui64 uint64 = math.MaxUint64
    var ui uint64 = (1 << bits.UintSize) - 1
    var i uint64 = (1 << bits.UintSize) / 2 - 1
    var mi int64 = (1 << bits.UintSize) / -2

    fmt.Printf(" MinInt32: %d\n", mi32)
    fmt.Printf(" MaxInt32:  %d\n", i32)
    fmt.Printf("MaxUint32:  %d\n", ui32)
    fmt.Printf(" MinInt64: %d\n", mi64)
    fmt.Printf(" MaxInt64:  %d\n", i64)
    fmt.Printf("MaxUint64:  %d\n", ui64)
    fmt.Printf("  MaxUint:  %d\n", ui)
    fmt.Printf("   MinInt: %d\n", mi)
    fmt.Printf("   MaxInt:  %d\n", i)
}

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Remove the project from the server from the Server View. Then run the project under the same server.

The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .

How to convert R Markdown to PDF?

I think you really need pandoc, which great software was designed and built just for this task :) Besides pdf, you could convert your md file to e.g. docx or odt among others.

Well, installing an up-to-date version of Pandoc might be challanging on Linux (as you would need the entire haskell-platform?to build from the sources), but really easy on Windows/Mac with only a few megabytes of download.

If you have the brewed/knitted markdown file you can just call pandoc in e.g bash or with the system function within R. A POC demo of that latter is implemented in the ?andoc.convert function of my little package (which you must be terribly bored of as I try to point your attention there at every opportunity).

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

Why am I getting ImportError: No module named pip ' right after installing pip?

Follow steps given in https://michlstechblog.info/blog/python-install-python-with-pip-on-windows-by-the-embeddable-zip-file/. Replace x with version number of Python.

  1. Open the pythonxx.__pth file, located in your python folder.
  2. Edit the contents (e.g. D:\Pythonx.x.x to the following):
 D:\Pythonx.x.x 
 D:\Pythonx.x.x\DLLs
 D:\Pythonx.x.x\lib
 D:\Pythonx.x.x\lib\plat-win 
 D:\Pythonx.x.x\lib\site-packages

How to make a Bootstrap accordion collapse when clicking the header div?

All you need to do is to to use...

  • data-toggle="collapse"
  • data-target="#ElementToExpandOnClick"

...on the element you want to click to trigger the collapse/expand effect.

The element with data-toggle="collapse" will be the element to trigger the effect. The data-target attribute indicates the element that will expand when the effect is triggered.

Optionally you can set the data-parent if you want to create an accordion effect instead of independent collapsible, e.g.:

  • data-parent="#accordion"

I would also add the following CSS to the elements with data-toggle="collapse" if they aren't <a> tags, e.g.:

.panel-heading {
    cursor: pointer;
}

Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.

CSS disable text selection

::selection,::moz-selection {color:currentColor;background:transparent}

In JavaScript can I make a "click" event fire programmatically for a file input element?

This code works for me. Is this what you are trying to do?

<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button  id="addfiles" >Add files</button>

<script language="javascript" type="text/javascript">
   $("#addfiles").click(function(){
      $("#fileinput").click();
   });
</script>

How npm start runs a server on port 8000

To start the port correctly in your desired port use:

npm start -- --port 8000

Deleting an object in java?

If you want help an object go away, set its reference to null.

String x = "sadfasdfasd";
// do stuff
x = null;

Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

Apache is downloading php files instead of displaying them

For people who have found this post from Google almost 6 years in the future (and beyond!), you may run into this problem with Apache 2 and PHP 7 while also using the UserDir module.

Another possible cause of this problem could be that you are trying to run the script in a "user directory" from the the UserDir module. Running PHP scripts in user directories is disabled by default. You will run into this problem if the script is in the public_html directory in your home folder and you are trying to access it from http://localhost/~your_username.

To fix this, open up /etc/apache2/mods-enabled/php7.2.conf. You must comment or delete the tag block at the bottom that reads

<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

Export DataBase with MySQL Workbench with INSERT statements

Go to Menu Server and Click on Data Export. There you can select the table and select the option Dump Structure and Data' from the drop-down.

Pass Array Parameter in SqlCommand

If you are using MS SQL Server 2008 and above you can use table-valued parameters like described here http://www.sommarskog.se/arrays-in-sql-2008.html.

1. Create a table type for each parameter type you will be using

The following command creates a table type for integers:

create type int32_id_list as table (id int not null primary key)

2. Implement helper methods

public static SqlCommand AddParameter<T>(this SqlCommand command, string name, IEnumerable<T> ids)
{
  var parameter = command.CreateParameter();      

  parameter.ParameterName = name;
  parameter.TypeName = typeof(T).Name.ToLowerInvariant() + "_id_list";
  parameter.SqlDbType = SqlDbType.Structured;
  parameter.Direction = ParameterDirection.Input;

  parameter.Value = CreateIdList(ids);

  command.Parameters.Add(parameter);
  return command;
}

private static DataTable CreateIdList<T>(IEnumerable<T> ids)
{
  var table = new DataTable();
  table.Columns.Add("id", typeof (T));

  foreach (var id in ids)
  {
    table.Rows.Add(id);
  }

  return table;
}

3. Use it like this

cmd.CommandText = "select * from TableA where Age in (select id from @age)"; 
cmd.AddParameter("@age", new [] {1,2,3,4,5});

Are loops really faster in reverse?

Short answer

For normal code, especially in a high level language like JavaScript, there is no performance difference in i++ and i--.

The performance criteria is the use in the for loop and the compare statement.

This applies to all high level languages and is mostly independent from the use of JavaScript. The explanation is the resulting assembler code at the bottom line.

Detailed explanation

A performance difference may occur in a loop. The background is that on the assembler code level you can see that a compare with 0 is just one statement which doesn't need an additional register.

This compare is issued on every pass of the loop and may result in a measurable performance improvement.

for(var i = array.length; i--; )

will be evaluated to a pseudo code like this:

 i=array.length
 :LOOP_START
 decrement i
 if [ i = 0 ] goto :LOOP_END
 ... BODY_CODE
 :LOOP_END

Note that 0 is a literal, or in other words, a constant value.

for(var i = 0 ; i < array.length; i++ )

will be evaluated to a pseudo code like this (normal interpreter optimisation supposed):

 end=array.length
 i=0
 :LOOP_START
 if [ i < end ] goto :LOOP_END
 increment i
 ... BODY_CODE
 :LOOP_END

Note that end is a variable which needs a CPU register. This may invoke an additional register swapping in the code and needs a more expensive compare statement in the if statement.

Just my 5 cents

For a high level language, readability, which facilitates maintainability, is more important as a minor performance improvement.

Normally the classic iteration from array start to end is better.

The quicker iteration from array end to start results in the possibly unwanted reversed sequence.

Post scriptum

As asked in a comment: The difference of --i and i-- is in the evaluation of i before or after the decrementing.

The best explanation is to try it out ;-) Here is a Bash example.

 % i=10; echo "$((--i)) --> $i"
 9 --> 9
 % i=10; echo "$((i--)) --> $i"
 10 --> 9

JSLint is suddenly reporting: Use the function form of "use strict"

I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.

How do you access the matched groups in a JavaScript regular expression?

In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:

var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);

After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):

var yourstring = 'something format_abc something format_def something format_ghi';

var matches = [];
yourstring.replace(/format_([^\s]+)/igm, function(m, p1){ matches.push(p1); } );

After this, I don't think I'm ever going to use .match() for hardly anything ever again.

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Ambiguous date formats are interpreted according to the language of the login. This works

set dateformat mdy

select CAST('03/28/2011 18:03:40' AS DATETIME)

This doesn't

set dateformat dmy

select CAST('03/28/2011 18:03:40' AS DATETIME)

If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss

Constants in Objective-C

Try using a class method:

+(NSString*)theMainTitle
{
    return @"Hello World";
}

I use it sometimes.

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

Forbidden :You don't have permission to access /phpmyadmin on this server

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace the existing <Directory> ... </Directory> node with the following:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #Require ip 127.0.0.1
       #Require ip ::1
       Require all granted
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

How can I convert String to Int?

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN

List all tables in postgresql information_schema

For listing your tables use:

SELECT table_name FROM information_schema.tables WHERE table_schema='public'

It will only list tables that you create.

How to send data in request body with a GET when using jQuery $.ajax()

In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.

You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.

If you aren't absolutely tied to GET requests with the body being the data, you have two options.

POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.

GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.

url: 'somesite.com/models/thing?ids=1,2,3'

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

How to split a comma-separated value to columns

You can use split function.

SELECT 
(select top 1 item from dbo.Split(FullName,',') where id=1 ) as Name,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) as Surname,
FROM MyTbl

Cannot connect to the Docker daemon on macOS

This problem:

$ brew install docker docker-machine
$ docker ps

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This apparently meant do the following:

$ docker-machine create default # default driver is apparently vbox:
Running pre-create checks...
Error with pre-create check: "VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path"
$  brew cask install virtualbox
…
$ docker-machine create default 
# works this time
$ docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
$ eval "$(docker-machine env default)"
$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

It finally works.

You can use the “xhyve” driver if you don’t want to install virtual box. Also you can install the “docker app” (then run it) which apparently makes it so you don’t have to run some of the above. brew cask install docker then run the app, see the other answers. But apparently isn't necessary per se.

Python: For each list element apply a function across the list

If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list...

l = [1,2,3,4,5]

def f(i,j):
   return i+j 

# Prints min value of f(i,j) along with i and j
print min( (f(i,j),i,j) for i in l for j in l)

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

How do I round to the nearest 0.5?

decimal d = // your number..

decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
    return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
    return Math.Ceil(d);
return Math.Floor(d);

Where is a log file with logs from a container?

As of 8/22/2018, the logs can be found in :

/data/docker/containers/<container id>/<container id>-json.log

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

How to use curl in a shell script?

url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi

Adding value to input field with jQuery

You have to escape [ and ]. Try this:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
    $('#' + fieldID).val("hello world");
});

Demo: http://jsfiddle.net/7RJtf/1/

R legend placement in a plot

You have to add the size of the legend box to the ylim range

#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)

#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)

#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))

enter image description here

Is there a way to get the source code from an APK file?

1. Extracting the source from a native Android application

The source code of a native Android application is not difficult to obtain, but it does require extra tools that are compatible with Windows, Mac, and Linux. My personal favorites when it comes to tools are dex2jar and JD-GUI.

If you’re unfamiliar with these tools, dex2jar will read Dalvik Executable files and convert them to the standard JAR format. JD-GUI will read JAR files and decompile the class files found in them.

To make the extraction process easier to understand, let’s start by creating a fresh native Android project:

android create project --target 19 --name TestProject --path . --activity TestProjectActivity --package com.nraboy.testproject

The above command will leave you with an Android project in your current command prompt path.

Since our project has an Activity class already included, lets jump straight into the build process. You can give me a hard time all day long about using Ant instead of Gradle or Maven, but for this tutorial I’m going to stick with it.

ant debug

The above command will create a debug build typically found at bin/TestProject-debug.apk.

Using your favorite unzip tool, extract the APK file. 7-zip is a popular tool, but if you’re on a Mac you can just run the following from the Terminal:

unzip TestProject-debug.apk

This will leave us with a bunch of files and folders, but one is important to us. Make note of classes.dex because it contains all of our source code. To convert it into something readable we need to run dex2jar on it. You can use dex2jar on Mac, Linux, and Windows, but I’m going to explain from a Mac perspective.

With the classes.dex file in your extracted dex2jar directory, run the following from the Terminal:

./dex2jar.sh classes.dex

Open the JD-GUI application that you downloaded because it is now time to decode the JAR and packaged class files. Open the freshly created classes_dex2jar.jar file and you should see something like the following:

enter image description here See how easy it was to get to the source code of your native Android APK? Now what can you do to better protect yourself?

The Android SDK ships with Proguard, which is a obfuscation module. What is obfuscation you ask?

Obfuscation via Wikipedia:

Obfuscation (or beclouding) is the hiding of intended meaning in communication, making communication confusing, willfully ambiguous, and harder to interpret.

While obfuscation will not encrypt your source code, it will make it more difficult to make sense of. With Proguard configured, run Ant in release mode and your code should be obfuscated on build.

2. Extracting the source from a hybrid Android application

The source code of hybrid applications are by far the easiest to extract. You don’t need any extra software installed on your computer, just access to the APK file.

To make things easier to understand, lets first create a fresh Apache Cordova project and then extract it. Start by doing the following:

cordova create TestProject com.example.testproject TestProject
cd TestProject
cordova platform add android

During the project creation process you are left with the default Apache Cordova CSS, HTML, and JavaScript templates. That is fine for us in this example. Let’s go ahead and build our project into a distributed APK file:

cordova build android

You’re going to be left with platforms/android/ant-build/CordovaApp-debug.apk or something along the lines of platforms/android/ant-build/*-debug.apk.

Even though this is a debug build, it is still very usable. With 7-zip or similar installed, right click the APK file and choose to extract or unzip it. In the extracted directory, you should now have access to all your web based source files. I say web based because any Java files used by Apache Cordova will have been compiled into class files. However, CSS, HTML, and JavaScript files do not get touched.

You just saw how depressingly easy it is to get hybrid application source code. So what can you do to better protect yourself?

You can uglify your code, which is a form of obfuscation.

Doing this will not encrypt your code, but it will make it that much more difficult to make sense of.

If you want to uglify your code, I recommend you install UglifyJS since it is pretty much the standard as of now. If you prefer to use a task runner, Grunt and Gulp have modules for UglifyJS as well.

Get error message if ModelState.IsValid fails?

Try

ModelState.Values.First().Errors[0].ErrorMessage

How to read existing text files without defining path

You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:

string fullPathToFile = Path.Combine(dir, fileName);

If you don't supply the base directory dir then you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.

For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.

Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.

One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.

php execute a background process

You might want to try to append this to your command

>/dev/null 2>/dev/null &

eg.

shell_exec('service named reload >/dev/null 2>/dev/null &');

Read Content from Files which are inside Zip file

As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.

In order to extract all of the files contained inside of a zip file in this API, you'd do this:

In Java 8:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories 
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

In java 7:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for(Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                    throws IOException {
                // In a full implementation, you'd need to create each 
                // sub-directory of the destination directory before 
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

This is another valid way to make a copy of a vector, just use its constructor:

std::vector<int> newvector(oldvector);

This is even simpler than using std::copy to walk the entire vector from start to finish to std::back_insert them into the new vector.

That being said, your .swap() one is not a copy, instead it swaps the two vectors. You would modify the original to not contain anything anymore! Which is not a copy.

How do I do pagination in ASP.NET MVC?

Entity

public class PageEntity
{
    public int Page { get; set; }
    public string Class { get; set; }
}

public class Pagination
{
    public List<PageEntity> Pages { get; set; }
    public int Next { get; set; }
    public int Previous { get; set; }
    public string NextClass { get; set; }
    public string PreviousClass { get; set; }
    public bool Display { get; set; }
    public string Query { get; set; }
}

HTML

<nav>
    <div class="navigation" style="text-align: center">
        <ul class="pagination">
            <li class="page-item @Model.NextClass"><a class="page-link" href="?page=@(@[email protected])">&laquo;</a></li>
            @foreach (var item in @Model.Pages)
            {
                <li class="page-item @item.Class"><a class="page-link" href="?page=@([email protected])">@item.Page</a></li>
            }
            <li class="page-item @Model.NextClass"><a class="page-link" href="?page=@(@[email protected])">&raquo;</a></li>
        </ul>
    </div>
 </nav>

Paging Logic

public Pagination GetCategoryPaging(int currentPage, int recordCount, string query)
{
    string pageClass = string.Empty; int pageSize = 10, innerCount = 5;

    Pagination pagination = new Pagination();
    pagination.Pages = new List<PageEntity>();
    pagination.Next = currentPage + 1;
    pagination.Previous = ((currentPage - 1) > 0) ? (currentPage - 1) : 1;
    pagination.Query = query;

    int totalPages = ((int)recordCount % pageSize) == 0 ? (int)recordCount / pageSize : (int)recordCount / pageSize + 1;

    int loopStart = 1, loopCount = 1;

    if ((currentPage - 2) > 0)
    {
        loopStart = (currentPage - 2);
    }

    for (int i = loopStart; i <= totalPages; i++)
    {
        pagination.Pages.Add(new PageEntity { Page = i, Class = string.Empty });

        if (loopCount == innerCount)
        { break; }

        loopCount++;
    }

    if (totalPages <= innerCount)
    {
        pagination.PreviousClass = "disabled";
    }

    foreach (var item in pagination.Pages.Where(x => x.Page == currentPage))
    {
        item.Class = "active";
    }

    if (pagination.Pages.Count() <= 1)
    {
        pagination.Display = false;
    }

    return pagination;
}

Using Controller

public ActionResult GetPages()
{
    int currentPage = 1; string search = string.Empty;
    if (!string.IsNullOrEmpty(Request.QueryString["page"]))
    {
        currentPage = Convert.ToInt32(Request.QueryString["page"]);
    }

    if (!string.IsNullOrEmpty(Request.QueryString["q"]))
    {
        search = "&q=" + Request.QueryString["q"];
    }
    /* to be Fetched from database using count */
    int recordCount = 100;

    Place place = new Place();
    Pagination pagination = place.GetCategoryPaging(currentPage, recordCount, search);

    return PartialView("Controls/_Pagination", pagination);
}

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

In Python, can I call the main() of an imported module?

Assuming you are trying to pass the command line arguments as well.

import sys
import myModule


def main():
    # this will just pass all of the system arguments as is
    myModule.main(*sys.argv)

    # all the argv but the script name
    myModule.main(*sys.argv[1:])

Capture Signature using HTML5 and iPad

Another OpenSource signature field is https://github.com/applicius/jquery.signfield/ , registered jQuery plugin using Sketch.js .

Using R to download zipped data file, extract, and import data

I found that the following worked for me. These steps come from BTD's YouTube video, Managing Zipfile's in R:

zip.url <- "url_address.zip"

dir <- getwd()

zip.file <- "file_name.zip"

zip.combine <- as.character(paste(dir, zip.file, sep = "/"))

download.file(zip.url, destfile = zip.combine)

unzip(zip.file)

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

You could try DELETE FROM <your table >;.

The server will show you the name of the restriction and the table, and deleting that table you can delete what you need.

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

How to Convert unsigned char* to std::string in C++?

BYTE *str1 = "Hello World";
std::string str2((char *)str1);  /* construct on the stack */

Alternatively:

std::string *str3 = new std::string((char *)str1); /* construct on the heap */
cout << &str3;
delete str3;

Regex pattern to match at least 1 number and 1 character in a string

The accepted answers is not worked as it is not allow to enter special characters.

Its worked perfect for me.

^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$

  • one digit must
  • one character must (lower or upper)
  • every other things optional

Thank you.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

IF NOT EXISTS(SELECT * FROM Clock
WHERE clockDate = '08/10/2012') AND userName = 'test')

Has an extra parenthesis. I think it's fine if you remove it:

IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = '08/10/2012' AND userName = 'test')

Also, GETDATE() will put the current date in the column, though if you don't want the time you'll have to play a little. I think CONVERT(varchar(8), GETDATE(), 112) would give you just the date (not time) portion.

IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = CONVERT(varchar(8), GETDATE(), 112)
AND userName = 'test')

should probably do it.

PS: use a merge statement :)

How do I resolve this "ORA-01109: database not open" error?

have you tried SQL> alter database open; ? after first login?

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

Can you have if-then-else logic in SQL?

--Similar answer as above for the most part. Code included to test

DROP TABLE table1
GO
CREATE TABLE table1 (project int, customer int, company int, product int, price money)
GO
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
GO
SELECT TOP 1 WITH TIES product
        , price
        , CASE WhereFound WHEN 1 THEN 'Project'
                WHEN 2 THEN 'Customer'
                WHEN 3 THEN 'Company'
            ELSE 'No Match'
            END AS Source
FROM 
    (
     SELECT product, price, 1 as WhereFound FROM table1 where project = 11
     UNION ALL
     SELECT product, price, 2 FROM table1 where customer = 0
     UNION ALL
     SELECT product, price, 3 FROM table1 where company = 30
    ) AS tbl
ORDER BY WhereFound ASC

Can I change the name of `nohup.out`?

As the file handlers points to i-nodes (which are stored independently from file names) on Linux/Unix systems You can rename the default nohup.out to any other filename any time after starting nohup something&. So also one could do the following:

$ nohup something&
$ mv nohup.out nohup2.out
$ nohup something2&

Now something adds lines to nohup2.out and something2 to nohup.out.

java.lang.IllegalStateException: The specified child already has a parent

I had this code in a fragment and it was crashing if I try to come back to this fragment

if (mRootView == null) {
    mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} 

after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.

if (mRootView == null) {
    mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} else {
    ((ViewGroup) mRootView.getParent()).removeView(mRootView);
}

hope this helps

Github: Can I see the number of downloads for a repo?

The Github API does not provide the needed information anymore. Take a look at the releases page, mentioned in Stan Towianski's answer. As we discussed in the comments to that answer, the Github API only reports the downloads of 1 of the three files he offers per release.

I have checked the solutions, provided in some other answers to this questions. Vonc's answer presents the essential part of Michele Milidoni's solution. I installed his gdc script with the following result

# ./gdc stant
mdcsvimporter.mxt: 37 downloads
mdcsvimporter.mxt: 80 downloads
How-to-use-mdcsvimporter-beta-16.zip: 12 downloads

As you can clearly see, gdc does not report the download count of the tar.gz and zip files.

If you want to check without installing anything, try the web page where Somsubhra has installed the solution, mentioned in his answer. Fill in 'stant' as Github username and 'mdcsvimporter2015' as Repository name and you will see things like:

Download Info:
mdcsvimporter.mxt(0.20MB) - Downloaded 37 times.
Last updated on 2015-03-26

Alas, once again only a report without the downloads of the tar.gz and zip files. I have carefully examined the information that Github's API returns, but it is not provided anywhere. The download_count that the API does return is far from complete nowadays.

Javascript Object push() function

I assume that REALLY you get object from server and want to get object on output

Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])

_x000D_
_x000D_
var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response_x000D_
_x000D_
data = { ...data,_x000D_
  0: { "ID": "1", "Status": "Valid" },_x000D_
  1: { "ID": "2", "Status": "Invalid" },_x000D_
  2: { "ID": "3", "Status": "Valid" }_x000D_
}_x000D_
_x000D_
// solution 1: where output is sorted filtred array_x000D_
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);_x000D_
  _x000D_
// solution2: where output is filtered object_x000D_
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])_x000D_
  _x000D_
// show_x000D_
console.log('Object',data);_x000D_
console.log('Array ',arr);
_x000D_
_x000D_
_x000D_

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

SQL Developer is returning only the date, not the time. How do I fix this?

Can you try this?

Go to Tools> Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

How to set background color in jquery

$(this).css('background-color', 'red');

How do I pass a class as a parameter in Java?

public void foo(Class c){
        try {
            Object ob = c.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

How to invoke method using reflection

 import java.lang.reflect.*;


   public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

Also See

Detecting touch screen devices with Javascript

var isTouchDevice = 'ontouchstart' in document.documentElement;

Note: Just because a device supports touch events doesn't necessarily mean that it is exclusively a touch screen device. Many devices (such as my Asus Zenbook) support both click and touch events, even when they doen't have any actual touch input mechanisms. When designing for touch support, always include click event support and never assume any device is exclusively one or the other.

Why are my PowerShell scripts not running?

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

The above command worked for me even when the following error happens:

Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

Sending command line arguments to npm script

jakub.g's answer is correct, however an example using grunt seems a bit complex.

So my simpler answer:

- Sending a command line argument to an npm script

Syntax for sending command line arguments to an npm script:

npm run [command] [-- <args>]

Imagine we have an npm start task in our package.json to kick off webpack dev server:

"scripts": {
  "start": "webpack-dev-server --port 5000"
},

We run this from the command line with npm start

Now if we want to pass in a port to the npm script:

"scripts": {
  "start": "webpack-dev-server --port process.env.port || 8080"
},

running this and passing the port e.g. 5000 via command line would be as follows:

npm start --port:5000

- Using package.json config:

As mentioned by jakub.g, you can alternatively set params in the config of your package.json

"config": {
  "myPort": "5000"
}

"scripts": {
  "start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},

npm start will use the port specified in your config, or alternatively you can override it

npm config set myPackage:myPort 3000

- Setting a param in your npm script

An example of reading a variable set in your npm script. In this example NODE_ENV

"scripts": {
  "start:prod": "NODE_ENV=prod node server.js",
  "start:dev": "NODE_ENV=dev node server.js"
},

read NODE_ENV in server.js either prod or dev

var env = process.env.NODE_ENV || 'prod'

if(env === 'dev'){
    var app = require("./serverDev.js");
} else {
    var app = require("./serverProd.js");
}

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

Java String to JSON conversion

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

Can I set a TTL for @Cacheable

this can be done by extending org.springframework.cache.interceptor.CacheInterceptor , and override "doPut" method - org.springframework.cache.interceptor.AbstractCacheInvoker your override logic should use the cache provider put method that knows to set TTL for cache entry (in my case I use HazelcastCacheManager)

@Autowired
@Qualifier(value = "cacheManager")
private CacheManager hazelcastCacheManager;

@Override
protected void doPut(Cache cache, Object key, Object result) {
        //super.doPut(cache, key, result); 
        HazelcastCacheManager hazelcastCacheManager = (HazelcastCacheManager) this.hazelcastCacheManager;
        HazelcastInstance hazelcastInstance = hazelcastCacheManager.getHazelcastInstance();
        IMap<Object, Object> map = hazelcastInstance.getMap("CacheName");
        //set time to leave 18000 secondes
        map.put(key, result, 18000, TimeUnit.SECONDS);



}

on your cache configuration you need to add those 2 bean methods , creating your custom interceptor instance .

@Bean
public CacheOperationSource cacheOperationSource() {
    return new AnnotationCacheOperationSource();
}


@Primary
@Bean
public CacheInterceptor cacheInterceptor() {
    CacheInterceptor interceptor = new MyCustomCacheInterceptor();
    interceptor.setCacheOperationSources(cacheOperationSource());    
    return interceptor;
}

This solution is good when you want to set the TTL on the entry level , and not globally on cache level

Javascript how to split newline

It should be

yadayada.val.split(/\n/)

you're passing in a literal string to the split command, not a regex.

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

I faced the same issue with XAMPP and phpMyAdmin and this is how I solved it easily.


1. Open the XAMPP control panel
2. Then select the Explorer Button on the right


3. Then it will be navigated to the location where the configurations are and you have to
go in side the phpMyAdmin folder
and then right click on the highlighted folder and choose edit option on any text editor



4. Then edit only the following rounded section as of your MySQL server username and password
If your MySQL server username is root and
If your MySQL server password is root, keep as of the image

Change them according to your username and password which you have given to MySQL server



5. Save the changes and open your browser and paste
http://localhost/phpmyadmin/index.php
to navigate to phpMyAdmin

Sort a two dimensional array based on one column

Assuming your array contains strings, you can use the following:

String[] data = new String[] { 
    "2009.07.25 20:24 Message A",
    "2009.07.25 20:17 Message G",
    "2009.07.25 20:25 Message B",
    "2009.07.25 20:30 Message D",
    "2009.07.25 20:01 Message F",
    "2009.07.25 21:08 Message E",
    "2009.07.25 19:54 Message R"
};

Arrays.sort(data, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String t1 = s1.substring(0, 16); // date/time of s1
        String t2 = s2.substring(0, 16); // date/time of s2
        return t1.compareTo(t2);
    }
});

If you have a two-dimensional array, the solution is also very similar:

String[][] data = new String[][] { 
        { "2009.07.25 20:17", "Message G" },
        { "2009.07.25 20:25", "Message B" },
        { "2009.07.25 20:30", "Message D" },
        { "2009.07.25 20:01", "Message F" },
        { "2009.07.25 21:08", "Message E" },
        { "2009.07.25 19:54", "Message R" }
};

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] s1, String[] s2) {
        String t1 = s1[0];
        String t2 = s2[0];
        return t1.compareTo(t2);
    }
});

What does OpenCV's cvWaitKey( ) function do?

waits milliseconds to check if the key is pressed, if pressed in that interval return its ascii value, otherwise it still -1

How to get a variable type in Typescript?

I have checked a variable if it is a boolean or not as below

console.log(isBoolean(this.myVariable));

Similarly we have

isNumber(this.myVariable);
isString(this.myvariable);

and so on.

Search and replace in bash using regular expressions

This example in the input hello ugly world it searches for the regex bad|ugly and replaces it with nice

#!/bin/bash

# THIS FUNCTION NEEDS THREE PARAMETERS
# arg1 = input              Example:  hello ugly world
# arg2 = search regex       Example:  bad|ugly
# arg3 = replace            Example:  nice
function regex_replace()
{
  # $1 = hello ugly world
  # $2 = bad|ugly
  # $3 = nice

  # REGEX
  re="(.*?)($2)(.*)"

  if [[ $1 =~ $re ]]; then
    # if there is a match
    
    # ${BASH_REMATCH[0]} = hello ugly world
    # ${BASH_REMATCH[1]} = hello 
    # ${BASH_REMATCH[2]} = ugly
    # ${BASH_REMATCH[3]} = world    

    # hello + nice + world
    echo ${BASH_REMATCH[1]}$3${BASH_REMATCH[3]}
  else    
    # if no match return original input  hello ugly world
    echo "$1"
  fi    
}

# prints 'hello nice world'
regex_replace 'hello ugly world' 'bad|ugly' 'nice'

# to save output to a variable
x=$(regex_replace 'hello ugly world' 'bad|ugly' 'nice')
echo "output of replacement is: $x"
exit

Facebook Graph API : get larger pictures in one request

The best way to get all friends (who are using the App too, of course) with correct picture sizes is to use field expansion, either with one of the size tags (square, small, normal, large):

/me/friends?fields=picture.type(large)

(edit: this does not work anymore)

...or you can specify the width/height:

me/friends?fields=picture.width(100).height(100)

Btw, you can also write it like this:

me?fields=friends{picture.type(large)}

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

Transparent scrollbar with css

It might be too late, but still. For those who have not been helped by any method I suggest making custom scrollbar bar in pure javascript.

For a start, disable the standard scrollbar in style.css

::-webkit-scrollbar{
    width: 0;
}

Now let's create the scrollbar container and the scrollbar itself

<!DOCTYPE HTML>
<html lang="ru">
<head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="main.js"></script>
 ...meta
</head>

<body>

<div class="custom_scroll">
    <div class="scroll_block"></div>
</div>

...content

<script>customScroll();</script>
</body>
</html>

at the same time, we will connect the customScroll() function, and create it in the file main.js

 function customScroll() {
    let scrollBlock = documentSite.querySelector(".scroll_block");
    let body = documentSite.querySelector("body");
    let screenSize = screenHeight - scrollBlock.offsetHeight;
    documentSite.addEventListener("scroll", () => {
        scrollBlock.style.top = (window.pageYOffset / body.offsetHeight * (screenSize + (screenSize * (body.offsetHeight - (body.offsetHeight - screenHeight)) / (body.offsetHeight - screenHeight)) )) + "px";
    });
    setScroll(scrollBlock, body);
}

function setScroll(scrollBlock, body) {
    let newPos = 0, lastPos = 0;
        scrollBlock.onmousedown = onScrollSet;
        scrollBlock.onselectstart = () => {return false;};

    function onScrollSet(e) {
        e = e || window.event;
        lastPos = e.clientY;
        document.onmouseup = stopScroll;
        document.onmousemove = moveScroll;
        return false;
    }

    function moveScroll(e) {
        e = e || window.event;
        newPos = lastPos - e.clientY;
        lastPos = e.clientY;
        if(scrollBlock.offsetTop - newPos >= 0 && scrollBlock.offsetTop - newPos <= Math.ceil(screenHeight - scrollBlock.offsetHeight)) {
            window.scrollBy(0, -newPos / screenHeight *  body.offsetHeight);
        }
    }

    function stopScroll() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

adding styles for the scrollbar

.custom_scroll{
    width: 0.5vw;
    height: 100%;
    position: fixed;
    right: 0;
    z-index: 100;
}

.scroll_block{
    width: 0.5vw;
    height: 20vh;
    background-color: #ffffff;
    z-index: 101;
    position: absolute;
    border-radius: 4px;
}

Done!

scrollbar

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

the file path you ran is wrong. So if you are working on windows, go to the correct file location with cd and rerun from there.

MVC DateTime binding with incorrect date format

I set the below config on my MVC4 and it works like a charm

<globalization uiCulture="auto" culture="auto" />

How to set upload_max_filesize in .htaccess?

php_value upload_max_filesize 30M is correct.

You will have to contact your hosters -- some don't allow you to change values in php.ini

An attempt was made to access a socket in a way forbidden by its access permissions

Just Restart-Service hns can change the port occupier by Hyper-V. It might release the port you need.

Comparing two strings in C?

You try and compare pointers here, not the contents of what is pointed to (ie, your characters).

You must use either memcmp or str{,n}cmp to compare the contents.

In a Git repository, how to properly rename a directory?

Basic rename (or move):

git mv <old name> <new name>

Case sensitive rename—eg. from casesensitive to CaseSensitive—you must use a two step:

git mv casesensitive tmp
git mv tmp CaseSensitive

(More about case sensitivity in Git…)

…followed by commit and push would be the simplest way to rename a directory in a git repo.

ComboBox: Adding Text and Value to an Item (no Binding Source)

You can use this code to insert some items into a combo box with text and value.

C#

private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    combox.Items.Insert(0, "Copenhagen");
    combox.Items.Insert(1, "Tokyo");
    combox.Items.Insert(2, "Japan");
    combox.Items.Insert(0, "India");   
}

XAML

<ComboBox x:Name="combox" SelectionChanged="ComboBox_SelectionChanged_1"/>

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

CSS Font Border?

UPDATE

Here's a SCSS mixin to generate the stroke: http://codepen.io/pixelass/pen/gbGZYL

/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {List}            - text-shadow list
@function stroke($stroke, $color) {
  $shadow: ();
  $from: $stroke*-1;
  @for $i from $from through $stroke {
   @for $j from $from through $stroke {
      $shadow: append($shadow, $i*1px $j*1px 0 $color, comma);
    }
  }
  @return $shadow;
}
/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {Style}           - text-shadow
@mixin stroke($stroke, $color) {
  text-shadow: stroke($stroke, $color);
}

enter image description here

YES old question.. with accepted (and good) answers..

BUT...In case anybody ever needs this and hates typing code...

THIS is a 2px black border with CrossBrowser support (not IE) I needed this for @fontface fonts so it needed to be cleaner than previous seen answers... I takes every side pixelwise to make sure there are (almost) no gaps for "fuzzy" (handrawn or similar) fonts. Subpixels (0.5px) could be added but I don't need it.

Long code for just the border??? ...YES!!!

text-shadow: 1px 1px 0 #000,
    -1px 1px 0 #000,
    1px -1px 0 #000,
    -1px -1px 0 #000,
    0px 1px 0 #000,
    0px -1px 0 #000,
    -1px 0px 0 #000,
    1px 0px 0 #000,
    2px 2px 0 #000,
    -2px 2px 0 #000,
    2px -2px 0 #000,
    -2px -2px 0 #000,
    0px 2px 0 #000,
    0px -2px 0 #000,
    -2px 0px 0 #000,
    2px 0px 0 #000,
    1px 2px 0 #000,
    -1px 2px 0 #000,
    1px -2px 0 #000,
    -1px -2px 0 #000,
    2px 1px 0 #000,
    -2px 1px 0 #000,
    2px -1px 0 #000,
    -2px -1px 0 #000;

How to create an empty array in Swift?

Swift 5

// Create an empty array
var emptyArray = [String]()

// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")

// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)

// Remove elements from an array by index number
emptyArray.remove(at: 2)

// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
    emptyArray.remove(at: removeElement)
}

A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)

How do I set the proxy to be used by the JVM

I think configuring WINHTTP will also work.

Many programs including Windows Updates are having problems behind proxy. By setting up WINHTTP will always fix this kind of problems

Convert javascript array to string

we can use the function join() to make the string from the array, and as parameter of function join we giv it '' empty character.

var newStr =mArray.join('');

ipynb import another ipynb file

There is no problem at all using Jupyter with existing or new Python .py modules. With Jupyter running, simply fire up Spyder (or any editor of your choice) to build / modify your module class definitions in a .py file, and then just import the modules as needed into Jupyter.

One thing that makes this really seamless is using the autoreload magic extension. You can see documentation for autoreload here:

http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html

Here is the code to automatically reload the module any time it has been modified:

# autoreload sets up auto reloading of modified .py modules
import autoreload
%load_ext autoreload
%autoreload 2

Note that I tried the code mentioned in a prior reply to simulate loading .ipynb files as modules, and got it to work, but it chokes when you make changes to the .ipynb file. It looks like you need to restart the Jupyter development environment in order to reload the .ipynb 'module', which was not acceptable to me since I am making lots of changes to my code.

Output data from all columns in a dataframe in pandas

In ipython, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):

print paramdata.head(100).to_string()

How to revert a "git rm -r ."?

I had an identical situation. In my case the solution was:

git checkout -- .

check null,empty or undefined angularjs

just use -

if(!a) // if a is negative,undefined,null,empty value then...
{
    // do whatever
}
else {
    // do whatever
}

this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

How to use the TextWatcher class in Android?

Using TextWatcher in Android

Here is a sample code. Try using addTextChangedListener method of TextView

addTextChangedListener(new TextWatcher() {

        BigDecimal previousValue;
        BigDecimal currentValue;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int
                count) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    currentValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    previousValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (isFirstTimeChange) {
                isFirstTimeChange = false;
                return;
            }
            if (currentValue != null && previousValue != null) {
                if ((currentValue.compareTo(previousValue) > 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_green);
                    setBackgroundColor(flashOnColor);
                } else if ((currentValue.compareTo(previousValue) < 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_red);

                    setBackgroundColor(flashOffColor);
                } else {
                    //setBackgroundColor(textColor);
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000);
            }
        }
    });

angularjs: allows only numbers to be typed into a text box

Simply use HTML5

<input type="number" min="0"/>

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

Binding IIS Express to an IP Address

Below are the complete changes I needed to make to run my x64 bit IIS application using IIS Express, so that it was accessible to a remote host:

iisexpress /config:"C:\Users\test-user\Documents\IISExpress\config\applicationhost.config" /site:MyWebSite
Starting IIS Express ...
Successfully registered URL "http://192.168.2.133:8080/" for site "MyWebSite" application "/"
Registration completed for site "MyWebSite"
IIS Express is running.
Enter 'Q' to stop IIS Express

The configuration file (applicationhost.config) had a section added as follows:

<sites>
  <site name="MyWebsite" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\build\trunk\MyWebsite" />
    </application>
    <bindings>
      <binding protocol="http" bindingInformation=":8080:192.168.2.133" />
    </bindings>
  </site>

The 64 bit version of the .NET framework can be enabled as follows:

<globalModules>
    <!--
        <add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
        <add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
    -->             
    <add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

How to output git log with the first line only?

Have you tried this?

git log --pretty=oneline --abbrev-commit

The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.

Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.

The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline prints the whole short description, so all your 3 rows.

Site does not exist error for a2ensite

There's another good way, just edit the file apache2.conf theres a line at the end

IncludeOptional sites-enabled/*.conf

just remove the .conf at the end, like this

IncludeOptional sites-enabled/*

and restart the server.

(I tried this only in the Ubuntu 13.10, when I updated it.)

Dynamic constant assignment

Because constants in Ruby aren't meant to be changed, Ruby discourages you from assigning to them in parts of code which might get executed more than once, such as inside methods.

Under normal circumstances, you should define the constant inside the class itself:

class MyClass
  MY_CONSTANT = "foo"
end

MyClass::MY_CONSTANT #=> "foo"

If for some reason though you really do need to define a constant inside a method (perhaps for some type of metaprogramming), you can use const_set:

class MyClass
  def my_method
    self.class.const_set(:MY_CONSTANT, "foo")
  end
end

MyClass::MY_CONSTANT
#=> NameError: uninitialized constant MyClass::MY_CONSTANT

MyClass.new.my_method
MyClass::MY_CONSTANT #=> "foo"

Again though, const_set isn't something you should really have to resort to under normal circumstances. If you're not sure whether you really want to be assigning to constants this way, you may want to consider one of the following alternatives:

Class variables

Class variables behave like constants in many ways. They are properties on a class, and they are accessible in subclasses of the class they are defined on.

The difference is that class variables are meant to be modifiable, and can therefore be assigned to inside methods with no issue.

class MyClass
  def self.my_class_variable
    @@my_class_variable
  end
  def my_method
    @@my_class_variable = "foo"
  end
end
class SubClass < MyClass
end

MyClass.my_class_variable
#=> NameError: uninitialized class variable @@my_class_variable in MyClass
SubClass.my_class_variable
#=> NameError: uninitialized class variable @@my_class_variable in MyClass

MyClass.new.my_method
MyClass.my_class_variable #=> "foo"
SubClass.my_class_variable #=> "foo"

Class attributes

Class attributes are a sort of "instance variable on a class". They behave a bit like class variables, except that their values are not shared with subclasses.

class MyClass
  class << self
    attr_accessor :my_class_attribute
  end
  def my_method
    self.class.my_class_attribute = "blah"
  end
end
class SubClass < MyClass
end

MyClass.my_class_attribute #=> nil
SubClass.my_class_attribute #=> nil

MyClass.new.my_method
MyClass.my_class_attribute #=> "blah"
SubClass.my_class_attribute #=> nil

SubClass.new.my_method
SubClass.my_class_attribute #=> "blah"

Instance variables

And just for completeness I should probably mention: if you need to assign a value which can only be determined after your class has been instantiated, there's a good chance you might actually be looking for a plain old instance variable.

class MyClass
  attr_accessor :instance_variable
  def my_method
    @instance_variable = "blah"
  end
end

my_object = MyClass.new
my_object.instance_variable #=> nil
my_object.my_method
my_object.instance_variable #=> "blah"

MyClass.new.instance_variable #=> nil

How to add "required" attribute to mvc razor viewmodel text input editor

A newer way to do this in .NET Core is with TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Building on these examples (MaxLength, Label), you can extend the existing TagHelper to suit your needs.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

You'll then need to add it to be used in your views:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Given the following model:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

and view (snippet):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

Will result in this HTML:

<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

I hope this is helpful to anyone with same question but using .NET Core.

How do I parse JSON with Objective-C?

NSString* path  = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];

//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];


for (int i=0; i<[allKeys count]; i++) {
    NSDictionary *arrayResult = [allKeys objectAtIndex:i];
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);

}

file:

 [
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "MLMember",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  },
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "0.00",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  }
  ]

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

Counting the number of elements with the values of x in a vector

There is a standard function in R for that

tabulate(numbers)

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

Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]

See Cannot find or open the PDB file in Visual Studio C++ 2010

Inserting image into IPython notebook markdown

I put the IPython notebook in the same folder with the image. I use Windows. The image name is "phuong huong xac dinh.PNG".

In Markdown:

<img src="phuong huong xac dinh.PNG">

Code:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

How to check if a variable is empty in python?

Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.

bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.

If you wanted to handle strings containing numbers as PHP does, you could do something like:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

jQuery - Check if DOM element already exists

Also think about using

$(document).ready(function() {});

Don't know why no one here came up with this yet (kinda sad). When do you execute your code??? Right at the start? Then you might want to use upper mentioned ready() function so your code is being executed after the whole page (with all it's dom elements) has been loaded and not before! Of course this is useless if you run some code that adds dom elements after page load! Then you simply want to wait for those functions and execute your code afterwards...

jQuery load more data on scroll

Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.

var scrollLoad = true;
$(window).scroll(function(){
 if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
    // fetch data when we are 800px above the document end
    scrollLoad = false;
   }
  });

[var scrollLoad] is used to block the call until one new data is appended.

Hope this helps.

Integer division: How do you produce a double?

use something like:

double step = 1d / 5;

(1d is a cast to double)

Set default value of javascript object attributes

One approach would be to take a defaults object and merge it with the target object. The target object would override values in the defaults object.

jQuery has the .extend() method that does this. jQuery is not needed however as there are vanilla JS implementations such as can be found here:

http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/

How to write macro for Notepad++?

Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:

<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>

I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
I don't think it will record actions in dialogs (like search/replace).

Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.

Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
I tried some tricks, but I fear such task is beyond the macro capabilities.

Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)

[EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.

Convert a String to int?

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);

Can I position an element fixed relative to parent?

This solution works for me! Reference to the original detailed answer: https://stackoverflow.com/a/11833892/5385623

css:

.level1 {
    position: relative;
}


.level2 {
    position: absolute;
}


.level3 {
    position: fixed;
    /* Do not set top / left! */
}

html:

<div class='level1'>
    <div class='level2'>
        <div class='level3'>
            Content
        </div>
    </div>
</div>

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

Reset all the items in a form

    function setToggleInputsinPnl(pnlName) {
    var domCount = pnlName.length;
    for (var i = 0; i < domCount; i++) {
        if (pnlName[i].type == 'text') {
            pnlName[i].value = '';
        } else if (pnlName[i].type == 'select-one') {
               pnlName[i].value = '';
        }
    }
}

Select elements by attribute

A couple ideas were tossed around using "typeof", jQuery ".is" and ".filter" so I thought I would post up a quick perf compare of them. The typeof appears to be the best choice for this. While the others will work, there appears to be a clear performance difference when invoking the jq library for this effort.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

In my case, I did Build > Clean Project and it worked!

How can I build a recursive function in python?

Recursive function example:

def recursive(string, num):
    print "#%s - %s" % (string, num)
    recursive(string, num+1)

Run it with:

recursive("Hello world", 0)

Two models in one view in ASP MVC 3

Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

public class xViewModel
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

@model project.Models.Home.xViewModel

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x => x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

Why use pointers?

Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).

The best explanation of pointers and pointer arithmetic that I've read is in K & R's The C Programming Language. A good book for beginning learning C++ is C++ Primer.

Remove NA values from a vector

You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

Converting List<String> to String[] in Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

New features in java 7

Using Diamond(<>) operator for generic instance creation

Map<String, List<Trade>> trades = new TreeMap <> ();

Using strings in switch statements

String status=  “something”;
   switch(statue){
     case1: 
     case2: 
     default:
    }

Underscore in numeric literals

int val 12_15; long phoneNo = 01917_999_720L;

Using single catch statement for throwing multiple exception by using “|” operator

catch(IOException | NullPointerException ex){
          ex.printStackTrace();   
    }

No need to close() resources because Java 7 provides try-with-resources statement

try(FileOutputStream fos = new FileOutputStream("movies.txt");
      DataOutputStream dos = new DataOutputStream(fos)) {
              dos.writeUTF("Java 7 Block Buster");
  } catch(IOException e) {
        // log the exception
  }

binary literals with prefix “0b” or “0B”

How do I show the changes which have been staged?

You can use this command.

git diff --cached --name-only

The --cached option of git diff means to get staged files, and the --name-only option means to get only names of the files.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

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

Since ASP.NET MVC 3 RTM is out there is no need for config section for Razor. And these sections can be safely removed.

Escape double quotes in parameter

The 2nd document quoted by Peter Mortensen in his comment on the answer of Codesmith made things much clearer for me. That document was written by windowsinspired.com. The link repeated: A Better Way To Understand Quoting and Escaping of Windows Command Line Arguments.

Some further trial and error leads to the following guideline:

Escape every double quote " with a caret ^. If you want other characters with special meaning to the Windows command shell (e.g., <, >, |, &) to be interpreted as regular characters instead, then escape them with a caret, too.

If you want your program foo to receive the command line text "a\"b c" > d and redirect its output to file out.txt, then start your program as follows from the Windows command shell:

foo ^"a\^"b c^" ^> d > out.txt

If foo interprets \" as a literal double quote and expects unescaped double quotes to delimit arguments that include whitespace, then foo interprets the command as specifying one argument a"b c, one argument >, and one argument d.

If instead foo interprets a doubled double quote "" as a literal double quote, then start your program as

foo ^"a^"^"b c^" ^> d > out.txt

The key insight from the quoted document is that, to the Windows command shell, an unescaped double quote triggers switching between two possible states.

Some further trial and error implies that in the initial state, redirection (to a file or pipe) is recognized and a caret ^ escapes a double quote and the caret is removed from the input. In the other state, redirection is not recognized and a caret does not escape a double quote and isn't removed. Let's refer to these states as 'outside' and 'inside', respectively.

If you want to redirect the output of your command, then the command shell must be in the outside state when it reaches the redirection, so there must be an even number of unescaped (by caret) double quotes preceding the redirection. foo "a\"b " > out.txt won't work -- the command shell passes the entire "a\"b " > out.txt to foo as its combined command line arguments, instead of passing only "a\"b " and redirecting the output to out.txt.

foo "a\^"b " > out.txt won't work, either, because the caret ^ is encountered in the inside state where it is an ordinary character and not an escape character, so "a\^"b " > out.txt gets passed to foo.

The only way that (hopefully) always works is to keep the command shell always in the outside state, because then redirection works.

If you don't need redirection (or other characters with special meaning to the command shell), then you can do without the carets. If foo interprets \" as a literal double quote, then you can call it as

foo "a\"b c"

Then foo receives "a\"b c" as its combined arguments text and can interpret it as a single argument equal to a"b c.

Now -- finally -- to the original question. myscript '"test"' called from the Windows command shell passes '"test"' to myscript. Apparently myscript interprets the single and double quotes as argument delimiters and removes them. You need to figure out what myscript accepts as a literal double quote and then specify that in your command, using ^ to escape any characters that have special meaning to the Windows command shell. Given that myscript is also available on Unix, perhaps \" does the trick. Try

myscript \^"test\^"

or, if you don't need redirection,

myscript \"test\"

How to efficiently calculate a running standard deviation?

As the following answer describes: Does pandas/scipy/numpy provide a cumulative standard deviation function? The Python Pandas module contains a method to calculate the running or cumulative standard deviation. For that you'll have to convert your data into a pandas dataframe (or a series if it is 1D), but there are functions for that.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

List names of all tables in a SQL Server 2012 schema

Your should really use the INFORMATION_SCHEMA views in your database:

USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES

You can then filter that by table schema and/or table type, e.g.

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

How to dump raw RTSP stream to file?

You can use mplayer.

mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi

The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.

In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.

Create an empty list in python with certain size

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

Calling a function within a Class method?

Try this one:

class test {
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }

     private function bigTest(){
          //Big Test Here
     }

     private function smallTest(){
          //Small Test Here
     }

     public function scoreTest(){
          //Scoring code here;
     }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();

How to create table using select query in SQL Server?

select <column list> into <dest. table> from <source table>;

You could do this way.

SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
into   new_table_name
FROM   sys.dm_os_windows_info OPTION (RECOMPILE);

How to autowire RestTemplate using annotations

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateClient {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

How does one parse XML files?

Use a good XSD Schema to create a set of classes with xsd.exe and use an XmlSerializer to create a object tree out of your XML and vice versa. If you have few restrictions on your model, you could even try to create a direct mapping between you model classes and the XML with the Xml*Attributes.

There is an introductory article about XML Serialisation on MSDN.

Performance tip: Constructing an XmlSerializer is expensive. Keep a reference to your XmlSerializer instance if you intend to parse/write multiple XML files.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

re.sub(r'(.)(.)',r"\2\1",'abcdef1234')

However re is a bit slow.

def swap(s):
    i=iter(s)
    while True:
        a,b=next(i),next(i)
        yield b
        yield a

''.join(swap("abcdef1234"))

EnterKey to press button in VBA Userform

Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

Generate HTML table from 2D JavaScript array

Here's a version using template literals. It maps over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML:

_x000D_
_x000D_
let data = [_x000D_
  ['Title', 'Artist', 'Duration', 'Created'],_x000D_
  ['hello', 'me', '2', '2019'],_x000D_
  ['ola', 'me', '3', '2018'],_x000D_
  ['Bob', 'them', '4.3', '2006']_x000D_
];_x000D_
_x000D_
function getCells(data, type) {_x000D_
  return data.map(cell => `<${type}>${cell}</${type}>`).join('');_x000D_
}_x000D_
_x000D_
function createBody(data) {_x000D_
  return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');_x000D_
}_x000D_
_x000D_
function createTable(data) {_x000D_
  const [headings, ...rows] = data;_x000D_
  return `_x000D_
    <table>_x000D_
      <thead>${getCells(headings, 'th')}</thead>_x000D_
      <tbody>${createBody(rows)}</tbody>_x000D_
    </table>_x000D_
  `;_x000D_
}_x000D_
_x000D_
document.body.insertAdjacentHTML('beforeend', createTable(data));
_x000D_
table { border-collapse: collapse; }_x000D_
tr { border: 1px solid #dfdfdf; }_x000D_
th, td { padding: 2px 5px 2px 5px;}
_x000D_
_x000D_
_x000D_

How do I print the elements of a C++ vector in GDB?

put the following in ~/.gdbinit

define print_vector
    if $argc == 2
        set $elem = $arg0.size()
        if $arg1 >= $arg0.size()
            printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()
            set $elem = $arg1 -1
        end
        print *($arg0._M_impl._M_start + $elem)@1
    else
        print *($arg0._M_impl._M_start)@$arg0.size()
    end
end

document print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
end

After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this

gdb) help print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display

Example usage:

(gdb) print_vector videoconfig_.entries 0
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0,     payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}

jQuery ajax post file field

File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums

How to make a countdown timer in Android?

if you use the below code (as mentioned in accepted answer),

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

It will result in memory leak of the instance of the activity where you use this code, if you don't carefully clean up the references.

use the following code

//Declare timer
CountDownTimer cTimer = null;

//start timer function
void startTimer() {
    cTimer = new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
        }
        public void onFinish() {
        }
    };
    cTimer.start();
}


//cancel timer
void cancelTimer() {
    if(cTimer!=null)
        cTimer.cancel();
}

You need to call cTtimer.cancel() whenever the onDestroy()/onDestroyView() in the owning Activity/Fragment is called.

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

TSQL Default Minimum DateTime

Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.

The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.

-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS 
    BEGIN
        DECLARE @dateTime_min DATETIME ;
        SET @dateTime_min = '1/1/1753 12:00:00 AM'
        RETURN @dateTime_min ;
    END ;
GO


-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
  TestTableId INT IDENTITY(1, 1)
                  PRIMARY KEY CLUSTERED ,
  Value VARCHAR(50) ,
  Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;


-- INSERT VALUE INTO TABLE
INSERT  INTO TestTable
        ( Value )
VALUES  ( 'Value' ) ;


-- SELECT FROM TABLE
SELECT  TestTableId ,
        VALUE ,
        Modified
FROM    TestTable ;


-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;

How to get directory size in PHP

The following are other solutions offered elsewhere:

If on a Windows Host:

<?
    $f = 'f:/www/docs';
    $obj = new COM ( 'scripting.filesystemobject' );
    if ( is_object ( $obj ) )
    {
        $ref = $obj->getfolder ( $f );
        echo 'Directory: ' . $f . ' => Size: ' . $ref->size;
        $obj = null;
    }
    else
    {
        echo 'can not create object';
    }
?>

Else, if on a Linux Host:

<?
    $f = './path/directory';
    $io = popen ( '/usr/bin/du -sk ' . $f, 'r' );
    $size = fgets ( $io, 4096);
    $size = substr ( $size, 0, strpos ( $size, "\t" ) );
    pclose ( $io );
    echo 'Directory: ' . $f . ' => Size: ' . $size;
?>

Delete the 'first' record from a table in SQL Server, without a WHERE condition

WITH  q AS
        (
        SELECT TOP 1 *
        FROM    mytable
        /* You may want to add ORDER BY here */
        )
DELETE
FROM    q

Note that

DELETE TOP (1)
FROM   mytable

will also work, but, as stated in the documentation:

The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order.

Therefore, it's better to use WITH and an ORDER BY clause, which will let you specify more exactly which row you consider to be the first.

Is there a way to detect if a browser window is not currently active?

Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.

document.addEventListener("visibilitychange", onchange);

Current browser support:

  • Chrome 13+
  • Internet Explorer 10+
  • Firefox 10+
  • Opera 12.10+ [read notes]

The following code falls back to the less reliable blur/focus method in incompatible browsers:

(function() {
  var hidden = "hidden";

  // Standards:
  if (hidden in document)
    document.addEventListener("visibilitychange", onchange);
  else if ((hidden = "mozHidden") in document)
    document.addEventListener("mozvisibilitychange", onchange);
  else if ((hidden = "webkitHidden") in document)
    document.addEventListener("webkitvisibilitychange", onchange);
  else if ((hidden = "msHidden") in document)
    document.addEventListener("msvisibilitychange", onchange);
  // IE 9 and lower:
  else if ("onfocusin" in document)
    document.onfocusin = document.onfocusout = onchange;
  // All others:
  else
    window.onpageshow = window.onpagehide
    = window.onfocus = window.onblur = onchange;

  function onchange (evt) {
    var v = "visible", h = "hidden",
        evtMap = {
          focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
        };

    evt = evt || window.event;
    if (evt.type in evtMap)
      document.body.className = evtMap[evt.type];
    else
      document.body.className = this[hidden] ? "hidden" : "visible";
  }

  // set the initial state (but only if browser supports the Page Visibility API)
  if( document[hidden] !== undefined )
    onchange({type: document[hidden] ? "blur" : "focus"});
})();

onfocusin and onfocusout are required for IE 9 and lower, while all others make use of onfocus and onblur, except for iOS, which uses onpageshow and onpagehide.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Very simple:

Just use the below formation###

rules_id = ["9","10"]

sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))

note the str(tuple(rules_id)).

How do I install cURL on cygwin?

If someone is having problem with finding CURL in the list in setup.exe (Cygwin package manager) then trying downloading 64bit version of this setup. Worked for me.

Getting only response header from HTTP POST using curl

The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:

curl -s -I -X POST http://www.google.com

An -I by itself performs a HEAD request which can be overridden by -X POST to perform a POST (or any other) request and still only get the header data.

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

How to make several plots on a single page using matplotlib?

Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots which is very convenient:

fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)

where axes is a numpy.ndarray of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j].

Using Excel as front end to Access database (with VBA)

You could try something like XLLoop. This lets you implement excel functions (UDFs) on an external server (server implementations in many different languages are provided).

For example you could use a MySQL database and Apache web server and then write the functions in PHP to serve up the data to your users.

BTW, I work on the project so let me know if you have any questions.

Set Focus on EditText

For Xamarin.Android I have created this extension.

public static class ViewExtensions
{
    public static void FocusEditText(this EditText editText, Activity activity)
    {
        if (editText.RequestFocus())
        {
            InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
            imm.ShowSoftInput(editText, ShowFlags.Implicit);
        }
    }
}

Base64 String throwing invalid character error

If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>