Programs & Examples On #Hypertalk

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

Change input text border color without changing its height

Is this what you are looking for.

$("input.address_field").on('click', function(){  
     $(this).css('border', '2px solid red');
});

How to set the action for a UIBarButtonItem in Swift

Swift 5 & iOS 13+ Programmatic Example

  1. You must mark your function with @objc, see below example!
  2. No parenthesis following after the function name! Just use #selector(name).
  3. private or public doesn't matter; you can use private.

Code Example

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

How to draw a graph in PHP?

Your best bet is to look up php_gd2. It's a fairly decent image library that comes with PHP (just disabled in php.ini), and not only can you output your finished images in a couple formats, it's got enough functions that you should be able to do up a good graph fairly easily.

EDIT: it might help if I gave you a couple useful links:

http://www.libgd.org/ - You can get the latest php_gd2 here
http://ca3.php.net/gd - The php_gd manual.

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

Run Python script at startup in Ubuntu

Instructions

  • Copy the python file to /bin:

    sudo cp -i /path/to/your_script.py /bin

  • Add A New Cron Job:

    sudo crontab -e

    Scroll to the bottom and add the following line (after all the #'s):

    @reboot python /bin/your_script.py &

    The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.

  • Test it:

    sudo reboot

Practical example:

  • Add this file to your Desktop: test_code.py (run it to check that it works for you)

    from os.path import expanduser
    import datetime
    
    file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
    file.write("It worked!\n" + str(datetime.datetime.now()))
    file.close()
    
  • Run the following commands:

    sudo cp -i ~/Desktop/test_code.py /bin

    sudo crontab -e

  • Add the following line and save it:

    @reboot python /bin/test_code.py &

  • Now reboot your computer and you should find a new file on your Desktop: HERE.txt

How to list all files in a directory and its subdirectories in hadoop hdfs

Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.

def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
    val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
            files.foreach { fileStatus => {
                if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {                
                    filePaths+=fileStatus.getPath().toString()      
                }
                else if(fileStatus.isDirectory()) {
                    traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
                }
            }
    }   
}

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Javascript Error Null is not an Object

Try loading your javascript after.

Try this:

<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="submit" id="myButton" value="Go" />
</form>

<script src="js/script.js" type="text/javascript"></script>

MySQL DROP all tables, ignoring foreign keys

Just put here some useful comment made by Jonathan Watt to drop all tables

MYSQL="mysql -h HOST -u USERNAME -pPASSWORD DB_NAME"
$MYSQL -BNe "show tables" | awk '{print "set foreign_key_checks=0; drop table `" $1 "`;"}' | $MYSQL
unset MYSQL

It helps me and I hope it could be useful

Best practices for SQL varchar column length

Adding to a_horse_with_no_name's answer you might find the following of interest...

it does not make any difference whether you declare a column as VARCHAR(100) or VACHAR(500).

-- try to create a table with max varchar length
drop table if exists foo;
create table foo(name varchar(65535) not null)engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length - 2 bytes for the length
drop table if exists foo;
create table foo(name varchar(65533) not null)engine=innodb;

Executed Successfully

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65533))engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65532))engine=innodb;

Executed Successfully

Dont forget the length byte(s) and the nullable byte so:

name varchar(100) not null will be 1 byte (length) + up to 100 chars (latin1)

name varchar(500) not null will be 2 bytes (length) + up to 500 chars (latin1)

name varchar(65533) not null will be 2 bytes (length) + up to 65533 chars (latin1)

name varchar(65532) will be 2 bytes (length) + up to 65532 chars (latin1) + 1 null byte

Hope this helps :)

MySQL stored procedure return value

Add:

  • DELIMITER at the beginning and end of the SP.
  • DROP PROCEDURE IF EXISTS validar_egreso; at the beginning
  • When calling the SP, use @variableName.

This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).

DROP PROCEDURE IF EXISTS `validar_egreso`;

DELIMITER $$

CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
)
BEGIN

    DECLARE resta INT;
    SET resta = 0;

    SELECT (codigo_producto - cantidad) INTO resta;

    IF(resta > 1) THEN
       SET valido = 1;
    ELSE
       SET valido = -1;
    END IF;

    SELECT valido;
END $$

DELIMITER ;

-- execute the stored procedure
CALL validar_egreso(4, 1, @val);

-- display the result
select @val;

How to fix missing dependency warning when using useEffect React Hook?

You can set it directly as the useEffect callback:

useEffect(fetchBusinesses, [])

It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...)


Edit 02/21/2020

Just for completeness:

1. Use function as useEffect callback (as above)

useEffect(fetchBusinesses, [])

2. Declare function inside useEffect()

useEffect(() => {
  function fetchBusinesses() {
    ...
  }
  fetchBusinesses()
}, [])

3. Memoize with useCallback()

In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(fetchBusinesses, []).

const fetchBusinesses = useCallback(() => {
  ...
}, [])
useEffect(() => {
  fetchBusinesses()
}, [fetchBusinesses])

4. Disable eslint's warning

useEffect(() => {
  fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps

How can I echo a newline in a batch file?

If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used

@cmd /c echo.

simply using echo. causes the dreaded process_begin: CreateProcess(NULL, echo., ...) failed. error message.

I hope this helps at least one other person out there :)

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

Java FileWriter how to write to next Line

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...

"Fatal error: Cannot redeclare <function>"

I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')

jquery, find next element by class

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

Center an element in Bootstrap 4 Navbar

Updated for Bootstrap 4.1+

Bootstrap 4 the navbar now uses flexbox so the Website Name can be centered using mx-auto. The left and right side menus don't require floats.

<nav class="navbar navbar-expand-md navbar-fixed-top navbar-dark bg-dark main-nav">
    <div class="container">
        <ul class="nav navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="#">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Download</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Register</a>
            </li>
        </ul>
        <ul class="nav navbar-nav mx-auto">
            <li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
        </ul>
        <ul class="nav navbar-nav">
            <li class="nav-item">
                <a class="nav-link" href="#">Rates</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Help</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Contact</a>
            </li>
        </ul>
    </div>
</nav>

Navbar center with mx-auto Demo

If the Navbar only has a single navbar-nav, then justify-content-center can also be used to center.

EDIT

In the solution above, the Website Name is centered relative to the left and right navbar-nav so if the width of these adjacent navs are different the Website Name is no longer centered.

enter image description here

To resolve this, one of the flexbox workarounds for absolute centering can be used...

Option 1 - Use position:absolute;

Since it's ok to use absolute positioning in flexbox, one option is to use this on the item to be centered.

.abs-center-x {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

Navbar center with absolute position Demo

Option 2 - Use flexbox nesting

Finally, another option is to make the centered item also display:flexbox (using d-flex) and center justified. In this case each navbar component must have flex-grow:1

As of Bootstrap 4 Beta, the Navbar is now display:flex. Bootstrap 4.1.0 includes a new flex-fill class to make each nav section fill the width:

<nav class="navbar navbar-expand-sm navbar-dark bg-dark main-nav">
    <div class="container justify-content-center">
        <ul class="nav navbar-nav flex-fill w-100 flex-nowrap">
            <li class="nav-item active">
                <a class="nav-link" href="#">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Download</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Register</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">More</a>
            </li>
        </ul>
        <ul class="nav navbar-nav flex-fill justify-content-center">
            <li class="nav-item"><a class="nav-link" href="#">Center</a></li>
        </ul>
        <ul class="nav navbar-nav flex-fill w-100 justify-content-end">
            <li class="nav-item">
                <a class="nav-link" href="#">Help</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Contact</a>
            </li>
        </ul>
    </div>
</nav>

Navbar center with flexbox nesting Demo

Prior to Bootstrap 4.1.0 you can add the flex-fill class like this...

.flex-fill {
   flex:1
}

As of 4.1 flex-fill is included in Bootstrap.


Bootstrap 4 Navbar center demos
More centering demos
Center links on desktop, left align on mobile

Related:
How to center nav-items in Bootstrap?
Bootstrap NavBar with left, center or right aligned items
How move 'nav' element under 'navbar-brand' in my Navbar

enter image description here

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

How to check Elasticsearch cluster health?

The _cluster/health API can do far more than the typical output that most see with it:

 $ curl -XGET 'localhost:9200/_cluster/health?pretty'

Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.

Examples

all the indices health
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.11" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.12" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.13" : {
      "status" : "green",
      "number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0,
      "shards" : {
        "0" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "1" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "2" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0

The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

How to break nested loops in JavaScript?

Unfortunately you'll have to set a flag or use labels (think old school goto statements)

var breakout = false;

for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        breakout = true;
        break;
    }
    if (breakout) break;
    alert(1)
};

The label approach looks like:

end_loops:
for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        break end_loops;
    }
    alert(1)
};

edit: label incorrectly placed.

also see:

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.

To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.

For third party , copy the native library to the folder where the third party library resides and add it as an existing item.

After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.

How to schedule a task to run when shutting down windows

On Windows 10 Pro, the batch file can be registered; the workaround of registering cmd.exe and specifying the bat file as a param isn't needed. I just did this, registering both a shutdown script and a startup (boot) script, and it worked.

Page redirect with successful Ajax request

I think you can do that with:

window.location = "your_url";

How to read one single line of csv data in Python?

Just for reference, a for loop can be used after getting the first row to get the rest of the file:

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)  # gets the first line
    for row in reader:
        print(row)       # prints rows 2 and onward

Java ResultSet how to check if there are any results

Assuming you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst(). This avoids having to back-track if the data is to be read.

As explained in the documentation, this returns false if the cursor is not before the first record or if there are no rows in the ResultSet.

if (!resultSet.isBeforeFirst() ) {    
    System.out.println("No data"); 
} 

 

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Wait 5 seconds before executing next line

using angularjs:

$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)

Convert string to datetime

For chinese Rails developers:

DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I had a similar problem which was solved by going to the "SQL Server Configuration Manager" and making sure that the "SQL Server Browser" was configured to start automatically and was started.

I came across this solution in the answer of this forum post: http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/8cdc71eb-6929-4ae8-a5a8-c1f461bd61b4/

I hope this helps somebody out there.

How to run sql script using SQL Server Management Studio?

This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):

sqlcmd -S .\SQLExpress -i SqlScript.sql

Where SqlScript.sql is the script file name located at the current directory. See this Microsoft page for more examples

What is the purpose of meshgrid in Python / NumPy?

Basic Idea

Given possible x values, xs, (think of them as the tick-marks on the x-axis of a plot) and possible y values, ys, meshgrid generates the corresponding set of (x, y) grid points---analogous to set((x, y) for x in xs for y in yx). For example, if xs=[1,2,3] and ys=[4,5,6], we'd get the set of coordinates {(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}.

Form of the Return Value

However, the representation that meshgrid returns is different from the above expression in two ways:

First, meshgrid lays out the grid points in a 2d array: rows correspond to different y-values, columns correspond to different x-values---as in list(list((x, y) for x in xs) for y in ys), which would give the following array:

   [[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]

Second, meshgrid returns the x and y coordinates separately (i.e. in two different numpy 2d arrays):

   xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

Note, np.meshgrid can also generate grids for higher dimensions. Given xs, ys, and zs, you'd get back xcoords, ycoords, zcoords as 3d arrays. meshgrid also supports reverse ordering of the dimensions as well as sparse representation of the result.

Applications

Why would we want this form of output?

Apply a function at every point on a grid: One motivation is that binary operators like (+, -, *, /, **) are overloaded for numpy arrays as elementwise operations. This means that if I have a function def f(x, y): return (x - y) ** 2 that works on two scalars, I can also apply it on two numpy arrays to get an array of elementwise results: e.g. f(xcoords, ycoords) or f(*np.meshgrid(xs, ys)) gives the following on the above example:

array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])

Higher dimensional outer product: I'm not sure how efficient this is, but you can get high-dimensional outer products this way: np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

Contour plots in matplotlib: I came across meshgrid when investigating drawing contour plots with matplotlib for plotting decision boundaries. For this, you generate a grid with meshgrid, evaluate the function at each grid point (e.g. as shown above), and then pass the xcoords, ycoords, and computed f-values (i.e. zcoords) into the contourf function.

How to push object into an array using AngularJS

A couple of answers that should work above but this is how i would write it.

Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.

add-text.tpl.html

<div ng-controller="myController">
    <form ng-submit="addText(myText)">
        <input type="text" placeholder="Let's Go" ng-model="myText">
        <button type="submit">Add</button>
    </form>
    <ul>
        <li ng-repeat="text in arrayText">{{ text }}</li>
    </ul>
</div>

app.js

(function() {

    function myController($scope) {
        $scope.arrayText = ['hello', 'world'];
        $scope.addText = function(myText) {
             $scope.arrayText.push(myText);     
        };
    }

    angular.module('app', [])
        .controller('myController', myController);

})();

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

Difference between final and effectively final

This variable below is final, so we can't change it's value once initialised. If we try to we'll get a compilation error...

final int variable = 123;

But if we create a variable like this, we can change it's value...

int variable = 123;
variable = 456;

But in Java 8, all variables are final by default. But the existence of the 2nd line in the code makes it non-final. So if we remove the 2nd line from the above code, our variable is now "effectively final"...

int variable = 123;

So.. Any variable that is assigned once and only once, is "effectively final".

Google Maps Api v3 - find nearest markers

First you have to add the eventlistener

google.maps.event.addListener(map, 'click', find_closest_marker);

Then create a function that loops through the array of markers and uses the haversine formula to calculate the distance of each marker from the click.

function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<map.markers.length; i++ ) {
        var mlat = map.markers[i].position.lat();
        var mlng = map.markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    alert(map.markers[closest].title);
}

This keeps track of the closest markers and alerts its title.

I have my markers as an array on my map object

What is the difference between dict.items() and dict.iteritems() in Python2?

If you have

dict = {key1:value1, key2:value2, key3:value3,...}

In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

  • Lists as mutable snapshots: d.items() -> list(d.items())
  • Iterator objects: d.iteritems() -> iter(d.items())

The tuples are the same. You compared tuples in each so you get same.

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

How to remove single character from a String

*You can delete string value use the StringBuilder and deletecharAt.

String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
  char temp = sb.charAt(0);
  if(sb.indexOf(temp+"")!=1)
  {                             
    sb.deleteCharAt(sb.indexOf(temp+""));   
  }
}

NVIDIA NVML Driver/library version mismatch

I had reinstalled nvidia driver: run these commands in root mode:

  1. systemctl isolate multi-user.target

  2. modprobe -r nvidia-drm

  3. Reinstall Nvidia driver: chmod +x NVIDIA-Linux-x86_64–410.57.run

  4. systemctl start graphical.target

and finally check nvidia-smi

Thanks to: How To Install Nvidia Drivers and CUDA-10.0 for RTX 2080 Ti GPU on Ubuntu-16.04/18.04

How to unload kernel module 'nvidia-drm'?

getOutputStream() has already been called for this response

I didn't use JSP but I had similar error when I was setting response to return JSON object by calling PrintWriter's flush() method or return statement. Previous answer i.e wrapping return-statement into a try-block worked kind of: the error disappeared because return-statement makes method to ignore all code below try-catch, specifically in my case, line redirectStrategy.sendRedirect(request, response, destination_addr_string) which seem to modify the already committed response that causes the error. The simpler solution in my case was just to remove the line and let client app to take care of the redirection.

How to detect if javascript files are loaded?

I always make a call from the end of the JavaScript files for registering its loading and it used to work perfect for me for all the browsers.

Ex: I have an index.htm, Js1.js and Js2.js. I add the function IAmReady(Id) in index.htm header and call it with parameters 1 and 2 from the end of the files, Js1 and Js2 respectively. The IAmReady function will have a logic to run the boot code once it gets two calls (storing the the number of calls in a static/global variable) from the two js files.

JavaScript moving element in the DOM

Sorry for bumping this thread I stumbled over the "swap DOM-elements" problem and played around a bit

The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)

The Code:

$('#element1').insertAfter($('#element2'));

The jQuery documentation says that insertAfter() moves the element and doesn't clone it

Detect the Internet connection is offline?

an ajax call to your domain is the easiest way to detect if you are offline

$.ajax({
      type: "HEAD",
      url: document.location.pathname + "?param=" + new Date(),
      error: function() { return false; },
      success: function() { return true; }
   });

this is just to give you the concept, it should be improved.

E.g. error=404 should still mean that you online

How to force 'cp' to overwrite directory instead of creating another one inside?

Very similar to @Jonathan Wheeler:

If you do not want to remember, but not rewrite bar:

rm -r bar/
cp -r foo/ !$

!$ displays the last argument of your previous command.

How to check if an object is an array?

The best practice is to compare it using constructor, something like this

if(some_variable.constructor === Array){
  // do something
}

You can use other methods too like typeOf, converting it to a string and then comparing but comparing it with dataType is always a better approach.

How to split a delimited string in Ruby and convert it to an array?

the simplest way to convert a string that has a delimiter like a comma is just to use the split method

"1,2,3,4".split(',') # "1", "2", "3", "4"]

you can find more info on how to use the split method in the ruby docs

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

'NoneType' object is not subscriptable?

Don't use list as a variable name for it shadows the builtin.

And there is no need to determine the length of the list. Just iterate over it.

def printer(data):
    for element in data:
        print(element[0])

Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

FIFO class in Java

You don't have to implement your own FIFO Queue, just look at the interface java.util.Queue and its implementations

Parsing PDF files (especially with tables) with PDFBox

ObjectExtractor oe = new ObjectExtractor(document);

SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm(); // Tabula algo.

Page page = oe.extract(1); // extract only the first page

for (int y = 0; y < sea.extract(page).size(); y++) {
  System.out.println("table: " + y);
  Table table = sea.extract(page).get(y);

  for (int i = 0; i < table.getColCount(); i++) {
    for (int x = 0; x < table.getRowCount(); x++) {
      System.out.println("col:" + i + "/lin:x" + x + " >>" + table.getCell(x, i).getText());
    }
  }
}

PHP Warning: Module already loaded in Unknown on line 0

Comment out these two lines in php.ini

;extension=imagick.so
;extension="ixed.5.6.lin"

it should fix the issue.

What is the use of a cursor in SQL Server?

Cursor itself is an iterator (like WHILE). By saying iterator I mean a way to traverse the record set (aka a set of selected data rows) and do operations on it while traversing. Operations could be INSERT or DELETE for example. Hence you can use it for data retrieval for example. Cursor works with the rows of the result set sequentially - row by row. A cursor can be viewed as a pointer to one row in a set of rows and can only reference one row at a time, but can move to other rows of the result set as needed.

This link can has a clear explanation of its syntax and contains additional information plus examples.

Cursors can be used in Sprocs too. They are a shortcut that allow you to use one query to do a task instead of several queries. However, cursors recognize scope and are considered undefined out of the scope of the sproc and their operations execute within a single procedure. A stored procedure cannot open, fetch, or close a cursor that was not declared in the procedure.

Accessing localhost (xampp) from another computer over LAN network - how to?

Go to xampp-control in the Taskbar

xampp-control -> Apache --> Config --> httpd.conf

Notepad will open with the config file

Search for

Listen 80

One line above it, there will be something like this: 12.34.56:80

Change it

12.34.56:80 --> <your_ip_address eg:192.168.1.5>:80

Restart the apache service and check it, Hopefully it should work...

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

A simple algorithm for polygon intersection

The way I worked about the same problem

  1. breaking the polygon into line segments
  2. find intersecting line using IntervalTrees or LineSweepAlgo
  3. finding a closed path using GrahamScanAlgo to find a closed path with adjacent vertices
  4. Cross Reference 3. with DinicAlgo to Dissolve them

note: my scenario was different given the polygons had a common vertice. But Hope this can help

What is the best way to connect and use a sqlite database from C#

Another way of using SQLite database in NET Framework is to use Fluent-NHibernate.
[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]

Here is the brief 'Getting started' description how to do this in C# step by step:

https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started

It includes a source code as an Visual Studio project.

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

How to Extract Year from DATE in POSTGRESQL

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    'Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

Best way to store data locally in .NET (C#)

Keep it simple - as you said, a flat file is sufficient. Use a flat file.

This is assuming that you have analyzed your requirements correctly. I would skip the serializing as XML step, overkill for a simple dictionary. Same thing for a database.

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

Make the sql mode non strict

if using laravel go to config->database, the go to mysql settings and make the strict mode false

How to add ID property to Html.BeginForm() in asp.net mvc?

May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.

@using (Html.BeginForm("Login", "Account", new {  ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))

Hope this can help somebody :)

"Parse Error : There is a problem parsing the package" while installing Android application

You might also want to check the logs on the device to see if it's something simple like a permissions problem. You can check the logs using adb from a host/debug computer:

adb logcat

Or if you have access to the console (or when using Android-x86 get console by typing Alt+F1) then you can check the logs by using the logcat command:

logcat

How to make a vertical SeekBar in Android?

  1. For API 11 and later, can use seekbar's XML attributes(android:rotation="270") for vertical effect.

    <SeekBar
    android:id="@+id/seekBar1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:rotation="270"/>
    
  2. For older API level (ex API10), only use Selva's answer:
    https://github.com/AndroSelva/Vertical-SeekBar-Android

How to track down a "double free or corruption" error

Three basic rules:

  1. Set pointer to NULL after free
  2. Check for NULL before freeing.
  3. Initialise pointer to NULL in the start.

Combination of these three works quite well.

How to retrieve a file from a server via SFTP?

hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)

Example code from SFTPUpload.java

package net.schmizz.sshj.examples;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.File;
import java.io.IOException;

/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final String src = System.getProperty("user.home") + File.separator + "test_file";
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.put(new FileSystemFile(src), "/tmp");
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

}

How can I rename a single column in a table at select?

select table1.price, table2.price as other_price .....

What key shortcuts are to comment and uncomment code?

I went to menu: ToolsOptions.

EnvironmentKeyboard.

Show command containing and searched: comment

I changed Edit.CommentSelection and assigned Ctrl+/ for commenting.

And I left Ctrl+K then U for the Edit.UncommentSelection.

These could be tweaked to the user's preference as to what key they would prefer for commenting/uncommenting.

No module named 'openpyxl' - Python 3.4 - Ubuntu

If you don't use conda, just use :

pip install openpyxl

If you use conda, I'd recommend :

conda install -c anaconda openpyxl

instead of simply conda install openpyxl

Because there are issues right now with conda updating (see GitHub Issue #8842) ; this is being fixed and it should work again after the next release (conda 4.7.6)

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

protected void Page_PreInit(object sender, EventArgs e) 
{ 
 if (Membership.GetUser() == null) //check the user weather user is logged in or not
    this.Page.MasterPageFile = "~/General.master";
 else
    this.Page.MasterPageFile = "~/myMaster.master";
}

Hive insert query like SQL

You could definitely append data into an existing table. (But it is actually not an append at the HDFS level). It's just that whenever you do a LOAD or INSERT operation on an existing Hive table without OVERWRITE clause the new data will be put without replacing the old data. A new file will be created for this newly inserted data inside the directory corresponding to that table. For example :

I have a file named demo.txt which has 2 lines :

ABC
XYZ

Create a table and load this file into it

hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;

Now,if I do a SELECT on this table it'll give me :

hive> select * from demo;                        
OK    
ABC    
XYZ

Suppose, I have one more file named demo2.txt which has :

PQR

And I do a LOAD again on this table without using overwrite,

hive> load data inpath '/demo2.txt' into table demo;

Now, if I do a SELECT now, it'll give me,

hive> select * from demo;                       
OK
ABC
XYZ
PQR

HTH

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

HTML input arrays

There are some references and pointers in the comments on this page at PHP.net:

Torsten says

"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."

Jetboy says

"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."

ng-change get new value and original value

Just keep a currentValue variable in your controller that you update on every change. You can then compare that to the new value every time before you update it.'

The idea of using a watch is good as well, but I think a simple variable is the simplest and most logical solution.

How to parse float with two decimal places in javascript?

Simple JavaScript, string to float:

var it_price = chief_double($("#ContentPlaceHolder1_txt_it_price").val());

function chief_double(num){
    var n = parseFloat(num);
    if (isNaN(n)) {
        return "0";
    }
    else {
        return parseFloat(num);
    }
}

Http 415 Unsupported Media type error with JSON

Not sure about the reason but Removing lines charset=utf8 from con.setRequestProperty("Content-Type", "application/json; charset=utf8") resolved the issue.

RegEx: How can I match all numbers greater than 49?

I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:

/([5-9][0-9])|([1-9]\d{3}\d*)/

How to call external url in jquery?

Follow the below simple steps you will able to get the result

Step 1- Create one internal function getDetailFromExternal in your back end. step 2- In that function call the external url by using cUrl like below function

 function getDetailFromExternal($p1,$p2) {

        $url = "http://request url with parameters";
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true            
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
        exit;
    }

Step 3- Call that internal function from your front end by using javascript/jquery Ajax.

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

How to get Bitmap from an Uri?

I have try a lot of ways. this work for me perfectly.

If you choose pictrue from Gallery. You need to be ware of getting Uri from intent.clipdata or intent.data, because one of them may be null in different version.

  private fun onChoosePicture(data: Intent?):Bitmap {
        data?.let {
            var fileUri:Uri? = null

              data.clipData?.let {clip->
                  if(clip.itemCount>0){
                      fileUri = clip.getItemAt(0).uri
                  }
              }
            it.data?.let {uri->
                fileUri = uri
            }


               return MediaStore.Images.Media.getBitmap(this.contentResolver, fileUri )
}

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.

I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.

Here are essential parts of related functions in Start class look like:

ConfigureServices method:

    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder
                                  .WithOrigins("http://localhost:4200")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  //.AllowCredentials()
                                  ;
                          });
    });

Configure method:

        app.UseCors(MyAllowSpecificOrigins);

Found this from:

How to enable Logger.debug() in Log4j

You need to set the logger level to the lowest you want to display. For example, if you want to display DEBUG messages, you need to set the logger level to DEBUG.

The Apache log4j manual has a section on Configuration.

Printing integer variable and string on same line in SQL

declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
    
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */

Oracle SqlPlus - saving output in a file but don't show on screen

set termout off doesn't work from the command line, so create a file e.g. termout_off.sql containing the line:

set termout off

and call this from the SQL prompt:

SQL> @termout_off

Android RecyclerView addition & removal of items

Possibly a duplicate answer but quite useful for me. You can implement the method given below in RecyclerView.Adapter<RecyclerView.ViewHolder> and can use this method as per your requirements, I hope it will work for you

public void removeItem(@NonNull Object object) {
        mDataSetList.remove(object);
        notifyDataSetChanged();
    }

How do I include a pipe | in my linux find -exec command?

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

How to change identity column values programmatically?

Firstly the setting of IDENTITY_INSERT on or off for that matter will not work for what you require (it is used for inserting new values, such as plugging gaps).

Doing the operation through the GUI just creates a temporary table, copies all the data across to a new table without an identity field, and renames the table.

Adding Google Play services version to your app's manifest?

Replace version code with appropriate code of library version will solve your issue, like this:

 <integer name="google_play_services_version"> <versioncode> </integer>

How to get text from EditText?

If you are doing it before the setContentView() method call, then the values will be null.

This will result in null:

super.onCreate(savedInstanceState);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

setContentView(R.layout.main_contacts);

while this will work fine:

super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

How do I set the visibility of a text box in SSRS using an expression?

This didn't work

=IIf((CountRows("ScannerStatisticsData") = 0),False,True)

but this did and I can't really explain why

=IIf((CountRows("ScannerStatisticsData") < 1),False,True)

guess SSRS doesn't like equal comparisons as much as less than.

Retain precision with double in Java

        /*
        0.8                     1.2
        0.7                     1.3
        0.7000000000000002      2.3
        0.7999999999999998      4.2
        */
        double adjust = fToInt + 1.0 - orgV;
        
        // The following two lines works for me. 
        String s = String.format("%.2f", adjust);
        double val = Double.parseDouble(s);

        System.out.println(val); // output: 0.8, 0.7, 0.7, 0.8

Java word count program

    public class TotalWordsInSentence {
    public static void main(String[] args) {

        String str = "This is sample sentence";
        int NoOfWOrds = 1;

        for (int i = 0; i<str.length();i++){
            if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
                NoOfWOrds++;
            }
        }
         System.out.println("Number of Words in Sentence: " + NoOfWOrds);
    }
}

In this code, There wont be any problem regarding white-space in it.
just the simple for loop. Hope this helps...

How do I put an already-running process under nohup?

On my AIX system, I tried

nohup -p  processid>

This worked well. It continued to run my process even after closing terminal windows. We have ksh as default shell so the bg and disown commands didn't work.

How to use protractor to check if an element is visible?

Something to consider

.isDisplayed() assumes the element is present (exists in the DOM)

so if you do

expect($('[ng-show=saving]').isDisplayed()).toBe(true);

but the element is not present, then instead of graceful failed expectation, $('[ng-show=saving]').isDisplayed() will throw an error causing the rest of it block not executed

Solution

If you assume, the element you're checking may not be present for any reason on the page, then go with a safe way below

/**
*  element is Present and is Displayed
*  @param    {ElementFinder}      $element       Locator of element
*  @return   {boolean}
*/
let isDisplayed = function ($element) {
  return (await $element.isPresent()) && (await $element.isDisplayed())
}

and use

expect(await isDisplayed( $('[ng-show=saving]') )).toBe(true);

cast or convert a float to nvarchar?

Float won't convert into NVARCHAR directly, first we need to convert float into money datatype and then convert into NVARCHAR, see the examples below.

Example1

SELECT CAST(CAST(1234567890.1234  AS FLOAT) AS NVARCHAR(100))

output

1.23457e+009

Example2

SELECT CAST(CAST(CAST(1234567890.1234  AS FLOAT) AS MONEY) AS NVARCHAR(100))

output

1234567890.12

In Example2 value is converted into float to NVARCHAR

How can I handle the warning of file_get_contents() function in PHP?

My favourite way to do this is fairly simple:

if (false !== ($data = file_get_contents("http://www.google.com"))) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

I found this after experimenting with the try/catch from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last to get the text of the last error, and file_get_contents returns false on failure, so a simple "if" can catch that.

rsync copy over only certain types of files using include option

The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"

Predefined type 'System.ValueTuple´2´ is not defined or imported

For Visual Studio Code use the built in Terminal and run:

dotnet add package "System.ValueTuple"

Don't forget to run dotnet restore afterwards.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

How to find GCD, LCM on a set of numbers

int gcf(int a, int b)
{
    while (a != b) // while the two numbers are not equal...
    { 
        // ...subtract the smaller one from the larger one

        if (a > b) a -= b; // if a is larger than b, subtract b from a
        else b -= a; // if b is larger than a, subtract a from b
    }

    return a; // or return b, a will be equal to b either way
}

int lcm(int a, int b)
{
    // the lcm is simply (a * b) divided by the gcf of the two

    return (a * b) / gcf(a, b);
}

Jquery date picker z-index issue

Adding to Justin's answer, if you're worried about untidy markup or you don't want this value hard coded in CSS you can set the input before it is shown. Something like this:

$('input').datepicker({
    beforeShow:function(input){
        $(input).dialog("widget").css({
            "position": "relative",
            "z-index": 20
        });
    }
});

Note that you cannot omit the "position": "relative" rule, as the plugin either looks in the inline style for both rules or the stylesheet, but not both.

The dialog("widget") is the actual datepicker that pops up.

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

working with negative numbers in python

import time

print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

print ()


while x > 0:
    print (':',z)
    x = x - 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',z)

while x < 0:
    print (':',-(z))
    x = x + 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',-(z))

print ()  

Accessing Session Using ASP.NET Web API

To fix the issue:

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

in Global.asax.cs

Reading the selected value from asp:RadioButtonList using jQuery

Why so complex?

$('#id:checked').val();

Will work just fine!

How to change 1 char in the string?

I suggest you to use StringBuilder class for it and than parse it to string if you need.

System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();

You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower() it makes new string and your previous string doesn't change.

Having issues with a MySQL Join that needs to meet multiple conditions

You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc

How do I read configuration settings from Symfony2 config.yml?

I learnt a easy way from code example of http://tutorial.symblog.co.uk/

1) notice the ZendeskBlueFormBundle and file location

# myproject/app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }

framework:

2) notice Zendesk_BlueForm.emails.contact_email and file location

# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

parameters:
    # Zendesk contact email address
    Zendesk_BlueForm.emails.contact_email: [email protected]

3) notice how i get it in $client and file location of controller

# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

    public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
    {
    $client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
    ...
    }

How to modify values of JsonObject / JsonArray directly?

This works for modifying childkey value using JSONObject. import used is

import org.json.JSONObject;

ex json:(convert json file to string while giving as input)

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "test"
    },
}

Code

JSONObject jObject  = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);

output:

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "data1"
    },
}

how can I Update top 100 records in sql server

update tb set  f1=1 where id in (select top 100 id from tb where f1=0)

Is it possible to force Excel recognize UTF-8 CSV files automatically?

The bug with ignored BOM seems to be fixed for Excel 2013. I had same problem with Cyrillic letters, but adding BOM character \uFEFF did help.

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

UTF-8: General? Bin? Unicode?

  • utf8_bin compares the bits blindly. No case folding, no accent stripping.
  • utf8_general_ci compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij is not equal ? in this collation.
  • utf8_*_ci is a set of language-specific rules, but otherwise like unicode_ci. Some special cases: Ç, C, ch, ll
  • utf8_unicode_ci follows an old Unicode standard for comparisons. ij=?, but ae != æ
  • utf8_unicode_520_ci follows an newer Unicode standard. ae = æ

See collation chart for details on what is equal to what in various utf8 collations.

utf8, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4 if you want to go much beyond Europe.

The above points apply to utf8mb4, after suitable spelling change. Going forward, utf8mb4 and utf8mb4_unicode_520_ci are preferred.

  • utf16 and utf32 are variants on utf8; there is virtually no use for them.
  • ucs2 is closer to "Unicode" than "utf8"; there is virtually no use for it.

How to get unique values in an array

You can enter array with duplicates and below method will return array with unique elements.

function getUniqueArray(array){
    var uniqueArray = [];
    if (array.length > 0) {
       uniqueArray[0] = array[0];
    }
    for(var i = 0; i < array.length; i++){
        var isExist = false;
        for(var j = 0; j < uniqueArray.length; j++){
            if(array[i] == uniqueArray[j]){
                isExist = true;
                break;
            }
            else{
                isExist = false;
            }
        }
        if(isExist == false){
            uniqueArray[uniqueArray.length] = array[i];
        }
    }
    return uniqueArray;
}

How to implement onBackPressed() in Fragments?

I had the same problem and I created a new listener for it and used in my fragments.

1 - Your activity should have a listener interface and a list of listeners in it

2 - You should implement methods for adding and removing the listeners

3 - You should override the onBackPressed method to check that any of the listeners use the back press or not

public class MainActivity ... {

    /**
     * Back press listener list. Used for notifying fragments when onBackPressed called
     */
    private Stack<BackPressListener> backPressListeners = new Stack<BackPressListener>();


    ...

    /**
     * Adding new listener to back press listener stack
     * @param backPressListener
     */
    public void addBackPressListener(BackPressListener backPressListener) {
        backPressListeners.add(backPressListener);
    }

    /**
     * Removing the listener from back press listener stack
     * @param backPressListener
     */
    public void removeBackPressListener(BackPressListener backPressListener) {
        backPressListeners.remove(backPressListener);
    }


    // Overriding onBackPressed to check that is there any listener using this back press
    @Override
    public void onBackPressed() {

        // checks if is there any back press listeners use this press
        for(BackPressListener backPressListener : backPressListeners) {
            if(backPressListener.onBackPressed()) return;
        }

        // if not returns in the loop, calls super onBackPressed
        super.onBackPressed();
    }

}

4 - Your fragment must implement the interface for back press

5 - You need to add the fragment as a listener for back press

6 - You should return true from onBackPressed if the fragment uses this back press

7 - IMPORTANT - You must remove the fragment from the list onDestroy

public class MyFragment extends Fragment implements MainActivity.BackPressListener {


    ...

    @Override
    public void onAttach(Activity activity) {
        super.onCreate(savedInstanceState);

        // adding the fragment to listener list
        ((MainActivity) activity).addBackPressListener(this);
    }

    ...

    @Override
    public void onDestroy() {
        super.onDestroy();

        // removing the fragment from the listener list
        ((MainActivity) getActivity()).removeBackPressListener(this);
    }

    ...

    @Override
    public boolean onBackPressed() {

        // you should check that if this fragment is the currently used fragment or not
        // if this fragment is not used at the moment you should return false
        if(!isThisFragmentVisibleAtTheMoment) return false;

        if (isThisFragmentUsingBackPress) {
            // do what you need to do
            return true;
        }
        return false;
    }
}

There is a Stack used instead of the ArrayList to be able to start from the latest fragment. There may be a problem also while adding fragments to the back stack. So you need to check that the fragment is visible or not while using back press. Otherwise one of the fragments will use the event and latest fragment will not be closed on back press.

I hope this solves the problem for everyone.

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Just want to share my experience here. I came across the same issue while cross compiling for MTK platform on a Windows 64 bit machine. MinGW and MSYS are involved in the building process and this issue popped up. I solved it by changing the msys-1.0.dll file. Neither rebase.exe nor system reboot worked for me.

Since there is no rebase.exe installed on my computer. I installed cygwin64 and used the rebase.exe inside:

C:\cygwin64\bin\rebase.exe -b 0x50000000 msys-1.0.dll

Though rebasing looked successful, the error remained. Then I ran rebase command inside Cygwin64 terminal and got an error:

$ rebase -b 0x50000000 msys-1.0.dll
rebase: Invalid Baseaddress 0x50000000, must be > 0x200000000

I later tried a couple address but neither of them worked. So I ended up changing the msys-1.0.dll file and it solved the problem.

CSS list-style-image size

I did a kind of terminal emulator with Bootstrap and Javascript because I needed some dynamic to add easily new items, and I put the prompt from Javascript.

HTML:

  <div class="panel panel-default">
      <div class="panel-heading">Comandos SQL ejecutados</div>
      <div class="panel-body panel-terminal-body">
          <ul id="ulCommand"></ul>
      </div>
 </div>

Javascript:

function addCommand(command){
    //Creating the li tag   
    var li = document.createElement('li');
    //Creating  the img tag
    var prompt = document.createElement('img');
    //Setting the image 
    prompt.setAttribute('src','./lib/custom/img/terminal-prompt-white.png');
    //Setting the width (like the font)
    prompt.setAttribute('width','15px');
    //Setting height as auto
    prompt.setAttribute('height','auto');
    //Adding the prompt to the list item
    li.appendChild(prompt);
    //Creating a span tag to add the command
    //li.appendChild('el comando');   por que no es un nodo
    var span = document.createElement('span');
    //Adding the text to the span tag
    span.innerHTML = command;
    //Adding the span to the list item
    li.appendChild(span);
    //At the end, adding the list item to the list (ul)
    document.getElementById('ulCommand').appendChild(li);
}

CSS:

.panel-terminal-body {
  background-color: #423F3F;
  color: #EDEDED;
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 15px;
  padding-bottom: 15px;
  height: 300px;
}

.panel-terminal-body ul {
  list-style: none;
}

I hope this help you.

How to know if docker is already logged in to a docker registry server

The docker cli credential scheme is unsurprisingly uncomplicated, just take a look:

cat ~/.docker/config.json

{
  "auths": {
    "dockerregistry.myregistry.com": {},
    "https://index.docker.io/v1/": {}

This exists on Windows (use Get-Content ~\.docker\config.json) and you can also poke around the credential tool which also lists the username ... and I think you can even retrieve the password

. "C:\Program Files\Docker\Docker\resources\bin\docker-credential-wincred.exe" list

{"https://index.docker.io/v1/":"kcd"}

Using Selenium Web Driver to retrieve value of a HTML input

element.GetAttribute("value");

Eventhough if you don't see the "value" attribute in html dom, you will get the field value displayed on the GUI.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

Tried npm install mongoose --msvs_version=2012, if you have multiple Visual installed, it worked for me

Passing parameters in rails redirect_to

If you have some form data for example sent to home#action, now you want to redirect them to house#act while keeping the parameters, you can do this

redirect_to act_house_path(request.parameters)

How To Check If A Key in **kwargs Exists?

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

import sys

def myfunc(**kwargs):
    args = {'country':'England','town':'London',
            'currency':'Pound', 'language':'English'}

    diff = set(kwargs.keys()) - set(args.keys())
    if diff:
        print("Invalid args:",tuple(diff),file=sys.stderr)
        return

    args.update(kwargs)            
    print(args)

The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

Multiprocessing vs Threading Python

Another thing not mentioned is that it depends on what OS you are using where speed is concerned. In Windows processes are costly so threads would be better in windows but in unix processes are faster than their windows variants so using processes in unix is much safer plus quick to spawn.

MySQL JOIN ON vs USING?

Wikipedia has the following information about USING:

The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.

Tables that it was talking about:

enter image description here

The Postgres documentation also defines them pretty well:

The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.

The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.

How can I encode a string to Base64 in Swift?

You could just do a simple extension like:

import UIKit

// MARK: - Mixed string utils and helpers
extension String {


    /**
    Encode a String to Base64

    :returns: 
    */
    func toBase64()->String{

        let data = self.dataUsingEncoding(NSUTF8StringEncoding)

        return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    }

}

iOS 7 and up

Emulate ggplot2 default color palette

From page 106 of the ggplot2 book by Hadley Wickham:

The default colour scheme, scale_colour_hue picks evenly spaced hues around the hcl colour wheel.

With a bit of reverse engineering you can construct this function:

ggplotColours <- function(n = 6, h = c(0, 360) + 15){
  if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}

Demonstrating this in barplot:

y <- 1:3
barplot(y, col = ggplotColours(n = 3))

enter image description here

AssertNull should be used or AssertNotNull

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

send bold & italic text on telegram bot with html

If you are using PHP you can use this, and I'm sure it's almost similar in other languages as well

$WebsiteURL = "https://api.telegram.org/bot".$BotToken;
$text = "<b>This</b> <i>is some Text</i>";
$Update = file_get_contents($WebsiteURL."/sendMessage?chat_id=$chat_id&text=$text&parse_mode=html);

echo $Update;

Here is the list of all tags that you can use

<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://www.example.com/">inline URL</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>

Android Reading from an Input stream efficiently

Have you tried the built in method to convert a stream to a string? It's part of the Apache Commons library (org.apache.commons.io.IOUtils).

Then your code would be this one line:

String total = IOUtils.toString(inputStream);

The documentation for it can be found here: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29

The Apache Commons IO library can be downloaded from here: http://commons.apache.org/io/download_io.cgi

How to fix "The ConnectionString property has not been initialized"

You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).

If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.

var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);

If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.

Post your code (for the databound element and the web.config to be safe) and we can take a look at it.

EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString (if ConnectionString is the name of your connection string.)

How can I exclude one word with grep?

The -v option will show you all the lines that don't match the pattern.

grep -v ^unwanted_word

How to convert JSON to CSV format and store in a variable

Sometimes objects have different lengths. So I ran into the same problem as Kyle Pennell. But instead of sorting the array we simply traverse over it and pick the longest. Time complexity is reduced to O(n), compared to O(n log(n)) when sorting first.

I started with the code from Christian Landgren's updated ES6 (2016) version.

json2csv(json) {
    // you can skip this step if your input is a proper array anyways:
    const simpleArray = JSON.parse(json)
    // in array look for the object with most keys to use as header
    const header = simpleArray.map((x) => Object.keys(x))
      .reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []);

    // specify how you want to handle null values here
    const replacer = (key, value) => (
      value === undefined || value === null ? '' : value);
    let csv = simpleArray.map((row) => header.map(
      (fieldName) => JSON.stringify(row[fieldName], replacer)).join(','));
    csv = [header.join(','), ...csv];
    return csv.join('\r\n');
}

IOException: The process cannot access the file 'file path' because it is being used by another process

I had this problem and it was solved by following the code below

var _path=MyFile.FileName;
using (var stream = new FileStream
    (_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  { 
    // Your Code! ;
  }

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

vertical-align: middle with Bootstrap 2

As well as the previous answers are you could always use the Pull attrib as well:


    <ol class="row" id="possibilities">
       <li class="span6">
         <div class="row">
           <div class="span3">
             <p>some text here</p>
             <p>Text Here too</p>
           </div>
         <figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
        </div>
 </li>
 <li class="span6">
     <div class="row">
         <figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
         <div class="span3">
             <p>Some text</p>
             <p>Some text here too.</p>
         </div>
     </div>
 </li>

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

There are 2 versions of jdk in your PATH VARIABLE jdk1.6.0_45 and jdk1.8.0_25. Try removing the first one ie. jdk1.6.0_45 from the PATH

How to submit an HTML form without redirection

In order to achieve what you want, you need to use jQuery Ajax as below:

$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/Car/Edit/17/',
        type: 'post',
        data:$('#myForm').serialize(),
        success:function(){
            // Whatever you want to do after the form is successfully submitted
        }
    });
});

Also try this one:

function SubForm(e){
    e.preventDefault();
    var url = $(this).closest('form').attr('action'),
    data = $(this).closest('form').serialize();
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        success: function(){
           // Whatever you want to do after the form is successfully submitted
       }
   });
}

Final solution

This worked flawlessly. I call this function from Html.ActionLink(...)

function SubForm (){
    $.ajax({
        url: '/Person/Edit/@Model.Id/',
        type: 'post',
        data: $('#myForm').serialize(),
        success: function(){
            alert("worked");
        }
    });
}

WSDL validator?

If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.

When to use margin vs padding in CSS

Margin

Margin is usually used to create a space between the element itself and its surround.

for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.

Padding

I usually use when I've an element inside a border, <div> or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.

So briefly, it's situational; it depends on what you are trying to do.

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

How to get Toolbar from fragment?

For Kotlin users (activity as AppCompatActivity).supportActionBar?.show()

var self = this?

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.

Split a string by another string in C#

The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:

public static class Extensions
{
    public static string[] Split(this string toSplit, string splitOn) {
        return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
    }
}

That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:

"a big long string with stuff to split on".Split("g str");

Android Studio - debug keystore

If you use Windows, you will found it follow this: File-->Project Structure-->Facets

chose your Android project and in the "Facet 'Android'" window click TAB "Packaging",you will found what you want

How do you programmatically update query params in react-router?

Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.

When user uses search feature, I want him to be able to send url link for same query to a colleague.

import { push } from 'react-router-redux';
import qs from 'query-string';

export const search = () => (dispatch) => {
    const query = { firstName: 'John', lastName: 'Doe' };

    //API call to retrieve records
    //...

    const searchString = qs.stringify(query);

    dispatch(push({
        search: searchString
    }))
}

Disable Logback in SpringBoot

I found that excluding the full spring-boot-starter-logging module is not necessary. All that is needed is to exclude the org.slf4j:slf4j-log4j12 module.

Adding this to a Gradle build file will resolve the issue:

configurations {
    runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
    compile.exclude group: "org.slf4j", module: "slf4j-log4j12"
}

See this other StackOverflow answer for more details.

Get the size of the screen, current web page and browser window

To check height and width of your current loaded page of any website using "console" or after clicking "Inspect".

step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'

step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.

step 3: Now, write the following after the greater than sign ('>') i.e.

       > window.innerWidth
            output : your present window width in px (say 749)

       > window.innerHeight
            output : your present window height in px (say 359)

How can I use Helvetica Neue Condensed Bold in CSS?

"Helvetica Neue Condensed Bold" get working with firefox:

.class {
  font-family: "Helvetica Neue";
  font-weight: bold;
  font-stretch: condensed;
}

But it's fail with Opera.

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

Sorting a vector of custom objects

You are on the right track. std::sort will use operator< as comparison function by default. So in order to sort your objects, you will either have to overload bool operator<( const T&, const T& ) or provide a functor that does the comparison, much like this:

 struct C {
    int i;
    static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
 };

 bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }

 std::vector<C> values;

 std::sort( values.begin(), values.end() ); // uses operator<
 std::sort( values.begin(), values.end(), C::before );

The advantage of the usage of a functor is that you can use a function with access to the class' private members.

How to display .svg image using swift

There is no Inbuilt support for SVG in Swift. So we need to use other libraries.

The simple SVG libraries in swift are :

1) SwiftSVG Library

It gives you more option to Import as UIView, CAShapeLayer, Path, etc

To modify your SVG Color and Import as UIImage you can use my extension codes for the library mentioned in below link,

Click here to know on using SwiftSVG library :
Using SwiftSVG to set SVG for Image

|OR|

2) SVGKit Library

2.1) Use pod to install :

pod 'SVGKit', :git => 'https://github.com/SVGKit/SVGKit.git', :branch => '2.x'

2.2) Add framework

Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework

2.3) Add in Objective-C to Swift bridge file bridging-header.h :

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

2.4) Create SvgImg Folder (for better organization) in Project and add SVG files inside it.

Note : Adding Inside Assets Folder won't work and SVGKit searches for file only in Project folders

2.5) Use in your Swift Code as below :

import SVGKit

and

let namSvgImgVar: SVGKImage = SVGKImage(named: "NamSvgImj")

Note : SVGKit Automatically apends extention ".svg" to the string you specify

let namSvgImgVyuVar = SVGKImageView(SVGKImage: namSvgImgVar)

let namImjVar: UIImage = namSvgImgVar.UIImage

There are many more options for you to init SVGKImage and SVGKImageView

There are also other classes u can explore

    SVGRect
    SVGCurve
    SVGPoint
    SVGAngle
    SVGColor
    SVGLength

    and etc ...

How to implement a FSM - Finite State Machine in Java

Consider the easy, lightweight Java library EasyFlow. From their docs:

With EasyFlow you can:

  • implement complex logic but keep your code simple and clean
  • handle asynchronous calls with ease and elegance
  • avoid concurrency by using event-driven programming approach
  • avoid StackOverflow error by avoiding recursion
  • simplify design, programming and testing of complex java applications

How to tell PowerShell to wait for each command to end before starting the next?

Besides using Start-Process -Wait, piping the output of an executable will make Powershell wait. Depending on the need, I will typically pipe to Out-Null, Out-Default, Out-String or Out-String -Stream. Here is a long list of some other output options.

# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String

# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }

# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com

I do miss the CMD/Bash style operators that you referenced (&, &&, ||). It seems we have to be more verbose with Powershell.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

I just tested your snippet, and their is no double spacing line here. The end-of-line are \r\n, so what i would check in your case is:

  1. your editor is reading correctly DOS file
  2. no \n exist in values of your rows dict.

(Note that even by putting a value with \n, DictWriter automaticly quote the value.)

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

How do I get the localhost name in PowerShell?

A slight tweak on @CPU-100's answer, for the local FQDN:

[System.Net.DNS]::GetHostByName($Null).HostName

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

event.preventDefault() function not working in IE

I know this is quite an old post but I just spent some time trying to make this work in IE8.

It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.

Let's say that we have this code:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.

Even if I set returnValue property directly to false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

This also won't work, because I just set some property of jQuery custom event object.

Only solution that works for me is to set property returnValue of global variable event like this:

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.

UPDATE:

As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.

Error: No module named psycopg2.extensions

For Django 2 and python 3 install psycopg2 using pip3 :

pip3 install psycopg2

What is the difference between == and equals() in Java?

== is an operator and equals() is a method.

Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.

Easiest way to convert month name to month number in JS ? (Jan = 01)

function getMonthDays(MonthYear) {
  var months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];

  var Value=MonthYear.split(" ");      
  var month = (months.indexOf(Value[0]) + 1);      
  return new Date(Value[1], month, 0).getDate();
}

console.log(getMonthDays("March 2011"));

UTC Date/Time String to Timezone

Assuming the UTC is not included in the string then:

date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00';  //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date;  //Should get '2011-01-01 10:00:00 EST' or something like that

Or you could use the DateTime object.

How to open local files in Swagger-UI

I managed to load the local swagger.json specification using the following tools for Node.js and this will take hardly 5 minutes to finish

swagger-ui-dist

express

Follow below steps

  1. Create a folder as per your choice and copy your specification swagger.json to the newly created folder
  2. Create a file with the extension .js in my case swagger-ui.js in the same newly created folder and copy and save the following content in the file swagger-ui.js
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()

// this is will load swagger ui
app.use(express.static(pathToSwaggerUi))

// this will serve your swagger.json file using express
app.use(express.static(`${__dirname}`))

// use port of your choice
app.listen(5000)
  1. Install dependencies as npm install express and npm install swagger-ui-dist
  2. Run the express application using the command node swagger-ui.js
  3. Open browser and hit http://localhost/5000, this will load swagger ui with default URL as https://petstore.swagger.io/v2/swagger.json
  4. Now replace the default URL mentioned above with http://localhost:5000/swagger.json and click on the Explore button, this will load swagger specification from a local JSON file

You can use folder name, JSON file name, static public folder to serve swagger.json, port to serve as per your convenience

Contains case insensitive

Another options is to use the search method as follow:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

It looks more elegant then converting the whole string to lower case and it may be more efficient.
With toLowerCase() the code have two pass over the string, one pass is on the entire string to convert it to lower case and another is to look for the desired index.
With RegExp the code have one pass over the string which it looks to match the desired index.

Therefore, on long strings I recommend to use the RegExp version (I guess that on short strings this efficiency comes on the account of creating the RegExp object though)

Export table data from one SQL Server to another

Just for the kicks.

Since I wasnt able to create linked server and since just connecting to production server was not enough to use INSERT INTO i did the following:

  • created a backup of production server database
  • restored the database on my test server
  • executed the insert into statements

Its a backdoor solution, but since i had problems it worked for me.

Since i have created empty tables using SCRIPT TABLE AS / CREATE in order to transfer all the keys and indexes I couldnt use SELECT INTO. SELECT INTO only works if the tables do not exist on the destination location but it does not copy keys and indexes, so you have to do that manualy. The downside of using INSERT INTO statement is that you have to manualy provide with all the column names, plus it might give you some problems if some foreign key constraints fail.

Thanks to all anwsers, there are some great solutions but i have decided to accept marc_s anwser.

psql: could not connect to server: No such file or directory (Mac OS X)

Another class of reasons why this can happen is due to Postgres version updates.

You can confirm this is a problem by looking at the postgres logs:

tail -n 10000 /usr/local/var/log/postgres.log

and seeing entries like:

DETAIL:  The data directory was initialized by PostgreSQL version 12, which is not compatible with this version 13.0.

In this case (assuming you are on Mac and using brew), just run:

brew postgresql-upgrade-database

(Oddly, it failed on run 1 and worked on run 2, so try it twice before giving up)

nginx - client_max_body_size has no effect

Someone correct me if this is bad, but I like to lock everything down as much as possible, and if you've only got one target for uploads (as it usually the case), then just target your changes to that one file. This works for me on the Ubuntu nginx-extras mainline 1.7+ package:

location = /upload.php {
    client_max_body_size 102M;
    fastcgi_param PHP_VALUE "upload_max_filesize=102M \n post_max_size=102M";
    (...)
}

Correctly Parsing JSON in Swift 3

This is an other way to solve your problem. So please check out below solution. Hope it will help you.

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
    if let names = json["names"] as? [String] {
        print(names)
    }
} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " + 
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " + 
        itr.getCenter().getLongitude() + "\n");
}

Note: MyPojo[].class is the class having getter and setter of json properties.

Result:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

How to remove/ignore :hover css style on touch devices

According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with @media not all and (hover: none). It looks weird but it works.

I made a Sass mixin out of this for easier use:

@mixin hover-supported {
    @media not all and (hover: none) {
        &:hover {
            @content;
        }
    }
}

Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:

@media (hover: hover) {
    /* Device that can hover (desktops) */
}
@media (hover: none) {
    /* Device that can not hover with ease */
}
@media (pointer: coarse) {
    /* Device with limited pointing accuracy (touch) */
}
@media (pointer: fine) {
    /* Device with accurate pointing (desktop, stylus-based) */
}
@media (pointer: none) {
    /* Device with no pointing */
}

Example for specific targets:

@media (hover: none) and (pointer: coarse) {
    /* Smartphones and touchscreens */
}

@media (hover: hover) and (pointer: fine) {
    /* Desktops with mouse */
}

I love mixins, this is how I use my hover mixin to only target devices that supports it:

@mixin on-hover {
    @media (hover: hover) and (pointer: fine) {
        &:hover {
            @content;
        }
    }
}

button {
    @include on-hover {
        color: blue;
    }
}

Best way to do nested case statement logic in SQL Server

This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops

enter image description here

How to save picture to iPhone photo library?

In Swift:

    // Save it to the camera roll / saved photo album
    // UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, nil, nil, nil) or 
    UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)

    func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {
            if (error != nil) {
                // Something wrong happened.
            } else {
                // Everything is alright.
            }
    }

How to create a md5 hash of a string in C?

All of the existing answers use the deprecated MD5Init(), MD5Update(), and MD5Final().

Instead, use EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex(), e.g.

// example.c
//
// gcc example.c -lssl -lcrypto -o example

#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>

void bytes2md5(const char *data, int len, char *md5buf) {
  // Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
  EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  const EVP_MD *md = EVP_md5();
  unsigned char md_value[EVP_MAX_MD_SIZE];
  unsigned int md_len, i;
  EVP_DigestInit_ex(mdctx, md, NULL);
  EVP_DigestUpdate(mdctx, data, len);
  EVP_DigestFinal_ex(mdctx, md_value, &md_len);
  EVP_MD_CTX_free(mdctx);
  for (i = 0; i < md_len; i++) {
    snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
  }
}

int main(void) {
  const char *hello = "hello";
  char md5[33]; // 32 characters + null terminator
  bytes2md5(hello, strlen(hello), md5);
  printf("%s\n", md5);
}

Multi-Column Join in Hibernate/JPA Annotations

Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:

Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)

So if you are unwilling to make AnEmbeddableObject the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.

Pandas index column title or name

df.index.name should do the trick.

Python has a dir function that let's you query object attributes. dir(df.index) was helpful here.

How to catch a unique constraint error in a PL/SQL block?

As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */ in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.

Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME which has a unique constraint on a column called IDX_COL_NAME.

INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */ 
INTO TABLE_NAME(
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n)
SELECT 
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n);

This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:

Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.

For a simple test run on the JS perf page, I've documented some of the results:

_x000D_
_x000D_
<script>_x000D_
// Setup_x000D_
  var startString = "xxxxxxxxxabcxxxxxxabcxx";_x000D_
  var endStringRegEx = undefined;_x000D_
  var endStringString = undefined;_x000D_
  var endStringRegExNewStr = undefined;_x000D_
  var endStringRegExNew = undefined;_x000D_
  var endStringStoredRegEx = undefined;      _x000D_
  var re = new RegExp("abc", "g");_x000D_
</script>_x000D_
_x000D_
<script>_x000D_
// Tests_x000D_
  endStringRegEx = startString.replace(/abc/g, "def") // Regex_x000D_
  endStringString = startString.replace("abc", "def", "g") // String_x000D_
  endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String_x000D_
  endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp_x000D_
  endStringStoredRegEx = startString.replace(re, "def") // saved regex_x000D_
</script>
_x000D_
_x000D_
_x000D_

The results for Chrome 68 are as follows:

String replace:    9,936,093 operations/sec
Saved regex:       5,725,506 operations/sec
Regex:             5,529,504 operations/sec
New Regex String:  3,571,180 operations/sec
New Regex:         3,224,919 operations/sec

From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }

how to make a new line in a jupyter markdown cell

Just add <br> where you would like to make the new line.

$S$: a set of shops
<br>
$I$: a set of items M wants to get

Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html

Note that newlines using <br> does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br> as a space.

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

But here's the rub, sometimes you can't or don't want to wait. For example I want to use the new support for RubyMotion which includes RubyMotion project structure support, setup of rake files, setup of configurations that are hooked to iOS Simulator etc.

RubyMine has all of these now, IDEA does not. So I would have to generate a RubyMotion project outside of IDEA, then setup an IDEA project and hook up to that source folder etc and God knows what else.

What JetBrains should do is have a licensing model that would allow me, with the purchase of IDEA to use any of other IDEs, as opposed to just relying on IDEAs plugins.

I would be willing to pay more for that i.e. say 50 bucks more for said flexibility.

The funny thing is, I was originally a RubyMine customer that upgraded to IDEA, because I did want that polyglot setup. Now I'm contemplating paying for the upgrade of RubyMine, just because I need to do RubyMotion now. Also there are other potential areas where this out of sync issue might bite me again . For example torque box workflow / deployment support.

JetBrains has good IDEs but I guess I'm a bit annoyed.

Insert multiple lines into a file after specified pattern using shell script

This answer is easy to understand

  • Copy before the pattern
  • Add your lines
  • Copy after the pattern
  • Replace original file

    FILENAME='app/Providers/AuthServiceProvider.php'

STEP 1 copy until the pattern

sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp

STEP 2 add your lines

cat << 'EOL' >> ${FILENAME}_temp

HERE YOU COPY AND
PASTE MULTIPLE
LINES, ALSO YOU CAN
//WRITE COMMENTS

AND NEW LINES
AND SPECIAL CHARS LIKE $THISONE

EOL

STEP 3 add the rest of the file

grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp

REPLACE original file

mv ${FILENAME}_temp $FILENAME

if you need variables, in step 2 replace 'EOL' with EOL

cat << EOL >> ${FILENAME}_temp

this variable will expand: $variable1

EOL

What does the "map" method do in Ruby?

Map is a part of the enumerable module. Very similar to "collect" For Example:

  Class Car

    attr_accessor :name, :model, :year

    Def initialize (make, model, year)
      @make, @model, @year = make, model, year
    end

  end

  list = []
  list << Car.new("Honda", "Accord", 2016)
  list << Car.new("Toyota", "Camry", 2015)
  list << Car.new("Nissan", "Altima", 2014)

  p list.map {|p| p.model}

Map provides values iterating through an array that are returned by the block parameters.