Programs & Examples On #Guid generation

Send multiple checkbox data to PHP via jQuery ajax()

You may also try this,

var arr = $('input[name="myCheckboxes[]"]').map(function(){
  return $(this).val();
}).get();

console.log(arr);

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

You could resolve the problem with:

for line in open(your_file_path, 'rb'):

'rb' is reading the file in binary mode. Read more here.

Configure nginx with multiple locations with different root folders on subdomain

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

http://nginx.org/r/root

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

I had the same problem, but I had my activity declared in the Manifest file, with the correct name.

My problem was that I didn't have to imported a third party libraries in a "libs" folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar...).

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \
      http://localhost:3570/index.php/trainingServer/screencast.json

and see if that helps any.

Finding index of character in Swift String

Swift 5.0

public extension String {  
  func indexInt(of char: Character) -> Int? {
    return firstIndex(of: char)?.utf16Offset(in: self)
  }
}

Swift 4.0

public extension String {  
  func indexInt(of char: Character) -> Int? {
    return index(of: char)?.encodedOffset        
  }
}

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

Detect if device is iOS

Detecting iOS (both <12, and 13+)

Community wiki, as edit queue says it is full and all other answers are currently outdated or incomplete.

const iOS_1to12 = /iPad|iPhone|iPod/.test(navigator.platform);

const iOS13_iPad = (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1));

const iOS1to12quirk = function() {
  var audio = new Audio(); // temporary Audio object
  audio.volume = 0.5; // has no effect on iOS <= 12
  return audio.volume === 1;
};

const isIOS = !window.MSStream && (iOS_1to12 || iOS13_iPad || iOS1to12quirk());

How to set the value of a hidden field from a controller in mvc

if you are not using model as per your question you can do like this

@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })

else if you are using model (considering passing model has hdnFlag property), you can use this approch

@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

Matplotlib/pyplot: How to enforce axis range?

I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show function and savefig function.

  1. before you plot:

    fig = pylab.figure()
    ax = fig.gca()
    ax.set_autoscale_on(False)
    

This is to request an ax which is subplot(1,1,1).

  1. During the plot:

    ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
    ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
    
  2. After the plot:

    1. To show the image :

      fig.show()
      
    2. To save the figure :

      fig.savefig('the name of your figure')
      

I find out that put axis at the front of the code won't work even though I have set autoscale_on to False.

I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation. img

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

What does "exited with code 9009" mean during this build?

I have had the error 9009 when my post build event script was trying to run a batch file that did not exist in the path specified.

Combining (concatenating) date and time into a datetime

dealing with dates, dateadd must be used for precision

declare @a DATE = getdate()
declare @b time(7) = getdate()
select @b, @A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, @a), cast(@b as datetime2(0)))

Can I get the name of the currently running function in JavaScript?

According to MDN

Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

As noted this applies only if your script uses "strict mode". This is mainly for security reasons and sadly currently there's no alternative for this.

Icons missing in jQuery UI

You need downbload the jQueryUI, this contains de images that you need

enter link description here

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

What's the simplest way of detecting keyboard input in a script from the terminal?

The Python Documentation provides this snippet to get single characters from the keyboard:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            if c:
                print("Got character", repr(c))
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

You can also use the PyHook module to get your job done.

How to select multiple rows filled with constants?

select (level - 1) * row_dif + 1 as a, (level - 1) * row_dif + 2 as b, (level - 1) * row_dif + 3 as c
    from dual 
    connect by level <= number_of_rows;

something like that

select (level - 1) * 3 + 1 as a, (level - 1) * 3 + 2 as b, (level - 1) * 3 + 3 as c
    from dual 
    connect by level <= 3;

PHP: Get key from array?

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

libz.so.1: cannot open shared object file

This worked for me

sudo apt-get install libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5

Read a file one line at a time in node.js?

Since posting my original answer, I found that split is a very easy to use node module for line reading in a file; Which also accepts optional parameters.

var split = require('split');
fs.createReadStream(file)
    .pipe(split())
    .on('data', function (line) {
      //each chunk now is a seperate line! 
    });

Haven't tested on very large files. Let us know if you do.

Xcode 10: A valid provisioning profile for this executable was not found

I just disable my device from Apple Developer then problem solved. (tested many times on Xcode 12.4)

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

When you say you deleted references to those projects and re-added them, how did you re-add them, exactly? Did you use the "Browse" tab in the "Add Reference" dialog in Visual Studio? Or, did you use the "Projects" tab (which lists neighboring projects in your solution)?

Edit: If you use the "Browse" tab, and manually add the reference to your .dll that is located in the /Release folder, then Visual Studio will always look for the .dll in that location, regardless of what mode you're currently in (Debug or Release).

If you removed the actual .dll file from the Release folder (either manually or by doing "Clean Solution"), then your reference will break because the .dll does not exist.

I'd suggest removing the reference to ProjectX.dll, and add it in again--but this time, use the "Projects" tab in the "Add Reference" dialog. When you add a reference this way, Visual Studio knows where to get the appropriate .dll. If you're in Debug mode, it will get it from the /Debug folder. If in Release mode, the /Release folder. Your build error should go away, and you also will no longer be (improperly) referencing a Release .dll while in Debug mode.

How do I resolve "Run-time error '429': ActiveX component can't create object"?

I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

All these answers are fine if you execute one line at a time. However, the original question was to input a sql script that would be executed by a single db execute and all the solutions ( like checking to see if the column is there ahead of time ) would require the executing program either have knowledge of what tables and columns are being altered/added or do pre-processing and parsing of the input script to determine this information. Typically you are not going to run this in realtime or often. So the idea of catching an exception is acceptable and then moving on. Therein lies the problem...how to move on. Luckily the error message gives us all the information we need to do this. The idea is to execute the sql if it exceptions on an alter table call we can find the alter table line in the sql and return the remaining lines and execute until it either succeeds or no more matching alter table lines can be found. Heres some example code where we have sql scripts in an array. We iterate the array executing each script. We call it twice to get the alter table command to fail but the program succeeds because we remove the alter table command from the sql and re-execute the updated code.

#!/bin/sh
# the next line restarts using wish \

exec /opt/usr8.6.3/bin/tclsh8.6  "$0" ${1+"$@"}
foreach pkg {sqlite3 } {
    if { [ catch {package require {*}$pkg } err ] != 0 } {
    puts stderr "Unable to find package $pkg\n$err\n ... adjust your auto_path!";
    }
}
array set sqlArray {
    1 {
    CREATE TABLE IF NOT EXISTS Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      );
    CREATE TABLE IF NOT EXISTS Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        );
    INSERT INTO Version(version) values('1.0');
    }
    2 {
    CREATE TABLE IF NOT EXISTS Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        );
    ALTER TABLE Notes ADD COLUMN dump text;
    INSERT INTO Version(version) values('2.0');
    }
    3 {
    ALTER TABLE Version ADD COLUMN sql text;
    INSERT INTO Version(version) values('3.0');
    }
}

# create db command , use in memory database for demonstration purposes
sqlite3 db :memory:

proc createSchema { sqlArray } {
    upvar $sqlArray sql
    # execute each sql script in order 
    foreach version [lsort -integer [array names sql ] ] {
    set cmd $sql($version)
    set ok 0
    while { !$ok && [string length $cmd ] } {  
        try {
        db eval $cmd
        set ok 1  ;   # it succeeded if we get here
        } on error { err backtrace } {
        if { [regexp {duplicate column name: ([a-zA-Z0-9])} [string trim $err ] match columnname ] } {
            puts "Error:  $err ... trying again" 
            set cmd [removeAlterTable $cmd $columnname ]
        } else {
            throw DBERROR "$err\n$backtrace"
        }
        }
    }
    }
}
# return sqltext with alter table command with column name removed
# if no matching alter table line found or result is no lines then
# returns ""
proc removeAlterTable { sqltext columnname } {
    set mode skip
    set result [list]
    foreach line [split $sqltext \n ] {
    if { [string first "alter table" [string tolower [string trim $line] ] ] >= 0 } {
        if { [string first $columnname $line ] } {
        set mode add
        continue;
        }
    }
    if { $mode eq "add" } {
        lappend result $line
    }
    }
    if { $mode eq "skip" } {
    puts stderr "Unable to find matching alter table line"
    return ""
    } elseif { [llength $result ] }  { 
    return [ join $result \n ]
    } else {
    return ""
    }
}
               
proc printSchema { } {
    db eval { select * from sqlite_master } x {
    puts "Table: $x(tbl_name)"
    puts "$x(sql)"
    puts "-------------"
    }
}
createSchema sqlArray
printSchema
# run again to see if we get alter table errors 
createSchema sqlArray
printSchema

expected output

Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------
Error:  duplicate column name: dump ... trying again
Error:  duplicate column name: sql ... trying again
Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------

Cannot drop database because it is currently in use

A brute force workaround could be:

  1. Stop the SQL Server Service.

  2. Delete the corresponding .mdf and .ldf files.

  3. Start the SQL Server Service.

  4. Connect with SSMS and delete the database.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry

ValueError: invalid literal for int () with base 10

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

ASP.NET MVC DropDownListFor with model of type List<string>

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })

Which gives a drop down list like so:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

Writing File to Temp Folder

The Path class is very useful here.
You get two methods called

Path.GetTempFileName

Path.GetTempPath

that could solve your issue

So for example you could write: (if you don't mind the exact file name)

using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
{
    sw.WriteLine("Your error message");
}

Or if you need to set your file name

string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
using(StreamWriter sw = new StreamWriter(myTempFile))
{
     sw.WriteLine("Your error message");
}

Installing NumPy via Anaconda in Windows

I had the same problem, getting the message "ImportError: No module named numpy".

I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:

conda list

So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:

conda install numpy

After I did that, the error with the import numpy was gone

instantiate a class from a variable in PHP?

How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);

Thanks to DisgruntledGoat for pointing that out.

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

What function is to replace a substring from a string in C?

You can use strrep()

char* strrep ( const char * cadena, const char * strf, const char * strr )

strrep (String Replace). Replaces 'strf' with 'strr' in 'cadena' and returns the new string. You need to free the returned string in your code after using strrep.

Parameters cadena The string with the text. strf The text to find. strr The replacement text.

Returns The text updated wit the replacement.

Project can be found at https://github.com/ipserc/strrep

How to use UTF-8 in resource properties with ResourceBundle

I tried to use the approach provided by Rod, but taking into consideration BalusC concern about not repeating the same work-around in all the application and came with this class:

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyResourceBundle {

    // feature variables
    private ResourceBundle bundle;
    private String fileEncoding;

    public MyResourceBundle(Locale locale, String fileEncoding){
        this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
        this.fileEncoding = fileEncoding;
    }

    public MyResourceBundle(Locale locale){
        this(locale, "UTF-8");
    }

    public String getString(String key){
        String value = bundle.getString(key); 
        try {
            return new String(value.getBytes("ISO-8859-1"), fileEncoding);
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }
}

The way to use this would be very similar than the regular ResourceBundle usage:

private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)

Or you can use the alternate constructor which uses UTF-8 by default:

private MyResourceBundle labels = new MyResourceBundle("es");

How to Set AllowOverride all

SuSE Linux Enterprise Server

Make sure you are editing the right file https://www.suse.com/documentation/sles11/book_sle_admin/data/sec_apache2_configuration.html

httpd.conf

The main Apache server configuration file. Avoid changing this file. It primarily contains include statements and global settings. Overwrite global settings in the pertinent configuration files listed here. Change host-specific settings (such as document root) in your virtual host configuration.

In such case vhosts.d/*.conf must be edited

How to install popper.js with Bootstrap 4?

Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.

For Bootstrap 4.1

Error Running React Native App From Terminal (iOS)

For me, it turns out that there was an iOS system update pending asking to restart the computer. Restart and let the update finish solved my problem.

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

Laravel: How to Get Current Route Name? (v5 ... v7)

I have used for getting route name in larvel 5.3

Request::path()

IF...THEN...ELSE using XML

Perhaps another way to code conditional constructs in XML:

<rule>
    <if>
        <conditions>
            <condition var="something" operator="&gt;">400</condition>
            <!-- more conditions possible -->
        </conditions>
        <statements>
            <!-- do something -->
        </statements>
    </if>
    <elseif>
        <conditions></conditions>
        <statements></statements>
    </elseif>
    <else>
        <statements></statements>
    </else>
</rule>

How to get domain URL and application name?

I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

At first you need to have enabled curl extension in PHP. Then you can use this function:

function file_get_contents_ssl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

It works similar to function file_get_contents(..).

Example:

echo file_get_contents_ssl("https://www.example.com/");

Output:

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

How do you disable viewport zooming on Mobile Safari?

This works fine in IOS 10.3.2

    document.addEventListener('touchmove', function(event) {
        event = event.originalEvent || event;
        if (event.scale !== 1) {
           event.preventDefault();
        }
    }, false);

thank you @arthur and @aleclarson

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

Open source face recognition for Android

You use class media.FaceDetector in android to detect face for free.

This is an example of face detection: https://github.com/betri28/FaceDetectCamera

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

jQuery counter to count up to a target number

I ended up creating my own plugin. Here it is in case this helps anyone:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});
        
        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;
        
        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);
            
            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));
                
                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }
                
                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;
                    
                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };
    
    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

Here's some sample code of how to use it:

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 1000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
//--></script>

<span class="timer"></span>

View the demo on JSFiddle: http://jsfiddle.net/YWn9t/

No Main class found in NetBeans

In project properties, under the run tab, specify your main class. Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.

Why is setTimeout(fn, 0) sometimes useful?

By calling setTimeout you give the page time to react to the whatever the user is doing. This is particularly helpful for functions run during page load.

Spring cron expression for every day 1:01:am

Something missing from gipinani's answer

@Scheduled(cron = "0 1 1,13 * * ?", zone = "CST")

This will execute at 1.01 and 13.01. It can be used when you need to run the job without a pattern multiple times a day.

And the zone attribute is very useful, when you do deployments in remote servers. This was introduced with spring 4.

Check if a row exists, otherwise insert

This is something I just recently had to do:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
    (
      @CustomerID AS INT,
      @UserName AS VARCHAR(25),
      @Password AS BINARY(16)
    )
AS 
    BEGIN
        IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
        BEGIN
            INSERT INTO [tblOnline_CustomerAccount] (
                [CustomerID],
                [UserName],
                [Password],
                [LastLogin]
            ) VALUES ( 
                /* CustomerID - int */ @CustomerID,
                /* UserName - varchar(25) */ @UserName,
                /* Password - binary(16) */ @Password,
                /* LastLogin - datetime */ NULL ) 
        END
        ELSE
        BEGIN
            UPDATE  [tblOnline_CustomerAccount]
            SET     UserName = @UserName,
                    Password = @Password
            WHERE   CustomerID = @CustomerID    
        END

    END

Can HTML checkboxes be set to readonly?

Most of the current answers have one or more of these problems:

  1. Only check for mouse not keyboard.
  2. Check only on page load.
  3. Hook the ever-popular change or submit events which won't always work out if something else has them hooked.
  4. Require a hidden input or other special elements/attributes that you have to undo in order to re-enable the checkbox using javascript.

The following is simple and has none of those problems.

$('input[type="checkbox"]').on('click keyup keypress keydown', function (event) {
    if($(this).is('[readonly]')) { return false; }
});

If the checkbox is readonly, it won't change. If it's not, it will. It does use jquery, but you're probably using that already...

It works.

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

Fastest method of screen capturing on Windows

Screen Recording can be done in C# using VLC API. I have done a sample program to demonstrate this. It uses LibVLCSharp and VideoLAN.LibVLC.Windows libraries. You could achieve many more features related to video rendering using this cross platform API.

For API documentation see: LibVLCSharp API Github

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using LibVLCSharp.Shared;

namespace ScreenRecorderNetApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Core.Initialize();

            using (var libVlc = new LibVLC())
            using (var mediaPlayer = new MediaPlayer(libVlc))
            {
                var media = new Media(libVlc, "screen://", FromType.FromLocation);
                media.AddOption(":screen-fps=24");
                media.AddOption(":sout=#transcode{vcodec=h264,vb=0,scale=0,acodec=mp4a,ab=128,channels=2,samplerate=44100}:file{dst=testvlc.mp4}");
                media.AddOption(":sout-keep");

                mediaPlayer.Play(media);
                Thread.Sleep(10*1000);
                mediaPlayer.Stop();
            }
        }
    }
}

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I can't see that you're adding these controls to the control hierarchy. Try:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

Events won't be invoked unless the control is part of the control hierarchy.

How to know whether refresh button or browser back button is clicked in Firefox

var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');

if(keyCode==116)
alert('you pressed f5 to reload page')

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

For Maven based projects you need a dependency.

<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
</dependency>

DataAdapter.Fill(Dataset)

You need to do this:

OleDbConnection connection = new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();

string query = 
    @"SELECT tbl_Computer.*,  tbl_Besitzer.*
    FROM tbl_Computer 
    INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
    WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection); 
DBAdapter.Fill(DS);

By the way, what is this DataSet1? This should be "DataSet".

How can I color Python logging output?

I have two submissions to add, one of which colorizes just the message (ColoredFormatter), and one of which colorizes the entire line (ColorizingStreamHandler). These also include more ANSI color codes than previous solutions.

Some content has been sourced (with modification) from: The post above, and http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html.

Colorizes the message only:

class ColoredFormatter(logging.Formatter):
    """Special custom formatter for colorizing log messages!"""

    BLACK = '\033[0;30m'
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    BROWN = '\033[0;33m'
    BLUE = '\033[0;34m'
    PURPLE = '\033[0;35m'
    CYAN = '\033[0;36m'
    GREY = '\033[0;37m'

    DARK_GREY = '\033[1;30m'
    LIGHT_RED = '\033[1;31m'
    LIGHT_GREEN = '\033[1;32m'
    YELLOW = '\033[1;33m'
    LIGHT_BLUE = '\033[1;34m'
    LIGHT_PURPLE = '\033[1;35m'
    LIGHT_CYAN = '\033[1;36m'
    WHITE = '\033[1;37m'

    RESET = "\033[0m"

    def __init__(self, *args, **kwargs):
        self._colors = {logging.DEBUG: self.DARK_GREY,
                        logging.INFO: self.RESET,
                        logging.WARNING: self.BROWN,
                        logging.ERROR: self.RED,
                        logging.CRITICAL: self.LIGHT_RED}
        super(ColoredFormatter, self).__init__(*args, **kwargs)

    def format(self, record):
        """Applies the color formats"""
        record.msg = self._colors[record.levelno] + record.msg + self.RESET
        return logging.Formatter.format(self, record)

    def setLevelColor(self, logging_level, escaped_ansi_code):
        self._colors[logging_level] = escaped_ansi_code

Colorizes the whole line:

class ColorizingStreamHandler(logging.StreamHandler):

    BLACK = '\033[0;30m'
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    BROWN = '\033[0;33m'
    BLUE = '\033[0;34m'
    PURPLE = '\033[0;35m'
    CYAN = '\033[0;36m'
    GREY = '\033[0;37m'

    DARK_GREY = '\033[1;30m'
    LIGHT_RED = '\033[1;31m'
    LIGHT_GREEN = '\033[1;32m'
    YELLOW = '\033[1;33m'
    LIGHT_BLUE = '\033[1;34m'
    LIGHT_PURPLE = '\033[1;35m'
    LIGHT_CYAN = '\033[1;36m'
    WHITE = '\033[1;37m'

    RESET = "\033[0m"

    def __init__(self, *args, **kwargs):
        self._colors = {logging.DEBUG: self.DARK_GREY,
                        logging.INFO: self.RESET,
                        logging.WARNING: self.BROWN,
                        logging.ERROR: self.RED,
                        logging.CRITICAL: self.LIGHT_RED}
        super(ColorizingStreamHandler, self).__init__(*args, **kwargs)

    @property
    def is_tty(self):
        isatty = getattr(self.stream, 'isatty', None)
        return isatty and isatty()

    def emit(self, record):
        try:
            message = self.format(record)
            stream = self.stream
            if not self.is_tty:
                stream.write(message)
            else:
                message = self._colors[record.levelno] + message + self.RESET
                stream.write(message)
            stream.write(getattr(self, 'terminator', '\n'))
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def setLevelColor(self, logging_level, escaped_ansi_code):
        self._colors[logging_level] = escaped_ansi_code

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

Laravel Checking If a Record Exists

This will check if particular email address exist in the table:

if (isset(User::where('email', Input::get('email'))->value('email')))
{
    // Input::get('email') exist in the table 
}

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

Converting RGB to grayscale/intensity

Check out the Color FAQ for information on this. These values come from the standardization of RGB values that we use in our displays. Actually, according to the Color FAQ, the values you are using are outdated, as they are the values used for the original NTSC standard and not modern monitors.

How can I show line numbers in Eclipse?

Update November 2015:

In Eclipse Mars 4.5.1, line numbers are (annoyingly) turned off by default again. Follow the below instructions to enable it.


Update December 2013:

Lars Vogel just published on his blog:

Line numbers are default in Eclipse SDK Luna (4.4) as of today

(December 10, 2013)

We conducted a user survey if users want to have line numbers activated in text editors in the Eclipse IDE by default.
The response was very clear:

YES : 80.07% (1852 responses)
NO  : 19.93% (461 responses)
Total  : 2313
Skipped:   15

With Bug 421313, Review - Line number should be activated by default, we enabled it for the Eclipse SDK build, I assume other Eclipse packages will follow.


Update August 2014

Line number default length is now 120 (instead of 80) for Eclipse Mars 4.5M1.
See "How to customize Eclipse's text editor code formating".


Original answer (March 2009)

To really have it by default, you can write a script which ensure, before launching eclipse, that:
[workspace]\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.ui.editors.prefs does contain:

lineNumberRuler=true

(with [workspace] being the root directory of your eclipse workspace)
Then eclipse will be opened with "line numbers shown 'by default' "


Otherwise, you can also type 'CTRL+1' and then "line", which will give you access to the command "Show line numbers"
(that will switch to option "show line numbers" in the text editors part of the option.

Or you can just type "numb" in Windows Preferences to access to the Text Editor part:

show line number

Picture from "How to display line numbers in Eclipse" of blog "Mkyong.com"

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

Can a table row expand and close?

Yes, a table row can slide up and down, but it's ugly, since it changes the shape of the table and makes everything jump. Instead, put and element in each td... something that makes sense like a p or h2 etc.

For how to implement a table slide toggle...

It's probably simplest to put the click handler on the entire table, .stopPropagation() and check what was clicked.

If a td in a row with a colspan is clicked, close the p in it. If it's not a td in a row with a colspan, then close then toggle the following row's p.

It is essentially to wrap all your written content in an element inside the tds, since you never want to slideUp a td or tr or table shape will change!

Something like:

$(function() {

      // Initially hide toggleable content
    $("td[colspan=3]").find("p").hide();

      // Click handler on entire table
    $("table").click(function(event) {

          // No bubbling up
        event.stopPropagation();

        var $target = $(event.target);

          // Open and close the appropriate thing
        if ( $target.closest("td").attr("colspan") > 1 ) {
            $target.slideUp();
        } else {
            $target.closest("tr").next().find("p").slideToggle();
        }                    
    });
});?

Try it out with this jsFiddle example.

... and try out this jsFiddle showing implementation of a + - - toggle.

The HTML just has to have alternating rows of several tds and then a row with a td of a colspan greater than 1. You can obviously adjust the specifics quite easily.

The HTML would look something like:

<table>
    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
    </td></tr>

    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
    </td></tr>

    <tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
    <tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
    </td></tr>    
</table>?

importing external ".txt" file in python

You can import modules but not text files. If you want to print the content do the following:

Open a text file for reading:

f = open('words.txt', 'r')

Store content in a variable:

content = f.read()

Print content of this file:

print(content)

After you're done close a file:

f.close()

How to nicely format floating numbers to string without unnecessary decimal 0's

You said you choose to store your numbers with the double type. I think this could be the root of the problem, because it forces you to store integers into doubles (and therefore losing the initial information about the value's nature). What about storing your numbers in instances of the Number class (superclass of both Double and Integer) and rely on polymorphism to determine the correct format of each number?

I know it may not be acceptable to refactor a whole part of your code due to that, but it could produce the desired output without extra code/casting/parsing.

Example:

import java.util.ArrayList;
import java.util.List;

public class UseMixedNumbers {

    public static void main(String[] args) {
        List<Number> listNumbers = new ArrayList<Number>();

        listNumbers.add(232);
        listNumbers.add(0.18);
        listNumbers.add(1237875192);
        listNumbers.add(4.58);
        listNumbers.add(0);
        listNumbers.add(1.2345);

        for (Number number : listNumbers) {
            System.out.println(number);
        }
    }

}

Will produce the following output:

232
0.18
1237875192
4.58
0
1.2345

How to change the colors of a PNG image easily?

If you are going to be programming an application to do all of this, the process will be something like this:

  1. Convert image from RGB to HSV
  2. adjust H value
  3. Convert image back to RGB
  4. Save image

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

I have used sudo, but it didnt solve the problem, I have fixed the issue by changing the node_modules folder permission,

sudo chmod -R 777 node_modules

If you want you can replace 777 with any other code if you dont set the permission for all user/group.

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

Prompt for user input in PowerShell

Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.

More below:

[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.

Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.

You're trying to ask for parameters.

You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.

If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.

Check if an element contains a class in JavaScript?

If the element only has one class name you can quickly check it by getting the class attribute. The other answers are much more robust but this certainly has it's use cases.

if ( element.getAttribute('class') === 'classname' ) {

}

Getting parts of a URL (Regex)

The best answer suggested here didn't work for me because my URLs also contain a port. However modifying it to the following regex worked for me:

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:\d+)?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$

How to check if a Docker image with a specific tag exist locally?

Just a bit from me to very good readers:

Build

#!/bin/bash -e
docker build -t smpp-gateway smpp
(if  [ $(docker ps -a | grep smpp-gateway | cut -d " " -f1) ]; then \
  echo $(docker rm -f smpp-gateway); \
else \
  echo OK; \
fi;);
docker run --restart always -d --network="host" --name smpp-gateway smpp-gateway:latest

Watch

docker logs --tail 50 --follow --timestamps smpp-gateway

Run

sudo docker exec -it \
$(sudo docker ps | grep "smpp-gateway:latest" | cut -d " " -f1) \
/bin/bash

Start new Activity and finish current one in Android?

FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.

http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY

Indent starting from the second line of a paragraph with CSS

If you style as list

  • you can "text-align: initial" and the subsequent lines will all indent. I realize this may not suit your needs, but I was checking to see if there was another solution before I change my markup..

    I guess putting the second line in would also work, but requires human thinking for the content to flow properly, and, of course, hard line breaks (which don't bother me, per se).

  • mySQL Error 1040: Too Many Connection

    It is worth knowing that if you run out of usable disc space on your server partition or drive, that this will also cause MySQL to return this error. If you're sure it's not the actual number of users connected then the next step is to check that you have free space on your MySQL server drive/partition.

    Edit January 2019:
    This is true of MySQL 5.7 and 5.8 . I do not know for versions above this.

    How to execute a file within the python interpreter?

    Python 2 + Python 3

    exec(open("./path/to/script.py").read(), globals())
    

    This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

    Python 3 exec Documentation

    Using ng-click vs bind within link function of Angular Directive

    Shouldn't it simply be:

    <button ng-click="clickingCallback()">Click me<button>
    

    Why do you want to write a new directive just to map your click event to a callback on your scope ? ng-click already does that for you.

    C# catch a stack overflow exception

    Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

    For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

    Programmatically set image to UIImageView with Xcode 6.1/Swift

    In xcode 8 you can directly choose image from the selection window (NEW)...

    • You just need to type - "image" and you will get a suggestion box then select -"Image Literal" from list (see in attached picture) and

    • then tap on the square you will be able to see all images(see in
      second attached picture) which are in your image assets... or select other image from there.

    enter image description here

    • Now tap on square box - (You will see that square box after selecting above option)

    enter image description here

    new Date() is working in Chrome but not Firefox

    One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date. "2014/11/24 17:38:20.177Z" They do not know how to handle .177Z. Chrome will work though.

    How to add an extra language input to Android?

    I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

    Linking to an external URL in Javadoc?

    Taken from the javadoc spec

    @see <a href="URL#value">label</a> : Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character.

    For example : @see <a href="http://www.google.com">Google</a>

    Pass correct "this" context to setTimeout callback?

    NOTE: This won't work in IE

    var ob = {
        p: "ob.p"
    }
    
    var p = "window.p";
    
    setTimeout(function(){
        console.log(this.p); // will print "window.p"
    },1000); 
    
    setTimeout(function(){
        console.log(this.p); // will print "ob.p"
    }.bind(ob),1000);
    

    Tuples( or arrays ) as Dictionary keys in C#

    The good, clean, fast, easy and readable ways is:

    • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
    • just make a simple key class derived from a tuple.

    add something similar like this:

    public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
    {
        public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }
    
        public TypeA DataA => Item1; 
    
        public TypeB DataB => Item2;
    
        public TypeC DataC => Item3;
    }
    

    So you can use it with dictionary:

    var myDictinaryData = new Dictionary<myKey, string>()
    {
        {new myKey(1, 2, 3), "data123"},
        {new myKey(4, 5, 6), "data456"},
        {new myKey(7, 8, 9), "data789"}
    };
    
    • You also can use it in contracts
    • as a key for join or groupings in linq
    • going this way you never ever mistype order of Item1, Item2, Item3 ...
    • you no need to remember or look into to code to understand where to go to get something
    • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

    Arduino error: does not name a type?

    My code was out of void setup() or void loop() in Arduino.

    What is the difference between printf() and puts() in C?

    puts is the simple choice and adds a new line in the end and printfwrites the output from a formatted string.

    See the documentation for puts and for printf.

    I would recommend to use only printf as this is more consistent than switching method, i.e if you are debbugging it is less painfull to search all printfs than puts and printf. Most times you want to output a variable in your printouts as well, so puts is mostly used in example code.

    Wait until flag=true

    With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true

    _x000D_
    _x000D_
    //First define some delay function which is called from async function_x000D_
    function __delay__(timer) {_x000D_
        return new Promise(resolve => {_x000D_
            timer = timer || 2000;_x000D_
            setTimeout(function () {_x000D_
                resolve();_x000D_
            }, timer);_x000D_
        });_x000D_
    };_x000D_
    _x000D_
    //Then Declare Some Variable Global or In Scope_x000D_
    //Depends on you_x000D_
    var flag = false;_x000D_
    _x000D_
    //And define what ever you want with async fuction_x000D_
    async function some() {_x000D_
        while (!flag)_x000D_
            await __delay__(1000);_x000D_
    _x000D_
        //...code here because when Variable = true this function will_x000D_
    };
    _x000D_
    _x000D_
    _x000D_

    How do I get only directories using Get-ChildItem?

    A bit more readable and simple approach could be achieved with the script below:

    $Directory = "./"
    Get-ChildItem $Directory -Recurse | % {
        if ($_.Attributes -eq "Directory") {
            Write-Host $_.FullName
        }
    }
    

    Hope this helps!

    How to enable directory listing in apache web server

    Try this.

    <Directory "/home/userx/Downloads">
      Options +Indexes
      AllowOverride all
      Order allow,deny 
      Allow from all 
      Require all granted
    </Directory>
    

    If that doesn't work, you probably have 'deny indexes' somewhere that's overriding your config.

    Changing the Git remote 'push to' default

    If you did git push origin -u localBranchName:remoteBranchName and on sequentially git push commands, you get errors that then origin doesn't exist, then follow these steps:

    1. git remote -v

    Check if there is any remote that I don't care. Delete them with git remote remove 'name'

    1. git config --edit

    Look for possible signs of a old/non-existent remote. Look for pushdefault:

    [remote]
      pushdefault = oldremote
    

    Update oldremote value and save.

    git push should work now.

    Getting RSA private key from PEM BASE64 Encoded private key file

    The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:

    The usual openssl genrsa command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12 will create a PKCS8 file.

    The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec. SSLeay formatted keys, on the other hand, can not be opened natively.

    To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)

    Key Format Identification

    By inference from the OpenSSL man pages, key headers for two formats are as follows:

    PKCS8 Format

    Non-encrypted: -----BEGIN PRIVATE KEY-----
    Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----

    SSLeay Format

    -----BEGIN RSA PRIVATE KEY-----

    (These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY----- work natively)

    Retrieve a single file from a repository

    A nuanced variant of some of the answers here that answers the OP's question:

    git archive [email protected]:foo/bar.git \
      HEAD path/to/file.txt | tar -xO path/to/file.txt > file.txt
    

    How to install JSON.NET using NuGet?

    I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

    enter image description here

    PHP - Get bool to echo false when false

    Your'e casting a boolean to boolean and expecting an integer to be displayed. It works for true but not false. Since you expect an integer:

    echo (int)$bool_val;
    

    jquery beforeunload when closing (not leaving) the page?

    Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?

    Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.

    var link_was_clicked = false;
    document.addEventListener("click", function(e) {
       if (e.target.nodeName.toLowerCase() === 'a') {
          link_was_clicked = true;
       }
    }, true);
    
    window.onbeforeunload = function(e) {
        if(link_was_clicked) {
            return;
        }
        return confirm('Are you sure?');
    }
    

    How to merge multiple dicts with same key or different key?

    def merge(d1, d2, merge):
        result = dict(d1)
        for k,v in d2.iteritems():
            if k in result:
                result[k] = merge(result[k], v)
            else:
                result[k] = v
        return result
    
    d1 = {'a': 1, 'b': 2}
    d2 = {'a': 1, 'b': 3, 'c': 2}
    print merge(d1, d2, lambda x, y:(x,y))
    
    {'a': (1, 1), 'c': 2, 'b': (2, 3)}
    

    Converting Go struct to JSON

    Related issue:

    I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

    Wasted a lot of time, so posting solution here.

    In Go:

    // web server
    
    type Foo struct {
        Number int    `json:"number"`
        Title  string `json:"title"`
    }
    
    foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
    fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)
    

    In JavaScript:

    // web call & receive in "data", thru Ajax/ other
    
    var Foo = JSON.parse(data);
    console.log("number: " + Foo.number);
    console.log("title: " + Foo.title);
    

    Android - Best and safe way to stop thread

    This situation isn't in any way different from the standard Java. You can use the standard way to stop a thread:

    class WorkerThread extends Thread {
        volatile boolean running = true;
    
        public void run() {
            // Do work...
            if (!running) return;
            //Continue doing the work
        }
    }
    

    The main idea is to check the value of the field from time to time. When you need to stop your thread, you set running to false. Also, as Chris has pointed out, you can use the interruption mechanism.

    By the way, when you use AsyncTask, your apporach won't differ much. The only difference is that you will have to call isCancel() method from your task instead of having a special field. If you call cancel(true), but don't implement this mechanism, the thread still won't stop by itself, it will run to the end.

    Check Postgres access for a user

    Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.

    SELECT grantee,table_catalog, table_schema, table_name, privilege_type
    FROM   information_schema.table_privileges 
    WHERE  grantee not in ('pg_monitor','PUBLIC');
    

    Python re.sub(): how to substitute all 'u' or 'U's with 'you'

    Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

    [Uu]
    

    Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

    Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

    What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

    r'(?<![a-zA-Z])[uU](?![a-zA-Z])'
    

    Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

    These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

    Of course, you can remove the spaces around you from the replacement string.

    If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

    r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'
    

    And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

    r'(?<!\w)[uU](?!\w)'
    

    Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

    As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

    re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)
    

    or

    re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)
    

    depending on your preference.

    I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

    How to hide/show more text within a certain length (like youtube)

    Here's a really simple solution that worked for me,

    <span id="text">Extra Text</span>
    <span id="more">show more...</span>
    <span id="less">show less...</span>
    
    <script>
     $("#text").hide();
     $("#less").hide();
     $("#more").click( function() {
       $("#text").show();
       $("#less").show();
       $("#more").hide();
     });
     $("#less").click( function() {
       $("#text").hide();
       $("#less").hide();
       $("#more").show();
     });
    </script>
    

    How to insert element into arrays at specific position?

    You can insert elements during a foreach loop, since this loop works on a copy of the original array, but you have to keep track of the number of inserted lines (I call this "bloat" in this code):

    $bloat=0;
    foreach ($Lines as $n=>$Line)
        {
        if (MustInsertLineHere($Line))
            {
            array_splice($Lines,$n+$bloat,0,"string to insert");
            ++$bloat;
            }
        }
    

    Obviously, you can generalize this "bloat" idea to handle arbitrary insertions and deletions during the foreach loop.

    Javascript, Change google map marker color

    I have 4 ships to set on one single map, so I use the Google Developers example and then twisted it

    https://developers.google.com/maps/documentation/javascript/examples/icon-complex

    In the function bellow I set 3 more color options:

    function setMarkers(map, locations) {
    ...
    var image = {
        url: 'img/bullet_amarelo.png',
        // This marker is 20 pixels wide by 32 pixels tall.
        size: new google.maps.Size(40, 40),
        // The origin for this image is 0,0.
        origin: new google.maps.Point(0,0),
        // The anchor for this image is the base of the flagpole at 0,32.
        anchor: new google.maps.Point(0, 40)
      };
      var image1 = {
                url: 'img/bullet_azul.png',
                // This marker is 20 pixels wide by 32 pixels tall.
                size: new google.maps.Size(40, 40),
                // The origin for this image is 0,0.
                origin: new google.maps.Point(0,0),
                // The anchor for this image is the base of the flagpole at 0,32.
                anchor: new google.maps.Point(0, 40)
              };
      var image2 = {
              url: 'img/bullet_vermelho.png',
              // This marker is 20 pixels wide by 32 pixels tall.
              size: new google.maps.Size(40, 40),
              // The origin for this image is 0,0.
              origin: new google.maps.Point(0,0),
              // The anchor for this image is the base of the flagpole at 0,32.
              anchor: new google.maps.Point(0, 40)
            };
      var image3 = {
              url: 'img/bullet_verde.png',
              // This marker is 20 pixels wide by 32 pixels tall.
              size: new google.maps.Size(40, 40),
              // The origin for this image is 0,0.
              origin: new google.maps.Point(0,0),
              // The anchor for this image is the base of the flagpole at 0,32.
              anchor: new google.maps.Point(0, 40)
            };
    ...
    }
    

    And in the FOR bellow I set one color for each ship:

    for (var i = 0; i < locations.length; i++) {
    ...
        if (i==0) var imageV=image;
        if (i==1) var imageV=image1;
        if (i==2) var imageV=image2;
        if (i==3) var imageV=image3;
    ...
    # remember to change icon: image to icon: imageV
    }
    

    The final result:

    http://www.mercosul-line.com.br/site/teste.html

    Pandas timeseries plot setting x-axis major and minor ticks and labels

    Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

    But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

    So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt 
    import matplotlib.dates as dates
    
    idx = pd.date_range('2011-05-01', '2011-07-01')
    s = pd.Series(np.random.randn(len(idx)), index=idx)
    
    fig, ax = plt.subplots()
    ax.plot_date(idx.to_pydatetime(), s, 'v-')
    ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                    interval=1))
    ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
    ax.xaxis.grid(True, which="minor")
    ax.yaxis.grid()
    ax.xaxis.set_major_locator(dates.MonthLocator())
    ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
    plt.tight_layout()
    plt.show()
    

    pandas_like_date_fomatting

    (my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

    What is a singleton in C#?

    another way to implement singleton in c#, i personally prefer this way because you can access the instance of the singeton class as a property instead of a method.

    public class Singleton
        {
            private static Singleton instance;
    
            private Singleton() { }
    
            public static Singleton Instance
            {
                get
                {
                    if (instance == null)
                        instance = new Singleton();
                    return instance;
                }
            }
    
            //instance methods
        }
    

    but well, as far as i know both ways are considered 'right' so it's just a thing of personal flavor.

    Inheriting constructors

    If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

    class A
    {
        public: 
            explicit A(int x) {}
    };
    
    class B: public A
    {
         using A::A;
    };
    

    This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

    Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

    What does java:comp/env/ do?

    There is also a property resourceRef of JndiObjectFactoryBean that is, when set to true, used to automatically prepend the string java:comp/env/ if it is not already present.

    <bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="jdbc/loc"/>
      <property name="resourceRef" value="true"/>
    </bean>
    

    Custom domain for GitHub project pages

    The selected answer is the good one, but is long, so you might not read the key point:

    I got an error with the SSL when accesign www.example.com but it worked fine if I go to example.com

    If it happens the same to you, probably your error is that in the DNS configuration you have set:

    CNAME www.example.com --> example.com  (WRONG)
    

    But, what you have to do is:

    CNAME www.example.com --> username.github.io  (GOOD)
    

    or

    CNAME www.example.com --> organization.github.io  (GOOD)
    

    That was my error

    A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

    declare @cur cursor
    declare @idx int       
    declare @Approval_No varchar(50) 
    
    declare @ReqNo varchar(100)
    declare @M_Id  varchar(100)
    declare @Mail_ID varchar(100)
    declare @temp  table
    (
    val varchar(100)
    )
    declare @temp2  table
    (
    appno varchar(100),
    mailid varchar(100),
    userod varchar(100)
    )
    
    
        declare @slice varchar(8000)       
        declare @String varchar(100)
        --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
    set @String = '20131'
    
    
        select @idx = 1       
            if len(@String)<1 or @String is null  return       
    
        while @idx!= 0       
        begin       
            set @idx = charindex(',',@String)       
            if @idx!=0       
                set @slice = left(@String,@idx - 1)       
            else       
                set @slice = @String
    
                --select @slice       
                insert into @temp values(@slice)
            set @String = right(@String,len(@String) - @idx)       
            if len(@String) = 0 break
    
    
        end
        -- select distinct(val) from @temp
    
    
    SET @cur = CURSOR FOR select distinct(val) from @temp
    
    
    --open cursor    
    OPEN @cur    
    --fetchng id into variable    
    FETCH NEXT    
        FROM @cur into @Approval_No 
    
          --
        --loop still the end    
         while @@FETCH_STATUS = 0  
        BEGIN   
    
    
    select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
    and Approval_Sr_No=@Approval_No
    
       insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  
    
    FETCH NEXT    
          FROM @cur into @Approval_No    
     end  
        --close cursor    
        CLOSE @cur    
    
    select * from @tem
    

    How can I replace every occurrence of a String in a file with PowerShell?

    I prefer using the File-class of .NET and its static methods as seen in the following example.

    $content = [System.IO.File]::ReadAllText("c:\bla.txt").Replace("[MYID]","MyValue")
    [System.IO.File]::WriteAllText("c:\bla.txt", $content)
    

    This has the advantage of working with a single String instead of a String-array as with Get-Content. The methods also take care of the encoding of the file (UTF-8 BOM, etc.) without you having to take care most of the time.

    Also the methods don't mess up the line endings (Unix line endings that might be used) in contrast to an algorithm using Get-Content and piping through to Set-Content.

    So for me: Fewer things that could break over the years.

    A little-known thing when using .NET classes is that when you have typed in "[System.IO.File]::" in the PowerShell window you can press the Tab key to step through the methods there.

    Variable number of arguments in C++?

    If you know the range of number of arguments that will be provided, you can always use some function overloading, like

    f(int a)
        {int res=a; return res;}
    f(int a, int b)
        {int res=a+b; return res;}
    

    and so on...

    What's the difference between the 'ref' and 'out' keywords?

    Since you're passing in a reference type (a class) there is no need use ref because per default only a reference to the actual object is passed and therefore you always change the object behind the reference.

    Example:

    public void Foo()
    {
        MyClass myObject = new MyClass();
        myObject.Name = "Dog";
        Bar(myObject);
        Console.WriteLine(myObject.Name); // Writes "Cat".
    }
    
    public void Bar(MyClass someObject)
    {
        someObject.Name = "Cat";
    }
    

    As long you pass in a class you don't have to use ref if you want to change the object inside your method.

    How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

    Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.

    The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.

    Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:

    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, true);
    ajax.responseType = 'blob';
    ajax.onreadystatechange = function(){
        ...
        if(ajax.responseType === 'blob'){
            // Convert the blob to a string
            var reader = new window.FileReader();
            reader.addEventListener('loadend', function() {
               // For ISO-8859-1 there's no further conversion required
               Promise.resolve(reader.result);
            });
            reader.readAsBinaryString(ajax.response);
        }
    }
    

    Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.

    Found conflicts between different versions of the same dependent assembly that could not be resolved

    I could solve this installing Newtonsoft Json in the web project with nugget packages

    Combining paste() and expression() functions in plot labels

    EDIT: added a new example for ggplot2 at the end

    See ?plotmath for the different mathematical operations in R

    You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments

    Sometimes you will need to change the margins in you're putting superscripts on the y-axis.

    par(mar=c(5, 4.3, 4, 2) + 0.1)
    plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
         ylab = expression(yLab ~ y^2 ~ m^-2),
         main="Plot 1")
    

    enter image description here

    plot(1:10, xlab = expression(xLab * x^2 * m^-2),
         ylab = expression(yLab * y^2 * m^-2),
         main="Plot 2")
    

    enter image description here

    plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
         ylab = expression(yLab ~ y^2 * m^-2),
         main="Plot 3")
    

    enter image description here

    Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.

    plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
         ylab = expression("Temperature (" * degree * C *")"))
    

    enter image description here

    Here is a ggplot example using expression with a nonsense example

    require(ggplot2)
    

    Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages

    # require(pacman)
    # p_load(ggplot2)
    
    data = data.frame(x = 1:10, y = 1:10)
    
    ggplot(data, aes(x,y)) + geom_point() + 
      xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) + 
      ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()
    

    enter image description here

    What is the idiomatic Go equivalent of C's ternary operator?

    The map ternary is easy to read without parentheses:

    c := map[bool]int{true: 1, false: 0} [5 > 4]
    

    How to load a resource bundle from a file resource in Java?

    If you wanted to load message files for different languages, just use the shared.loader= of catalina.properties... for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html

    Check if a Windows service exists and delete in PowerShell

    I used the "-ErrorAction SilentlyContinue" solution but then later ran into the problem that it leaves an ErrorRecord behind. So here's another solution to just checking if the Service exists using "Get-Service".

    # Determines if a Service exists with a name as defined in $ServiceName.
    # Returns a boolean $True or $False.
    Function ServiceExists([string] $ServiceName) {
        [bool] $Return = $False
        # If you use just "Get-Service $ServiceName", it will return an error if 
        # the service didn't exist.  Trick Get-Service to return an array of 
        # Services, but only if the name exactly matches the $ServiceName.  
        # This way you can test if the array is emply.
        if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
            $Return = $True
        }
        Return $Return
    }
    
    [bool] $thisServiceExists = ServiceExists "A Service Name"
    $thisServiceExists 
    

    But ravikanth has the best solution since the Get-WmiObject will not throw an error if the Service didn't exist. So I settled on using:

    Function ServiceExists([string] $ServiceName) {
        [bool] $Return = $False
        if ( Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" ) {
            $Return = $True
        }
        Return $Return
    }
    

    So to offer a more complete solution:

    # Deletes a Service with a name as defined in $ServiceName.
    # Returns a boolean $True or $False.  $True if the Service didn't exist or was 
    # successfully deleted after execution.
    Function DeleteService([string] $ServiceName) {
        [bool] $Return = $False
        $Service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" 
        if ( $Service ) {
            $Service.Delete()
            if ( -Not ( ServiceExists $ServiceName ) ) {
                $Return = $True
            }
        } else {
            $Return = $True
        }
        Return $Return
    }
    

    CLEAR SCREEN - Oracle SQL Developer shortcut?

    Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.

    Run script.

    Alt+PgDn     -  puts you in Script Output panel.
    Ctrl+Shift+D -  clears panel.
    Alt+PgUp     -  puts you back in editor panel. 
    

    Cross-Domain Cookies

    There's no such thing as cross domain cookies. You could share a cookie between foo.example.com and bar.example.com but never between example.com and example2.com and that's for security reasons.

    Common HTTPclient and proxy

    Here is how I solved this problem for the old (< 4.3) HttpClient (which I cannot upgrade), using the answer of Santosh Singh (who I gave a +1):

    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
      try {
        HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
        hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
        httpclient.setHostConfiguration(hostConfiguration);
        this.getLogger().warn("USING PROXY: "+httpclient.getHostConfiguration().getProxyHost());
      } catch (Exception e) {
        throw new ProcessingException("Cannot set proxy!", e);
      }
    }
    

    How do I get column names to print in this C# program?

    Code for Find the Column Name same as using the Like in sql.

    foreach (DataGridViewColumn column in GrdMarkBook.Columns)  
                          //GrdMarkBook is Data Grid name
    {                      
        string HeaderName = column.HeaderText.ToString();
    
        //  This line Used for find any Column Have Name With Exam
    
        if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
        {
            int CoumnNo = column.Index;
        }
    }
    

    How can I show an image using the ImageView component in javafx and fxml?

    It's recommended to put the image to the resources, than you can use it like this:

    imageView = new ImageView("/gui.img/img.jpg");
    

    Figure out size of UILabel based on String in Swift

    Use an extension on String

    Swift 3

    extension String {
        func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        
            return ceil(boundingBox.height)
        }
    
        func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
            let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    
            return ceil(boundingBox.width)
        }
    }
    

    and also on NSAttributedString (which is very useful at times)

    extension NSAttributedString {
        func height(withConstrainedWidth width: CGFloat) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
        
            return ceil(boundingBox.height)
        }
    
        func width(withConstrainedHeight height: CGFloat) -> CGFloat {
            let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
            let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
        
            return ceil(boundingBox.width)
        }
    }
    

    Swift 4 & 5

    Just change the value for attributes in the extension String methods

    from

    [NSFontAttributeName: font]
    

    to

    [.font : font]
    

    Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

    You can do this way:

    String cert = DataAccessUtils.singleResult(
        jdbcTemplate.queryForList(
            "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where ID_STR_RT = :id_str_rt and ID_NMB_SRZ = :id_nmb_srz",
            new MapSqlParameterSource()
                .addValue("id_str_rt", "999")
                .addValue("id_nmb_srz", "60230009999999"),
            String.class
        )
    )
    

    DataAccessUtils.singleResult + queryForList:

    • returns null for empty result
    • returns single result if exactly 1 row found
    • throws exception if more then 1 rows found. Should not happen for primary key / unique index search

    DataAccessUtils.singleResult

    In nodeJs is there a way to loop through an array without using array size?

    This is the natural javascript option

    _x000D_
    _x000D_
    var myArray = ['1','2',3,4]_x000D_
    _x000D_
    myArray.forEach(function(value){_x000D_
      console.log(value);_x000D_
    });
    _x000D_
    _x000D_
    _x000D_

    However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:

    _x000D_
    _x000D_
    let myArray = ["a","b","c","d"];_x000D_
    for (let item of myArray) {_x000D_
      console.log(item);_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    Or you could create an asyncForEach explained here:

    https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

    Loop through list with both content and index

    enumerate() makes this prettier:

    for index, value in enumerate(S):
        print index, value
    

    See here for more.

    Auto number column in SharePoint list

    If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

    WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

    A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

    HTML inside Twitter Bootstrap popover

    You cannot use <li href="#" since it belongs to <a href="#" that's why it wasn't working, change it and it's all good.

    Here is working JSFiddle which shows you how to create bootstrap popover.

    Relevant parts of the code is below:

    HTML:

    <!-- 
    Note: Popover content is read from "data-content" and "title" tags.
    -->
    <a tabindex="0"
       class="btn btn-lg btn-primary" 
       role="button" 
       data-html="true" 
       data-toggle="popover" 
       data-trigger="focus" 
       title="<b>Example popover</b> - title" 
       data-content="<div><b>Example popover</b> - content</div>">Example popover</a>
    

    JavaScript:

    $(function(){
        // Enables popover
        $("[data-toggle=popover]").popover();
    });
    

    And by the way, you always need at least $("[data-toggle=popover]").popover(); to enable the popover. But in place of data-toggle="popover" you can also use id="my-popover" or class="my-popover". Just remember to enable them using e.g: $("#my-popover").popover(); in those cases.

    Here is the link to the complete spec: Bootstrap Popover

    Bonus:

    If for some reason you don't like or cannot read content of a popup from the data-content and title tags. You can also use e.g. hidden divs and a bit more JavaScript. Here is an example about that.

    Empty responseText from XMLHttpRequest

    Is http://api.xxx.com/ part of your domain? If not, you are being blocked by the same origin policy.

    You may want to check out the following Stack Overflow post for a few possible workarounds:

    ScalaTest in sbt: is there a way to run a single test without tags?

    I wanted to add a concrete example to accompany the other answers

    You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):

    Play Project

    You can test just the Login tests by running the following command from the SBT console:

    test:testOnly *LoginServiceSpec
    

    If you are running the command from outside the SBT console, you would do the following:

    sbt "test:testOnly *LoginServiceSpec"
    

    Inserting a value into all possible locations in a list

    Use insert() to insert an element before a given position.

    For instance, with

    arr = ['A','B','C']
    arr.insert(0,'D')
    

    arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

    Now, for

    arr = ['A','B','C']
    arr.insert(4,'D')
    

    arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

    However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

    Here's some example code:

    import itertools
    arr = ['A','B','C']
    perms = itertools.permutations(arr)
    for perm in perms:
        print perm
    

    will print out

    ('A', 'B', 'C')
    ('A', 'C', 'B')
    ('B', 'A', 'C')
    ('B', 'C', 'A')
    ('C', 'A', 'B')
    ('C', 'B', 'A')
    

    415 Unsupported Media Type - POST json to OData service in lightswitch 2012

    It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

    So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

    If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

    In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

    You could fix this in one of two ways:

    1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
    2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

      DataServiceVersion: 2.0;
      

    (Option 2 assumes that you aren't using any v3 features in your request payload.)

    Using env variable in Spring Boot's application.properties

    I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.

    On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.

    Getting the idea from PHP Symfony 3 framework that has a parameters.yml (.gitignored) and a parameters.yml.dist (which is a sample that creates the first one through composer install),

    I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.

    Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:

    application.yml.dist (sample)

        spring:
          profiles:
            active: local/dev/prod
          datasource:
            username:
            password:
            url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    

    application.yml (.gitignore-d on dev server)

    spring:
      profiles:
        active: dev
      datasource:
        username: root
        password: verysecretpassword
        url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    

    application.yml (.gitignore-d on local machine)

    spring:
      profiles:
        active: dev
      datasource:
        username: root
        password: rootroot
        url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    

    application-dev.yml (extra environment specific properties not sensitive)

    spring:
      datasource:
        testWhileIdle: true
        validationQuery: SELECT 1
      jpa:
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: create-droop
          naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
        properties:
          hibernate:
            dialect: org.hibernate.dialect.MySQL57InnoDBDialect
    

    Same can be done with .properties

    How to get the file extension in PHP?

    A better method is using strrpos + substr (faster than explode for that) :

    $userfile_name = $_FILES['image']['name'];
    $userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
    

    But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php

    Does Python have an argc argument?

    In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

    'sudo gem install' or 'gem install' and gem locations

    You can also install gems in your local environment (without sudo) with

    gem install --user-install <gemname>
    

    I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.

    You can check where the gems go by looking at gempaths with gem environment. In my case it's "~/.gem/ruby/1.8".

    If you need some binaries from local installs added to your path, you can add something to your bashrc like:

    if which ruby >/dev/null && which gem >/dev/null; then
        PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
    fi
    

    (from http://guides.rubygems.org/faqs/#user-install)

    Read Variable from Web.Config

    Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File

    How to call a SOAP web service on Android

    If you can use JSON, there is a whitepaper, a video and the sample.code in Developing Application Services with PHP Servers and Android Phone Clients.

    Max or Default?

    I think the issue is what do you want to happen when the query has no results. If this is an exceptional case then I would wrap the query in a try/catch block and handle the exception that the standard query generates. If it's ok to have the query return no results, then you need to figure out what you want the result to be in that case. It may be that @David's answer (or something similar will work). That is, if the MAX will always be positive, then it may be enough to insert a known "bad" value into the list that will only be selected if there are no results. Generally, I would expect a query that is retrieving a maximum to have some data to work on and I would go the try/catch route as otherwise you are always forced to check if the value you obtained is correct or not. I'd rather that the non-exceptional case was just able to use the obtained value.

    Try
       Dim x = (From y In context.MyTable _
                Where y.MyField = value _
                Select y.MyCounter).Max
       ... continue working with x ...
    Catch ex As SqlException
           ... do error processing ...
    End Try
    

    Change Select List Option background colour on hover

    In FF also CSS filter works fine. E.g. hue-rotate:

    option {
        filter: hue-rotate(90deg);
    }
    

    https://jsfiddle.net/w3a740jq/4/

    Android get Current UTC time

    see my answer here:

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

    I've fully tested it by changing the timezones on the emulator

    Execute jar file with multiple classpath libraries from command prompt

    Regardless of the OS the below command should work:

    java -cp "MyJar.jar;lib/*" com.mainClass
    

    Always use quotes and please take attention that lib/*.jar will not work.

    CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

    This is rather long post and it gives a more detailed explanation of the issue.

    The problem (in my case) comes when you have Multi Slot Content Projection

    See also content projection for more info.

    For example If you have a component which looks like this:

    html file:

     <div>
      <span>
        <ng-content select="my-component-header">
          <!-- optional header slot here -->
        </ng-content>
      </span>
    
      <div class="my-component-content">
        <ng-content>
          <!-- content slot here -->
        </ng-content>
      </div>
    </div>
    

    ts file:

    @Component({
      selector: 'my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.scss'],
    })
    export class MyComponent {    
    }
    

    And you want to use it like:

    <my-component>
      <my-component-header>
        <!-- this is optional --> 
        <p>html content here</p>
      </my-component-header>
    
    
      <p>blabla content</p>
      <!-- other html -->
    </my-component>
    

    And then you get template parse errors that is not a known Angular component and the matter of fact it isn't - it is just a reference to an ng-content in your component:

    And then the simplest fix is adding

    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ],
    

    ... to your app.module.ts


    But there is an easy and clean approach to this problem - instead of using <my-component-header> to insert html in the slot there - you can use a class name for this task like this:

    html file:

     <div>
      <span>
        <ng-content select=".my-component-header">  // <--- Look Here :)
          <!-- optional header slot here -->
        </ng-content>
      </span>
    
      <div class="my-component-content">
        <ng-content>
          <!-- content slot here -->
        </ng-content>
      </div>
    </div>
    

    And you want to use it like:

    <my-component>
      <span class="my-component-header">  // <--- Look Here :) 
         <!-- this is optional --> 
        <p>html content here</p>
      </span>
    
    
      <p>blabla content</p>
      <!-- other html -->
    </my-component>
    

    So ... no more components that do not exist so there are no problems in that, no errors, no need for CUSTOM_ELEMENTS_SCHEMA in app.module.ts

    So If You were like me and did not want to add CUSTOM_ELEMENTS_SCHEMA to the module - using your component this way does not generates errors and is more clear.

    For more info about this issue - https://github.com/angular/angular/issues/11251

    For more info about Angular content projection - https://blog.angular-university.io/angular-ng-content/

    You can see also https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

    CMAKE_MAKE_PROGRAM not found

    I have two suggestions:

    1. Do you have make in your %PATH% environment variable? On my system, I need to add %MINGW_DIR%\bin to %PATH%.

    2. Do you have make installed? Depending on your mingw installation, it can be a separate package.

    3. Last resort: Can you pass the full path to make on the commandline? cmake -D"CMAKE_MAKE_PROGRAM:PATH=C:/MinGW-32/bin/make.exe" ..\Source

    How to know if a Fragment is Visible?

    One thing to be aware of, is that isVisible() returns the visible state of the current fragment. There is a problem in the support library, where if you have nested fragments, and you hide the parent fragment (and therefore all the children), the child still says it is visible.

    isVisible() is final, so can't override unfortunately. My workaround was to create a BaseFragment class that all my fragments extend, and then create a method like so:

    public boolean getIsVisible()
    {
        if (getParentFragment() != null && getParentFragment() instanceof BaseFragment)
        {
            return isVisible() && ((BaseFragment) getParentFragment()).getIsVisible();
        }
        else
        {
            return isVisible();
        }
    }
    

    I do isVisible() && ((BaseFragment) getParentFragment()).getIsVisible(); because we want to return false if any of the parent fragments are hidden.

    This seems to do the trick for me.

    Font Awesome 5 font-family issue

    The problem is in the font-weight.
    For Font Awesome 5 you have to use {font-weight:900}

    How to check iOS version?

    I always keep those in my Constants.h file:

    #define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES) 
    #define IS_OS_5_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
    #define IS_OS_6_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
    #define IS_OS_7_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    #define IS_OS_8_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    

    When using SASS how can I import a file from a different directory?

    Looks like some changes to SASS have made possible what you've initially tried doing:

    @import "../subdir/common";
    

    We even got this to work for some totally unrelated folder located in c:\projects\sass:

    @import "../../../../../../../../../../projects/sass/common";
    

    Just add enough ../ to be sure you'll end up at the drive root and you're good to go.

    Of course, this solution is far from pretty, but I couldn't get an import from a totally different folder to work, neither using I c:\projects\sass nor setting the environment variable SASS_PATH (from: :load_paths reference) to that same value.

    Create a simple HTTP server with Java?

    A servlet container is definitely the way to go. If Tomcat or Jetty are too heavyweight for you, consider Winstone or TTiny.

    How can I build a recursive function in python?

    Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

    One solution is to define a simple recursive function:

    u0 = ...
    
    def f(x):
      ...
    
    def u(n):
      if n==0: return u0
      return f(u(n-1))
    

    Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

    Another solution is a simple loop:

    def u(n):
      ux = u0
      for i in xrange(n):
        ux=f(ux)
      return ux
    

    But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

    def u(n):
      ux = u0
      for i in xrange(n):
        ux=f(ux)
      yield ux
    
    for val in u(1000):
      print val
    

    There are many other options, but I guess these are the main ones.

    How do I toggle an ng-show in AngularJS based on a boolean?

    It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

    For example, this will not work:

    <div ng-controller="ControllerA">
      <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
    
      <div ng-controller="ControllerB">
        <div ng-show="isReplyFormOpen" id="replyForm">
        </div>
      </div>
    
    </div>
    

    To solve this, create a global variable (ie. in Controller A or your main Controller):

    .controller('ControllerA', function ($scope) {
      $scope.global = {};
    }
    

    Then add a 'global' prefix to your click and show variables:

    <div ng-controller="ControllerA">
      <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>
    
      <div ng-controller="ControllerB">
        <div ng-show="global.isReplyFormOpen" id="replyForm">
        </div>
      </div>
    
    </div>
    

    For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.

    Webpack "OTS parsing error" loading fonts

    I experienced the same problem, but for different reasons.

    After Will Madden's solution didn't help, I tried every alternative fix I could find via the Intertubes - also to no avail. Exploring further, I just happened to open up one of the font files at issue. The original content of the file had somehow been overwritten by Webpack to include some kind of configuration info, likely from previous tinkering with the file-loader. I replaced the corrupted files with the originals, and voilà, the errors disappeared (for both Chrome and Firefox).

    How do I change Android Studio editor's background color?

    You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

    enter image description here

    Android Studio 2.1

    Preference -> Search for Appearance -> UI options , Click on DropDown Theme

    enter image description here

    Android 2.2

    Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

    EDIT :

    Import External Themes

    You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

    Sorting table rows according to table header column using javascript or jquery

    You might want to see this page:
    http://blog.niklasottosson.com/?p=1914

    I guess you can go something like this:

    DEMO:http://jsfiddle.net/g9eL6768/2/

    HTML:

     <table id="mytable"><thead>
      <tr>
         <th id="sl">S.L.</th>
         <th id="nm">name</th>
      </tr>
       ....
    

    JS:

    //  sortTable(f,n)
    //  f : 1 ascending order, -1 descending order
    //  n : n-th child(<td>) of <tr>
    function sortTable(f,n){
        var rows = $('#mytable tbody  tr').get();
    
        rows.sort(function(a, b) {
    
            var A = getVal(a);
            var B = getVal(b);
    
            if(A < B) {
                return -1*f;
            }
            if(A > B) {
                return 1*f;
            }
            return 0;
        });
    
        function getVal(elm){
            var v = $(elm).children('td').eq(n).text().toUpperCase();
            if($.isNumeric(v)){
                v = parseInt(v,10);
            }
            return v;
        }
    
        $.each(rows, function(index, row) {
            $('#mytable').children('tbody').append(row);
        });
    }
    var f_sl = 1; // flag to toggle the sorting order
    var f_nm = 1; // flag to toggle the sorting order
    $("#sl").click(function(){
        f_sl *= -1; // toggle the sorting order
        var n = $(this).prevAll().length;
        sortTable(f_sl,n);
    });
    $("#nm").click(function(){
        f_nm *= -1; // toggle the sorting order
        var n = $(this).prevAll().length;
        sortTable(f_nm,n);
    });
    

    Hope this helps.

    Global Git ignore

    If you're using VSCODE, you can get this extension to handle the task for you. It watches your workspace each time you save your work and helps you to automatically ignore the files and folders you specified in your vscode settings.json ignoreit (vscode extension)

    How to concatenate int values in java?

    just to not forget the format method

    String s = String.format("%s%s%s%s%s", a, b, c, d, e);
    

    (%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)

    Copy/duplicate database without using mysqldump

    Actually i wanted to achieve exactly that in PHP but none of the answers here were very helpful so here's my – pretty straightforward – solution using MySQLi:

    // Database variables
    
    $DB_HOST = 'localhost';
    $DB_USER = 'root';
    $DB_PASS = '1234';
    
    $DB_SRC = 'existing_db';
    $DB_DST = 'newly_created_db';
    
    
    
    // MYSQL Connect
    
    $mysqli = new mysqli( $DB_HOST, $DB_USER, $DB_PASS ) or die( $mysqli->error );
    
    
    
    // Create destination database
    
    $mysqli->query( "CREATE DATABASE $DB_DST" ) or die( $mysqli->error );
    
    
    
    // Iterate through tables of source database
    
    $tables = $mysqli->query( "SHOW TABLES FROM $DB_SRC" ) or die( $mysqli->error );
    
    while( $table = $tables->fetch_array() ): $TABLE = $table[0];
    
    
        // Copy table and contents in destination database
    
        $mysqli->query( "CREATE TABLE $DB_DST.$TABLE LIKE $DB_SRC.$TABLE" ) or die( $mysqli->error );
        $mysqli->query( "INSERT INTO $DB_DST.$TABLE SELECT * FROM $DB_SRC.$TABLE" ) or die( $mysqli->error );
    
    
    endwhile;
    

    Creating a new user and password with Ansible

    Generating random password for user

    first need to define users variable then follow below

    tasks:

    - name: Generate Passwords
      become: no
      local_action: command pwgen -N 1 8
      with_items: '{{ users }}'
      register: user_passwords
    
    - name: Update User Passwords
      user:
        name: '{{ item.item }}'
        password: "{{ item.stdout | password_hash('sha512')}}"
        update_password: on_create
      with_items: '{{ user_passwords.results }}'
    
    - name: Save Passwords Locally
      become: no
      local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
      with_items: '{{ user_passwords.results }}'
    

    Using 'sudo apt-get install build-essentials'

    The package is called build-essential without the plural "s". So

    sudo apt-get install build-essential
    

    should do what you want.

    Trying to load local JSON file to show data in a html page using JQuery

    Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

    According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

    A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

    Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

    <script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
    <script type="text/javascript" language="javascript" src="priorities.json"></script> 
    
    <script type="text/javascript">
       $(document).ready(function(e) {
             alert(jsonObject.start.count);
       });
    </script>
    

    Your priorities.json file:

    var jsonObject = {
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    }
    

    Or declare a callback function on your page and wrap it like jsonp technique:

    <script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
         <script type="text/javascript">
               $(document).ready(function(e) {
    
               });
    
               function jsonCallback(jsonObject){
                   alert(jsonObject.start.count);
               }
            </script>
    
     <script type="text/javascript" language="javascript" src="priorities.json"></script> 
    

    Your priorities.json file:

    jsonCallback({
        "start": {
            "count": "5",
            "title": "start",
            "priorities": [
                {
                    "txt": "Work"
                },
                {
                    "txt": "Time Sense"
                },
                {
                    "txt": "Dicipline"
                },
                {
                    "txt": "Confidence"
                },
                {
                    "txt": "CrossFunctional"
                }
            ]
        }
        })
    

    Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

    With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

    I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...

    But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.

    If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...

    .ssh/config file for windows (git)

    These instructions work fine in Linux. In Windows, they are not working for me today.

    I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.

    If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.

    The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.

    First, I start the key agent in the Git BASH shell:

    $ eval $(ssh-agent -s)
    Agent pid 6276
    
    $ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
    Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
    Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)
    

    Then I change to the directory where I want to clone the repo

    $ cd ~/Documents/GIT/
    
    $ git clone [email protected]:test/spr2018.git
    Cloning into 'spr2018'...
    remote: Counting objects: 3, done.
    remote: Compressing objects: 100% (2/2), done.
    remote: Total 3 (delta 0), reused 0 (delta 0)
    Receiving objects: 100% (3/3), done.
    

    I fought with this for a long long time.

    Here are other things I tried along the way

    At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.

    After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.

    A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.

    In the git bash shell, run this

    $ ssh -T git@name-of-your-server
    

    Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:

    $ ssh -T [email protected]
    Welcome to GitLab, Paul E. Johnson!
    

    On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.

    $ ssh -T [email protected]
    [email protected]'s password:
    

    Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:

    $ ssh -T [email protected]
    Welcome to GitLab, Paul E. Johnson!
    

    You would hear the sound of me dancing with joy if you were here.

    To figure out what was going wrong, you can I run 'ssh' with "-Tvv"

    In Linux, I see this when it succeeds:

    debug1: Offering RSA public key: pauljohn@pols124
    debug2: we sent a publickey packet, wait for reply
    debug1: Server accepts key: pkalg ssh-rsa blen 279
    debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
    debug1: Authentication succeeded (publickey).
    

    In Windows, when this fails, I see it looking for default names:

    debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
    debug2: set_newkeys: mode 1
    debug1: rekey after 4294967296 blocks
    debug1: SSH2_MSG_NEWKEYS sent
    debug1: expecting SSH2_MSG_NEWKEYS
    debug1: SSH2_MSG_NEWKEYS received
    debug2: set_newkeys: mode 0
    debug1: rekey after 4294967296 blocks
    debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
    debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
    debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
    debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
    debug2: service_accept: ssh-userauth
    debug1: SSH2_MSG_SERVICE_ACCEPT received
    debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
    debug1: Next authentication method: publickey
    debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
    debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
    debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
    debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
    debug2: we did not send a packet, disable method
    debug1: Next authentication method: password
    [email protected]'s password:
    

    That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.

    I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.

    Ripple effect on Android Lollipop CardView

    For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:

    private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
        private MadeUpCardView cardView;
    
        public MadeUpCardViewHolder(View v){
            super(v);
    
            this.cardView = (MadeUpCardView)v;
    
            // Declaring in XML Layout doesn't seem to work in RecyclerViews
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int[] attrs = new int[]{R.attr.selectableItemBackground};
                TypedArray typedArray = context.obtainStyledAttributes(attrs);
                int selectableItemBackground = typedArray.getResourceId(0, 0);
                typedArray.recycle();
    
                this.cardView.setForeground(context.getDrawable(selectableItemBackground));
                this.cardView.setClickable(true);
            }
        }
    }
    

    Where MadeupCardView extends CardView Kudos to this answer for the TypedArray part.

    Set language for syntax highlighting in Visual Studio Code

    Another reason why people might struggle to get Syntax Highlighting working is because they don't have the appropriate syntax package installed. While some default syntax packages come pre-installed (like Swift, C, JS, CSS), others may not be available.

    To solve this you can Cmd + Shift + P ? "install Extensions" and look for the language you want to add, say "Scala".

    enter image description here

    Find the suitable Syntax package, install it and reload. This will pick up the correct syntax for your files with the predefined extension, i.e. .scala in this case.

    On top of that you might want VS Code to treat all files with certain custom extensions as your preferred language of choice. Let's say you want to highlight all *.es files as JavaScript, then just open "User Settings" (Cmd + Shift + P ? "User Settings") and configure your custom files association like so:

      "files.associations": {
        "*.es": "javascript"
      },
    

    How to check command line parameter in ".bat" file?

    In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

    ... the /I switch, if specified, says to do case insensitive string compares.

    it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

    IF /I "%1"=="-b" GOTO SPECIFIC
    

    GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

    Are you ssh'ing to a directory that's inside your work tree? If the root of your ssh mount point doesn't include the .git dir, then zsh won't be able to find git info. Make sure you're mounting something that includes the root of the repo.

    As for GIT_DISCOVERY_ACROSS_FILESYSTEM, it doesn't do what you want. Git by default will stop at a filesystem boundary. If you turn that on (and it's just an env var), then git will cross the filesystem boundary and keep looking. However, that's almost never useful, because you'd be implying that you have a .git directory on your local machine that's somehow meant to manage a work tree that's comprised partially of an sshfs mount. That doesn't make much sense.

    Serializing class instance to JSON

    This can be easily handled with pydantic, as it already has this functionality built-in.

    Option 1: normal way

    from pydantic import BaseModel
    
    class testclass(BaseModel):
        value1: str = "a"
        value2: str = "b"
    
    test = testclass()
    
    >>> print(test.json(indent=4))
    {
        "value1": "a",
        "value2": "b"
    }
    

    Option 2: using pydantic's dataclass

    import json
    from pydantic.dataclasses import dataclass
    from pydantic.json import pydantic_encoder
    
    @dataclass
    class testclass:
        value1: str = "a"
        value2: str = "b"
    
    test = testclass()
    >>> print(json.dumps(test, indent=4, default=pydantic_encoder))
    {
        "value1": "a",
        "value2": "b"
    }
    

    Ruby get object keys as array

    hash = {"apple" => "fruit", "carrot" => "vegetable"}
    array = hash.keys   #=> ["apple", "carrot"]
    

    it's that simple

    Hashing with SHA1 Algorithm in C#

    Fastest way is this :

        public static string GetHash(string input)
        {
            return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
        }
    

    For Small character output use x2 in replace of of X2

    What exactly is Python's file.flush() doing?

    Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.

    How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

    just put all apache comons jar and file upload jar in lib folder of tomcat

    How can I copy network files using Robocopy?

    I use the following format and works well.

    robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
    

    to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

    Python: Continuing to next iteration in outer loop

    I think one of the easiest ways to achieve this is to replace "continue" with "break" statement,i.e.

    for ii in range(200):
     for jj in range(200, 400):
        ...block0...
        if something:
            break
     ...block1...       
    

    For example, here is the easy code to see how exactly it goes on:

    for i in range(10):
        print("doing outer loop")
        print("i=",i)
        for p in range(10):
            print("doing inner loop")
            print("p=",p)
            if p==3:
                print("breaking from inner loop")
                break
        print("doing some code in outer loop")
    

    Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

    The SQL Server login required is DOMAIN\machinename$. This is the how the calling NT AUTHORITY\NETWORK SERVICE appears to SQL Server (and file servers etc)

    In SQL,

    CREATE LOGIN [XYZ\Gandalf$] FROM WINDOWS
    

    Angular window resize event

    Here is an update to @GiridharKamik answer above with the latest version of Rxjs.

    import { Injectable } from '@angular/core';
    import { Observable, BehaviorSubject, fromEvent } from 'rxjs';
    import { pluck, distinctUntilChanged, map } from 'rxjs/operators';
    
    @Injectable()
    export class WindowService {
        height$: Observable<number>;
        constructor() {
            const windowSize$ = new BehaviorSubject(getWindowSize());
    
            this.height$ = windowSize$.pipe(pluck('height'), distinctUntilChanged());
    
            fromEvent(window, 'resize').pipe(map(getWindowSize))
                .subscribe(windowSize$);
        }
    
    }
    
    function getWindowSize() {
        return {
            height: window.innerHeight
            //you can sense other parameters here
        };
    };
    

    What tool can decompile a DLL into C++ source code?

    There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.

    MVC3 EditorFor readOnly

    For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.

    I have this in my Model.

        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
        public DateTime issueDate { get; set; }
    

    and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.

    To make it work the way I want I put this in the View...

         @Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})
    

    and this in my ready function...

         $('#issueDate').prop('readOnly', true);
    

    I hope this would be helpful for someone out there. Sorry for my English

    What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

    1. return None or return can be used to exit out of a function or program, both does the same thing
    2. quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
        import site
        
        def func():
            print("Hi")
            quit()
            print("Bye")
    
    1. exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
    import site
        
        def func():
            print("Hi")
            exit()
            print("Bye")
    
    1. sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
    import sys 
      height = 150
      
    if height < 165: # in cm 
          
        # exits the program 
        sys.exit("Height less than 165")     
    else: 
        print("You ride the rollercoaster.") 
    
    1. os._exit(n) function can be used to exit from a process, and need to import os module for that.

    C programming in Visual Studio

    Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name

    Casting objects in Java

    Lets say you have Class A as superclass and Class B subclass of A.

    public class A {
    
        public void printFromA(){
            System.out.println("Inside A");
        }
    }
    public class B extends A {
    
        public void printFromB(){
            System.out.println("Inside B");
        }
    
    }
    
    public class MainClass {
    
        public static void main(String []args){
    
            A a = new B();
            a.printFromA(); //this can be called without typecasting
    
            ((B)a).printFromB(); //the method printFromB needs to be typecast 
        }
    }
    

    List submodules in a Git repository

    I use this:

    git config --list|egrep ^submodule
    

    Creating a very simple 1 username/password login in php

    <?php
    session_start();
      mysql_connect('localhost','root','');
        mysql_select_db('database name goes here');
        $error_msg=NULL;
        //log out code
        if(isset($_REQUEST['logout'])){
                    unset($_SESSION['user']);
                    unset($_SESSION['username']);
                    unset($_SESSION['id']);
                    unset($_SESSION['role']);
            session_destroy();
        }
        //
    
        if(!empty($_POST['submit'])){
            if(empty($_POST['username']))
                $error_msg='please enter username';
            if(empty($_POST['password']))
                $error_msg='please enter password';
            if(empty($error_msg)){
                $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
                $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
                $records=mysql_query($sql) or die(mysql_error());
    
                if($record_new=mysql_fetch_array($records)){
    
                    $_SESSION['user']=$record_new;
                    $_SESSION['id']=$record_new['id'];
                    $_SESSION['username']=$record_new['username'];
                    $_SESSION['role']=$record_new['role'];
                    header('location:index.php');
                    $error_msg='welcome';
                    exit();
                }else{
                    $error_msg='invalid details';
                }
            }       
        }
    
    ?>
    
    // replace the location with whatever page u want the user to visit when he/she log in
    

    How to open child forms positioned within MDI parent in VB.NET?

    Dont set MDI Child property from MDIForm

    In Chileform Load event give the below code

        Dim l As Single = (MDIForm1.ClientSize.Width - Me.Width) / 2
        Dim t As Single = ((MDIForm1.ClientSize.Height - Me.Height) / 2) - 30
        Me.SetBounds(l, t, Me.Width, Me.Height)
        Me.MdiParent = MDIForm1
    

    end

    try this code