Programs & Examples On #Webpart connection

How are cookies passed in the HTTP protocol?

Apart from what it's written in other answers, other details related to path of cookie, maximum age of cookie, whether it's secured or not also passed in Set-Cookie response header. For instance:

Set-Cookie:name=value[; expires=date][; domain=domain][; path=path][; secure]


However, not all of these details are passed back to the server by the client when making next HTTP request.

You can also set HttpOnly flag at the end of your cookie, to indicate that your cookie is httponly and must not allowed to be accessed, in scripts by javascript code. This helps to prevent attacks such as session-hijacking.

For more information, see RFC 2109. Also have a look at Nicholas C. Zakas's article, HTTP cookies explained.

Why does Oracle not find oci.dll?

I had this issue, I run 64 bit Windows and had downloaded the 64 bit TOAD package. I finally arrived at the conclusion that it was because I unzipped the package in a windows share using cygwin command line unzip. Turned out TOAD wasn't liking the permissions on some files. When I unzipped using windows File Explorer everything worked as expected.

android: data binding error: cannot find symbol class

I have got the same error, but with Kotlin usage.

To resolve it, i make some changes in gradles files :

In project's Gradle file :

dependencies {
    classpath "com.android.tools.build:gradle:3.1.2"
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.40"
}

In app's Gradle file :

dependencies {

    ...
    implementation "android.arch.lifecycle:extensions:1.1.1"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.30"
    kapt 'com.android.databinding:compiler:3.1.2'
}


kapt {
    generateStubs = true
}

//used to resolve annotation conflicts
configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:23.1.1'
    }
}

How to pass parameters to $http in angularjs?

Here is a simple mathed to pass values from a route provider

//Route Provider
$routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});


//Controller
$http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
        .then(function(res){
            //....
        })

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Find a pair of elements from an array whose sum equals a given number

Here is a solution witch takes into account duplicate entries. It is written in javascript and assumes array is sorted. The solution runs in O(n) time and does not use any extra memory aside from variable.

var count_pairs = function(_arr,x) {
  if(!x) x = 0;
  var pairs = 0;
  var i = 0;
  var k = _arr.length-1;
  if((k+1)<2) return pairs;
  var halfX = x/2; 
  while(i<k) {
    var curK = _arr[k];
    var curI = _arr[i];
    var pairsThisLoop = 0;
    if(curK+curI==x) {
      // if midpoint and equal find combinations
      if(curK==curI) {
        var comb = 1;
        while(--k>=i) pairs+=(comb++);
        break;
      }
      // count pair and k duplicates
      pairsThisLoop++;
      while(_arr[--k]==curK) pairsThisLoop++;
      // add k side pairs to running total for every i side pair found
      pairs+=pairsThisLoop;
      while(_arr[++i]==curI) pairs+=pairsThisLoop;
    } else {
      // if we are at a mid point
      if(curK==curI) break;
      var distK = Math.abs(halfX-curK);
      var distI = Math.abs(halfX-curI);
      if(distI > distK) while(_arr[++i]==curI);
      else while(_arr[--k]==curK);
    }
  }
  return pairs;
}

I solved this during an interview for a large corporation. They took it but not me. So here it is for everyone.

Start at both side of the array and slowly work your way inwards making sure to count duplicates if they exist.

It only counts pairs but can be reworked to

  • find the pairs
  • find pairs < x
  • find pairs > x

Enjoy!

C# Return Different Types?

May be you need "dynamic" type?

public dynamic GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return /*what boject you needed*/ ;`enter code here`   
}

This version of the application is not configured for billing through Google Play

Conclusions in 2021

For all of you who concerned about debugging - You CAN run and debug and test the code in debug mode

Here's how you can test the process:

(This of course relies on the fact that you have already added and activated your products, and your code is ready for integration with those products)

  1. Add com.android.vending.BILLING to the manifest
  2. Upload signed apk to internal testing
  3. Add license testers (Play console -> Settings -> License testing) - If you use multiple accounts on your device and you're not sure which one to use, just add all of them as testers.
  4. Run the application, as you normally would, from Android Studio (* The application should have the same version code as the one you just uploaded to internal testing)

I did the above and it is working just fine.

Python's most efficient way to choose longest string in list?

len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)

How to check the Angular version?

There are many way, you check angular version Just pent the comand prompt(for windows) and type

1. ng version
2. ng v
3. ng -v

check the angular version using comand line

4. You can pakage.json file

check the angular version on pakage.json file

5.You can check in browser by presing F12 then goto elements tab

check the angular version on your browser

Full understanding of subversion about(x.x.x) please see angular documentation angularJS and angular 2+

Minimum and maximum value of z-index?

Out of experience, I think the correct maximum z-index is 2147483638.

error: pathspec 'test-branch' did not match any file(s) known to git

just follow three steps, git branch problem will be solved.

git remote update
git fetch
git checkout --track origin/test-branch

C# error: Use of unassigned local variable

A couple of different ways to solve the problem:

Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}

How can I center <ul> <li> into div

Just add text-align: center; to your <ul>. Problem solved.

Make a float only show two decimal places

In Swift Language, if you want to show you need to use it in this way. To assign double value in UITextView, for example:

let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)

If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way:

println(NSString(format:"%.2f", result))

jQuery 'input' event

Occurs when the text content of an element is changed through the user interface.

It's not quite an alias for keyup because keyup will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup event).

A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl by itself will not trigger the event, but Ctrl-V to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.

See this page and the comments on this answer for more details.

Print all key/value pairs in a Java ConcurrentHashMap

The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.

To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:

//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();

//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet()) {
  System.out.println(e.getKey()+"="+e.getValue());
}

Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.

Hope this helps you.

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

How can I call PHP functions by JavaScript?

Void Function

<?php
function printMessage() {
    echo "Hello World!";
}
?>

<script>
    document.write("<?php printMessage() ?>");
</script>

Value Returning Function

<?php
function getMessage() {
    return "Hello World!";
}
?>

<script>
    var text = "<?php echo getMessage() ?>";
</script>

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

UILabel - auto-size label to fit text?

If we want that UILabel should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this

Steps

  1. Put UILabel in view controller and place it wherever you want. Also put 0 for numberOfLines property of UILabel.

  2. Give it Top, Leading and Trailing space pin constraint.

enter image description here

  1. Now it will give warning, Click on the yellow arrow.

enter image description here

  1. Click on Update Frame and click on Fix Misplacement. Now this UILabel will shrink if text is less and expand if text is more.

Retrieving an element from array list in Android?

Maybe the following helps you.

arraylistname.get(position);

Angular Directive refresh on parameter change

If You're under AngularJS 1.5.3 or newer, You should consider to move to components instead of directives. Those works very similar to directives but with some very useful additional feautures, such as $onChanges(changesObj), one of the lifecycle hook, that will be called whenever one-way bindings are updated.

app.component('conversation ', {
    bindings: {
    type: '@',
    typeId: '='
    },
    controller: function() {
        this.$onChanges = function(changes) {
            // check if your specific property has changed
            // that because $onChanges is fired whenever each property is changed from you parent ctrl
            if(!!changes.typeId){
                refreshYourComponent();
            }
        };
    },
    templateUrl: 'conversation .html'
});

Here's the docs for deepen into components.

How to retrieve images from MySQL database and display in an html tag

Technically, you can too put image data in an img tag, using data URIs.

<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />

There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

How to check if Location Services are enabled?

This is a very useful method that returns "true" if the Location services are enabled:

public static boolean locationServicesEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps_enabled = false;
        boolean net_enabled = false;

        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception gps_enabled");
        }

        try {
            net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception network_enabled");
        }
        return gps_enabled || net_enabled;
}

Get MIME type from filename extension

My take at those mimetypes, using the apache list, the below script will give you a dictionary with all the mimetypes.

var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();

foreach (var row in rawData)
{
    if (row.StartsWith("#")) continue;

    var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
    if (rowData.Length != 2) continue;

    var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    if (!mimeTypeToExtension.ContainsKey(rowData[0]))
    {
        mimeTypeToExtension.Add(rowData[0], extensions);
    }

    foreach (var extension in extensions)
    {
        if (!extensionToMimeType.ContainsKey(extension))
        {
            extensionToMimeType.Add(extension, rowData[0]);
        }
    }

}

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

Convert python long/int to fixed size byte array

long/int to the byte array looks like exact purpose of struct.pack. For long integers that exceed 4(8) bytes, you can come up with something like the next:

>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
        parts.append(i & limit)
        i >>= 32

>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'

>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L

Android ImageView Animation

Use a RotateAnimation, setting the pivot point to the centre of your image.

RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

// Start animating the image
final ImageView splash = (ImageView) findViewById(R.id.splash);
splash.startAnimation(anim);

// Later.. stop the animation
splash.setAnimation(null);

How to drop all tables in a SQL Server database?

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

Recompile PHP with mbstring.

./configure --enable-http --with-apxs2 --with-mysql --with-gd --with-curl --with-mbstring

make 

make install

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.

Data-frame Object has no Attribute

I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.

Forwarding port 80 to 8080 using NGINX

you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _ your_domain;

    location /health {
            access_log off;
            return 200 "healthy\n";
    }

    location / {
            proxy_pass http://localhost:8080; 
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache_bypass $http_upgrade;
    }
  }

ImportError: No module named dateutil.parser

i have same issues on my MacOS and it's work for me to try

pip3 install python-dateutil

on Ubuntu

sudo apt-get install python-dateutil

Check here

Running a CMD or BAT in silent mode

I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)

That should answer your question.

Here it is:


From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---| 

Update after Tammen's feedback:

If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

JVM option -Xss - What does it do exactly?

It indeed sets the stack size on a JVM.

You should touch it in either of these two situations:

  • StackOverflowError (the stack size is greater than the limit), increase the value
  • OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.

The latter usually comes when your Xss is set too large - then you need to balance it (testing!)

Saving image to file

You could try to save the image using this approach

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   int width = Convert.ToInt32(drawImage.Width); 
   int height = Convert.ToInt32(drawImage.Height); 
   Bitmap bmp = new Bitmap(width,height);        
   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);
   bmp.Save(dialog.FileName, ImageFormat.Jpeg);
}

Open window in JavaScript with HTML inserted

When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.

Here is an example:

var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Assuming you are using Eclipse, on a MAC you can:

  1. Launch Eclipse.app
  2. Choose Eclipse -> Preferences
  3. Choose Java -> Installed JREs
  4. Click the Add... button
  5. Choose MacOS X VM as the JRE type. Press Next.
  6. In the "JRE Home:" field, type /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
  7. You should see the system libraries in the list titled "JRE system libraries:"
  8. Give the JRE a name. The recommended name is JDK 1.7. Click Finish.
  9. Check the checkbox next to the JRE entry you just created. This will cause Eclipse to use it as the default JRE for all new Java projects. Click OK.
  10. Now, create a new project. For this verification, from the menu, select File -> New -> Java Project.
  11. In the dialog that appears, enter a new name for your project. For this verification, type Test17Project
  12. In the JRE section of the dialog, select Use default JRE (currently JDK 1.7)
  13. Click Finish.

Hope this helps

Understanding Matlab FFT example

There are some misconceptions here.

Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.

The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.

The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

Get the index of the object inside an array, matching a condition

One step using Array.reduce() - no jQuery

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

will return null if index was not found.

How to pass parameter to click event in Jquery

Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

NodeJS accessing file with relative path

You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');
var path = require('path');

var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.

Vue-router redirect on page not found (404)

@mani's response is now slightly outdated as using catch-all '*' routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with

{ path: '/:pathMatch(.*)*', component: PathNotFound },

Essentially, you should be able to replace the '*' path with '/:pathMatch(.*)*' and be good to go!

Reason: Vue Router doesn't use path-to-regexp anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.

(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...

I'm running Visual Studio 2019 and Xamarin.

I also switched back to my WiFi but was on a hot spot.

I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.

It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.

I could not understand how it worked perfectly before and then stopped with no code change.

This is my code for reference:

using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();

to_string is not a member of std, says g++ (mingw)

For me, ensuring that I had:

#include <iostream>  
#include<string>  
using namespace std;

in my file made something like to_string(12345) work.

Clear the form field after successful submission of php form

Put the onClick function in the button submit:

<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />

In the <head>, define the function clearform(), and set the textbox value to "":

function clearform()
{
    document.getElementById("firstname").value=""; //don't forget to set the textbox id
    document.getElementById("lastname").value="";
}

This way the textbox will be cleared when you click the submit button.

How to add jQuery in JS file

If you want to include jQuery code from another JS file, this should do the trick:

I had the following in my HTML file:

<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>

I created a separate my_jquery.js file with the following:

$(document).ready(function() {
  $('a').click(function(event) {
    event.preventDefault();
    $(this).hide("slow");
  });
});

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following to your xml:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>annotations</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

How to detect running app using ADB command

I just noticed that top is available in adb, so you can do things like

  adb shell
  top -m 5

to monitor the top five CPU hogging processes.

Or

  adb shell top -m 5 -s cpu -n 20 |tee top.log

to record this for one minute and collect the output to a file on your computer.

Combining COUNT IF AND VLOOK UP EXCEL

If your are referring to two worksheets please use this formula

=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)

In case referring to to more than two worksheets please use this formula

=COUNTIF(Worksheet2!$A$1:$A$50,Worksheet1cellA1)+=COUNTIF
(Worksheet3!$A$1:$A$50,Worksheet1cellA1)+=
               COUNTIF(Worksheet4!$A$1:$A$50,Worksheet1cellA1)

Git remote branch deleted, but still it appears in 'branch -a'

git remote prune origin, as suggested in the other answer, will remove all such stale branches. That's probably what you'd want in most cases, but if you want to just remove that particular remote-tracking branch, you should do:

git branch -d -r origin/coolbranch

(The -r is easy to forget...)

-r in this case will "List or delete (if used with -d) the remote-tracking branches." according to the Git documentation found here: https://git-scm.com/docs/git-branch

Fixed Table Cell Width

Now in HTML5/CSS3 we have better solution for the problem. In my opinion this purely CSS solution is recommended:

_x000D_
_x000D_
table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/_x000D_
table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/_x000D_
table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/_x000D_
table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/_x000D_
table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
_x000D_
<table class="fixed">_x000D_
    <tr>_x000D_
        <td>Veryverylongtext</td>_x000D_
        <td>Actuallythistextismuchlongeeeeeer</td>_x000D_
        <td>We should use spaces tooooooooooooo</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You need to set the table's width even in haunter's solution. Otherwise it doesn't work.
Also a new CSS3 feature that vsync suggested is: word-break:break-all;. This will break the words without spaces in them to multiple lines too. Just modify the code like this:

table.fixed { table-layout:fixed; width:90px; word-break:break-all;}

Final result

Rendered table

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

MS SQL compare dates?

Try This:

BEGIN

declare @Date1 datetime
declare @Date2 datetime

declare @chkYear int
declare @chkMonth int
declare @chkDay int
declare @chkHour int
declare @chkMinute int
declare @chkSecond int
declare @chkMiliSecond int

set @Date1='2010-12-31 15:13:48.593'
set @Date2='2010-12-31 00:00:00.000'

set @chkYear=datediff(yyyy,@Date1,@Date2)
set @chkMonth=datediff(mm,@Date1,@Date2)
set @chkDay=datediff(dd,@Date1,@Date2)
set @chkHour=datediff(hh,@Date1,@Date2)
set @chkMinute=datediff(mi,@Date1,@Date2)
set @chkSecond=datediff(ss,@Date1,@Date2)
set @chkMiliSecond=datediff(ms,@Date1,@Date2)

if @chkYear=0 AND @chkMonth=0 AND @chkDay=0 AND @chkHour=0 AND @chkMinute=0 AND @chkSecond=0 AND @chkMiliSecond=0
    Begin
        Print 'Both Date is Same'
    end
else
    Begin
        Print 'Both Date is not Same'
    end
End

ajax jquery simple get request

var dataString = "flag=fetchmediaaudio&id="+id;

$.ajax
({
  type: "POST",
  url: "ajax.php",
  data: dataString,
  success: function(html)
  {
     alert(html);
  }
});

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

How to get C# Enum description from value?

Update

The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

In Enums.NET you'd use:

string description = ((MyEnum)value).AsString(EnumFormat.Description);

Original post

I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description

I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

Convert interface{} to int

You need to do type assertion for converting your interface{} to int value.

iAreaId := val.(int)
iAreaId, ok := val.(int)

More information is available.

Attribute Error: 'list' object has no attribute 'split'

I think you've actually got a wider confusion here.

The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.

And then you're doing for points in Type, and expecting each such points to give you a new x and y. But that isn't going to happen. Types is just two values, x and y, so first points will be x, and then points will be y, and then you'll be done. So, again, you need to loop over each line and get the x and y values from each line, not loop over a single Types from a single line.

So, everything has to go inside a loop over every line in the file, and do the split into x and y once for each line. Like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]
        print(x,y)

getQuakeData()

As a side note, you really should close the file, ideally with a with statement, but I'll get to that at the end.


Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):
        print(x,y)

getQuakeData()

Or, a better way to write that might be:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:
            print(x,y)

getQuakeData()

Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

Was able to solve this problem in my asp.net mvc project by updating my version of Newton.Json (old Version = 9.0.0.0 to new Version 11.0.0.0) usign Package Manager.

Find the similarity metric between two strings

Here's what i thought of:

import string

def match(a,b):
    a,b = a.lower(), b.lower()
    error = 0
    for i in string.ascii_lowercase:
            error += abs(a.count(i) - b.count(i))
    total = len(a) + len(b)
    return (total-error)/total

if __name__ == "__main__":
    print(match("pple inc", "Apple Inc."))

Typescript interface default values

You can use the Partial mapped type as explained in the documentation: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

In your example, you'll have:

interface IX {
    a: string;
    b: any;
    c: AnotherType;
}

let x: Partial<IX> = {
    a: 'abc'
}

How to get a substring between two strings in PHP?

an edited version of what Alejandro García Iglesias put.

This allows you to pick a specific location of the string you want to get based on the number of times the result is found.

function get_string_between_pos($string, $start, $end, $pos){
    $cPos = 0;
    $ini = 0;
    $result = '';
    for($i = 0; $i < $pos; $i++){
      $ini = strpos($string, $start, $cPos);
      if ($ini == 0) return '';
      $ini += strlen($start);
      $len = strpos($string, $end, $ini) - $ini;
      $result = substr($string, $ini, $len);
      $cPos = $ini + $len;
    }
    return $result;
  }

usage:

$text = 'string has start test 1 end and start test 2 end and start test 3 end to print';

//get $result = "test 1"
$result = $this->get_string_between_pos($text, 'start', 'end', 1);

//get $result = "test 2"
$result = $this->get_string_between_pos($text, 'start', 'end', 2);

//get $result = "test 3"
$result = $this->get_string_between_pos($text, 'start', 'end', 3);

strpos has an additional optional input to start its search at a specific point. so I store the previous position in $cPos so when the for loop checks again, it starts at the end of where it left off.

Black transparent overlay on image hover with only CSS?

I would give a min-height and min-width to your overlay div of the size of the image, and change the background color on hover

.overlay { position: absolute; top: 0; left: 0;  z-index: 200; min-height:200px; min-width:200px; background-color: none;}
.overlay:hover { background-color: red;}

javascript - pass selected value from popup window to parent window input box

If you want a popup window rather than a <div />, I would suggest the following approach.

In your parent page, you call a small helper method to show the popup window:

<input type="button" name="choice" onClick="selectValue('sku1')" value="?">

Add the following JS methods:

function selectValue(id)
{
    // open popup window and pass field id
    window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
      'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}

function updateValue(id, value)
{
    // this gets called from the popup window and updates the field with a new value
    document.getElementById(id).value = value;
}

Your sku.php receives the selected field via $_GET['id'] and uses it to construct the parent callback function:

?>
<script type="text/javascript">
function sendValue(value)
{
    var parentId = <?php echo json_encode($_GET['id']); ?>;
    window.opener.updateValue(parentId, value);
    window.close();
}
</script>

For each row in your popup, change code to this:

<td><input type=button value="Select" onClick="sendValue('<?php echo $rows['packcode']; ?>')" /></td>

Following this approach, the popup window doesn't need to know how to update fields in the parent form.

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

Why do I get "MismatchSenderId" from GCM server side?

InstanceID.getInstance(getApplicationContext()).getToken(authorizedEntity,scope)

authorizedEntity is the project number of the server

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

What is the difference between Trap and Interrupt?

A trap is called by code like programs and used e. g. to call OS routines (i. e. normally synchronous). An interrupt is called by events (many times hardware, like the network card having received data, or the CPU timer), and - as the name suggests - interrupts the normal control flow, as the CPU has to switch to the driver routine to handle the event.

Java 8 Streams: multiple filters vs. complex condition

A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options

For small array 10 element throughput ops/s: 10 element array For medium 10,000 elements throughput ops/s: enter image description here For large array 1,000,000 elements throughput ops/s: 1M elements

NOTE: tests runs on

  • 8 CPU
  • 1 GB RAM
  • OS version: 16.04.1 LTS (Xenial Xerus)
  • java version: 1.8.0_121
  • jvm: -XX:+UseG1GC -server -Xmx1024m -Xms1024m

UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same

Benchmark mode: Throughput, ops/time Java 8vs11

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }

How do you cast a List of supertypes to a List of subtypes?

Quite strange that manually casting a list is still not provided by some tool box implementing something like:

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends E, E> List<T> cast(List<E> list) {
    return (List) list;
}

Of course, this won't check items one by one, but that is precisely what we want to avoid here, if we well know that our implementation only provides the sub-type.

Execute Shell Script after post build in Jenkins

You should be able to do that with the Batch Task plugin.

  1. Create a batch task in the project.
  2. Add a "Invoke batch tasks" post-build option selecting the same project.

An alternative can also be Post build task plugin.

Is it possible to program Android to act as physical USB keyboard?

Some others figured out that this is wrong. In the meantime i share their opinion. I'm sorry.

Old WRONG answer:

In my opinion this is barely possible.

Your Computer identifies any USB device with the USB device descriptor or the usb interface descriptor. To be able to use your android device as a keyboard, you would have to change these. Actually i think these are saved on a ROM in the device, so you would have to change hardware. The device needs to identifiy itself with the host even if its only charging in turned off state (has to tell usb host about the power consumption, otherwise only a few mA max). For me this points into the direction, that you would have to change hardware

"Easiest" way would proabably be assemble an adapter containing a usb host chip with a µC that converts the received data (which you still had to send via usb) to ps/2 or usb-client signals that u send to the computer.

In my opinion the easiest way would be: Buy one of these Keyboards you can roll and put them in your bag too.

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

Importing a long list of constants to a Python file

As an alternative to using the import approach described in several answers, have a look a the configparser module.

The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

Conversion failed when converting date and/or time from character string while inserting datetime

I'm Tried this and it's working with me :

SELECT CONVERT(date, yourDate ,104)

Jquery Validate custom error message location

What you should use is the errorLabelContainer

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var validator = $('#form').validate({_x000D_
    rules: {_x000D_
      first: {_x000D_
        required: true_x000D_
      },_x000D_
      second: {_x000D_
        required: true_x000D_
      }_x000D_
    },_x000D_
    messages: {},_x000D_
    errorElement : 'div',_x000D_
    errorLabelContainer: '.errorTxt'_x000D_
  });_x000D_
});
_x000D_
.errorTxt{_x000D_
  border: 1px solid red;_x000D_
  min-height: 20px;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
  <input type="text" name="first" />_x000D_
  <input type="text" name="second" />_x000D_
  <div class="errorTxt"></div>_x000D_
  <input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_


If you want to retain your structure then

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var validator = $('#form').validate({_x000D_
    rules: {_x000D_
      first: {_x000D_
        required: true_x000D_
      },_x000D_
      second: {_x000D_
        required: true_x000D_
      }_x000D_
    },_x000D_
    messages: {},_x000D_
    errorPlacement: function(error, element) {_x000D_
      var placement = $(element).data('error');_x000D_
      if (placement) {_x000D_
        $(placement).append(error)_x000D_
      } else {_x000D_
        error.insertAfter(element);_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
#errNm1 {_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#errNm2 {_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
  <input type="text" name="first" data-error="#errNm1" />_x000D_
  <input type="text" name="second" data-error="#errNm2" />_x000D_
  <div class="errorTxt">_x000D_
    <span id="errNm2"></span>_x000D_
    <span id="errNm1"></span>_x000D_
  </div>_x000D_
  <input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Android: How to overlay a bitmap and draw over a bitmap?

I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.

Read more or download demo here

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 10, 10, null);
        return result;
    }

and call the above function on button click and pass the two images to our function as shown below

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

For more than two images, you can follow this link, how to merge multiple images programmatically on android

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

'float' vs. 'double' precision

Do doubles always have 16 significant figures while floats always have 7 significant figures?

No. Doubles always have 53 significant bits and floats always have 24 significant bits (except for denormals, infinities, and NaN values, but those are subjects for a different question). These are binary formats, and you can only speak clearly about the precision of their representations in terms of binary digits (bits).

This is analogous to the question of how many digits can be stored in a binary integer: an unsigned 32 bit integer can store integers with up to 32 bits, which doesn't precisely map to any number of decimal digits: all integers of up to 9 decimal digits can be stored, but a lot of 10-digit numbers can be stored as well.

Why don't doubles have 14 significant figures?

The encoding of a double uses 64 bits (1 bit for the sign, 11 bits for the exponent, 52 explicit significant bits and one implicit bit), which is double the number of bits used to represent a float (32 bits).

How can I run a windows batch file but hide the command window?

For any executable file, you can run your program using cmd with "c" parameter:

cmd /c "your program address"\"YourFileName".bat  

(->if it's a batch file!) As a final solution, I suggest that you create a .cmd file and put this command in it:

cmd /c "your program address"\"YourFileName".bat
exit

Now just run this .cmd file.

How can I check for an empty/undefined/null string in JavaScript?

Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this.

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

How to include a quote in a raw Python string

Since I stumbled on this answer, and it greatly helped me, but I found a minor syntactic issue, I felt I should save others possible frustration. The triple quoted string works for this scenario as described, but note that if the " you want in the string occurs at the end of the string itself:

somestr = """This is a string with a special need to have a " in it at the end""""

You will hit an error at execution because the """" (4) quotes in a row confuses the string reader, as it thinks it has hit the end of the string already and then finds a random " out there. You can validate this by inserting a space into the 4 quotes like so: " """ and it will not have the error.

In this special case you will need to either use:

somestr = 'This.....at the end"'

or use the method described above of building multiple strings with mixed " and ' and then concatenating them after the fact.

How do I set the default font size in Vim?

Try a \<Space> before 12, like so:

:set guifont=Monospace\ 12

Build project into a JAR automatically in Eclipse

This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

How to import/include a CSS file using PHP code and not HTML code?

This is an older post, however as the info is still relevant today an additional option may help others.

  • Define a constant for the file path per Stefan's answer. The definition can be placed at the top of the PHP page itself, or within an included/required external file such as config.php. (http://php.net/manual/en/function.include.php)

  • Echo the constant in PHP tags, then add the filename directly after. That's it!
    Works for other linked files such as JavaScript as well.

<?php
define('CSS_PATH', 'template/css/'); //define CSS path 
define('JS_PATH', 'template/js/'); //define JavaScript path 
?>
<!-- Doctype should be declared, even in PHP file -->
<!DOCTYPE html> 
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css">
<script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script>
</head>
<body>
</body>
</html>

How to execute Python code from within Visual Studio Code

As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

How to change the default docker registry from docker.io to my private registry?

Haven't tried, but maybe hijacking the DNS resolution process by adding a line in /etc/hosts for hub.docker.com or something similar (docker.io?) could work?

Why would one mark local variables and method parameters as "final" in Java?

My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.

I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.

But, of course, it's all personal preference ;-)

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

Run multiple python scripts concurrently

I had to do this and used subprocess.

import subprocess

subprocess.run("python3 script1.py & python3 script2.py", shell=True)

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

Javascript call() & apply() vs bind()?

Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

I do this a lot:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

A simple, naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

Hope this helps.

How do I load an url in iframe with Jquery

here is Iframe in view:

<iframe class="img-responsive" id="ifmReport" width="1090" height="1200" >

    </iframe>

Load it in script:

 $('#ifmReport').attr('src', '/ReportViewer/ReportViewer.aspx');

how to change text box value with jQuery?

<style>
    .form-cus {
        width: 200px;
        margin: auto;
        position: relative;
    }
        .form-cus .putval, .form-cus .getval {
            width: 100%;
        }
        .form-cus .putval {
            position: absolute;
            left: 0px;
            top: 0;
            color: transparent !important;
            box-shadow: 0 0 0 0 !important;
            background-color: transparent !important;
            border: 0px;
            outline: 0 none;
        }
            .form-cus .putval::selection {
                color: transparent;
                background: lightblue;
            }
</style>

<link href="css/bootstrap.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<div class="form-group form-cus">
    <input class="putval form-control" type="text" id="input" maxlength="16" oninput="xText();">
    <input class="getval form-control" type="text" id="output" maxlength="16">
</div>

<script type="text/javascript">
    function xText() {
        var x = $("#input").val();
        var x_length = x.length;
        var a = '';
        for (var i = 0; i < x_length; i++) {
            a += "x";
        }
        $("#output").val(a);
     }
    $("#input").click(function(){
     $("#output").trigger("click");
    })

</script>

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I had this error message:

Error: Can't open display: localhost:13.0

This fixed it for me:

export DISPLAY="localhost:10.0"

You can use this too:

export DISPLAY="127.0.0.1:10.0"

How to change the default encoding to UTF-8 for Apache?

Just leave it empty: 'default_charset' in WHM :::::: default_charset =''

p.s. - In WHM go --------) Home »Service Configuration »PHP Configuration Editor ----) click 'Advanced Mode' ----) find 'default_charset' and leave it blank ---- just nothing, not utf8, not ISO

Check if DataRow exists by column name in c#?

You can use

try {
   user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
   // do something if you want 
}

In HTML5, should the main navigation be inside or outside the <header> element?

It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.

They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.

You can read more about it at HTML5 Doctor.

Curl : connection refused

Make sure you have a service started and listening on the port.

netstat -ln | grep 8080

and

sudo netstat -tulpn

How do I check if an array includes a value in JavaScript?

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

Of course, you may as well extend Array prototype:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

And now you can simply use the following:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Unable to allocate array with shape and data type

This is likely due to your system's overcommit handling mode.

In the default mode, 0,

Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slightly more memory in this mode. This is the default.

The exact heuristic used is not well explained here, but this is discussed more on Linux over commit heuristic and on this page.

You can check your current overcommit mode by running

$ cat /proc/sys/vm/overcommit_memory
0

In this case you're allocating

>>> 156816 * 36 * 53806 / 1024.0**3
282.8939827680588

~282 GB, and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.

If (as root) you run:

$ echo 1 > /proc/sys/vm/overcommit_memory

This will enable "always overcommit" mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).

I tested this myself on a machine with 32 GB of RAM. With overcommit mode 0 I also got a MemoryError, but after changing it back to 1 it works:

>>> import numpy as np
>>> a = np.zeros((156816, 36, 53806), dtype='uint8')
>>> a.nbytes
303755101056

You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.

Can an interface extend multiple interfaces in Java?

Yes, you can do it. An interface can extend multiple interfaces, as shown here:

interface Maininterface extends inter1, inter2, inter3 {  
  // methods
}

A single class can also implement multiple interfaces. What if two interfaces have a method defining the same name and signature?

There is a tricky point:

interface A {
    void test();
}

interface B {
    void test();
}

class C implements A, B {

    @Override
    public void test() {

    }     

}

Then single implementation works for both :).

Read my complete post here:

http://codeinventions.blogspot.com/2014/07/can-interface-extend-multiple.html

Reliable method to get machine's MAC address in C#

I really like AVee's solution with the lowest IP connection metric! But if a second nic with the same metric is installed, the MAC comparison could fail...

Better you store the description of the interface with the MAC. In later comparisons you can identify the right nic by this string. Here is a sample code:

   public static string GetMacAndDescription()
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
        IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
        string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
        string description = (from o in objects orderby o["IPConnectionMetric"] select o["Description"].ToString()).FirstOrDefault();
        return mac + ";" + description;
    }

    public static string GetMacByDescription( string description)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
        IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
        string mac = (from o in objects where o["Description"].ToString() == description select o["MACAddress"].ToString()).FirstOrDefault();
        return mac;
    }

Apply global variable to Vuejs

In your main.js file, you have to import Vue like this :

import Vue from 'vue'

Then you have to declare your global variable in the main.js file like this :

Vue.prototype.$actionButton = 'Not Approved'

If you want to change the value of the global variable from another component, you can do it like this :

Vue.prototype.$actionButton = 'approved'

https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example

How to convert CSV to JSON in Node.js

I have used csvtojson library for converting csv string to json array. It has variety of function which can help you to convert to JSON.
It also supports reading from file and file streaming.

Be careful while parsing the csv which can contain the comma(,) or any other delimiter . For removing the delimiter please see my answer here.

How to select date without time in SQL

Convert it back to datetime after converting to date in order to keep same datatime if needed

select Convert(datetime, Convert(date, getdate())  )

C++ Structure Initialization

I faced a similar problem today, where I have a struct that I want to fill with test data which will be passed as arguments to a function I'm testing. I wanted to have a vector of these structs and was looking for a one-liner method to initialize each struct.

I ended up going with a constructor function in the struct, which I believe was also suggested in a few answers to your question.

It's probably bad practice to have the arguments to the constructor have the same names as the public member variables, requiring use of the this pointer. Someone can suggest an edit if there is a better way.

typedef struct testdatum_s {
    public:
    std::string argument1;
    std::string argument2;
    std::string argument3;
    std::string argument4;
    int count;

    testdatum_s (
        std::string argument1,
        std::string argument2,
        std::string argument3,
        std::string argument4,
        int count)
    {
        this->rotation = argument1;
        this->tstamp = argument2;
        this->auth = argument3;
        this->answer = argument4;
        this->count = count;
    }

} testdatum;

Which I used in in my test function to call the function being tested with various arguments like this:

std::vector<testdatum> testdata;

testdata.push_back(testdatum("val11", "val12", "val13", "val14", 5));
testdata.push_back(testdatum("val21", "val22", "val23", "val24", 1));
testdata.push_back(testdatum("val31", "val32", "val33", "val34", 7));

for (std::vector<testdatum>::iterator i = testdata.begin(); i != testdata.end(); ++i) {
    function_in_test(i->argument1, i->argument2, i->argument3, i->argument4m i->count);
}

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

How do you share code between projects/solutions in Visual Studio?

As of VisualStudio 2015, if you keep all your code in one solution, you can share code by adding a shared project. Then add a reference to this shared project for each project you want to use the code in, as well as the proper using directives.

Windows batch script launch program and exit console

The simplest way ist just to start it with start

start notepad.exe

Here you can find more information about start

Apache VirtualHost 403 Forbidden

Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error. You would also see a log message of the form "client denied by server configuration". The feature is requiring a user identity to access a directory. It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive

Require all denied

This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:

Require all granted

as in

<Directory "your directory here">
   Order allow,deny
   Allow from all
   # New directive needed in Apache 2.4.3: 
   Require all granted
</Directory>

What's the idiomatic syntax for prepending to a short python list?

Lets go over 4 methods

  1. Using insert()
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using [] and +
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using Slicing
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using collections.deque.appendleft()
>>> 
>>> from collections import deque
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 

Handle Button click inside a row in RecyclerView

Just put an override method named getItemId Get it by right click>generate>override methods>getItemId Put this method in the Adapter class

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

Launch Minecraft from command line - username and password as prefix

To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...] Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command. Arguments are separated line by line to make it easier to find useful ones.

java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge

Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.

Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here

How to get Map data using JDBCTemplate.queryForMap

I know this is really old, but this is the simplest way to query for Map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html

How to scanf only integer and repeat reading if the user enters non-numeric characters?

Use scanf("%d",&rows) instead of scanf("%s",input)

This allow you to get direcly the integer value from stdin without need to convert to int.

If the user enter a string containing a non numeric characters then you have to clean your stdin before the next scanf("%d",&rows).

your code could look like this:

#include <stdio.h>  
#include <stdlib.h> 

int clean_stdin()
{
    while (getchar()!='\n');
    return 1;
}

int main(void)  
{ 
    int rows =0;  
    char c;
    do
    {  
        printf("\nEnter an integer from 1 to 23: ");

    } while (((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) || rows<1 || rows>23);

    return 0;  
}

Explanation

1)

scanf("%d%c", &rows, &c)

This means expecting from the user input an integer and close to it a non numeric character.

Example1: If the user enter aaddk and then ENTER, the scanf will return 0. Nothing capted

Example2: If the user enter 45 and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting \n

Example3: If the user enter 45aaadd and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting a

2)

(scanf("%d%c", &rows, &c)!=2 || c!='\n')

In the example1: this condition is TRUE because scanf return 0 (!=2)

In the example2: this condition is FALSE because scanf return 2 and c == '\n'

In the example3: this condition is TRUE because scanf return 2 and c == 'a' (!='\n')

3)

((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())

clean_stdin() is always TRUE because the function return always 1

In the example1: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

In the example2: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is FALSE so the condition after the && will not checked (because what ever its result is the whole condition will be FALSE ) so the clean_stdin() will not be executed and the whole condition is FALSE

In the example3: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

So you can remark that clean_stdin() will be executed only if the user enter a string containing non numeric character.

And this condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) will return FALSE only if the user enter an integer and nothing else

And if the condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) is FALSE and the integer is between and 1 and 23 then the while loop will break else the while loop will continue

How can I create an editable combo box in HTML/Javascript?

Forget datalist element that good solution for autocomplete function, but not for combobox feature.

css:

.combobox {
    display: inline-block;
    position: relative;
}

.combobox select {
    display: none;
    position: absolute;
    overflow-y: auto;
}

html:

<div class="combobox">
    <input type="number" name="" value="" min="" max="" step=""/><br/>
    <select size="3">
        <option value="0"> 0</option>
        <option value="25"> 25</option>
        <option value="40"> 40</option>
    </select>
</div>

js (jQuery):

$('.combobox').each(function() {
    var
        $input = $(this).find('input'),
        $select = $(this).find('select');
    function hideSelect() {
        setTimeout(function() {
            if (!$select.is(':focus') && !$input.is(':focus')) {
                $select
                    .hide()
                    .css('z-index', 1);
            }
        }, 20);
    }
    $input
        .focusin(function() {
            if (!$select.is(':visible')) {
                $select
                    .outerWidth($input.outerWidth())
                    .show()
                    .css('z-index', 100);
            }
        })
        .focusout(hideSelect)
        .on('input', function() {
            $select.val('');
        });
    $select
        .change(function() {
            $input.val($select.val());
        })
        .focusout(hideSelect);
});

This works properly even when you use text input instead of number.

adb shell command to make Android package uninstall dialog appear

You can do it from adb using this command:

adb shell am start -a android.intent.action.DELETE -d package:<your app package>

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How can I check if a View exists in a Database?

There are already many ways specified above but one of my favourite is missing..

GO
IF OBJECT_ID('nView', 'V') IS NOT NULL
    DROP VIEW nView;
GO

WHERE nView is the name of view

UPDATE 2017-03-25: as @hanesjw suggested to drop a Store Procedure use P instead of V as the second argument of OBJECT_ID

GO
IF OBJECT_ID( 'nProcedure', 'P' ) IS NOT NULL 
    DROP PROCEDURE dbo.sprocName; 
GO

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

Visualizing decision tree in scikit-learn

If you run into issues with grabbing the source .dot directly you can also use Source.from_file like this:

from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Is it possible to declare a variable in Gradle usable in Java?

https://stackoverflow.com/a/17201265/12021422 Answer by @rciovati works

But make sure you rebuild the project to be able to remove the error from Android Studio IDE

I spent 30 minutes trying to figure out why the new property variables aren't accessible.

If the "Make Project" as marked with red color doesn't work then try the "Rebuild Project" Button as marked with green color.

enter image description here

How to make Bitmap compress without change the bitmap size?

Here's a short means I used to reduce the size of Images that have a high byteCount (basically pixels)

fun resizeImage(image: Bitmap): Bitmap {

    val width = image.width
    val height = image.height

    val scaleWidth = width / 10
    val scaleHeight = height / 10

    if (image.byteCount <= 1000000)
        return image

    return Bitmap.createScaledBitmap(image, scaleWidth, scaleHeight, false)
}

This returns a scaled Bitmap that is over 10 times smaller than the Bitmap passed as a parameter. Might not be the most ideal solution but it works.

Create a pointer to two-dimensional array

In

int *ptr= l_matrix[0];

you can access like

*p
*(p+1)
*(p+2)

after all 2 dimensional arrays are also stored as 1-d.

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

get basic SQL Server table structure information

Name and datatype:

USE OurDatabaseName
GO

SELECT 
    sc.name AS [Columne Name], 
    st1.name AS [User Type],
    st2.name AS [Base Type]
FROM dbo.syscolumns sc
    INNER JOIN dbo.systypes st1 ON st1.xusertype = sc.xusertype
    INNER JOIN dbo.systypes st2 ON st2.xusertype = sc.xtype
-- STEP TWO: Change OurTableName to the table name
WHERE sc.id = OBJECT_ID('OurTableName')
ORDER BY sc.colid

Or:

SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'OurTableName'

FileSystemWatcher Changed event is raised twice

One possible 'hack' would be to throttle the events using Reactive Extensions for example:

var watcher = new FileSystemWatcher("./");

Observable.FromEventPattern<FileSystemEventArgs>(watcher, "Changed")
            .Throttle(new TimeSpan(500000))
            .Subscribe(HandleChangeEvent);

watcher.EnableRaisingEvents = true;

In this case I'm throttling to 50ms, on my system that was enough, but higher values should be safer. (And like I said, it's still a 'hack').

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me

$date = '15-12-2016';
$nameOfDay = date('D', strtotime($date));
echo $nameOfDay;

Use l instead of D, if you prefer the full textual representation of the name

Using SQL LOADER in Oracle to import CSV file

If your text is: Joe said, "Fred was here with his "Wife"".
This is saved in a CSV as:
"Joe said, ""Fred was here with his ""Wife""""."
(Rule is double quotes go around the whole field, and double quotes are converted to two double quotes). So a simple Optionally Enclosed By clause is needed but not sufficient. CSVs are tough due to this rule. You can sometimes use a Replace clause in the loader for that field but depending on your data this may not be enough. Often pre-processing of a CSV is needed to load in Oracle. Or save it as an XLS and use Oracle SQL Developer app to import to the table - great for one-time work, not so good for scripting.

How can I generate random alphanumeric strings?

Just some performance comparisons of the various answers in this thread:

Methods & Setup

// what's available
public static string possibleChars = "abcdefghijklmnopqrstuvwxyz";
// optimized (?) what's available
public static char[] possibleCharsArray = possibleChars.ToCharArray();
// optimized (precalculated) count
public static int possibleCharsAvailable = possibleChars.Length;
// shared randomization thingy
public static Random random = new Random();


// http://stackoverflow.com/a/1344242/1037948
public string LinqIsTheNewBlack(int num) {
    return new string(
    Enumerable.Repeat(possibleCharsArray, num)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());
}

// http://stackoverflow.com/a/1344258/1037948
public string ForLoop(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)];
    }
    return new string(result);
}

public string ForLoopNonOptimized(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleChars[random.Next(possibleChars.Length)];
    }
    return new string(result);
}

public string Repeat(int num) {
    return new string(new char[num].Select(o => possibleCharsArray[random.Next(possibleCharsAvailable)]).ToArray());
}

// http://stackoverflow.com/a/1518495/1037948
public string GenerateRandomString(int num) {
  var rBytes = new byte[num];
  random.NextBytes(rBytes);
  var rName = new char[num];
  while(num-- > 0)
    rName[num] = possibleCharsArray[rBytes[num] % possibleCharsAvailable];
  return new string(rName);
}

//SecureFastRandom - or SolidSwiftRandom
static string GenerateRandomString(int Length) //Configurable output string length
{
    byte[] rBytes = new byte[Length]; 
    char[] rName = new char[Length];
    SolidSwiftRandom.GetNextBytesWithMax(rBytes, biasZone);
    for (var i = 0; i < Length; i++)
    {
        rName[i] = charSet[rBytes[i] % charSet.Length];
    }
    return new string(rName);
}

Results

Tested in LinqPad. For string size of 10, generates:

  • from Linq = chdgmevhcy [10]
  • from Loop = gtnoaryhxr [10]
  • from Select = rsndbztyby [10]
  • from GenerateRandomString = owyefjjakj [10]
  • from SecureFastRandom = VzougLYHYP [10]
  • from SecureFastRandom-NoCache = oVQXNGmO1S [10]

And the performance numbers tend to vary slightly, very occasionally NonOptimized is actually faster, and sometimes ForLoop and GenerateRandomString switch who's in the lead.

  • LinqIsTheNewBlack (10000x) = 96762 ticks elapsed (9.6762 ms)
  • ForLoop (10000x) = 28970 ticks elapsed (2.897 ms)
  • ForLoopNonOptimized (10000x) = 33336 ticks elapsed (3.3336 ms)
  • Repeat (10000x) = 78547 ticks elapsed (7.8547 ms)
  • GenerateRandomString (10000x) = 27416 ticks elapsed (2.7416 ms)
  • SecureFastRandom (10000x) = 13176 ticks elapsed (5ms) lowest [Different machine]
  • SecureFastRandom-NoCache (10000x) = 39541 ticks elapsed (17ms) lowest [Different machine]

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Access camera from a browser

The HTML5 spec does allow accessing the webcamera, but last I checked, it is far from finalized, and has very, very little browser support.

This is a link to get you started: http://www.html5rocks.com/en/tutorials/getusermedia/intro/

You'll probably have to use flash if you want it to work cross-browser.

W3 draft

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

What is the difference between buffer and cache memory in Linux?

I think this page will help understanding the difference between buffer and cache deeply. http://www.tldp.org/LDP/sag/html/buffer-cache.html

Reading from a disk is very slow compared to accessing (real) memory. In addition, it is common to read the same part of a disk several times during relatively short periods of time. For example, one might first read an e-mail message, then read the letter into an editor when replying to it, then make the mail program read it again when copying it to a folder. Or, consider how often the command ls might be run on a system with many users. By reading the information from disk only once and then keeping it in memory until no longer needed, one can speed up all but the first read. This is called disk buffering, and the memory used for the purpose is called the buffer cache.

Since memory is, unfortunately, a finite, nay, scarce resource, the buffer cache usually cannot be big enough (it can't hold all the data one ever wants to use). When the cache fills up, the data that has been unused for the longest time is discarded and the memory thus freed is used for the new data.

Disk buffering works for writes as well. On the one hand, data that is written is often soon read again (e.g., a source code file is saved to a file, then read by the compiler), so putting data that is written in the cache is a good idea. On the other hand, by only putting the data into the cache, not writing it to disk at once, the program that writes runs quicker. The writes can then be done in the background, without slowing down the other programs.

How to check whether an object is a date?

I have been using a much simpler way but am not sure if this is only available in ES6 or not.

let a = {name: "a", age: 1, date: new Date("1/2/2017"), arr: [], obj: {} };
console.log(a.name.constructor.name); // "String"
console.log(a.age.constructor.name);  // "Number"
console.log(a.date.constructor.name); // "Date"
console.log(a.arr.constructor.name);  // "Array"
console.log(a.obj.constructor.name);  // "Object"

However, this will not work on null or undefined since they have no constructor.

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

React Router v4 - How to get current route?

In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.

import { useLocation } from 'react-router-dom'

function HeaderView() {
  const location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}

How to define a variable in a Dockerfile?

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.


This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

how does int main() and void main() work

If you really want to understand ANSI C 89, I need to correct you in one thing; In ANSI C 89 the difference between the following functions:

int main()
int main(void)
int main(int argc, char* argv[])

is:

int main()

  • a function that expects unknown number of arguments of unknown types. Returns an integer representing the application software status.

int main(void)

  • a function that expects no arguments. Returns an integer representing the application software status.

int main(int argc, char * argv[])

  • a function that expects argc number of arguments and argv[] arguments. Returns an integer representing the application software status.

About when using each of the functions

int main(void)

  • you need to use this function when your program needs no initial parameters to run/ load (parameters received from the OS - out of the program it self).

int main(int argc, char * argv[])

  • you need to use this function when your program needs initial parameters to load (parameters received from the OS - out of the program it self).

About void main()

In ANSI C 89, when using void main and compiling the project AS -ansi -pedantic (in Ubuntu, e.g) you will receive a warning indicating that your main function is of type void and not of type int, but you will be able to run the project. Most C developers tend to use int main() on all of its variants, though void main() will also compile.

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Best way to repeat a character in C#

Albeit very similar to a previous suggestion, I like to keep it simple and apply the following:

string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");

Standard .Net really,

Push method in React Hooks (useState)?

To expand a little further, here are some common examples. Starting with:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

C++ - struct vs. class

You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.

A quick Google search suggests that POD stands for "Plain Old Data".

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Lodash - difference between .extend() / .assign() and .merge()

Another difference to pay attention to is handling of undefined values:

mergeInto = { a: 1}
toMerge = {a : undefined, b:undefined}
lodash.extend({}, mergeInto, toMerge) // => {a: undefined, b:undefined}
lodash.merge({}, mergeInto, toMerge)  // => {a: 1, b:undefined}

So merge will not merge undefined values into defined values.

GitHub "fatal: remote origin already exists"

for using git you have to be

root

if not then use sudo

for removing origin :

git remote remove origin

for adding origin :

git remote add origin http://giturl

How to change ViewPager's page?

I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num ). That allows you to programatically switch to another page within the ViewPager.

I'd need to see a stack trace from logcat to be more specific if this is not the problem.

How do I remove blank elements from an array?

Here is a solution if you have mixed types in your array:

[nil,"some string here","",4,3,2]

Solution:

[nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}

Output:

=> ["some string here", 4, 3, 2]

jQuery delete confirmation box

Try with below code:

$('.close').click(function(){
var checkstr =  confirm('are you sure you want to delete this?');
if(checkstr == true){
  // do your code
}else{
return false;
}
});

OR

function deleteItem(){
    var checkstr =  confirm('are you sure you want to delete this?');
    if(checkstr == true){
      // do your code
    }else{
    return false;
    }
  }

This may work for you..

Thanks.

Configuring RollingFileAppender in log4j

Regarding error: log4j:ERROR Element type "rollingPolicy" must be declared

  1. Use a log4j.jar version newer than log4j-1.2.14.jar, which has a log4j.dtd defining rollingPolicy.
  2. of course you also need apache-log4j-extras-1.1.jar
  3. Check if any other third party jars you are using perhaps have an older version of log4j.jar packed inside. If so, make sure your log4j.jar comes first in the order before the third party containing the older log4j.jar.

How to set custom ActionBar color / style?

Custom Color:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

                <item name="colorPrimary">@color/ColorPrimary</item>
                <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
                <!-- Customize your theme here. -->
     </style>

Custom Style:

 <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>

For More: Android ActionBar

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

  1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt
  2. Go to your JRE_HOME/bin or JDK/JRE/bin
  3. Type the command
  4. keytool -keystore ..\lib\security\cacerts -import -alias your.ssl.server.name -file .\relative-path-to-cert-file\your.ssl.server.name.crt
  5. Restart your Java process

Getters \ setters for dummies

What's so confusing about it... getters are functions that are called when you get a property, setters, when you set it. example, if you do

obj.prop = "abc";

You're setting the property prop, if you're using getters/setters, then the setter function will be called, with "abc" as an argument. The setter function definition inside the object would ideally look something like this:

set prop(var) {
   // do stuff with var...
}

I'm not sure how well that is implemented across browsers. It seems Firefox also has an alternative syntax, with double-underscored special ("magic") methods. As usual Internet Explorer does not support any of this.

How to change value of ArrayList element in java

The list is maintaining an object reference to the original value stored in the list. So when you execute this line:

Integer x = i.next();

Both x and the list are storing a reference to the same object. However, when you execute:

x = Integer.valueOf(9);

nothing has changed in the list, but x is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as

list.set(index, Integer.valueof(9))

Note: this has nothing to do with the immutability of Integer, as others are suggesting. This is just basic Java object reference behaviour.


Here's a complete example, to help explain the point. Note that this makes use of the ListIterator class, which supports removing/setting items mid-iteration:

import java.util.*;

public class ListExample {

  public static void main(String[] args) {

    List<Foo> fooList = new ArrayList<Foo>();
    for (int i = 0; i < 9; i++)
      fooList.add(new Foo(i, i));

    // Standard iterator sufficient for altering elements
    Iterator<Foo> iterator = fooList.iterator();

    if (iterator.hasNext()) {
      Foo foo = iterator.next();
      foo.x = 99;
      foo.y = 42;
    }

    printList(fooList);    

    // List iterator needed for replacing elements
    ListIterator<Foo> listIterator = fooList.listIterator();

    if (listIterator.hasNext()) {
      // Need to call next, before set.
      listIterator.next();
      // Replace item returned from next()
      listIterator.set(new Foo(99,99));
    }

    printList(fooList);
  }

  private static void printList(List<?> list) {
    Iterator<?> iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
    System.out.println();
  }

  private static class Foo {
    int x;
    int y;

    Foo(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public String toString() {
      return String.format("[%d, %d]", x, y);
    }
  }
}

This will print:

[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]

How do I start PowerShell from Windows Explorer?

Windows 10 made it much easier. You can either:

  • SHIFT + Mouse Right Click on a folder, and you get a menu item Open PowerShell window here.

Or you can:

  • File -> Open Windows PowerShell.

And for a bonus ...

If you Mouse Right Click on File -> Open Windows PowerShell, then you can Add to Quick Access Toolbar:

enter image description here

Which puts a handy icon here:

enter image description here

And now you can just click that icon. :)

Basic HTTP authentication with Node and Express 4

I used the code for the original basicAuth to find the answer:

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

Match two strings in one line with grep

I think this is what you were looking for:

grep -E "string1|string2" filename

I think that answers like this:

grep 'string1.*string2\|string2.*string1' filename

only match the case where both are present, not one or the other or both.

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

Message 'src refspec master does not match any' when pushing commits in Git

If you are using Git Bash on Windows, try restarting it. It worked for me!

Oracle Age calculation from Date of birth and Today

select (extract(year from current_date)-extract(year from Date_of_birth)) as Age from table_name;`

age=current_year - birth_year;

extract(year/month/date from date) //oracle function for extracting values from date

Spring configure @ResponseBody JSON format

You can do the following(jackson version < 2):

Custom mapper class:

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        super.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
        super.getSerializationConfig()
                .setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
        super.getSerializationConfig()
                .set(SerializationConfig.Feature.INDENT_OUTPUT, false);
    }
}

Spring config:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper">
                <bean class="package.CustomObjectMapper"/>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Android: How to Programmatically set the size of a Layout

You can get the actual height of called layout with this code:

public int getLayoutSize() {
// Get the layout id
    final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
    final AtomicInteger layoutHeight = new AtomicInteger();

    root.post(new Runnable() { 
    public void run() { 
        Rect rect = new Rect(); 
        Window win = getWindow();  // Get the Window
                win.getDecorView().getWindowVisibleDisplayFrame(rect);

                // Get the height of Status Bar
                int statusBarHeight = rect.top;

                // Get the height occupied by the decoration contents 
                int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();

                // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop  
                int titleBarHeight = contentViewTop - statusBarHeight; 
                Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop); 

                // By now we got the height of titleBar & statusBar
                // Now lets get the screen size
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);   
                int screenHeight = metrics.heightPixels;
                int screenWidth = metrics.widthPixels;
                Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);   

                // Now calculate the height that our layout can be set
                // If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also 
                layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
                Log.i("MY", "Layout Height = " + layoutHeight);   

            // Lastly, set the height of the layout       
            FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
            rootParams.height = layoutHeight.get();
            root.setLayoutParams(rootParams);
        }
    });

return layoutHeight.get();
}

Chrome disable SSL checking for sites?

To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

Detect when browser receives file download

Based on Elmer's example I've prepared my own solution. After elements click with defined download class it lets to show custom message on the screen. I've used focus trigger to hide the message.

JavaScript

$(function(){$('.download').click(function() { ShowDownloadMessage(); }); })

function ShowDownloadMessage()
{
     $('#message-text').text('your report is creating, please wait...');
     $('#message').show();
     window.addEventListener('focus', HideDownloadMessage, false);
}

function HideDownloadMessage(){
    window.removeEventListener('focus', HideDownloadMessage, false);                   
    $('#message').hide();
}

HTML

<div id="message" style="display: none">
    <div id="message-screen-mask" class="ui-widget-overlay ui-front"></div>
    <div id="message-text" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable waitmessage">please wait...</div>
</div>

Now you should implement any element to download:

<a class="download" href="file://www.ocelot.com.pl/prepare-report">Download report</a>

or

<input class="download" type="submit" value="Download" name="actionType">

After each download click you will see message your report is creating, please wait...

Read file-contents into a string in C++

The most efficient, but not the C++ way would be:

   FILE* f = fopen(filename, "r");

   // Determine file size
   fseek(f, 0, SEEK_END);
   size_t size = ftell(f);

   char* where = new char[size];

   rewind(f);
   fread(where, sizeof(char), size, f);

   delete[] where;

#EDIT - 2

Just tested the std::filebuf variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.

   std::ifstream file(filename, std::ios::binary);
   std::streambuf* raw_buffer = file.rdbuf();

   char* block = new char[size];
   raw_buffer->sgetn(block, size);
   delete[] block;

I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary and rb) modes.

[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN      ] IO.C_Kotti
[       OK ] IO.C_Kotti (78 ms)
[ RUN      ] IO.CPP_Nikko
[       OK ] IO.CPP_Nikko (106 ms)
[ RUN      ] IO.CPP_Beckmann
[       OK ] IO.CPP_Beckmann (1891 ms)
[ RUN      ] IO.CPP_Neil
[       OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[  PASSED  ] 4 tests.

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

How to Get JSON Array Within JSON Object?

  Gson gson = new Gson();
                Type listType = new TypeToken<List<Data>>() {}.getType();
                List<Data>     cartProductList = gson.fromJson(response.body().get("data"), listType);
                Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();

Setting Action Bar title and subtitle

Try this one:

android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("This is Title");
ab.setSubtitle("This is Subtitle");

How to implement LIMIT with SQL Server?

Starting with SQL SERVER 2012, you can use the OFFSET FETCH Clause:

USE AdventureWorks;
GO
SELECT SalesOrderID, OrderDate
FROM Sales.SalesOrderHeader 
ORDER BY SalesOrderID
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY;
GO

http://msdn.microsoft.com/en-us/library/ms188385(v=sql.110).aspx

This may not work correctly when the order by is not unique.

If the query is modified to ORDER BY OrderDate, the result set returned is not as expected.

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

EF LINQ include multiple and nested entities

this is from my project

 var saleHeadBranch = await _context.SaleHeadBranch
 .Include(d => d.SaleDetailBranch)
 .ThenInclude(d => d.Item)
 .Where(d => d.BranchId == loginTkn.branchId)
 .FirstOrDefaultAsync(d => d.Id == id);

Compare two dates with JavaScript

function datesEqual(a, b)
{
   return (!(a>b || b>a))
}

How do you write multiline strings in Go?

Go and multiline strings

Using back ticks you can have multiline strings:

package main

import "fmt"

func main() {

    message := `This is a 
Multi-line Text String
Because it uses the raw-string back ticks 
instead of quotes.
`

    fmt.Printf("%s", message)
}

Instead of using either the double quote (“) or single quote symbols (‘), instead use back-ticks to define the start and end of the string. You can then wrap it across lines.

If you indent the string though, remember that the white space will count.

Please check the playground and do experiments with it.