Programs & Examples On #.net 4.0 beta 2

Version 4.0 Beta 2 of the .NET Framework, it accompanied the release of Visual Studio 2010 Beta 2.

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

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

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

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

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

Fastest way to set all values of an array?

Arrays.fill(myArray, 'c');

Arrays.fill

Although it is quite possible that this is doing the loop in the background and is therefore not any more efficient than what you have (other than the lines of code savings). If you really care about efficiency, try the following in comparison to the above:

int size = 50;
char[] array = new char[size];
for (int i=0; i<size; i++){
  array[i] = 'c';
}

Notice that the above doesn't call array.size() for each iteration.

Listing files in a directory matching a pattern in Java

What about a wrapper around your existing code:

public Collection<File> getMatchingFiles( String directory, String extension ) {
     return new ArrayList<File>()( 
         getAllFilesThatMatchFilenameExtension( directory, extension ) );
 }

I will throw a warning though. If you can live with that warning, then you're done.

How to hide keyboard in swift on pressing return key?

Swift 3

Add this code below to your VC

//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true);
    return false;
}

Works for me

How do I rotate text in css?

I guess this is what you are looking for?

Added an example:

The html:

<div class="example-date">
  <span class="day">31</span> 
  <span class="month">July</span> 
  <span class="year">2009</span>
</div>

The css:

.year
{
    display:block;
    -webkit-transform: rotate(-90deg); 
    -moz-transform: rotate(-90deg); 
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); //For IE support
}

Alle examples are from the mentioned site.

How to create a zip file in Java

Here is an example code to compress a Whole Directory(including sub files and sub directories), it's using the walk file tree feature of Java NIO.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To use this, just call

ZipCompress.compress("target/directoryToCompress");

and you'll get a zip file directoryToCompress.zip

How do I find the time difference between two datetime objects in python?

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> seconds_in_day = 24 * 60 * 60
datetime.timedelta(0, 8, 562000)
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference. In the example above it is 0 minutes, 8 seconds and 562000 microseconds.

C# HttpClient 4.5 multipart/form-data upload

It works more or less like this (example using an image/jpg file):

async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
    var requestContent = new MultipartFormDataContent(); 
    //    here you can specify boundary if you need---^
    var imageContent = new ByteArrayContent(ImageData);
    imageContent.Headers.ContentType = 
        MediaTypeHeaderValue.Parse("image/jpeg");

    requestContent.Add(imageContent, "image", "image.jpg");

    return await client.PostAsync(url, requestContent);
}

(You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)

When completed, you'll find the response content inside HttpResponseMessage.Content that you can consume with HttpContent.ReadAs*Async.

reading from app.config file

This:

Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);

works fine for me.

Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.

Also, be sure you set system.configuration.dll as a reference in your project or build script.

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

CSS to make table 100% of max-width

I had to use:

table, tbody {
    width: 100%;
}

The table alone wasn't enough, the tbody was also needed for it to work for me.

RegEx to parse or validate Base64 data

The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex

which is in the current version looks like:

module.exports = function (opts) {
  opts = opts || {};
  var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';

  return opts.exact ? new RegExp('(?:^' + regex + '$)') :
                    new RegExp('(?:^|\\s)' + regex, 'g');
};

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

If you want to style the output of a data frame in a jupyter notebook cell, you can set the display style on a per-dataframe basis:

df = pd.DataFrame({'A': np.random.randn(4)*1e7})
df.style.format("{:.1f}")

enter image description here

See the documentation here.

How to run vbs as administrator from vbs?

If UAC is enabled on the computer, something like this should work:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

'actual code

How to make rpm auto install dependencies

For me worked just with

# yum install ffmpeg-2.6.4-1.fc22.x86_64.rpm

And automatically asked authorization to dowload the depedencies. Below the example, i am using fedora 22

[root@localhost lukas]# yum install ffmpeg-2.6.4-1.fc22.x86_64.rpm
Yum command has been deprecated, redirecting to '/usr/bin/dnf install  ffmpeg-2.6.4-1.fc22.x86_64.rpm'.
See 'man dnf' and 'man yum2dnf' for more information.
To transfer transaction metadata from yum to DNF, run:
'dnf install python-dnf-plugins-extras-migrate && dnf-2 migrate'

Last metadata expiration check performed 0:28:24 ago on Fri Sep 25 12:43:44 2015.
Dependencies resolved.
====================================================================================================================
 Package               Arch           Version                                  Repository                      Size
====================================================================================================================
Installing:
 SDL                   x86_64         1.2.15-17.fc22                           fedora                         214 k
 ffmpeg                x86_64         2.6.4-1.fc22                             @commandline                   1.5 M
 ffmpeg-libs           x86_64         2.6.4-1.fc22                             rpmfusion-free-updates         5.0 M
 fribidi               x86_64         0.19.6-3.fc22                            fedora                          69 k
 lame-libs             x86_64         3.99.5-5.fc22                            rpmfusion-free                 345 k
 libass                x86_64         0.12.1-1.fc22                            updates                         85 k
 libavdevice           x86_64         2.6.4-1.fc22                             rpmfusion-free-updates          75 k
 libdc1394             x86_64         2.2.2-3.fc22                             fedora                         124 k
 libva                 x86_64         1.5.1-1.fc22                             fedora                          79 k
 openal-soft           x86_64         1.16.0-5.fc22                            fedora                         292 k
 opencv-core           x86_64         2.4.11-5.fc22                            updates                        1.9 M
 openjpeg-libs         x86_64         1.5.1-14.fc22                            fedora                          89 k
 schroedinger          x86_64         1.0.11-7.fc22                            fedora                         315 k
 soxr                  x86_64         0.1.2-1.fc22                             updates                         83 k
 x264-libs             x86_64         0.142-12.20141221git6a301b6.fc22         rpmfusion-free                 587 k
 x265-libs             x86_64         1.6-1.fc22                               rpmfusion-free                 486 k
 xvidcore              x86_64         1.3.2-6.fc22                             rpmfusion-free                 264 k

Transaction Summary
====================================================================================================================
Install  17 Packages

Total size: 11 M
Total download size: 9.9 M
Installed size: 35 M
Is this ok [y/N]: y

Convert Xml to DataTable

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

ldap_bind: Invalid Credentials (49)

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

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

Try an explicit URI:

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

or prevent defaults with:

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

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

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

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

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

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

    slapd -h ldap://localhost -d 481

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

  • if debug is enabled, then try also

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

Task vs Thread differences

Source

Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

How to include static library in makefile

CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine
LIBS = libmine.a -lpthread 

Escaping single quote in PHP when inserting into MySQL

For anyone finding this solution in 2015 and moving forward...

The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.

See: php.net

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_real_escape_string()

PDO::quote()

How to print a stack trace in Node.js?

In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link

Then walk through the trace.

  var stackTrace = require('stack-trace');
  .
  .
  .
  var trace = stackTrace.get();
  trace.map(function (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  
  });

Or just simply print the trace:

var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

Unable to open a file with fopen()

A little error checking goes a long way -- you can always test the value of errno or call perror() or strerror() to get more information about why the fopen() call failed.

Otherwise the suggestions about checking the path are probably correct... most likely you're not in the directory you think you are from the IDE and don't have the permissions you expect.

CSS: center element within a <div> element

I have found another solution

<style type="text/css">
    .container {
        width:600px; //set how much you want
        overflow: hidden; 
        position: relative;
     }
     .containerSecond{
        position: absolute; 
        top:0px; 
        left:-500%; 
        width:1100%;
     }
     .content{
        width: 800px; //your content size 
        margin:0 auto;
     }           
</style>

and in body

<div class="container">
   <div class="containerSecond">
       <div class="content"></div>
   </div>
</div>

This will center your content div whenever your container is bigger or smaller. In this case your content should be bigger than 1100% of container to not be centered, but in that case you can make with of containerSecond bigger, and it will work

How to Convert date into MM/DD/YY format in C#

See, here you can get only date by passing a format string. You can get a different date format as per your requirement as given below for current date:

DateTime.Now.ToString("M/d/yyyy");

Result : "9/1/2016"

DateTime.Now.ToString("M-d-yyyy");

Result : "9-1-2016"

DateTime.Now.ToString("yyyy-MM-dd");

Result : "2016-09-01"

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

Result : "2016-09-01 09:20:10"

For more details take a look at MSDN reference for Custom Date and Time Format Strings

How do you easily create empty matrices javascript?

There is something about Array.fill I need to mention.

If you just use below method to create a 3x3 matrix.

Array(3).fill(Array(3).fill(0));

You will find that the values in the matrix is a reference.

enter image description here


Optimized solution (prevent passing by reference):

If you want to pass by value rather than reference, you can leverage Array.map to create it.

Array(3).fill(null).map(() => Array(3).fill(0));

enter image description here

JFrame Maximize window

Provided that you are extending JFrame:

public void run() {
    MyFrame myFrame = new MyFrame();
    myFrame.setVisible(true);
    myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}

How to hide element using Twitter Bootstrap and show it using jQuery?

Twitter Bootstrap provides classes for toggling content, see https://github.com/twbs/bootstrap/blob/3ee5542c990817324f0a07b97d01d1fe206fd8d6/less/utilities.less.

I'm completely new to jQuery, and after reading their docs I came to another solution to combine Twitter Bootstrap + jQuery.

First, the solution to 'hide' and 'show' an element (class wsis-collapse) when clicking on another element (class wsis-toggle), is to use .toggle.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle();
    });
});

You already have hidden the element .wsis-collapse by using Twitter Bootstrap (V3) class .hidden also:

.hidden {
  display: none !important;
  visibility: hidden !important;
}

When you click on .wsis-toggle, the jQuery is adding an inline style:

display: block

Because of the !important in the Twitter Bootstrap, this inline style has no effect, so we need to remove the .hidden class, but I won't recommend .removeClass for this! Because when jQuery is going to hide something again, it's also adding an inline style:

display: none

This is not the same as the .hidden class of Twitter Bootstrap, which is optimized for AT as well (screen readers). So, if we want to show the hidden div, we need to get rid of the .hidden class of Twitter Bootstrap, so we get rid of the important statements, but if we hide it again, we want to have the .hidden class back again! We can using [.toggleClass][3] for this.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden" );
    });
});

This way you keep using the hidden class every time the content is hidden.

The .show class in TB is actually the same as the inline style of the jQuery, both 'display: block'. But if the .show class at some point will be different, then you simply add this class as well:

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden show" );
    });
});

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())

Find and replace string values in list

An example with for loop (I prefer List Comprehensions).

a, b = '[br]', '<br />'
for i, v in enumerate(words):
    if a in v:
        words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

Cannot install Aptana Studio 3.6 on Windows

I had a problem installing Aptana 3.6.1 on my windows machine. It always shows "fail to locate node.js installer missing windows msi" No matter how many times I tried to.

Here is how I solved the problem:

  1. Install Git: This link is for windows and will automatically have the file ready to dowload https://git-scm.com/download/win

  2. Instead of installing the latest version, I chose a little earlier version (also 3) but it's 3.2.2 instead of 3.61 (the current one on the Aptana page) : http://www.filehorse.com/download-aptana/11489/

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

Stop mouse event propagation

I just checked in an Angular 6 application, the event.stopPropagation() works on an event handler without even passing $event

(click)="doSomething()"  // does not require to pass $event


doSomething(){
   // write any code here

   event.stopPropagation();
}

eval command in Bash and its typical uses

The eval statement tells the shell to take eval’s arguments as command and run them through the command-line. It is useful in a situation like below:

In your script if you are defining a command into a variable and later on you want to use that command then you should use eval:

/home/user1 > a="ls | more"
/home/user1 > $a
bash: command not found: ls | more
/home/user1 > # Above command didn't work as ls tried to list file with name pipe (|) and more. But these files are not there
/home/user1 > eval $a
file.txt
mailids
remote_cmd.sh
sample.txt
tmp
/home/user1 >

"Cannot GET /" with Connect on Node.js

The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:

var harp = require("harp")
harp.server(projectPath [,args] [,callback])

Hope this helps.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

In case of shared hosting when you do not have command line access simply navigate to laravel/bootstrap/cache folder and delete (or rename) config.php and you are all done!

number_format() with MySQL

At least as far back as MySQL 5.5 you can use format:

SELECT FORMAT(123456789.123456789,2);
/* produces 123,456,789.12 */

SELECT FORMAT(123456789.123456789,2,'de_DE');
/* 
    produces 123.456.789,12
    note the swapped . and , for the de_DE locale (German-Germany) 
*/

From the MySQL docs: https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format

Available locales are listed elsewhere in the docs: https://dev.mysql.com/doc/refman/5.5/en/locale-support.html

Maximum length of HTTP GET request

A similar question is here: Is there a limit to the length of a GET request?

I've hit the limit and on my shared hosting account, but the browser returned a blank page before it got to the server I think.

How do I programmatically click a link with javascript?

Simply like that :

<a id="myLink" onclick="alert('link click');">LINK 1</a>
<a id="myLink2" onclick="document.getElementById('myLink').click()">Click link 1</a>

or at page load :

<body onload="document.getElementById('myLink').click()">
...
<a id="myLink" onclick="alert('link click');">LINK 1</a>
...
</body>

Java Error: illegal start of expression

Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.

In the case of local variables you can not use any kind of accessor (public, protected or private).

You should also know what the static keyword means. In method checkYourself, you use the Integer array locations.

The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.

public class Test { //Capitalized name for classes are used in Java
   private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later. 

   public Test(int[] locations) {
      this.locations = locations;//To access to class member, when method argument has the same name use `this` key word. 
   }

   public boolean checkYourSelf(int value) { //This method is accessed only from a object.
      for(int location : locations) {
         if(location == value) {
            return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
         }
      }
      return false; //Method should be simple and perform one task. So you can get more flexibility. 
   }
   public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it. 

   public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
      Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.  
      String result;
      if(test.checkYourSelf(2)) {//We moved outside the string
        result = "Hurray";        
      } else {
        result = "Try again"
      }
      System.out.println(result); //We have only one place where write is done. Easy to change in future.
   } 
}

Ignoring new fields on JSON objects using Jackson

Starting with Jackson version 2.4 and above there have been some changes. Here is how you do it now:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

..........................................................................

 ObjectMapper mapper = new ObjectMapper();
    // to prevent exception when encountering unknown property:
 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Note: The @annotation based solution remains the same so if you like to use that see the other answers.

For more information see the 10 minutes Configuration tutorial at: https://github.com/FasterXML/jackson-databind

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

Java character array initializer

you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.

or even simpler just use String.charAt() in the loop to populate array like below:

String ini="Hi there";
  char[] array=new  char[ini.length()];

  for(int count=0;count<array.length;count++){
         array[count] = ini.charAt(count);
  System.out.print(" "+array[count]);
  }

or one liner would be

  String ini="Hi there";
  char[] array=ini.toCharArray();

event.preventDefault() function not working in IE

To disable a keyboard key after IE9, use : e.preventDefault();

To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;

If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :

try {
    e.keyCode = 0;
}catch (e) {}

Here is a full example for IE7/8 only :

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Reference : How to disable keyboard shortcuts in IE7 / IE8

Difference between ${} and $() in Bash

  1. your understanding is right. For detailed info on {} see bash ref - parameter expansion

  2. 'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.

With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done in essence manage everything about the iteration yourself

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How do I set the time zone of MySQL?

This work for me for a location in India:

SET GLOBAL time_zone = "Asia/Calcutta";
SET time_zone = "+05:30";
SET @@session.time_zone = "+05:30";

How to manually trigger click event in ReactJS?

You can use ref callback which will return the node. Call click() on that node to do a programmatic click.

Getting the div node

clickDiv(el) {
  el.click()
}

Setting a ref to the div node

<div 
  id="element1"
  className="content"
  ref={this.clickDiv}
  onClick={this.uploadLogoIcon}
>

Check the fiddle

https://jsfiddle.net/pranesh_ravi/5skk51ap/1/

Hope it helps!

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Stop all active ajax requests in jQuery

Just as important: say you want to log off and you are generating new requests with timers: because session data is renewed with each new bootstrap (maybe you can tell I am talking Drupal, but this could be any site that uses sessions)... I had to go through all my scripts with a search and replace, cause I had a ton of stuff running in different cases: global variables at the top:

var ajReq = [];
var canAj = true;
function abort_all(){
 for(x in ajReq){
    ajReq[x].abort();
    ajReq.splice(x, 1)
 }
 canAj = false;
}
function rmvReq(ranNum){
 var temp = [];
 var i = 0;
 for(x in ajReq){
    if(x == ranNum){
     ajReq[x].abort();
     ajReq.splice(x, 1);
    }
    i++;
 }
}
function randReqIndx(){
 if(!canAj){ return 0; }
 return Math.random()*1000;
}
function getReqIndx(){
 var ranNum;
 if(ajReq.length){
    while(!ranNum){
     ranNum = randReqIndx();
     for(x in ajReq){
    if(x===ranNum){
     ranNum = null;
    }
     }
    }
    return ranMum;
 }
 return randReqIndx();
}
$(document).ready(function(){
 $("a").each(function(){
    if($(this).attr('href').indexOf('/logout')!=-1){          
     $(this).click(function(){
    abort_all();                 
     });
    }
 })
});
// Then in all of my scripts I wrapped my ajax calls... If anyone has a suggestion for a 
    // global way to do this, please post
var reqIndx = getReqIndx();
if(reqIndx!=0){
ajReq[reqIndx] = $.post(ajax, { 'action': 'update_quantities', iids:iidstr, qtys:qtystr },  
function(data){
 //..do stuff
 rmvReq(reqIndx);
 },'json');
}

PHP remove special character from string

<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string); 
echo $string = str_replace( array( '-', '.' ), '', $string);
?>

Converting between datetime, Timestamp and datetime64

This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.

I have come across another way to do the conversion that only involves modules numpy and datetime, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime) will return a datetime.datetime object if the original datetime64 is in micro-second units while other units return an integer timestamp. I use module xarray for data I/O from Netcdf files which uses the datetime64 in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,

import numpy as np
import datetime

def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
    t = np.datetime64( usert, 'us').astype(datetime.datetime)
return t

Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.

How to cherry-pick from a remote branch?

Since "zebra" is a remote branch, I was thinking I don't have its data locally.

You are correct that you don't have the right data, but tried to resolve it in the wrong way. To collect data locally from a remote source, you need to use git fetch. When you did git checkout zebra you switched to whatever the state of that branch was the last time you fetched. So fetch from the remote first:

# fetch just the one remote
git fetch <remote>
# or fetch from all remotes
git fetch --all
# make sure you're back on the branch you want to cherry-pick to
git cherry-pick xyz

Shell equality operators (=, ==, -eq)

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

Finally, I usually prefer to use the form if [ "$a" == "$b" ]

How to use putExtra() and getExtra() for string data

Put String in Intent Object

  Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
  intent.putExtra("key",your_String);
  StartActivity(intent);

NextAcitvity in onCreate method get String

String my_string=getIntent().getStringExtra("key");

that is easy and short method

Reimport a module in python while interactive

Another small point: If you used the import some_module as sm syntax, then you have to re-load the module with its aliased name (sm in this example):

>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

"Comparison method violates its general contract!"

In my case, it was an infinite sort. That is, at first the line moved up according to the condition, and then the same line moved down to the same place. I added one more condition at the end that unambiguously established the order of the lines.

How to find MAC address of an Android device programmatically

It's Working

    package com.keshav.fetchmacaddress;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Collections;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Log.e("keshav","getMacAddr -> " +getMacAddr());
        }
    
        public static String getMacAddr() {
            try {
                List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface nif : all) {
                    if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
    
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }
    
                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        // res1.append(Integer.toHexString(b & 0xFF) + ":");
                        res1.append(String.format("%02X:",b)); 
                    }
    
                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            } catch (Exception ex) {
                //handle exception
            }
            return "";
        }
    }

UPDATE 1

This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.

 StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    // res1.append(Integer.toHexString(b & 0xFF) + ":");
                    res1.append(String.format("%02X:",b)); 
                }

How to make a HTTP PUT request?


protected void UpdateButton_Click(object sender, EventArgs e)
        {
            var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
            var bytes = Encoding.ASCII.GetBytes(values);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
            request.Method = "PUT";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            var response =  (HttpWebResponse) request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
                UpdateResponseLabel.Text = "Update completed";
            else
                UpdateResponseLabel.Text = "Error in update";
        }

How to add a default "Select" option to this ASP.NET DropDownList control?

I have tried with following code. it's working for me fine

ManageOrder Order = new ManageOrder();
Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString());
Organization.DataValueField = "OrganisationID";
Organization.DataTextField = "OrganisationName";                
Organization.DataBind();                
Organization.Items.Insert(0, new ListItem("Select Organisation", "0"));

Get file from project folder java

If you don't specify any path and put just the file (Just like you did), the default directory is always the one of your project (It's not inside the "src" folder. It's just inside the folder of your project).

How to use background thread in swift?

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
    // Conversion into base64 string
    self.uploadImageString =  uploadPhotoDataJPEG.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
})

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Difference between require, include, require_once and include_once?

There are require and include_once as well.

So your question should be...

  1. When should I use require vs. include?
  2. When should I use require_once vs. require

The answer to 1 is described here.

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The answer to 2 can be found here.

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

disable viewport zooming iOS 10+ safari?

I've been able to fix this using the touch-action css property on individual elements. Try setting touch-action: manipulation; on elements that are commonly clicked on, like links or buttons.

append new row to old csv file python

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using 'a' for appending when you open the file.

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using 'ab' instead of 'a' this will, however, cause you TypeError: a bytes-like object is required, not 'str' in python and CSV in Python 3.6. Adding the newline='', as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

SVG gradient using CSS

Here is a solution where you can add a gradient and change its colours using only CSS:

_x000D_
_x000D_
// JS is not required for the solution. It's used only for the interactive demo._x000D_
const svg = document.querySelector('svg');_x000D_
document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green'));_x000D_
document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red'));
_x000D_
svg.green stop:nth-child(1) {_x000D_
  stop-color: #60c50b;_x000D_
}_x000D_
svg.green stop:nth-child(2) {_x000D_
  stop-color: #139a26;_x000D_
}_x000D_
_x000D_
svg.red stop:nth-child(1) {_x000D_
  stop-color: #c84f31;_x000D_
}_x000D_
svg.red stop:nth-child(2) {_x000D_
  stop-color: #dA3448;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop offset="0%" />_x000D_
    <stop offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>_x000D_
_x000D_
<br/>_x000D_
<button id="greenButton">Green</button>_x000D_
<button id="redButton">Red</button>
_x000D_
_x000D_
_x000D_

disable horizontal scroll on mobile web

This works for me across all mobile devices in both portrait and landscape modes.

<meta name="viewport" content="width=device-width, initial-scale = 0.86, maximum-scale=3.0, minimum-scale=0.86">

Check existence of input argument in a Bash shell script

As a small reminder, the numeric test operators in Bash only work on integers (-eq, -lt, -ge, etc.)

I like to ensure my $vars are ints by

var=$(( var + 0 ))

before I test them, just to defend against the "[: integer arg required" error.

How to download python from command-line?

apt-get install python2.7 will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.

How to "scan" a website (or page) for info, and bring it into my program?

This is referred to as screen scraping, wikipedia has this article on the more specific web scraping. It can be a major challenge because there's some ugly, mess-up, broken-if-not-for-browser-cleverness HTML out there, so good luck.

Docker Networking - nginx: [emerg] host not found in upstream

With links there is an order of container startup being enforced. Without links the containers can start in any order (or really all at once).

I think the old setup could have hit the same issue, if the waapi_php_1 container was slow to startup.

I think to get it working, you could create an nginx entrypoint script that polls and waits for the php container to be started and ready.

I'm not sure if nginx has any way to retry the connection to the upstream automatically, but if it does, that would be a better option.

Where to download Microsoft Visual c++ 2003 redistributable

After a bit of googling, it seems that there never was a separate redistributable for Visual C++ 2003 (7.1). At least that is what a post on the microsoft forum says.

You may however be able to extract the runtime DLLs from the VC 7.1 DST timezone update.

Can one do a for each loop in java in reverse order?

As of the comment: You should be able to use Apache Commons ReverseListIterator

Iterable<String> reverse 
    = new IteratorIterable(new ReverseListIterator(stringList));

for(String string: reverse ){
    //...do something
}

As @rogerdpack said, you need to wrap the ReverseListIterator as an Iterable.

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Starting Docker as Daemon on Ubuntu

This problem really cost me some hours.

My system is Ubuntu 14.04, I installed docker by sudo apt-get install docker, and typed some other commands that caused the problem.

  1. I google "unknown job: docker.io", answers did not take effect.

  2. I looked for reasons of "unknown job" in /etc/init.d/, found no proper answer .

  3. I looked for way to debug script in /etc/init.d/, found no proper answer.

  4. Then, I did a clean:

    1. sudo apt-get remove docker.io
    2. rm every suspicious file by find / -name "*docker*", such as /etc/init/docker.io.conf, /etc/init.d/docker.io .
  5. Follow the latest official document: https://docs.docker.com/installation/, there is a lot of outdated documentation which can be misleading.

Finally, it fixed the problem.

Note: If you are in China, because of the GFW, you may need to set the https_proxy to install docker from https://get.docker.com/ .

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

Windows batch script launch program and exit console

start "" ExeToExecute

method does not work for me in the case of Xilinx xsdk, because as pointed out by @jeb in the comments below it is actaully a bat file.

so what does not work de-facto is

start "" BatToExecute

I am trying to open xsdk like that and it opens a separate cmd that needs to be closed and xsdk can run on its own

Before launching xsdk I run (source) the Env / Paths (with settings64.bat) so that xsdk.bat command gets recognized (simply as xsdk, withoitu the .bat)

what works with .bat

call BatToExecute

Programmatically set image to UIImageView with Xcode 6.1/Swift

How about this;

myImageView.image=UIImage(named: "image_1")

where image_1 is within the assets folder as image_1.png.

This worked for me since i'm using a switch case to display an image slide.

Top 5 time-consuming SQL queries in Oracle

You could find disk intensive full table scans with something like this:

SELECT Disk_Reads DiskReads, Executions, SQL_ID, SQL_Text SQLText, 
   SQL_FullText SQLFullText 
FROM
(
   SELECT Disk_Reads, Executions, SQL_ID, LTRIM(SQL_Text) SQL_Text, 
      SQL_FullText, Operation, Options, 
      Row_Number() OVER 
         (Partition By sql_text ORDER BY Disk_Reads * Executions DESC) 
         KeepHighSQL
   FROM
   (
       SELECT Avg(Disk_Reads) OVER (Partition By sql_text) Disk_Reads, 
          Max(Executions) OVER (Partition By sql_text) Executions, 
          t.SQL_ID, sql_text, sql_fulltext, p.operation,p.options
       FROM v$sql t, v$sql_plan p
       WHERE t.hash_value=p.hash_value AND p.operation='TABLE ACCESS' 
       AND p.options='FULL' AND p.object_owner NOT IN ('SYS','SYSTEM')
       AND t.Executions > 1
   ) 
   ORDER BY DISK_READS * EXECUTIONS DESC
)
WHERE KeepHighSQL = 1
AND rownum <=5;

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

is there a css hack for safari only NOT chrome?

I like to use the following method:

var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isSafari) { 
  $('head').append('<link rel="stylesheet" type="text/css" href="path/to/safari.css">') 
};

How to concatenate string variables in Bash

I wanted to build a string from a list. Couldn't find an answer for that so I post it here. Here is what I did:

list=(1 2 3 4 5)
string=''

for elm in "${list[@]}"; do
    string="${string} ${elm}"
done

echo ${string}

and then I get the following output:

1 2 3 4 5

How to set base url for rest in spring boot?

With Spring Boot 1.2+ (<2.0) all it takes is a single property in application.properties:

spring.data.rest.basePath=/api

ref link : https://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-started.changing-base-uri

For 2.x, use

server.servlet.context-path=/api

How to reload current page without losing any form data?

You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.

let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)

The optional second parameter of each FormPersistence function defines whether to use local storage (false) or session storage (true). In your case, session storage is likely more appropriate.

The form data by default will be cleared from storage upon submission, unless you pass false as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.

What is unexpected T_VARIABLE in PHP?

There might be a semicolon or bracket missing a line before your pasted line.

It seems fine to me; every string is allowed as an array index.

failed to push some refs to [email protected]

Just switch the branch to main, It will surely work, and delete the project from Heroku remote. Delete all branches from local and use only one "main".

For reference: https://help.heroku.com/O0EXQZTA/how-do-i-switch-branches-from-master-to-main

How to get a pixel's x,y coordinate color from an image?

The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

enter image description here

Console output:

(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT

_x000D_
_x000D_
image = new MarvinImage();_x000D_
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);_x000D_
_x000D_
function imageLoaded(){_x000D_
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
}
_x000D_
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
_x000D_
_x000D_
_x000D_

What does %5B and %5D in POST requests stand for?

Well it's the usual url encoding

So they stand for [, respectively ]

How do you get the magnitude of a vector in Numpy?

Fastest way I found is via inner1d. Here's how it compares to other numpy methods:

import numpy as np
from numpy.core.umath_tests import inner1d

V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)   
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))

print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]

import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)')              # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))')             # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))')            # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))')                 # 2 function calls in 0.009 seconds

inner1d is ~3x faster than linalg.norm and a hair faster than einsum

Java Does Not Equal (!=) Not Working?

== and != work on object identity. While the two Strings have the same value, they are actually two different objects.

use !"success".equals(statusCheck) instead.

How to compare strings in an "if" statement?

You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).

The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."

Multiple select in Visual Studio?

Update: MixEdit extension now provides this ability.

MultiEdit extension for VS allows for something similar (doesn't support multiple selections as of this writing, just multiple carets)

Head over to Hanselman's for a quick animated gif of this in action: Simultaneous Editing for Visual Studio with the free MultiEdit extension

Android: How to handle right to left swipe gestures

This issue still exists. An OnTouchListener with an OnSwipeTouchListener solves it in a simple way:

myView.setOnTouchListener(
    new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if(!swipe.onTouch(v, event)) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    // your code here

                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // your code here

                    return true;
                }
            }
            return false;
        }

    }
);

where swipe refers to a class which records whether swipe methods have been invoked, then forwards events to the delegate OnSwipeTouchListener.

private class DirtyOnSwipeTouchListener extends OnSwipeTouchListener {
    private boolean dirty = false;
    private OnSwipeTouchListener delegate;

    public DirtyOnSwipeTouchListener(Context ctx, OnSwipeTouchListener delegate) {
        super(ctx);

        this.delegate = delegate;
    }

    private void reset() {
        dirty = false;
    }

    public void onSwipeTop() {
        dirty = true;
        delegate.onSwipeTop();
    }

    public void onSwipeRight() {
        dirty = true;
        delegate.onSwipeRight();
    }

    public void onSwipeLeft() {
        dirty = true;
        delegate.onSwipeLeft();
    }

    public void onSwipeBottom() {
        dirty = true;
        delegate.onSwipeBottom();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            super.onTouch(v, event);

            return dirty;
        } finally {
            dirty = false;
        }

    }
};

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Closing Excel Application using VBA

I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.

Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.

ThisWorkbook.Saved = True

and then, right after

Application.Quit

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Oracle sqlldr TRAILING NULLCOLS required, but why?

Try giving 5 ',' in every line, similar to line number 4.

javascript: Disable Text Select

One might also use, works ok in all browsers, require javascript:

onselectstart = (e) => {e.preventDefault()}

Example:

_x000D_
_x000D_
onselectstart = (e) => {_x000D_
  e.preventDefault()_x000D_
  console.log("nope!")_x000D_
  }
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


One other js alternative, by testing CSS supports, and disable userSelect, or MozUserSelect for Firefox.

_x000D_
_x000D_
let FF_x000D_
if (CSS.supports("( -moz-user-select: none )")){FF = 1} else {FF = 0}_x000D_
(FF===1) ? document.body.style.MozUserSelect="none" : document.body.style.userSelect="none"
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


Pure css, same logic. Warning you will have to extend those rules to every browser, this can be verbose.

_x000D_
_x000D_
@supports (user-select:none) {_x000D_
  div {_x000D_
    user-select:none_x000D_
  }_x000D_
}_x000D_
_x000D_
@supports (-moz-user-select:none) {_x000D_
  div {_x000D_
    -moz-user-select:none_x000D_
  }_x000D_
}
_x000D_
<div>Select me!</div>
_x000D_
_x000D_
_x000D_

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

How to test that no exception is thrown?

You can expect that exception is not thrown by creating a rule.

@Rule
public ExpectedException expectedException = ExpectedException.none();

How can a divider line be added in an Android RecyclerView?

Simply add a margin of x amount at the bottom of an item in your RecycleView Adapter.

onCreateViewHolder

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(0, 0, 0, 5);
itemView.setLayoutParams(layoutParams);

How to link to specific line number on github

Related to how to link to the README.md of a GitHub repository to a specific line number of code

You have three cases:

  1. We can link to (custom commit)

    But Link will ALWAYS link to old file version, which will NOT contains new updates in the master branch for example. Example:

    https://github.com/username/projectname/blob/b8d94367354011a0470f1b73c8f135f095e28dd4/file.txt#L10
    
  2. We can link to (custom branch) like (master-branch). But the link will ALWAYS link to the latest file version which will contain new updates. Due to new updates, the link may point to an invalid business line number. Example:

    https://github.com/username/projectname/blob/master/file.txt#L10
    
  3. GitHub can NOT make AUTO-link to any file either to (custom commit) nor (master-branch) Because of following business issues:

    • line business meaning, to link to it in the new file
    • length of target highlighted code which can be changed

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

Difference between Subquery and Correlated Subquery

I think below explanation will help to you.. differentiation between those: Correlated subquery is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.

non-correlated subquery is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.

plain subquery is not dependent on the outer query,

How do I run a spring boot executable jar in a Production environment?

In a production environment you want your app to be started again on a machine restart etc, creating a /etc/init.d/ script and linking to the appropriate runlevel to start and stop it is the correct approach. Spring Boot will not extend to covering this as it is a operating system specific setup and the are tonnes of other options, do you want it running in a chroot jail, does it need to stop / start before some other software etc.

What is the correct way to create a single-instance WPF application?

Please check the proposed solution from here that uses a semaphore to determine if an existing instance is already running, works for a WPF application and can pass arguments from second instance to the first already running instance by using a TcpListener and a TcpClient:

It works also for .NET Core, not only for .NET Framework.

how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white to the HTML element. I overwrote that and everything was easy to handle from there.

ActionBarActivity is deprecated

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity.

Read here and here for more information.

How to return a boolean method in java?

Best way would be to declare Boolean variable within the code block and return it at end of code, like this:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

I find this the best way.

"query function not defined for Select2 undefined error"

In case you initialize an empty input do this:

$(".yourelement").select2({
 data: {
  id: "",
  text: ""
 }
});

Read the first comment below, it explains why and when you should use the code in my answer.

How to change users in TortoiseSVN

If you want to remove only one saved password, e.g. for "user1":

  • Go to the saved password directory (*c:\Users\USERNAME\AppData\Roaming\Subversion\auth\svn.simple\*)
  • You will find several files in this folder (named with hash value)
  • Find the file which contains the username "user1", which you want to change (open it with Notepad).
  • Remove the file.
  • Next time you will connect to your SVN server, Tortoise will prompt you for new username and password.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Move textfield when keyboard appears swift

Here is my version for a solution for Swift 2.2:

First register for Keyboard Show/Hide Notifications

NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: #selector(MessageThreadVC.keyboardWillShow(_:)),
                                                 name: UIKeyboardWillShowNotification,
                                                 object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: #selector(MessageThreadVC.keyboardWillHide(_:)),
                                                 name: UIKeyboardWillHideNotification,
                                                 object: nil)

Then in methods coresponding for those notifications move the main view up or down

func keyboardWillShow(sender: NSNotification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
  self.view.frame.origin.y = -keyboardSize.height
  }
}

func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = 0
}

The trick is in the "keyboardWillShow" part which get calls every time "QuickType Suggestion Bar" is expanded or collapsed. Then we always set the y coordinate of the main view which equals the negative value of total keyboard height (with or without the "QuickType bar" portion).

At the end do not forget to remove observers

deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}

SonarQube Exclude a directory

Easiest way is to go to the server URL after starting the server(localhost:8080) then login as admin,Go to settings>Exclusions> Source File Exclusions- Add your packages here. Restart the server.

Apple Mach-O Linker Error when compiling for device

Just ran into the same issue.

The solution (for me) = check your frameworks.

In my case I had added classes related to CoreData without "CoreData.framework". Adding it solved the MACH_O complaining.

Performing a Stress Test on Web Application?

I had good results with FunkLoad :

  • easy to script user interaction
  • reports are clear
  • can monitor server load

Javascript to stop HTML5 video playback on modal window close

When you close the video you just need to pause it.

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer")[0].pause();
    return false;                   
});

<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>

Also, for reference, here's the Opera documentation for scripting video controls.

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

There's a nice jquery plugin called Jquery Mask Plugin that designed to make masks on form fields and html elements, but you can also used it to simply define what kind of data could be typed inside of a field:

$('.numeric-input').mask('0#');

Now only numbers will be allowed inside your form field.

Byte Array and Int conversion in Java

here is my implementation

public static byte[] intToByteArray(int a) {
    return BigInteger.valueOf(a).toByteArray();
}

public static int byteArrayToInt(byte[] b) {
    return new BigInteger(b).intValue();
}

Difference between array_map, array_walk and array_filter

The idea of mapping an function to array of data comes from functional programming. You shouldn't think about array_map as a foreach loop that calls a function on each element of the array (even though that's how it's implemented). It should be thought of as applying the function to each element in the array independently.

In theory such things as function mapping can be done in parallel since the function being applied to the data should ONLY affect the data and NOT the global state. This is because an array_map could choose any order in which to apply the function to the items in (even though in PHP it doesn't).

array_walk on the other hand it the exact opposite approach to handling arrays of data. Instead of handling each item separately, it uses a state (&$userdata) and can edit the item in place (much like a foreach loop). Since each time an item has the $funcname applied to it, it could change the global state of the program and therefor requires a single correct way of processing the items.

Back in PHP land, array_map and array_walk are almost identical except array_walk gives you more control over the iteration of data and is normally used to "change" the data in-place vs returning a new "changed" array.

array_filter is really an application of array_walk (or array_reduce) and it more-or-less just provided for convenience.

adb not finding my device / phone (MacOS X)

Solution specific to Nexus 4 and Nexus 5 for OS X

Got no device listed in the "List of devices attached" when I ran: adb devices

Fix:

  1. Get the SDK (Latest Version) from developer.android.com
  2. Put developer mode on nexus 4 ( About Phone > Build Number > tap 7 times to enter Dev Mode)
  3. A new menu option will come up in the 'Settings' : { } Developer Options
  4. Make sure you check the following under { } Developer options:
    • USB Debugging : Debug mode when USB is connected (Accept the RSA fingerprint popup)
    • Verify apps over USB : Check apps installed via ADB/ADT for Harmful behavior

Try listing your device from ./adb devices and it should work.

Answer taken from: Any idea why adb does not recognize my nexus 4 on mac

The most accurate way to check JS object's type?

var o = ...
var proto =  Object.getPrototypeOf(o);
proto === SomeThing;

Keep a handle on the prototype you expect the object to have, then compare against it.

for example

var o = "someString";
var proto =  Object.getPrototypeOf(o);
proto === String.prototype; // true

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

When to use RDLC over RDL reports?

if you want to use report in asp.net then use .rdl if you want to use /view in report builder / report server then use .rdlc just by converting format manually it works

How to pass parameters using ui-sref in ui-router to controller

I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would be the controller:

.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    //..
    var foo = $stateParams.foo; //getting fooVal
    var bar = $stateParams.bar; //getting barVal
    //..
    $scope.state = $state.current
    $scope.params = $stateParams; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These two links will correctly pass arguments into the controller:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">

Also, the controller does consume $stateParams instead of $stateParam.

Link to doc:

You can check it here

params : {}

There is also new, more granular setting params : {}. As we've already seen, we can declare parameters as part of url. But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url:

.state('other', {
    url: '/other/:foo?bar',
    params: { 
        // here we define default value for foo
        // we also set squash to false, to force injecting
        // even the default value into url
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        // this parameter is now array
        // we can pass more items, and expect them as []
        bar : { 
          array : true,
        },
        // this param is not part of url
        // it could be passed with $state.go or ui-sref 
        hiddenParam: 'YES',
      },
    ...

Settings available for params are described in the documentation of the $stateProvider

Below is just an extract

  • value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
  • array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
  • squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.

We can call these params this way:

// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

How to install Android SDK on Ubuntu?

If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:

  • sudo apt install android-sdk android-sdk-platform-23
  • export ANDROID_HOME=/usr/lib/android-sdk
  • In build.gradle, change compileSdkVersion to 23 and buildToolsVersion to 24.0.0
  • run gradle build

How to display count of notifications in app launcher icon

ShortcutBadger is a library that adds an abstraction layer over the device brand and current launcher and offers a great result. Works with LG, Sony, Samsung, HTC and other custom Launchers.

It even has a way to display Badge Count in Pure Android devices desktop.

Updating the Badge Count in the application icon is as easy as calling:

int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);

It includes a demo application that allows you to test its behavior.

Convert integer to hex and hex to integer

SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:

--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX

--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC

android pinch zoom

I have an open source library that does this very well. It's a four gesture library that comes with an out-of-the-box pan zoom setting. You can find it here: https://bitbucket.org/warwick/hacergestov3 Or you can download the demo app here: https://play.google.com/store/apps/details?id=com.WarwickWestonWright.HacerGestoV3Demo This is a pure canvas library so it can be used in pretty any scenario. Hope this helps.

Getting a HeadlessException: No X11 DISPLAY variable was set

This appears to be a more general SWING/AWT/JDK problem that just the JBOSS installer:

The accepted answer below solved the issue for me :

Unable to run java gui programs with ubuntu

("sudo apt-get install openjdk-6-jdk")

Traits vs. interfaces

Other answers did a great job of explaining differences between interfaces and traits. I will focus on a useful real world example, in particular one which demonstrates that traits can use instance variables - allowing you add behavior to a class with minimal boilerplate code.

Again, like mentioned by others, traits pair well with interfaces, allowing the interface to specify the behavior contract, and the trait to fulfill the implementation.

Adding event publish / subscribe capabilities to a class can be a common scenario in some code bases. There's 3 common solutions:

  1. Define a base class with event pub/sub code, and then classes which want to offer events can extend it in order to gain the capabilities.
  2. Define a class with event pub/sub code, and then other classes which want to offer events can use it via composition, defining their own methods to wrap the composed object, proxying the method calls to it.
  3. Define a trait with event pub/sub code, and then other classes which want to offer events can use the trait, aka import it, to gain the capabilities.

How well does each work?

#1 Doesn't work well. It would, until the day you realize you can't extend the base class because you're already extending something else. I won't show an example of this because it should be obvious how limiting it is to use inheritance like this.

#2 & #3 both work well. I'll show an example which highlights some differences.

First, some code that will be the same between both examples:

An interface

interface Observable {
    function addEventListener($eventName, callable $listener);
    function removeEventListener($eventName, callable $listener);
    function removeAllEventListeners($eventName);
}

And some code to demonstrate usage:

$auction = new Auction();

// Add a listener, so we know when we get a bid.
$auction->addEventListener('bid', function($bidderName, $bidAmount){
    echo "Got a bid of $bidAmount from $bidderName\n";
});

// Mock some bids.
foreach (['Moe', 'Curly', 'Larry'] as $name) {
    $auction->addBid($name, rand());
}

Ok, now lets show how the implementation of the Auction class will differ when using traits.

First, here's how #2 (using composition) would look like:

class EventEmitter {
    private $eventListenersByName = [];

    function addEventListener($eventName, callable $listener) {
        $this->eventListenersByName[$eventName][] = $listener;
    }

    function removeEventListener($eventName, callable $listener) {
        $this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
            return $existingListener === $listener;
        });
    }

    function removeAllEventListeners($eventName) {
        $this->eventListenersByName[$eventName] = [];
    }

    function triggerEvent($eventName, array $eventArgs) {
        foreach ($this->eventListenersByName[$eventName] as $listener) {
            call_user_func_array($listener, $eventArgs);
        }
    }
}

class Auction implements Observable {
    private $eventEmitter;

    public function __construct() {
        $this->eventEmitter = new EventEmitter();
    }

    function addBid($bidderName, $bidAmount) {
        $this->eventEmitter->triggerEvent('bid', [$bidderName, $bidAmount]);
    }

    function addEventListener($eventName, callable $listener) {
        $this->eventEmitter->addEventListener($eventName, $listener);
    }

    function removeEventListener($eventName, callable $listener) {
        $this->eventEmitter->removeEventListener($eventName, $listener);
    }

    function removeAllEventListeners($eventName) {
        $this->eventEmitter->removeAllEventListeners($eventName);
    }
}

Here's how #3 (traits) would look like:

trait EventEmitterTrait {
    private $eventListenersByName = [];

    function addEventListener($eventName, callable $listener) {
        $this->eventListenersByName[$eventName][] = $listener;
    }

    function removeEventListener($eventName, callable $listener) {
        $this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
            return $existingListener === $listener;
        });
    }

    function removeAllEventListeners($eventName) {
        $this->eventListenersByName[$eventName] = [];
    }

    protected function triggerEvent($eventName, array $eventArgs) {
        foreach ($this->eventListenersByName[$eventName] as $listener) {
            call_user_func_array($listener, $eventArgs);
        }
    }
}

class Auction implements Observable {
    use EventEmitterTrait;

    function addBid($bidderName, $bidAmount) {
        $this->triggerEvent('bid', [$bidderName, $bidAmount]);
    }
}

Note that the code inside the EventEmitterTrait is exactly the same as what's inside the EventEmitter class except the trait declares the triggerEvent() method as protected. So, the only difference you need to look at is the implementation of the Auction class.

And the difference is large. When using composition, we get a great solution, allowing us to reuse our EventEmitter by as many classes as we like. But, the main drawback is the we have a lot of boilerplate code that we need to write and maintain because for each method defined in the Observable interface, we need to implement it and write boring boilerplate code that just forwards the arguments onto the corresponding method in our composed the EventEmitter object. Using the trait in this example lets us avoid that, helping us reduce boilerplate code and improve maintainability.

However, there may be times where you don't want your Auction class to implement the full Observable interface - maybe you only want to expose 1 or 2 methods, or maybe even none at all so that you can define your own method signatures. In such a case, you might still prefer the composition method.

But, the trait is very compelling in most scenarios, especially if the interface has lots of methods, which causes you to write lots of boilerplate.

* You could actually kinda do both - define the EventEmitter class in case you ever want to use it compositionally, and define the EventEmitterTrait trait too, using the EventEmitter class implementation inside the trait :)

What is a reasonable code coverage % for unit tests (and why)?

I prefer to do BDD, which uses a combination of automated acceptance tests, possibly other integration tests, and unit tests. The question for me is what the target coverage of the automated test suite as a whole should be.

That aside, the answer depends on your methodology, language and testing and coverage tools. When doing TDD in Ruby or Python it's not hard to maintain 100% coverage, and it's well worth doing so. It's much easier to manage 100% coverage than 90-something percent coverage. That is, it's much easier to fill coverage gaps as they appear (and when doing TDD well coverage gaps are rare and usually worth your time) than it is to manage a list of coverage gaps that you haven't gotten around to and miss coverage regressions due to your constant background of uncovered code.

The answer also depends on the history of your project. I've only found the above to be practical in projects managed that way from the start. I've greatly improved the coverage of large legacy projects, and it's been worth doing so, but I've never found it practical to go back and fill every coverage gap, because old untested code is not well understood enough to do so correctly and quickly.

Using TortoiseSVN via the command line

My solution was to use DOSKEY to set up some aliases to for the commands I use the most:

DOSKEY svc=TortoiseProc.exe /command:commit /path:.
DOSKEY svu=TortoiseProc.exe /command:update /path:.
DOSKEY svl=TortoiseProc.exe /command:log /path:.
DOSKEY svd=TortoiseProc.exe /command:diff /path:$*

Google "doskey persist" for tips on how to set up a .cmd file that runs every time you open the command prompt like a .*rc file in Unix.

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

Refresh certain row of UITableView based on Int in Swift

SWIFT 4.2

    func reloadYourRows(name: <anyname>) {
    let row = <your array name>.index(of: <name passing in>)
    let reloadPath = IndexPath(row: row!, section: 0)
    tableView.reloadRows(at: [reloadPath], with: .middle)
    }

Save a list to a .txt file

You can use inbuilt library pickle

This library allows you to save any object in python to a file

This library will maintain the format as well

import pickle
with open('/content/list_1.txt', 'wb') as fp:
    pickle.dump(list_1, fp)

you can also read the list back as an object using same library

with open ('/content/list_1.txt', 'rb') as fp:
    list_1 = pickle.load(fp)

reference : Writing a list to a file with Python

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

How to use target in location.href

try this one, which simulates a click on an anchor.

var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

Efficient way to add spaces between characters in a string

A very pythonic and practical way to do it is by using the string join() method:

str.join(iterable)

The official Python documentations says:

Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

How to use it?

Remember: this is a string method.

This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

Let's have some practical example!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

In practice you would do it like this:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

What happens if you use a hyphen as a string instead?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

Can Mockito capture arguments of a method called multiple times?

You can also use @Captor annotated ArgumentCaptor. For example:

@Mock
List<String> mockedList;

@Captor
ArgumentCaptor<String> argCaptor;

@BeforeTest
public void init() {
    //Initialize objects annotated with @Mock, @Captor and @Spy.
    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldCallAddMethodTwice() {
    mockedList.add("one");
    mockedList.add("two");
    Mockito.verify(mockedList, times(2)).add(argCaptor.capture());

    assertEquals("one", argCaptor.getAllValues().get(0));
    assertEquals("two", argCaptor.getAllValues().get(1));
}

Setting the selected attribute on a select list using jQuery

I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() {
      var $this = $(this);
      if ($this.text() == 'B') {
         $this.attr('selected','selected');
         return false;
      }
 });

CSS: how to add white space before element's content?

Don't fart around with inserting spaces. For one, older versions of IE won't know what you're talking about. Besides that, though, there are cleaner ways in general.

For colorless indents, use the text-indent property.

p { text-indent: 1em; }

JSFiddle demo

Edit:

If you want the space to be colored, you might consider adding a thick left border to the first letter. (I'd almost-but-not-quite say "instead", because the indent can be an issue if you use both. But it feels dirty to me to rely solely on the border to indent.) You can specify how far away, and how wide, the color is using the first letter's left margin/padding/border width.

p:first-letter { border-left: 1em solid red; }

Demo

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

mysql_fetch_array() expects parameter 1 to be resource problem

You are not doing error checking after the call to mysql_query:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
    die('Invalid query: ' . mysql_error());
}

In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.

Pods stuck in Terminating status

I stumbled upon this recently to free up resource in my cluster. here is the command to delete them all.

kubectl get pods --all-namespaces | grep Terminating | while read line; do 
pod_name=$(echo $line | awk '{print $2}' ) name_space=$(echo $line | awk 
'{print $1}' ); kubectl delete pods $pod_name -n $name_space --grace-period=0 --force; 
done

hope this help someone who read this

Check line for unprintable characters while reading text file

If every char in the file is properly encoded in UTF-8, you won't have any problem reading it using a reader with the UTF-8 encoding. Up to you to check every char of the file and see if you consider it printable or not.

Get generic type of java.util.List

Generally impossible, because List<String> and List<Integer> share the same runtime class.

You might be able to reflect on the declared type of the field holding the list, though (if the declared type does not itself refer to a type parameter whose value you don't know).

How do I parse command line arguments in Java?

As one of the comments mentioned earlier (https://github.com/pcj/google-options) would be a good choice to start with.

One thing I want to add-on is:

1) If you run into some parser reflection error, please try use a newer version of the guava. in my case:

maven_jar(
    name = "com_google_guava_guava",
    artifact = "com.google.guava:guava:19.0",
    server = "maven2_server",
)

maven_jar(
    name = "com_github_pcj_google_options",
    artifact = "com.github.pcj:google-options:jar:1.0.0",
    server = "maven2_server",
)

maven_server(
    name = "maven2_server",
    url = "http://central.maven.org/maven2/",
)

2) When running the commandline:

bazel run path/to/your:project -- --var1 something --var2 something -v something

3) When you need the usage help, just type:

bazel run path/to/your:project -- --help

Get a random item from a JavaScript array

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]

Assigning a function to a variable

I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:

import sys
fun = eval(sys.argv[1])
fun()

In the present case, fun = x.

Create numpy matrix filled with NaNs

Another alternative is numpy.broadcast_to(val,n) which returns in constant time regardless of the size and is also the most memory efficient (it returns a view of the repeated element). The caveat is that the returned value is read-only.

Below is a comparison of the performances of all the other methods that have been proposed using the same benchmark as in Nico Schlömer's answer.

enter image description here

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

After trying all the methods available on internet and my own trial and error tricks 100 times. Finally I was able to solve it. – Apeksha Sahu 6 mins ago
Goto iTunes in Mac --> accounts-->Authorize this computer – Apeksha Sahu 5 mins ago
second step.... Goto developer in settings in iPad and iPhone and reindex with identifiers and clear trust computers everything. It worked for me........ ....... After reinstalling Mac OSHigh seria 10.13.15 version from Mac OS seirra beta latest version, to reinstalling Xcode latest version, after updating all certificates. etc etc etc... as many methods as you can think I did. – enter image description here

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

copy the below content to file tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>

<user username="notadmin" password="not_real_pass" roles="manager-gui"/>
<user username="cargo" password="not_real_pass" roles="manager-script"/>


</tomcat-users>

I have tested, it just works!

enter image description here

Convert NSNumber to int in Objective-C

Have a look at the documentation. Use the intValue method:

NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];

How to submit an HTML form without redirection

The desired effect can also be achieved by moving the submit button outside of the form as described here:

Prevent page reload and redirect on form submit ajax/jquery

Like this:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>

<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

Gson library in Android Studio

Use gradle dependencies to get the Gson in your project. Your application build.gradle should look like this-

dependencies {
  implementation 'com.google.code.gson:gson:2.8.2'
}

Add leading zeroes to number in Java?

How about just:

public static String intToString(int num, int digits) {
    String output = Integer.toString(num);
    while (output.length() < digits) output = "0" + output;
    return output;
}

angular.js ng-repeat li items with html content

ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:

HTML-side: (the same as the accepted answer stated):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

But in the controller-side:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}

Javascript swap array elements

You can swap any number of objects or literals, even of different types, using a simple identity function like this:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

For your problem:

var swap = function (x){return x};
list[y]  = swap(list[x], list[x]=list[y]);

This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

How to scale Docker containers in production

A sensible approach to scaling Docker could be:

  1. Each service will be a docker container
  2. Intra container service discovery managed through links (new feature from docker 0.6.5)
  3. Containers will be deployed through Dokku
  4. Applications will be managed through Shipyard which in its turn is using hipache

Another docker open sourced project from Yandex:

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

pull/push from multiple remote locations

Since git 1.8 (October 2012) you are able to do this from the command line:

git remote set-url origin --push --add user1@repo1
git remote set-url origin --push --add user2@repo2
git remote -v

Then git push will push to user1@repo1, then push to user2@repo2.

What is ANSI format?

Technically, ANSI should be the same as US-ASCII. It refers to the ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII. Use of the top-bit-set characters is not defined in ASCII/ANSI as it is a 7-bit character set.

However years of misuse of the term by the DOS and subsequently Windows community has left its practical meaning as “the system codepage of whatever machine is being used”. The system codepage is also sometimes known as ‘mbcs’, since on East Asian systems that can be a multiple-byte-per-character encoding. Some code pages can even use top-bit-clear bytes as trailing bytes in a multibyte sequence, so it's not even strict compatible with plain ASCII... but even then, it's still called “ANSI”.

On US and Western European default settings, “ANSI” maps to Windows code page 1252. This is not the same as ISO-8859-1 (although it is quite similar). On other machines it could be anything else at all. This makes “ANSI” utterly useless as an external encoding identifier.

What is the '.well' equivalent class in Bootstrap 4

None of the answers seemed to work well with buttons. Bootstrap v4.1.1

<div class="card bg-light">
    <div class="card-body">
        <button type="submit" class="btn btn-primary">
            Save
        </button>
        <a href="/" class="btn btn-secondary">
            Cancel
        </a>
    </div>
</div>

With block equivalent in C#?

There is another an interesting implementation of with-pattern

public static T With<T>(this T o, params object[] pattern) => o;
public static T To<T>(this T o, out T x) => x = o;

You may browse more details by the link and research online code samples.

Variations of usage

static Point Sample0() => new Point().To(out var p).With(
    p.X = 123,
    p.Y = 321,
    p.Name = "abc"
);

public static Point GetPoint() => new Point { Name = "Point Name" };
static string NameProperty { get; set; }
static string NameField;

static void Sample1()
{
    string nameLocal;
    GetPoint().To(out var p).With(
        p.X = 123,
        p.Y = 321,
        p.Name.To(out var name), /* right side assignment to the new variable */
        p.Name.To(out nameLocal), /* right side assignment to the declared var */
        NameField = p.Name, /* left side assignment to the declared variable */
        NameProperty = p.Name /* left side assignment to the property */
    );

    Console.WriteLine(name);
    Console.WriteLine(nameLocal);
    Console.WriteLine(NameField);
    Console.WriteLine(NameProperty);
}

static void Sample2() /* non-null propogation sample */
{
    ((Point)null).To(out var p)?.With(
        p.X = 123,
        p.Y = 321,
        p.Name.To(out var name)
    );

    Console.WriteLine("No exception");
}

static void Sample3() /* recursion */
{
    GetPerson().To(out var p).With(
        p.Name.To(out var name),
        p.Subperson.To(out var p0).With(
            p0.Name.To(out var subpersonName0)
        ),
        p.GetSubperson().To(out var p1).With( /* method return */
            p1.Name.To(out var subpersonName1)
        )
    );

    Console.WriteLine(subpersonName0);
    Console.WriteLine(subpersonName1);
}

If you work with structs [value types] the similar extension method will be useful too

public static TR Let<T, TR>(this T o, TR y) => y;

May be applied after With method because by default will be returned the unmodified copy of struct

struct Point
{
    public double X;
    public double Y;
    public string Name;
}

static Point Sample0() => new Point().To(out var p).With(
    p.X = 123,
    p.Y = 321,
    p.Name = "abc"
).Let(p);

Enjoy if you like!

Execute a large SQL script (with GO commands)

I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)

All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands

public static bool ExecuteExternalScript(string filePath)
{
    using (StreamReader file = new StreamReader(filePath))
    using (SqlConnection conn = new SqlConnection(dbConnStr))
    {
        StringBuilder sql = new StringBuilder();

        string line;
        while ((line = file.ReadLine()) != null)
        {
            // replace GO with semi-colon
            if (line == "GO")
                sql.Append(";");
            // remove inline comments
            else if (line.IndexOf("--") > -1)
                sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
            // just the line as it is
            else
                sql.AppendFormat(" {0} ", line);
        }
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
        cmd.ExecuteNonQuery();
    }

    return true;
}

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

How to switch back to 'master' with git?

For deleting the branch you have to stash the changes made on the branch or you need to commit the changes you made on the branch. Follow the below steps if you made any changes in the current branch.

  1. git stash or git commit -m "XXX"
  2. git checkout master
  3. git branch -D merchantApi

Note: Above steps will delete the branch locally.

Get the difference between dates in terms of weeks, months, quarters, and years

Here the still lacking lubridate answer (although Gregor's function is built on this package)

The lubridate timespan documentation is very helpful for understanding the difference between periods and duration. I also like the lubridate cheatsheet and this very useful thread

library(lubridate)

dates <- c(dmy('14.01.2013'), dmy('26.03.2014'))

span <- dates[1] %--% dates[2] #creating an interval object

#creating period objects 
as.period(span, unit = 'year') 
#> [1] "1y 2m 12d 0H 0M 0S"
as.period(span, unit = 'month')
#> [1] "14m 12d 0H 0M 0S"
as.period(span, unit = 'day')
#> [1] "436d 0H 0M 0S"

Periods do not accept weeks as units. But you can convert durations to weeks:

as.duration(span)/ dweeks(1)
#makes duration object (in seconds) and divides by duration of a week (in seconds)
#> [1] 62.28571

Created on 2019-11-04 by the reprex package (v0.3.0)

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

Creating a copy of an object in C#

The easiest way to do this is writing a copy constructor in the MyClass class.

Something like this:

namespace Example
{
    class MyClass
    {
        public int val;

        public MyClass()
        {
        }

        public MyClass(MyClass other)
        {
            val = other.val;
        }
    }
}

The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value

class Program
{
    static void Main(string[] args)
    {
        MyClass objectA = new MyClass();
        MyClass objectB = new MyClass(objectA);
        objectA.val = 10;
        objectB.val = 20;
        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.ReadKey();
    }
}

output:

objectA.val = 10

objectB.val = 20               

Loading local JSON file

What I did was editing the JSON file little bit.

myfile.json => myfile.js

In the JSON file, (make it a JS variable)

{name: "Whatever"} => var x = {name: "Whatever"}

At the end,

export default x;

Then,

import JsonObj from './myfile.js';

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of using a PreferenceActivity to directly load preferences, use an AppCompatActivity or equivalent that loads a PreferenceFragmentCompat that loads your preferences. It's part of the support library (now Android Jetpack) and provides compatibility back to API 14.

In your build.gradle, add a dependency for the preference support library:

dependencies {
    // ...
    implementation "androidx.preference:preference:1.0.0-alpha1"
}

Note: We're going to assume you have your preferences XML already created.

For your activity, create a new activity class. If you're using material themes, you should extend an AppCompatActivity, but you can be flexible with this:

public class MyPreferencesActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_preferences_activity)
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, MyPreferencesFragment())
                    .commitNow()
        }
    }
}

Now for the important part: create a fragment that loads your preferences from XML:

public class MyPreferencesFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.my_preferences_fragment); // Your preferences fragment
    }
}

For more information, read the Android Developers docs for PreferenceFragmentCompat.

How to achieve function overloading in C?

The following approach is similar to a2800276's, but with some C99 macro magic added:

// we need `size_t`
#include <stddef.h>

// argument types to accept
enum sum_arg_types { SUM_LONG, SUM_ULONG, SUM_DOUBLE };

// a structure to hold an argument
struct sum_arg
{
    enum sum_arg_types type;
    union
    {
        long as_long;
        unsigned long as_ulong;
        double as_double;
    } value;
};

// determine an array's size
#define count(ARRAY) ((sizeof (ARRAY))/(sizeof *(ARRAY)))

// this is how our function will be called
#define sum(...) _sum(count(sum_args(__VA_ARGS__)), sum_args(__VA_ARGS__))

// create an array of `struct sum_arg`
#define sum_args(...) ((struct sum_arg []){ __VA_ARGS__ })

// create initializers for the arguments
#define sum_long(VALUE) { SUM_LONG, { .as_long = (VALUE) } }
#define sum_ulong(VALUE) { SUM_ULONG, { .as_ulong = (VALUE) } }
#define sum_double(VALUE) { SUM_DOUBLE, { .as_double = (VALUE) } }

// our polymorphic function
long double _sum(size_t count, struct sum_arg * args)
{
    long double value = 0;

    for(size_t i = 0; i < count; ++i)
    {
        switch(args[i].type)
        {
            case SUM_LONG:
            value += args[i].value.as_long;
            break;

            case SUM_ULONG:
            value += args[i].value.as_ulong;
            break;

            case SUM_DOUBLE:
            value += args[i].value.as_double;
            break;
        }
    }

    return value;
}

// let's see if it works

#include <stdio.h>

int main()
{
    unsigned long foo = -1;
    long double value = sum(sum_long(42), sum_ulong(foo), sum_double(1e10));
    printf("%Le\n", value);
    return 0;
}

Is there a constraint that restricts my generic method to numeric types?

If all you want is use one numeric type, you could consider creating something similar to an alias in C++ with using.

So instead of having the very generic

T ComputeSomething<T>(T value1, T value2) where T : INumeric { ... }

you could have

using MyNumType = System.Double;
T ComputeSomething<MyNumType>(MyNumType value1, MyNumType value2) { ... }

That might allow you to easily go from double to int or others if needed, but you wouldn't be able to use ComputeSomething with double and int in the same program.

But why not replace all double to int then? Because your method may want to use a double whether the input is double or int. The alias allows you to know exactly which variable uses the dynamic type.

How to parse date string to Date?

String target = "27-09-1991 20:29:30";
DateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date result =  df.parse(target);
System.out.println(result); 

This works fine?

How to save S3 object to a file using boto3

Note: I'm assuming you have configured authentication separately. Below code is to download the single object from the S3 bucket.

import boto3

#initiate s3 client 
s3 = boto3.resource('s3')

#Download object to the file    
s3.Bucket('mybucket').download_file('hello.txt', '/tmp/hello.txt')

How to return a table from a Stored Procedure?

It's VERY important to include:

 SET NOCOUNT ON;

into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

THEN, in vb60 you can:

SET RS = CN.EXECUTE(SQL)

OR:

RS.OPEN CN, RS, SQL

What are functional interfaces used for in Java 8?

A lambda expression can be assigned to a functional interface type, but so can method references, and anonymous classes.

One nice thing about the specific functional interfaces in java.util.function is that they can be composed to create new functions (like Function.andThen and Function.compose, Predicate.and, etc.) due to the handy default methods they contain.