Programs & Examples On #Canexecute

Error: the entity type requires a primary key

Removed and added back in the table using Scaffold-DbContext and the error went away

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used BufferedReader. After reading, I closed the buffer.

Meanwhile I switched and now I'm reading the content using FileInputStream. Also after finishing reading I close the stream. And now it's working.

The problem is I don't have the explanation for this.

I don't know BufferedReader and FileOutputStream to be incompatible.

How to run bootRun with spring profile via gradle task

Configuration for 4 different task with different profiles and gradle tasks dependencies:

  • bootRunLocal and bootRunDev - run with specific profile
  • bootPostgresRunLocal and bootPostgresRunDev same as prev, but executing custom task runPostgresDocker and killPostgresDocker before/after bootRun

build.gradle:

final LOCAL='local'
final DEV='dev'

void configBootTask(Task bootTask, String profile) {
    bootTask.main = bootJar.mainClassName
    bootTask.classpath = sourceSets.main.runtimeClasspath

    bootTask.args = [ "--spring.profiles.active=$profile" ]
//    systemProperty 'spring.profiles.active', profile // this approach also may be used
    bootTask.environment = postgresLocalEnvironment
}

bootRun {
    description "Run Spring boot application with \"$LOCAL\" profile"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunLocal(type: BootRun, dependsOn: 'classes') {
    description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunDev(type: BootRun, dependsOn: 'classes') {
    description "Run Spring boot application with \"$DEV\" profile"
    doFirst() {
        configBootTask(it, DEV)
    }
}

task bootPostgresRunLocal(type: BootRun) {
    description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootPostgresRunDev(type: BootRun) {
    description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, DEV)
    }
}

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

how to pass parameter from @Url.Action to controller function

Try this

public ActionResult CreatePerson(string Enc)

 window.location = '@Url.Action("CreatePerson", "Person", new { Enc = "id", actionType = "Disable" })'.replace("id", id).replace("&amp;", "&");

you will get the id inside the Enc string.

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

If performance is a concern, I would use operator.itemgetter instead of lambda as built-in functions perform faster than hand-crafted functions. The itemgetter function seems to perform approximately 20% faster than lambda based on my testing.

From https://wiki.python.org/moin/PythonSpeed:

Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).

Here is a comparison of sorting speed using lambda vs itemgetter.

import random
import operator

# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.
l = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]

# Test the performance with a lambda function sorting on name
%timeit sorted(l, key=lambda x: x['name'])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Test the performance with itemgetter sorting on name
%timeit sorted(l, key=operator.itemgetter('name'))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Check that each technique produces the same sort order
sorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))
True

Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.

How to Load an Assembly to AppDomain with all references recursively?

On your new AppDomain, try setting an AssemblyResolve event handler. That event gets called when a dependency is missing.

All possible array initialization syntaxes

For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };

Subset of rows containing NA (missing) values in a chosen column of a data frame

Prints all the rows with NA data:

tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]

Test for array of string type in TypeScript

You can have do it easily using Array.prototype.some() as below.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && !test.some((value) => typeof value !== 'string')
}
const myArray = ["A", "B", "C"]
console.log(isStringArray(myArray)) // will be log true if string array

I believe this approach is better that others. That is why I am posting this answer.

Update on Sebastian Vittersø's comment

Here you can use Array.prototype.every() as well.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && test.every((value) => typeof value === 'string')
}

How to ignore HTML element from tabindex?

Don't forget that, even though tabindex is all lowercase in the specs and in the HTML, in Javascript/the DOM that property is called tabIndex.

Don't lose your mind trying to figure out why your programmatically altered tab indices calling element.tabindex = -1 isn't working. Use element.tabIndex = -1.

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

How do I iterate over a range of numbers defined by variables in Bash?

If you're on BSD / OS X you can use jot instead of seq:

for i in $(jot $END); do echo $i; done

sql: check if entry in table A exists in table B

Or if "NOT EXISTS" are not implemented

SELECT *
FROM   B
WHERE (SELECT count(*)  FROM   A WHERE  A.ID = B.ID) < 1

How to use orderby with 2 fields in linq?

Use ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

You can also use query syntax and say:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

Required attribute on multiple checkboxes with the same name?

Here is improvement for icova's answer. It also groups inputs by name.

$(function(){
  var allRequiredCheckboxes = $(':checkbox[required]');
  var checkboxNames = [];

  for (var i = 0; i < allRequiredCheckboxes.length; ++i){
    var name = allRequiredCheckboxes[i].name;
    checkboxNames.push(name);
  }

  checkboxNames = checkboxNames.reduce(function(p, c) {
    if (p.indexOf(c) < 0) p.push(c);
    return p;
  }, []);

  for (var i in checkboxNames){
    !function(){
      var name = checkboxNames[i];
      var checkboxes = $('input[name="' + name + '"]');
      checkboxes.change(function(){
        if(checkboxes.is(':checked')) {
          checkboxes.removeAttr('required');
        } else {
          checkboxes.attr('required', 'required');
        }
      });
    }();
  }

});

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

Is there a way to check if a file is in use?

Would something like this help?

var fileWasWrittenSuccessfully = false;
while (fileWasWrittenSuccessfully == false)
{
    try
    {
        lock (new Object())
        {
            using (StreamWriter streamWriter = new StreamWriter("filepath.txt"), true))
            {
                streamWriter.WriteLine("text");
            }
        }

        fileWasWrittenSuccessfully = true;
    }
    catch (Exception)
    {

    }
}

Highcharts - how to have a chart with dynamic height?

What if you hooked the window resize event:

$(window).resize(function() 
{    
    chart.setSize(
       $(document).width(), 
       $(document).height()/2,
       false
    );   
});

See example fiddle here.

Highcharts API Reference : setSize().

How to generate components in a specific folder with Angular CLI?

Firstly to create a Component you need to use:-

  • ng g c componentname

    By using above command New Component will be created in a folder with
    (componentname) you specified above.

But if you need to create a component inside of another component or in specific folder:-

  • ng g c componentname/newComponentName

Spring @Autowired and @Qualifier

The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

Ex:-

public interface Vehicle {
     public void start();
     public void stop();
}

There are two beans, Car and Bike implements Vehicle interface

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

Reference:- @Qualifier annotation example

How can you run a command in bash over and over until success?

until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

Git Ignores and Maven targets

It is possible to use patterns in a .gitignore file. See the gitignore man page. The pattern */target/* should ignore any directory named target and anything under it. Or you may try */target/** to ignore everything under target.

Simple proof that GUID is not unique

Well if the running time of 83 billion years does not scare you, think that you will also need to store the generated GUIDs somewhere to check if you have a duplicate; storing 2^128 16-byte numbers would only require you to allocate 4951760157141521099596496896 terabytes of RAM upfront, so imagining you have a computer which could fit all that and that you somehow find a place to buy terabyte DIMMs at 10 grams each, combined they will weigh more than 8 Earth masses, so you can seriously shift it off the current orbit, before you even press "Run". Think twice!

Python datetime to string without microsecond component

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

This line

secondNumber = Screen.text!.toInt()!

means: Get the Screen object, get the text property and please crash if it doesn't exist, then get the text converted to an integer, and please crash if it doesn't exist.

That's what the ! means: "I am sure this thing exists, so please crash if it doesn't". And crash is what it did.

Make the image go behind the text and keep it in center using CSS

Make it a background image that is centered.

.wrapper {background:transparent url(yourimage.jpg) no-repeat center center;}

<div class="wrapper">
 ...input boxes and labels and submit button here
</div>

Keep SSH session alive

We can keep our ssh connection alive by having following Global configurations

Add the following line to the /etc/ssh/ssh_config file:

ServerAliveInterval 60

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

Java - How to access an ArrayList of another class?

You can do this by providing in class numbers:

  • A method that returns the ArrayList object itself.
  • A method that returns a non-modifiable wrapper of the ArrayList. This prevents modification to the list without the knowledge of the class numbers.
  • Methods that provide the set of operations you want to support from class numbers. This allows class numbers to control the set of operations supported.

By the way, there is a strong convention that Java class names are uppercased.

Case 1 (simple getter):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return list; }
      ...
}

Case 2 (non-modifiable wrapper):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return Collections.unmodifiableList( list ); }
      ...
}

Case 3 (specific methods):

public class Numbers {
      private List<Integer> list;
      public void addToList( int i ) { list.add(i); }
      public int getValueAtIndex( int index ) { return list.get( index ); }
      ...
}

Drawable image on a canvas

The good way to draw a Drawable on a canvas is not decoding it yourself but leaving it to the system to do so:

Drawable d = getResources().getDrawable(R.drawable.foobar, null);
d.setBounds(left, top, right, bottom);
d.draw(canvas);

This will work with all kinds of drawables, not only bitmaps. And it also means that you can re-use that same drawable again if only the size changes.

What do the different readystates in XMLHttpRequest mean, and how can I use them?

  • 0 : UNSENT Client has been created. open() not called yet.
  • 1 : OPENED open() has been called.
  • 2 : HEADERS_RECEIVED send() has been called, and headers and status are available.
  • 3 : LOADING Downloading; responseText holds partial data.
  • 4 : DONE The operation is complete.

(From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState)

Python 3: ImportError "No Module named Setuptools"

Windows 7:

I have given a complete solution here for python selenium webdriver

1. Setup easy install (windows - simplified)
    a. download ez.setup.py (https://bootstrap.pypa.io/ez_setup.py) from 'https://pypi.python.org/pypi/setuptools'
    b. move ez.setup.py to C:\Python27\
    c. open cmd prompt
    d. cd C:\Python27\
    e. C:\Python27\python.exe ez.setup.py install

PowerShell To Set Folder Permissions

Another example using PowerShell for set permissions (File / Directory) :

Verify permissions

Get-Acl "C:\file.txt" | fl *

Apply full permissions for everyone

$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"

Screenshots: enter image description here enter image description here

Hope this helps

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Reverse / invert a dictionary mapping

Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))

def reverse_dict(dictionary):
    reverse_dict = {}
    for key, value in dictionary.iteritems():
        if not isinstance(value, (list, tuple)):
            value = [value]
        for val in value:
            reverse_dict[val] = reverse_dict.get(val, [])
            reverse_dict[val].append(key)
    for key, value in reverse_dict.iteritems():
        if len(value) == 1:
            reverse_dict[key] = value[0]
    return reverse_dict

Adding space/padding to a UILabel

If you want to add 2px padding around the textRect, just do this:

let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)

Datanode process not running in Hadoop

I Have applied some mixed configuration, and its worked for me.
First >>
Stop Hadoop all Services using ${HADOOP_HOME}/sbin/stop-all.sh

Second >>
Check mapred-site.xml which is located at your ${HADOOP_HOME}/etc/hadoop/mapred-site.xml and change the localhost to master.

Third >>
Remove the temporary folder created by hadoop
rm -rf //path//to//your//hadoop//temp//folder

Fourth >>
Add the recursive permission on temp.
sudo chmod -R 777 //path//to//your//hadoop//temp//folder

Fifth >>
Now Start all the services again. And First check that all service including datanode is running. enter image description here

Where to find extensions installed folder for Google Chrome on Mac?

They are found on either one of the below locations depending on how chrome was installed

  • When chrome is installed at the user level, it's located at:

~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions

  • When installed at the root level, it's at:

/Library/Application\ Support/Google/Chrome/Default/Extensions

The PowerShell -and conditional operator

You can simplify it to

if ($user_sam -and $user_case) {
  ...
}

because empty strings coerce to $false (and so does $null, for that matter).

How can I check MySQL engine type for a specific table?

or just

show table status;

just that this will llist all tables on your database.

css 'pointer-events' property alternative for IE

I faced similar issues:

  1. I faced this issue in a directive, i fixed it adding a as its parent element and making pointer-events:none for that

  2. The above fix did not work for select tag, then i added cursor:text (which was what i wanted) and it worked for me

If a normal cursor is needed you could add cursor:default

"webxml attribute is required" error in Maven

If you are migrating from XML-based to Java-based configuration and you have removed the need for web.xml by implementing WebApplicationInitializer, simply remove the requirement for the web.xml file to be present.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        ... 
    </configuration>

Does Java have something like C#'s ref and out keywords?

Direct answer: No

But you can simulate reference with wrappers.

And do the following:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

Out

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

And basically any other type such as:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Get data from file input in JQuery

FileReader API with jQuery, simple example.

_x000D_
_x000D_
( function ( $ ) {_x000D_
 // Add click event handler to button_x000D_
 $( '#load-file' ).click( function () {_x000D_
  if ( ! window.FileReader ) {_x000D_
   return alert( 'FileReader API is not supported by your browser.' );_x000D_
  }_x000D_
  var $i = $( '#file' ), // Put file input ID here_x000D_
   input = $i[0]; // Getting the element from jQuery_x000D_
  if ( input.files && input.files[0] ) {_x000D_
   file = input.files[0]; // The file_x000D_
   fr = new FileReader(); // FileReader instance_x000D_
   fr.onload = function () {_x000D_
    // Do stuff on onload, use fr.result for contents of file_x000D_
    $( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )_x000D_
   };_x000D_
   //fr.readAsText( file );_x000D_
   fr.readAsDataURL( file );_x000D_
  } else {_x000D_
   // Handle errors here_x000D_
   alert( "File not selected or browser incompatible." )_x000D_
  }_x000D_
 } );_x000D_
} )( jQuery );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="file" />_x000D_
<input type='button' id='load-file' value='Load'>_x000D_
<div id="file-content"></div>
_x000D_
_x000D_
_x000D_

To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);

How to sum all column values in multi-dimensional array?

You can use array_walk_recursive() to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).

$final = array();

array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

Example with array_walk_recursive() for the general case

Also, since PHP 5.5 you can use the array_column() function to achieve the result you want for the exact key, [gozhi], for example :

array_sum(array_column($input, 'gozhi')); 

Example with array_column() for the specified key

If you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :

$final = array_shift($input);

foreach ($final as $key => &$value){
   $value += array_sum(array_column($input, $key));
}    

unset($value);

Example with array_column() in case all inner arrays have the same keys

If you want a general-case solution using array_column() then at first you may consider to get all unique keys , and then get the sum for each key :

$final = array();

foreach($input as $value)
    $final = array_merge($final, $value);

foreach($final as $key => &$value)
    $value = array_sum(array_column($input, $key));

unset($value);

Example with array_column() for the general case

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)

How can I preview a merge in git?

git log currentbranch..otherbranch will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.

git diff currentbranch otherbranch will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.

Would these help?

Make a float only show two decimal places

in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000

How do you get the length of a string?

In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

MDN says: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is my error code:

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'ByStore$'. Make sure the object exists and that you spell its name and the path name correctly. If 'ByStore$' is not a local object, check your network connection or contact the server administrator.".

Msg 7350, Level 16, State 2, Procedure PeopleCounter_daily, Line 26

Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

My problem was the excel file was missing at the path. Just put the file with the correct sheet will do.

Does Python have a ternary conditional operator?

Other answers correctly talk about the Python ternary operator. I would like to complement by mentioning a scenario for which the ternary operator is often used but for which there is a better idiom. This is the scenario of using a default value.

Suppose we want to use option_value with a default value if it is not set:

run_algorithm(option_value if option_value is not None else 10)

or, if option_value is never set to a falsy value (0, "", etc), simply

run_algorithm(option_value if option_value else 10)

However, in this case an ever better solution is simply to write

run_algorithm(option_value or 10)

How to check variable type at runtime in Go language

See type assertions here:

http://golang.org/ref/spec#Type_assertions

I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

How to position a CSS triangle using ::after?

Add a class:

.com_box:after {
     content: '';
    position: absolute;
    left: 18px;
    top: 50px;
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #000;
    clear: both;

}

Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/

how to end ng serve or firebase serve

ctrl + c OR ctrl + Pause/Break

Both will ask for Terminate batch job, then press Y or y and click enter.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Try this:

Select user_id
from yourtable
where ancestry in ('England', 'France', 'Germany')
group by user_id
having count(user_id) = 3

The last line means the user's ancestry has all 3 countries.

SQL - ORDER BY 'datetime' DESC

  1. use single quotes for strings
  2. do NOT put single quotes around table names(use ` instead)
  3. do NOT put single quotes around numbers (you can, but it's harder to read)
  4. do NOT put AND between ORDER BY and LIMIT
  5. do NOT put = between ORDER BY, LIMIT keywords and condition

So you query will look like:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

Best way to iterate through a Perl array

In single line to print the element or array.

print $_ for (@array);

NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array; ex.

my @array = qw( 1 2 3 );
for (@array) {
        $_ = $_ *2 ;
}
print "@array";

output: 2 4 6

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

How to use onSaveInstanceState() and onRestoreInstanceState()?

This happens because you use the savedValue in the onCreate() method. The savedValue is updated in onRestoreInstanceState() method, but onRestoreInstanceState() is called after the onCreate() method. You can either:

  1. Update the savedValue in onCreate() method, or
  2. Move the code that use the new savedValue in onRestoreInstanceState() method.

But I suggest you to use the first approach, making the code like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int display_mode = getResources().getConfiguration().orientation;

    if (display_mode == 1) {

        setContentView(R.layout.main_grid);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        mGrid.setVisibility(0x00000000);
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    } else {
        setContentView(R.layout.main_grid_land);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        Log.d("Mode", "land");
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    }
    if (savedInstanceState != null) {
        savedUser = savedInstanceState.getString("TEXT");
    } else {
        savedUser = ""
    }
    Log.d("savedUser", savedUser);
    if (savedUser.equals("admin")) { //value 0
        adapter.setApps(appManager.getApplications());
    } else if (savedUser.equals("prof")) { //value 1
        adapter.setApps(appManager.getTeacherApplications());
    } else {// default value
        appManager = new ApplicationManager(this, getPackageManager());
        appManager.loadApplications(true);
        bindApplications();
    }
}

Truncating a table in a stored procedure

You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.

You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.

1) Execute immediate

2) DBMS_SQL package

3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);

Hope this answers your question with explanation.

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

How do I get my Python program to sleep for 50 milliseconds?

Use time.sleep():

import time
time.sleep(50 / 1000)

See the Python documentation: https://docs.python.org/library/time.html#time.sleep

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:


IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

Validating URL in Java

There is a way to perform URL validation in strict accordance to standards in Java without resorting to third-party libraries:

boolean isValidURL(String url) {
  try {
    new URI(url).parseServerAuthority();
    return true;
  } catch (URISyntaxException e) {
    return false;
  }
}

The constructor of URI checks that url is a valid URI, and the call to parseServerAuthority ensures that it is a URL (absolute or relative) and not a URN.

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

How to implement a read only property

yet another way (my favorite), starting with C# 6

private readonly int MyVal = 5;

public int MyProp => MyVal;

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions

getOutputStream() has already been called for this response

I had this problem only the second time I went to export. Once I added:

response.getOutputStream().flush();
response.getOutputStream().close();

after the export was done, my code started working all of the time.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

Android change SDK version in Eclipse? Unable to resolve target android-x

This can happen when you mistakenly import an Android project into your Eclipse workspace as a Java project. The solution in this case: delete the project from the workspace in the Package Explorer, then go to File -> Import -> Android -> Existing Android code into workspace.

How to destroy an object?

Short answer: Both are needed.

I feel like the right answer was given but minimally. Yeah generally unset() is best for "speed", but if you want to reclaim memory immediately (at the cost of CPU) should want to use null.

Like others mentioned, setting to null doesn't mean everything is reclaimed, you can have shared memory (uncloned) objects that will prevent destruction of the object. Moreover, like others have said, you can't "destroy" the objects explicitly anyway so you shouldn't try to do it anyway.

You will need to figure out which is best for you. Also you can use __destruct() for an object which will be called on unset or null but it should be used carefully and like others said, never be called directly!

see:

http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/

What is difference between assigning NULL and unset?

How to go from Blob to ArrayBuffer

Just to complement Mr @potatosalad answer.

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Why this is better? Because then we may use arrow function without losing the context

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

String to list in Python

Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

How can I find the length of a number?

A way for integers without banal converting to string:

var num = 9999999999; // your number
var length = 1;
while (num >= 10) {
   num /= 10;
   length++;
}
alert(length);

powershell - extract file name and extension

This is an adaptation, if anyone is curious. I needed to test whether RoboCopy successfully copied one file to multiple servers for its integrity:

   $Comp = get-content c:\myfile.txt

ForEach ($PC in $Comp) {
    dir "\\$PC\Folder\Share\*.*" | Select-Object $_.BaseName
}

Nice and simple, and it shows the directory and the file inside it. If you want to specify one file name or extension, just replace the *'s with whatever you want.

    Directory: \\SERVER\Folder\Share

Mode                LastWriteTime     Length Name                                                                                                                                             
----                -------------     ------ ----                                                                                                                                             
-a---         2/27/2015   5:33 PM    1458935 Test.pptx                                                                                                             

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Statement

DEFINER=username@`%

is an issue in your backup dump.

The solution that you can work around is to remove all the entry from sql dump file and import data from GCP console.

cat DUMP_FILE_NAME.sql | sed -e 's/DEFINER=<username>@%//g' > NEW-CLEANED-DUMP.sql

Try importing new file(NEW-CLEANED-DUMP.sql).

Move seaborn plot legend to a different position?

Modifying the example here:

You can use legend_out = False

import seaborn as sns
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                    data=titanic, kind="bar",
                    size=6, palette="muted",
                   legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")

enter image description here

How do you use "git --bare init" repository?

The --bare flag creates a repository that doesn’t have a working directory. The bare repository is the central repository and you can't edit(store) codes here for avoiding the merging error.

For example, when you add a file in your local repository (machine 1) and push it to the bare repository, you can't see the file in the bare repository for it is always 'empty'. However, you really push something to the repository and you can see it inexplicitly by cloning another repository in your server(machine 2).

Both the local repository in machine 1 and the 'copy' repository in machine 2 are non-bare. relationship between bare and non-bare repositories

The blog will help you understand it. https://www.atlassian.com/git/tutorials/setting-up-a-repository

Rails: select unique values from a column

Another way to collect uniq columns with sql:

Model.group(:rating).pluck(:rating)

What does -save-dev mean in npm install grunt --save-dev

--save-dev: Package will appear in your devDependencies.

According to the npm install docs.

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

In other words, when you run npm install, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).

According to the package.json docs

Edit: Attempt at visualising what npm install does:

  • yourproject
    • dependency installed
      • dependency installed
        • dependency installed
        • devDependency NOT installed
      • devDependency NOT installed
    • devDependency installed
      • dependency installed
      • devDependency NOT installed

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

How to Install Font Awesome in Laravel Mix

the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.

at first use this command to install font-awesome-free npm install --save-dev @fortawesome/fontawesome-free

after that you can do this

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";

and I copy the font path like below this is optional

.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');

and finally just run the script npm run dev or npm run watch in laravel

How can I parse a string with a comma thousand separator to a number?

It's baffling that they included a toLocaleString but not a parse method. At least toLocaleString without arguments is well supported in IE6+.

For a i18n solution, I came up with this:

First detect the user's locale decimal separator:

var decimalSeparator = 1.1;
decimalSeparator = decimalSeparator.toLocaleString().substring(1, 2);

Then normalize the number if there's more than one decimal separator in the String:

var pattern = "([" + decimalSeparator + "])(?=.*\\1)";separator
var formatted = valor.replace(new RegExp(pattern, "g"), "");

Finally, remove anything that is not a number or a decimal separator:

formatted = formatted.replace(new RegExp("[^0-9" + decimalSeparator + "]", "g"), '');
return Number(formatted.replace(decimalSeparator, "."));

Generate random integers between 0 and 9

While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):

How can I generate random integers between 0 and 9 (inclusive) in Python?

For clarity, here we demonstrate how to get multiple random integers.

Given

>>> import random


lo = 0
hi = 10
size = 5

Code

Multiple, Random Integers

# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]

# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]

# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]

# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]

# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]

Sample of Random Integers

# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]

# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]

Details

Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

See also R. Hettinger's talk on Chunking and Aliasing using examples from the random module.

Here is a comparison of some random functions in the Standard Library and Numpy:

| | random                | numpy.random                     |
|-|-----------------------|----------------------------------|
|A| random()              | random()                         |
|B| randint(low, high)    | randint(low, high)               |
|C| randrange(low, high)  | randint(low, high)               |
|D| shuffle(seq)          | shuffle(seq)                     |
|E| choice(seq)           | choice(seq)                      |
|F| choices(seq, k)       | choice(seq, size)                |
|G| sample(seq, k)        | choice(seq, size, replace=False) |

You can also quickly convert one of many distributions in Numpy to a sample of random integers.3

Examples

>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10,  3,  1, 16])

>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])

>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])

1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al. 2@prashanth mentions this module showing one integer. 3Demonstrated by @Siddharth Satpathy

Distribution certificate / private key not installed

If you are using the certificate in a new computer or not. The easiest thing to do would be to revoke the previous certificate relating to the project. Then re-upload to the store. Xcode will generate a new one.

How to do a recursive find/replace of a string with awk or sed?

find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

-print0 tells find to print each of the results separated by a null character, rather than a new line. In the unlikely event that your directory has files with newlines in the names, this still lets xargs work on the correct filenames.

\( -type d -name .git -prune \) is an expression which completely skips over all directories named .git. You could easily expand it, if you use SVN or have other folders you want to preserve -- just match against more names. It's roughly equivalent to -not -path .git, but more efficient, because rather than checking every file in the directory, it skips it entirely. The -o after it is required because of how -prune actually works.

For more information, see man find.

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

python variable NameError

In addition to the missing quotes around 100Mb in the last else, you also want to quote the constants in your if-statements if tSizeAns == "1":, because raw_input returns a string, which in comparison with an integer will always return false.

However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.

Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:

tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns] 

This however does only work as long as tSizeAns is guaranteed to be in the range of tSize. Otherwise you would have to either catch the KeyError exception or use a defaultdict:

lookup = {"1": "100Mb", "2": "200Mb"} try:     tSize = lookup[tSizeAns] except KeyError:     tSize = "100Mb" 

or

from collections import defaultdict  [...]  lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"}) tSize = lookup[tSizeAns] 

In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.

Login to website, via C#

Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest and HttpWebResponse otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie' didn't return anything despite other websites does.

So I think this where we need to store cookies for next Requests, so I added this.


To the "POSTing to the login form" code block :

var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;


And To the "GETting the page behind the login form" :

HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);


Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest and WebResponse with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET

super() in Java

For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

public class DeveloperSteps extends ScenarioSteps {

public DeveloperSteps(Pages pages) {
    super(pages);
}........

How to set data attributes in HTML elements

HTML

<div id="mydiv" data-myval="10"></div>

JS

var a = $('#mydiv').data('myval'); //getter

$('#mydiv').data('myval',20); //setter

Demo

Reference

From the reference:

jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

It should be noted that jQuery's data() doesn't change the data attribute in HTML.

So, if you need to change the data attribute in HTML, you should use .attr() instead.

HTML

<div id="outer">
    <div id="mydiv" data-myval="10"></div>
</div>

?JS:

alert($('#outer').html());   // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());   //alerts <div id="mydiv" data-myval="20"> </div>

See this demo

Find an object in array?

For example, if we had an array of numbers:

let numbers = [2, 4, 6, 8, 9, 10]

We could find the first odd number like this:

let firstOdd = numbers.index { $0 % 2 == 1 }

That will send back 4 as an optional integer, because the first odd number (9) is at index four.

Error: «Could not load type MvcApplication»

I just had this problem with an ASP.NET MVC Web API project and none of the solutions did the trick.

I managed to solve the problem by rebooting the machine. I did an upgrade to Visual Studio 2013, which didn't require reboot, but that was probably causing the problem.

how to check if a form is valid programmatically using jQuery Validation Plugin

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  form.submit();
}else{
  console.log("Required field missing.");
}

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

How do I use jQuery to redirect?

This is a shorthand Ajax function, which is equivalent to:

$.ajax({  type: "POST",
           url: url,  
          data: { username: value_login.val(), firstname: value_firstname.val(), 
                  lastname: value_lastname.val(), email: value_email.val(),
                  password: value_password.val()
                },
          dataType: "json"
       success: success// -> call your func here  
      });

Hope This helps

How to convert datetime format to date format in crystal report using C#?

In crystal report formulafield date function aavailable there pass your date-time format in that You Will get the Date only here

Example: Date({MyTable.dte_QDate})

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

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

:nth-last-child(-n+2) should do the trick

How to replace master branch in Git, entirely, from another branch?

I found this to be the best way of doing this (I had an issue with my server not letting me delete).

On the server that hosts the origin repository, type the following from a directory inside the repository:

git config receive.denyDeleteCurrent ignore

On your workstation:

git branch -m master vabandoned                 # Rename master on local
git branch -m newBranch master                  # Locally rename branch newBranch to master
git push origin :master                         # Delete the remote's master
git push origin master:refs/heads/master        # Push the new master to the remote
git push origin abandoned:refs/heads/abandoned  # Push the old master to the remote

Back on the server that hosts the origin repository:

git config receive.denyDeleteCurrent true

Credit to the author of blog post http://www.mslinn.com/blog/?p=772

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Get list of passed arguments in Windows batch script (.bat)

The following code simulates an array ('params') - takes the parameters received by the script and stores them in the variables params_1 .. params_n, where n=params_0=the number of elements of the array:

@echo off

rem Storing the program parameters into the array 'params':
rem Delayed expansion is left disabled in order not to interpret "!" in program parameters' values;
rem however, if a parameter is not quoted, special characters in it (like "^", "&", "|") get interpreted at program launch
set /a count=0
:repeat
    set /a count+=1
    set "params_%count%=%~1"
    shift
    if defined params_%count% (
        goto :repeat
    ) else (
        set /a count-=1
    )    
set /a params_0=count

rem Printing the program parameters stored in the array 'params':
rem After the variables params_1 .. params_n are set with the program parameters' values, delayed expansion can
rem be enabled and "!" are not interpreted in the variables params_1 .. params_n values
setlocal enabledelayedexpansion
    for /l %%i in (1,1,!params_0!) do (
        echo params_%%i: "!params_%%i!"
    )
endlocal

pause
goto :eof

php stdClass to array

The following code will read all emails & print the Subject, Body & Date.

<?php
  $imap=imap_open("Mailbox","Email Address","Password");
  if($imap){$fixMessages=1+imap_num_msg($imap);  //Check no.of.msgs
/*
By adding 1 to "imap_num_msg($imap)" & starting at $count=1
   the "Start" & "End" non-messages are ignored
*/
    for ($count=1; $count<$fixMessages; $count++){
      $objectOverview=imap_fetch_overview($imap,$count,0);
print '<br>$objectOverview: '; print_r($objectOverview);
print '<br>objectSubject ='.($objectOverview[0]->subject));
print '<br>objectDate ='.($objectOverview[0]->date);
      $bodyMessage=imap_fetchbody($imap,$count,1);
print '<br>bodyMessage ='.$bodyMessage.'<br><br>';
    }  //for ($count=1; $count<$fixMessages; $count++)
  }  //if($imap)
  imap_close($imap);
?>

This outputs the following:

$objectOverview: Array ( [0] => stdClass Object ( [subject] => Hello
[from] => Email Address [to] => Email Address [date] => Sun, 16 Jul 2017 20:23:18 +0100
[message_id] =>  [size] => 741 [uid] => 2 [msgno] => 2 [recent] => 0 [flagged] => 0 
[answered] => 0 [deleted] => 0 [seen] => 1 [draft] => 0 [udate] => 1500232998 ) )
objectSubject =Hello
objectDate =Sun, 16 Jul 2017 20:23:18 +0100
bodyMessage =Test 

Having struggled with various suggestions I have used trial & error to come up with this solution. Hope it helps.

How to prevent the "Confirm Form Resubmission" dialog?

Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.


When to use GET and POST:

One way to get rid of this error message is to make your form use GET instead of POST. Just keep in mind that this is not always an appropriate solution (read below).

Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.

Examples of when to use POST would include:

  • A login form
  • A contact form
  • A submit payment form
  • Something that adds, edits or deletes entries from a database
  • An image uploader (note, if using GET with an <input type="file"> field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)
  • A form with many fields (which would create a long URL if using GET)

In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.

Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.

Examples would include:

  • Performing a search in a search engine
  • A navigation form for navigating around the website
  • Performing one-time actions using a nonce or single use password (such as an "unsubscribe" link in an email).

In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.

If you use POST:

To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?

So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.

Here is a simple example using PHP:

if(!empty($_POST['username'] && !empty($_POST['password'])) {
    $user = new User;
    $user->login($_POST['username'], $_POST['password']);

    if ($user->isLoggedIn()) {
        header("Location: /admin/welcome.php");
        exit;
    }
    else {
        header("Location: /login.php?invalid_login");
    }
}

Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:

if (isset($_GET['invalid_login'])) {
    echo "Your username and password combination is invalid";
}

How to turn on front flash light programmatically in Android?

Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.

It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!

To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.


Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.

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

I thought I'd add that for Tomcat 7.x, <Context> is not in the server.xml, but in the context.xml. Removing and re-adding the project did not seem to help my similar issue, which was a web.xml issue, which I found out by checking the context.xml which had this line in the <Context> section:

<WatchedResource>WEB-INF/web.xml</WatchedResource>

The solution in WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property brought me closer to my answer, as the change of publishing into a separate XML did resolve the error reported above for me, but unfortunately it generated a second error that I'm still investigating.

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:myproject' did not find a matching property.

Convert object string to JSON

Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.

https://github.com/douglascrockford/JSON-js

Does a TCP socket connection have a "keep alive"?

For Windows according to Microsoft docs

  • KeepAliveTime (REG_DWORD, milliseconds, by default is not set which means 7,200,000,000 = 2 hours) - analogue to tcp_keepalive_time
  • KeepAliveInterval (REG_DWORD, milliseconds, by default is not set which means 1,000 = 1 second) - analogue to tcp_keepalive_intvl
  • Since Windows Vista there is no analogue to tcp_keepalive_probes, value is fixed to 10 and cannot be changed

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

How to get Android application id?

If your are looking for the value defined by applicationId in gradle, you can simply use

BuildConfig.APPLICATION_ID 

Converting any object to a byte array in java

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

Android studio doesn't list my phone under "Choose Device"

I know this is old and answered, but after 2 weeks of smashing my head on the table I FINALLY fixed my specific issue...

SAMSUNG KNOX was my problem. Version 2.2+ of MyKnox will not allow USB debugging.

I uninstalled MyKnox and now it works.

I hope this saves someone 2 weeks of head smashing.

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

Password masking console application

(My) nuget package to do this, based on the top answer:

install-package PanoramicData.ConsoleExtensions

Usage:

using PanoramicData.ConsoleExtensions;

...

Console.Write("Password: ");
var password = ConsolePlus.ReadPassword();
Console.WriteLine();

Project URL: https://github.com/panoramicdata/PanoramicData.ConsoleExtensions

Pull requests welcome.

Module is not available, misspelled or forgot to load (but I didn't)

It should be

var app = angular.module("MesaViewer", []);

This is the syntax you need to define a module and you need the array to show it has no dependencies.

You use the

angular.module("MesaViewer");

syntax when you are referencing a module you've already defined.

Dynamically creating keys in a JavaScript associative array

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

This is ok, but it iterates through every property of the array object.

If you want to only iterate through the properties myArray.one, myArray.two... you try like this:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

Now you can access both by myArray["one"] and iterate only through these properties.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Start the server in debug mode and It will track changes inside methods. Other changes It will ask to restart the module.

How to lose margin/padding in UITextView?

Storyboard or Interface Builder solution using User Defined Runtime Attributes:

Screenshots are of iOS 7.1 & iOS 6.1 with contentInset = {{-10, -5}, {0, 0}}.

User Defined Runtime Attributes

output

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

Installing Java on OS X 10.9 (Mavericks)

From the OP:

I finally reinstalled it from Java for OS X 2013-005. It solved this issue.

Div vertical scrollbar show

What browser are you testing in?

What DOCType have you set?

How exactly are you declaring your CSS?

Are you sure you haven't missed a ; before/after the overflow-y: scroll?

I've just tested the following in IE7 and Firefox and it works fine

_x000D_
_x000D_
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents -->        _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Call and receive output from Python script in Java?

First I would recommend to use ProcessBuilder ( since 1.5 )
Simple usage is described here
https://stackoverflow.com/a/14483787
For more complex example refer to
http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

I've encountered problem when launching Python script from Java, script was producing too much output to standard out and everything went bad.

how to declare global variable in SQL Server..?

There is no way to declare a global variable in Transact-SQL. However, if all you want your variables for is to be accessible across batches of a single script, you can use the SQLCMD tool or the SQLCMD mode of SSMS and define that tool/mode-specific variables like this:

:setvar myvar 10

and then use them like this:

$(myvar)

To use SSMS's SQLCMD mode:

enter image description here

Remove Array Value By index in jquery

Your example code is wrong and will throw a SyntaxError. You seem to have confused the syntax of creating an object Object with creating an Array.

The correct syntax would be: var arr = [ "abc", "def", "ghi" ];

To remove an item from the array, based on its value, use the splice method:

arr.splice(arr.indexOf("def"), 1);

To remove it by index, just refer directly to it:

arr.splice(1, 1);

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

Bootstrap modal: is not a function

The problem happened to me just in production just because I imported jquery with HTTP and not HTTPS (and production is HTTPS)

How to clear the cache in NetBeans

Just install cache eraser plugin, it is compatible with nb6.9, 7.0,7.1,7.2 and 7.3: To configure the plugin you have to provide the cache dir which is in netbean's about screen. Then with Tools->erase cache, you clear the netbeans cache. That is all, good luck.

http://plugins.netbeans.org/plugin/40014/cache-eraser

Multiple left-hand assignment with JavaScript

Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;.

If the value of any of these variables is 1 after this statement, then logically it must have started from the right, otherwise the value or var1 and var2 would be undefined.

You can think of it as equivalent to var var1 = (var2 = (var3 = 1)); where the inner-most set of parenthesis is evaluated first.

Maven2 property that indicates the parent directory

I've found a solution to solve this problem: use ${parent.relativePath}

<parent>
    <artifactId>xxx</artifactId>
    <groupId>xxx</groupId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
</parent>
<build>
    <filters>
        <filter>${parent.relativePath}/src/main/filters/filter-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

MongoDB "root" user

The best superuser role would be the root.The Syntax is:

use admin

db.createUser(
{
    user: "root",
    pwd: "password",
    roles: [ "root" ]
})

For more details look at built-in roles.

Hope this helps !!!

How can I upload files asynchronously?

You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.


var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2'); 
formData.append('file', $('input[type=file]')[0].files[0]);

$.ajax({
    url: 'post back url',
    data: formData,
// other attributes of AJAX
});

Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

How to fix Error: listen EADDRINUSE while using nodejs?

Error reason: You are trying to use the busy port number

Two possible solutions for Windows/Mac

  1. Free currently used port number
  2. Select another port number for your current program


1. Free Port Number

Windows

1. netstat -ano | findstr :4200
2. taskkill /PID 5824 /F

enter image description here

Mac

You can try netstat

netstat -vanp tcp | grep 3000

For OSX El Capitan and newer (or if your netstat doesn't support -p), use lsof

sudo lsof -i tcp:3000

if this does not resolve your problem, Mac users can refer to complete discussion about this issue Find (and kill) process locking port 3000 on Mac


2. Change Port Number?

Windows

set PORT=5000

Mac

export PORT=5000

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

If you have any programming experience, you can probably learn the C# syntax in a few hours, and be comfortable with it within a week or so. However, you will not be writing complex structures unless you write a lot of code with it. It's really the same as learning any language: you can learn all the words and grammer fairly quickly, but it takes a while to be fluent.

EDIT

A book you may want to pick up for learning C# is C# in a Nutshell (3.0) which I found to be very useful, and has been recommended by several people here.

c# dictionary How to add multiple values for single key?

If I understood what you want:

dictionary.Add("key", new List<string>()); 

later...

dictionary["key"].Add("string to your list");

Defining and using a variable in batch file

The spaces are significant. You created a variable named 'location ' with a value of
' "bob"'. Note - enclosing single quotes were added to show location of space.

If you want quotes in your value, then your code should look like

set location="bob"

If you don't want quotes, then your code should look like

set location=bob

Or better yet

set "location=bob"

The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like & | etc.

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

Learn about CORS, try crossorigin.me is work fine

Example: https://crossorigin.me/https://fr.s.us/js/jquery-ui.css

Not show a message error and continue page white, u need see error is try

http://cors.io/?u=https://fr.s.us/js/jquery-ui.css

enjoin us ;-)

Suppress warning messages using mysql from within Terminal, but password written in bash script

shell> mysql_config_editor set --login-path=local
     --host=localhost --user=localuser --password
Enter password: enter password "localpass" here
shell> mysql_config_editor set --login-path=remote
     --host=remote.example.com --user=remoteuser --password
Enter password: enter password "remotepass" here

To see what mysql_config_editor wrote to the .mylogin.cnf file, use the print command:

shell> mysql_config_editor print --all
[local]
user = localuser
password = *****
host = localhost
[remote]
user = remoteuser
password = *****
host = remote.example.com

The print command displays each login path as a set of lines beginning with a group header indicating the login path name in square brackets, followed by the option values for the login path. Password values are masked and do not appear as clear text.

As shown by the preceding examples, the .mylogin.cnf file can contain multiple login paths. In this way, mysql_config_editor makes it easy to set up multiple “personalities” for connecting to different MySQL servers. Any of these can be selected by name later using the --login-path option when you invoke a client program. For example, to connect to the local server, use this command:

shell> mysql --login-path=local

To connect to the remote server, use this command:

shell> mysql --login-path=remote

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

Difference between the Apache HTTP Server and Apache Tomcat?

If you are using java technology(Servlet/JSP) for making web application you will probably use Apache Tomcat. However, if you are using other technologies like Perl, PHP or ruby, its better(easier) to use Apache HTTP Server.

Complex nesting of partials and templates

Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.

EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.

Here's the main app page

<!-- primary nav -->
<a href="#/page/1">Page 1</a>
<a href="#/page/2">Page 2</a>
<a href="#/page/3">Page 3</a>

<!-- display the view -->
<div ng-view>
</div>

Directive for the sub navigation

app.directive('mySubNav', function(){
    return {
        restrict: 'E',
        scope: {
           current: '=current'
        },
        templateUrl: 'mySubNav.html',
        controller: function($scope) {
        }
    };
});

template for the sub navigation

<a href="#/page/1/sub/1">Sub Item 1</a>
<a href="#/page/1/sub/2">Sub Item 2</a>
<a href="#/page/1/sub/3">Sub Item 3</a>

template for a main page (from primary nav)

<my-sub-nav current="sub"></my-sub-nav>

<ng-switch on="sub">
  <div ng-switch-when="1">
      <my-sub-area1></my-sub-area>
  </div>
  <div ng-switch-when="2">
      <my-sub-area2></my-sub-area>
  </div>
  <div ng-switch-when="3">
      <my-sub-area3></my-sub-area>
  </div>
</ng-switch>

Controller for a main page. (from the primary nav)

app.controller('page1Ctrl', function($scope, $routeParams) {
     $scope.sub = $routeParams.sub;
});

Directive for a Sub Area

app.directive('mySubArea1', function(){
    return {
        restrict: 'E',
        templateUrl: 'mySubArea1.html',
        controller: function($scope) {
            //controller for your sub area.
        }
    };
});

Select distinct values from a table field

Say your model is 'Shop'

class Shop(models.Model):
    street = models.CharField(max_length=150)
    city = models.CharField(max_length=150)

    # some of your models may have explicit ordering
    class Meta:
        ordering = ('city')

Since you may have the Meta class ordering attribute set, you can use order_by() without parameters to clear any ordering when using distinct(). See the documentation under order_by()

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.

and distinct() in the note where it discusses issues with using distinct() with ordering.

To query your DB, you just have to call:

models.Shop.objects.order_by().values('city').distinct()

It returns a dictionnary

or

models.Shop.objects.order_by().values_list('city').distinct()

This one returns a ValuesListQuerySet which you can cast to a list. You can also add flat=True to values_list to flatten the results.

See also: Get distinct values of Queryset by field

How are parameters sent in an HTTP POST request?

You cannot type it directly on the browser URL bar.

You can see how POST data is sent on the Internet with Live HTTP Headers for example. Result will be something like that

http://127.0.0.1/pass.php
POST /pass.php HTTP/1.1

Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1/pass.php
Cookie: passx=87e8af376bc9d9bfec2c7c0193e6af70; PHPSESSID=l9hk7mfh0ppqecg8gialak6gt5
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
username=zurfyx&pass=password

Where it says

Content-Length: 30
    username=zurfyx&pass=password

will be the post values.

Operation must use an updatable query. (Error 3073) Microsoft Access

Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.

I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.

BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.

--

Serialize form data to JSON

I couldn't find an answer that would solve this:

[{name:"Vehicle.Make", value: "Honda"}, {name:"Vehicle.VIN", value: "123"}]

This calls for this object:

{Vehicle: {Make: "Honda", "VIN": "123"}}

So I had to write a serializer of my own that would solve this:

function(formArray){
        var obj = {};
        $.each(formArray, function(i, pair){
            var cObj = obj, pObj, cpName;
            $.each(pair.name.split("."), function(i, pName){
                pObj = cObj;
                cpName = pName;
                cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
            });
            pObj[cpName] = pair.value;
        });
        return obj;
    }

Maybe it will help somebody.

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

How to delete an element from a Slice in Golang

To remove an element from the middle of a slice, preserving the order of the remaining elements, use copy to slide the higher-numbered elements down by one to fill the gap:

func remove(slice []int, i int) []int {
  copy(slice[i:], slice[i+1:])
  return slice[:len(slice)-1]
}

If it is not necessary to preserve the order, we can simply move the last element to the gap.

func remove(slice []int, i int) []int {
  slice[i] = slice[len(slice)-1]
  return slice[:len(slice)-1]
}

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

Accessing the web page's HTTP Headers in JavaScript

It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.


Use the following JavaScript code to get all the HTTP headers by performing a get request:

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

com.jcraft.jsch.JSchException: UnknownHostKey

setting known host is better than setting fingure print value.

When you set known host, try to manually ssh (very first time, before application runs) from the box the application runs.

Proper way to renew distribution certificate for iOS

Your live apps will not be taken down. Nothing will happen to anything that is live in the app store.

Once they formally expire, the only thing that will be impacted is your ability to sign code (and thus make new builds and provide updates).

Regarding your distribution certificate, once it expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. If you want to renew it before it expires, revoke the current certificate and you will get a button to request a new one.

Regarding the provisioning profile, don't worry about it before expiration, just keep using it. It's easy enough to just renew it once it expires.

The peace of mind is that nothing will happen to your live app in the store.

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

multiple conditions for filter in spark data frames

df2 = df1.filter("Status = 2 OR Status = 3")

Worked for me.

Check if $_POST exists

I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values. $_POST['value'] may not exist, thus throwing an "undefined index" error.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

Draw path between two points using Google Maps Android API v2

First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.

 public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString( sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString( destlat));
        urlString.append(",");
        urlString.append(Double.toString( destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        urlString.append("&key=YOUR_API_KEY");
        return urlString.toString();
 }

This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

This parser will return us string. We will call it like that.

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);

Now we will send this string to our drawpath function. The drawpath function is

public void drawPath(String  result) {

    try {
            //Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);
           Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                    .geodesic(true)
                    );
           /*
           for(int z = 0; z<list.size()-1;z++){
                LatLng src= list.get(z);
                LatLng dest= list.get(z+1);
                Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                .width(2)
                .color(Color.BLUE).geodesic(true));
            }
           */
    } 
    catch (JSONException e) {

    }
} 

Above code will draw the path on mMap. The code of decodePoly is

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng( (((double) lat / 1E5)),
                 (((double) lng / 1E5) ));
        poly.add(p);
    }

    return poly;
}

As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was

private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

I hope it will help.

How to save a figure in MATLAB from the command line?

When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.

source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

Update a submodule to the latest commit

Single line version

git submodule foreach "(git checkout master; git pull; cd ..; git add '$path'; git commit -m 'Submodule Sync')"

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

How can I programmatically get the MAC address of an iphone

It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.

As Apple stated:

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)

Simplest two-way encryption using PHP

PHP 7.2 moved completely away from Mcrypt and the encryption now is based on the maintainable Libsodium library.

All your encryption needs can be basically resolved through Libsodium library.

// On Alice's computer:
$msg = 'This comes from Alice.';
$signed_msg = sodium_crypto_sign($msg, $secret_sign_key);


// On Bob's computer:
$original_msg = sodium_crypto_sign_open($signed_msg, $alice_sign_publickey);
if ($original_msg === false) {
    throw new Exception('Invalid signature');
} else {
    echo $original_msg; // Displays "This comes from Alice."
}

Libsodium documentation: https://github.com/paragonie/pecl-libsodium-doc

Adding a simple spacer to twitter bootstrap

In Bootstrap 4 you can use classes like mt-5, mb-5, my-5, mx-5 (y for both top and bottom, x for both left and right).

According to their site:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Link: https://getbootstrap.com/docs/4.0/utilities/spacing/

Where is virtualenvwrapper.sh after pip install?

pip will not try to make things difficult for you on purpose.

The thing is commands based files are always installed in /bin folders they can be anywhere on the system path.

I had the same problem and I found that I have these files in my

~/.local/bin/

folder instead of

/usr/loca/bin/

which is the common case, but I think they changed the default path to

~ or $HOME

directory because its more isolate for the pip installations and provides a distinction between apt-get packages and pip packages.

So coming to the point you have two choices here either you go to your .bashrc and make changes like this

# for virtualenv wrapper
export WORKON_HOME=$HOME/Envs
export PROJECT_HOME=$HOME/Devel
source $HOME/.local/bin/virtualenvwrapper.sh

and than create a directory virtualenvwrapper under /usr/share/ and than symlink your virtualwrapper_lazy.sh like this

sudo ln -s ~/.local/bin/virtualenvwrapper_lazy.sh /usr/share/virtualenvwrapper/virtualenvwrapper_lazy.sh

and you can check if your workon command is working which will list your existing virtualenv's.

Python division

It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.

Example: Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:

>>> a = 1/2/3/4/5/4/3
>>> a
0

When we divide integers, not surprisingly it gets lower rounded.

>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0

If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.

>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0

Same scenario as above but shifting the float typecast a little closer to the left side.

>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445

Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.

Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this

Extra 2: Please be careful of the following scenario:

>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0

What does "dereferencing" a pointer mean?

Reviewing the basic terminology

It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....

  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.
  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know" at the end of this answer.

When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.

Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.

A pointer scenario

Consider in C, given a pointer such as p below...

const char* p = "abc";

...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p. This way C encodes text in memory is known as ASCIIZ.

For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.

Dereferencing the pointer

To refer to the characters p points to, we dereference p using one of these notations (again, for C):

assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
                     // p and 1 times the size of the things to which p points:
                     // In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b');  // Another notation for p[1]

You can also move pointers through the pointed-to data, dereferencing them as you go:

++p;  // Increment p so it's now 0x1001
assert(*p == 'b');  // p == 0x1001 which is where the 'b' is...

If you have some data that can be written to, then you can do things like this:

int x = 2;
int* p_x = &x;  // Put the address of the x variable into the pointer p_x
*p_x = 4;       // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4

Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.

Dereferencing and accessing a structure data member

In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:

typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159;  // Dereference and access data member x.d_
(*p).d_ *= -1;    // Another equivalent notation for accessing x.d_

Multi-byte data types

To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.

So, looking at a slightly more complex example:

double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3);  // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4);  // Actually looks at bytes from address p + 1 * sizeof(double)
                       // (sizeof(double) is almost always eight bytes)
++p;                   // Advance p by sizeof(double)
assert(*p == 13.4);    // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;       // Change sizes[3] from 19.4 to 29.8
                       // Note earlier ++p and + 2 here => sizes[3]

Pointers to dynamically allocated memory

Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...

int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10;            // Dereference the pointer to the memory, then write a value in
fn(*p);             // Call a function, passing it the value at address p
(*p) += 3;          // Change the value, adding 3 to it
free(p);            // Release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete:

int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10];      // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10]();    // Memory for ten ints that are value initialised (to 0)
delete[] p;

See also C++ smart pointers below.

Losing and leaking addresses

Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...

const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
    if (!isprint(*q))
        *q = '_';

printf("%s\n", p); // Only q was modified
free(p);

...or carefully orchestrate reversal of any changes...

const size_t n = ...;
p += n;
...
p -= n;  // Restore earlier value...
free(p);

C++ smart pointers

In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...

{
    std::unique_ptr<T> p{new T(42, "meaning")};
    call_a_function(p);
    // The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete

...and shared_ptr for share ownership (using reference counting)...

{
    auto p = std::make_shared<T>(3.14, "pi");
    number_storage1.may_add(p); // Might copy p into its container
    number_storage2.may_add(p); // Might copy p into its container    } // p's destructor will only delete the T if neither may_add copied it

Null pointers

In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:

const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
    switch (c) {
      case f: p_filename = optarg; break;
    }
if (p_filename)  // Only NULL converts to false
    ...   // Only get here if -f flag specified

In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).

Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...

More about memory addresses, and why you probably don't need to know

More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.

The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.

For example, an int* properly initialised to point to an int variable might - after casting to a float* - access memory in "GPU" memory quite distinct from the memory where the int variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int* effectively a random, invalid pointer within these other memory regions).

3GL programming languages like C and C++ tend to hide this complexity, such that:

  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used

  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"

  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them

  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));

and:

if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

How to find a text inside SQL Server procedures / triggers?

You can find it like

SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'

It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info

How can I display a modal dialog in Redux that performs asynchronous actions?

A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.

Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?

I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale

Rationale

react/react-dom comes comes with 2 basic assumptions/ideas:

  • every UI is hierarchical naturally. This why we have the idea of components which wrap each other
  • react-dom mounts (physically) child component to its parent DOM node by default

The problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.

Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your UI element: it'll render in fixed layer and should know its coordinates (which are that UI element coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.

Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...

How to convert a string to ASCII

I think this code may be help you:

string str = char.ConvertFromUtf32(65)

for each inside a for each - Java

most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...

Error inflating class android.support.v7.widget.Toolbar?

Please read this Google Blog post: http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html

<android.support.v7.widget.Toolbar
    android:id="@+id/my_awesome_toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />

Also, you are giving it the same "ID" twice, please remove the "id" from your include:

<include android:id="@+id/toolbar" layout="@layout/toolbar" />

Subversion stuck due to "previous operation has not finished"?

In my case, the error appeared when trying to commit from within an IDE. When I executed the commit of the same directories with TortoiseSVN in the explorer, the operation succeeded.

jQuery map vs. each

var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});

//lets use map function
$.map(intArray, function(element, index) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2,4,5. skip the number 3.
});

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

This cannot be done in one statement. You will have to use 2 statements

DELETE FROM TB1 WHERE PersonID = '2';
DELETE FROM TB2 WHERE PersonID = '2';

What is the difference between a web API and a web service?

Two things are very simple to understand,

  1. API: It's an layer on application which can serve other application request locally.
  2. Webs Service:Is an API which can serve request and respond over the network form remote system over the web or internet .

Note: All Web Service is API's but not all API' is web services

How to get datetime in JavaScript?

You can convert Date to almost any format using the Snippet I have added below.

Code:

dateFormat(new Date(),"dd/mm/yy h:MM TT")
//"20/06/14 6:49 PM"

Other examples

// Can also be used as a standalone function
dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

dateFormat(new Date(),"dddd d mmmm yyyy")
//Monday 2 June 2014"

Snippet:

Add following code taken from this link into your code.

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

setHintTextColor() in EditText

Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this

Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);

If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

VBA Excel - Insert row below with same format including borders and frames

Private Sub cmdInsertRow_Click()

    Dim lRow As Long
    Dim lRsp As Long
    On Error Resume Next

    lRow = Selection.Row()
    lRsp = MsgBox("Insert New row above " & lRow & "?", _
            vbQuestion + vbYesNo)
    If lRsp <> vbYes Then Exit Sub

    Rows(lRow).Select
    Selection.Copy
    Rows(lRow + 1).Select
    Selection.Insert Shift:=xlDown
    Application.CutCopyMode = False

   'Paste formulas and conditional formatting in new row created
    Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

End Sub

This is what I use. Tested and working,

Thanks,

Mac OS X and multiple Java versions

The cleanest way to manage multiple java versions on Mac is to use Homebrew.

And within Homebrew, use:

  • homebrew-cask to install the versions of java
  • jenv to manage the installed versions of java

As seen on http://hanxue-it.blogspot.ch/2014/05/installing-java-8-managing-multiple.html , these are the steps to follow.

  1. install homebrew
  2. install homebrew jenv
  3. install homebrew-cask
  4. install a specific java version using cask (see "homebrew-cask versions" paragraph below)
  5. add this version for jenv to manage it
  6. check the version is correctly managed by jenv
  7. repeat steps 4 to 6 for each version of java you need

homebrew-cask versions

Add the homebrew/cask-versions tap to homebrew using:

brew tap homebrew/cask-versions

Then you can look at all the versions available:

brew search java

Then you can install the version(s) you like:

brew cask install java7
brew cask install java6

And add them to be managed by jenv as usual.

jenv add <javaVersionPathHere>

I think this is the cleanest & simplest way to go about it.


Another important thing to note, as mentioned in Mac OS X 10.6.7 Java Path Current JDK confusing :

For different types of JDKs or installations, you will have different paths

You can check the paths of the versions installed using /usr/libexec/java_home -V, see How do I check if the Java JDK is installed on Mac?

On Mac OS X Mavericks, I found as following:

1) Built-in JRE default: /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

2) JDKs downloaded from Apple: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/

3) JDKs downloaded from Oracle: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home


Resources

How to solve maven 2.6 resource plugin dependency?

Step 1 : Check the proxy configured in eclipse is correct or not ? (Window->Preferences->General->Network Connections).

Step 2 : Right Click on Project-> Go to Maven -> Update the project

Step 3: Run as Maven Install.

==== By Following these steps, i am able to solve this error.

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

My problem was, that Visual Studio somehow automatically lowercased *ngFor to *ngfor on copy&paste.

JavaScript validation for empty input field

if(document.getElementById("question").value.length == 0)
{
    alert("empty")
}

python max function using 'key' and lambda expression

max function is used to get the maximum out of an iterable.

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

If no key argument is provided, the maximum is returned according to default Python orderings.

Examples -

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')

How to open a Bootstrap modal window using jQuery?

Try this. It's works for me well.

_x000D_
_x000D_
function clicked(item) {
         alert($(item).attr("id"));
        }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-rtl/3.4.0/css/bootstrap-rtl.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button onclick="clicked(this);" id="modalME">Click me</button>

<!-- Modal -->
  <div class="modal" id="modalME" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-header">
        <h2>Modal in CSS</h2>
        <a href="#close" class="btn-close" aria-hidden="true">×</a> <!--CHANGED TO "#close"-->
      </div>
      <div class="modal-body">
        <p>One modal example here.</p>
      </div>
      <div class="modal-footer">
        <a href="#close" class="btn">Nice!</a>  <!--CHANGED TO "#close"-->
      </div>
      </div>
    </div>
  </div>
  <!-- /Modal -->
_x000D_
_x000D_
_x000D_

GoTo Next Iteration in For Loop in java

use continue keyword .

EX:

for(int i = 0; i < 10; i++){
  if(i == 5){
    continue;
   }
}