Programs & Examples On #Msmq

Microsoft Message Queuing (MSMQ) is a message queuing implementation developed by Microsoft and deployed as part of its Windows platform since 1996. MSMQ is included on most versions of Windows but it's not installed by default.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

change html input type by JS?

_x000D_
_x000D_
$(".show-pass").click(function (e) {_x000D_
    e.preventDefault();_x000D_
    var type = $("#signupform-password").attr('type');_x000D_
    switch (type) {_x000D_
        case 'password':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'text');_x000D_
            return;_x000D_
        }_x000D_
        case 'text':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'password');_x000D_
            return;_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
_x000D_
_x000D_

Column count doesn't match value count at row 1

The error means that you are providing not as much data as the table wp_posts does contain columns. And now the DB engine does not know in which columns to put your data.

To overcome this you must provide the names of the columns you want to fill. Example:

insert into wp_posts (column_name1, column_name2)
values (1, 3)

Look up the table definition and see which columns you want to fill.

And insert means you are inserting a new record. You are not modifying an existing one. Use update for that.

Work with a time span in Javascript

/**
 * ??????????????,???????? 
 * English: Calculating the difference between the given time and the current time and then showing the results.
 */
function date2Text(date) {
    var milliseconds = new Date() - date;
    var timespan = new TimeSpan(milliseconds);
    if (milliseconds < 0) {
        return timespan.toString() + "??";
    }else{
        return timespan.toString() + "?";
    }
}

/**
 * ???????????
 * English: Using a function to calculate the time interval
 * @param milliseconds ???
 */
var TimeSpan = function (milliseconds) {
    milliseconds = Math.abs(milliseconds);
    var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
    milliseconds -= days * (1000 * 60 * 60 * 24);

    var hours = Math.floor(milliseconds / (1000 * 60 * 60));
    milliseconds -= hours * (1000 * 60 * 60);

    var mins = Math.floor(milliseconds / (1000 * 60));
    milliseconds -= mins * (1000 * 60);

    var seconds = Math.floor(milliseconds / (1000));
    milliseconds -= seconds * (1000);
    return {
        getDays: function () {
            return days;
        },
        getHours: function () {
            return hours;
        },
        getMinuts: function () {
            return mins;
        },
        getSeconds: function () {
            return seconds;
        },
        toString: function () {
            var str = "";
            if (days > 0 || str.length > 0) {
                str += days + "?";
            }
            if (hours > 0 || str.length > 0) {
                str += hours + "??";
            }
            if (mins > 0 || str.length > 0) {
                str += mins + "??";
            }
            if (days == 0 && (seconds > 0 || str.length > 0)) {
                str += seconds + "?";
            }
            return str;
        }
    }
}

How do I pass a unique_ptr argument to a constructor or a function?

tl;dr: Do not use unique_ptr's like that.

I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.

  1. Only take unique_ptr constructor parameters if you have publicly-exposed unique_ptr members.

unique_ptrs wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*> as suggested in the Core Guidelines.

Only if the purpose of your class is to hold unique_ptr's, and have others use those unique_ptr's as such - only then is it reasonable for your constructor or methods to take them.

  1. Don't expose the fact that you use unique_ptrs internally

Using unique_ptr for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.

Exact time measurement for performance testing

A better way is to use the Stopwatch class:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

Console.WriteLine("Elapsed={0}",sw.Elapsed);

Calculating distance between two points (Latitude, Longitude)

As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

How to import keras from tf.keras in Tensorflow?

Try from tensorflow.python import keras

with this, you can easily change keras dependent code to tensorflow in one line change.

You can also try from tensorflow.contrib import keras. This works on tensorflow 1.3

Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras to get keras in tensorflow.

How to store Emoji Character in MySQL Database

I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.

Your defualt character is utf-8. But emoji needs utf8mb4 to support it. If you have the permission to revise the configure file of mysql, you can follow this step.

Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).

step 1. open your my.cnf for mysql, add these following lines to your my.cnf.

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'

[mysql]
default-character-set = utf8mb4


[client]
default-character-set = utf8mb4

step2. stop your mysql service, and start mysql service

mysql.server stop
mysql.server start

Finished! Then you can check your character are changed into utf8mb4.

mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name            | Value                                                    |
+--------------------------+----------------------------------------------------------+
| character_set_client     | utf8mb4                                                  |
| character_set_connection | utf8mb4                                                  |
| character_set_database   | utf8mb4                                                  |
| character_set_filesystem | binary                                                   |
| character_set_results    | utf8mb4                                                  |
| character_set_server     | utf8mb4                                                  |
| character_set_system     | utf8                                                     |
| character_sets_dir       | /usr/local/Cellar/[email protected]/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)

Disable scrolling in an iPhone web application?

'self.webView.scrollView.bounces = NO;'

Just add this one line in the 'viewDidLoad' of the mainViewController.m file of your application. you can open it in the Xcode and add it .

This should make the page without any rubberband bounces still enabling the scroll in the app view.

Why use static_cast<int>(x) instead of (int)x?

  1. Allows casts to be found easily in your code using grep or similar tools.
  2. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions.
  3. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.

See Effective C++ Introduction

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

How to launch an EXE from Web page (asp.net)

Are you saying that you are having trouble inserting into a web page a link to a file that happens to have a .exe extension?

If that is the case, then take one step back. Imagine the file has a .htm extension, or a .css extension. How can you make that downloadable? If it is a static link, then the answer is clear: the file needs to be in the docroot for the ASP.NET app. IIS + ASP.NET serves up many kinds of content: .htm files, .css files, .js files, image files, implicitly. All these files are somewhere under the docroot, which by default is c:\inetpub\wwwroot, but for your webapp is surely something different. The fact that the file you want to expose has an .exe extension does not change the basic laws of IIS physics. The exe has to live under the docroot. The network share thing might work for some browsers.

The alternative of course is to dynamically write the content of the file directly to the Response.OutputStream. This way you don't need the .exe to be in your docroot, but it is not a direct download link. In this scenario, the file might be downloaded by a button click.

Something like this:

    Response.Clear(); 
    string FullPathFilename = "\\\\server\\share\\CorpApp1.exe";
    string archiveName= System.IO.Path.GetFileName(FullPathFilename);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("content-disposition", "filename=" + archiveName);
    Response.TransmitFile(FullPathFilename);
    Response.End();

Overriding fields or properties in subclasses

You could do this

class x
{
    private int _myInt;
    public virtual int myInt { get { return _myInt; } set { _myInt = value; } }
}

class y : x
{
    private int _myYInt;
    public override int myInt { get { return _myYInt; } set { _myYInt = value; } }
}

virtual lets you get a property a body that does something and still lets sub-classes override it.

How to Query an NTP Server using C#?

The .NET Micro Framework Toolkit found in the CodePlex has an NTPClient. I have never used it myself but it looks good.

There is also another example located here.

Bring a window to the front in WPF

myWindow.Activate();

Attempts to bring the window to the foreground and activates it.

That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want:

myWindow.TopMost = true;

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How to drop a database with Mongoose?

This works for me as of Mongoose v4.7.0:

mongoose.connection.dropDatabase();

how to use "tab space" while writing in text file

Use "\t". That's the tab space character.

You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

How do I install jmeter on a Mac?

  1. Download apache-Jmeter.zip file
  2. Unzip it
  3. Open terminal-> go to apache-Jmeter/bin
  4. sh jmeter.sh

How to upload a file and JSON data in Postman?

To send image along with json data in postman you just have to follow the below steps .

  • Make your method to post in postman
  • go to the body section and click on form-data
  • provide your field name select file from the dropdown list as shown below
  • you can also provide your other fields .
  • now just write your image storing code in your controller as shown below .

postman : enter image description here

my controller :

public function sendImage(Request $request)
{
    $image=new ImgUpload;  
    if($request->hasfile('image'))  
    {  
        $file=$request->file('image');  
        $extension=$file->getClientOriginalExtension();  
        $filename=time().'.'.$extension;  
        $file->move('public/upload/userimg/',$filename);  
        $image->image=$filename;  
    }  
    else  
    {  
        return $request;  
        $image->image='';  
    }  
    $image->save();
    return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}

That's it hope it will help you

Get selected value from combo box in C# WPF

Actually you can do it the following way as well.

Suppose your ComboBox name is comboBoxA. Then its value can be gotten as:

string combo = comboBoxA.SelectedValue.ToString();

I think it's now supported since your question is five years old.

php var_dump() vs print_r()

var_dump() :-

  1. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
  2. This function display number of element in a variable.
  3. This function display length of variable.
  4. Can't return the value only print the value.
  5. it is use for debugging purpose.

Example :-

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

output :-

   array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

print_r() :-

  1. Prints human-readable information about a variable.
  2. Not display number of element in a variable as var_dump().
  3. Not display length of variable in a variable as var_dump().
  4. Return the value if we set second parameter to true in printf_r().

Example :-

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Output:-

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Unix's 'ls' sort by name

From the man page (for bash ls):

Sort entries alphabetically if none of -cftuSUX nor --sort.

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Since sudo will not work with redirection >, I like the tee command for this purpose

echo "" | sudo tee fileName

Combine two arrays

This works:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

how to check if the input is a number or not in C?

A self-made solution:

bool isNumeric(const char *str) 
{
    while(*str != '\0')
    {
        if(*str < '0' || *str > '9')
            return false;
        str++;
    }
    return true;
}

Note that this solution should not be used in production-code, because it has severe limitations. But I like it for understanding C-Strings and ASCII.

jQuery ajax success callback function definition

Try rewriting your success handler to:

success : handleData

The success property of the ajax method only requires a reference to a function.

In your handleData function you can take up to 3 parameters:

object data
string textStatus
jqXHR jqXHR

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

Best way to select random rows PostgreSQL

Starting with PostgreSQL 9.5, there's a new syntax dedicated to getting random elements from a table :

SELECT * FROM mytable TABLESAMPLE SYSTEM (5);

This example will give you 5% of elements from mytable.

See more explanation on the documentation: http://www.postgresql.org/docs/current/static/sql-select.html

What are .a and .so files?

Wikipedia is a decent source for this info.

To learn about static library files like .a read Static libarary

To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.

How to take input in an array + PYTHON?

If the number of elements in the array is not given, you can alternatively make use of list comprehension like:

str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]

How to get back to most recent version in Git?

When you checkout to a specific commit, git creates a detached branch. So, if you call:

$ git branch 

You will see something like:

* (detached from 3i4j25)
  master
  other_branch

To come back to the master branch head you just need to checkout to your master branch again:

$ git checkout master

This command will automatically delete the detached branch.

If git checkout doesn't work you probably have modified files conflicting between branches. To prevent you to lose code git requires you to deal with these files. You have three options:

  1. Stash your modifications (you can pop them later):

    $ git stash
    
  2. Discard the changes reset-ing the detached branch:

    $ git reset --hard
    
  3. Create a new branch with the previous modifications and commit them:

    $ git checkout -b my_new_branch
    $ git add my_file.ext
    $ git commit -m "My cool msg"
    

After this you can go back to your master branch (most recent version):

$ git checkout master

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

How to set the thumbnail image on HTML5 video?

If you want a video first frame as a thumbnail, than you can use

Add #t=0.1 to your video source, like below

<video width="320" height="240" controls>
  <source src="video.mp4#t=0.1" type="video/mp4">
</video>

NOTE: make sure about your video type(ex: mp4, ogg, webm etc)

Get the device width in javascript

check it

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

How to URL encode a string in Ruby

If you want to "encode" a full URL without having to think about manually splitting it into its different parts, I found the following worked in the same way that I used to use URI.encode:

URI.parse(my_url).to_s

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

How to add results of two select commands in same query

UNION ALL once, aggregate once:

SELECT sum(hours) AS total_hours
FROM   (
   SELECT hours FROM resource
   UNION ALL
   SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
   ) x

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

C++ Double Address Operator? (&&)

&& is new in C++11, and it signifies that the function accepts an RValue-Reference -- that is, a reference to an argument that is about to be destroyed.

How to split a number into individual digits in c#?

I'd use modulus and a loop.

int[] GetIntArray(int num)
{
    List<int> listOfInts = new List<int>();
    while(num > 0)
    {
        listOfInts.Add(num % 10);
        num = num / 10;
    }
    listOfInts.Reverse();
    return listOfInts.ToArray();
}

How do I replace a character in a string in Java?

Try this code.You can replace any character with another given character. Here I tried to replace the letter 'a' with "-" character for the give string "abcdeaa"

OutPut -->_bcdef__

    public class Replace {

    public static void replaceChar(String str,String target){
        String result = str.replaceAll(target, "_");
        System.out.println(result);
    }

    public static void main(String[] args) {
        replaceChar("abcdefaa","a");
    }

}

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How can I solve ORA-00911: invalid character error?

I had the same problem and it was due to the end of line. I had copied from another document. I put everythng on the same line, then split them again and it worked.

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

Getting the folder name from a path

var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();

SASS - use variables across multiple files

Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:

@import 'base/_reset';

@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';

@import 'base/_typography';

@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';

@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';

@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';

@import 'vendors/_ui-grid';

@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';

And you can watch them with gulp/grunt/webpack etc, like:

gulpfile.js

// SASS Task

var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function(){
    return gulp
            .src('sass/**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass().on('error', sass.logError))
            .pipe(concat('styles.css'))
            .pipe(uglifycss({
                "maxLineLen": 80,
                "uglyComments": true
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./build/css/'));
});

gulp.task('watch', function () {
    gulp.watch('sass/**/*.scss', ['styles']);
});

gulp.task('default', ['watch']);

Android Intent Cannot resolve constructor

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Why do we use Base64?

Base64 instead of escaping special characters

I'll give you a very different but real example: I write javascript code to be run in a browser. HTML tags have ID values, but there are constraints on what characters are valid in an ID.

But I want my ID to losslessly refer to files in my file system. Files in reality can have all manner of weird and wonderful characters in them from exclamation marks, accented characters, tilde, even emoji! I cannot do this:

<div id="/path/to/my_strangely_named_file!@().jpg">
    <img src="http://myserver.com/path/to/my_strangely_named_file!@().jpg">
    Here's a pic I took in Moscow.
</div>

Suppose I want to run some code like this:

# ERROR
document.getElementById("/path/to/my_strangely_named_file!@().jpg");

I think this code will fail when executed.

With Base64 I can refer to something complicated without worrying about which language allows what special characters and which need escaping:

document.getElementById("18GerPD8fY4iTbNpC9hHNXNHyrDMampPLA");

Unlike using an MD5 or some other hashing function, you can reverse the encoding to find out what exactly the data was that actually useful.

I wish I knew about Base64 years ago. I would have avoided tearing my hair out with ‘encodeURIComponent’ and str.replace(‘\n’,’\\n’)

SSH transfer of text:

If you're trying to pass complex data over ssh (e.g. a dotfile so you can get your shell personalizations), good luck doing it without Base 64. This is how you would do it with base 64 (I know you can use SCP, but that would take multiple commands - which complicates key bindings for sshing into a server):

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

As Rahul stated, it is a common Chrome and an OSX bug. I was having similar issues in the past. In fact I finally got tired of making the 2 [yes I know it is not many] additional clicks when testing a local site for work.

As for a possible workaround to this issue [using Windows], I would using one of the many self signing certificate utilities available.

Recommended Steps:

  1. Create a Self Signed Cert
  2. Import Certificate into Windows Certificate Manager
  3. Import Certificate in Chrome Certificate Manager
    NOTE: Step 3 will resolve the issue experienced once Google addresses the bug...considering the time in has been stale there is no ETA in the foreseeable future.**

    As much as I prefer to use Chrome for development, I have found myself in Firefox Developer Edition lately. which does not have this issue.

    Hope this helps :)

How to make <div> fill <td> height

Modify the background image of the <td> itself.

Or apply some css to the div:

.thatSetsABackgroundWithAnIcon{
    height:100%;
}

How do I generate sourcemaps when using babel and webpack?

On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.

https://webpack.js.org/configuration/devtool

devtool best dev options

                                build   rebuild      quality                       look
eval-source-map                 slow    pretty fast  original source               worst
inline-source-map               slow    slow         original source               medium
cheap-module-eval-source-map    medium  fast         original source (lines only)  worst
inline-cheap-module-source-map  medium  pretty slow  original source (lines only)  best

lines only

Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.

REVISITING THIS

On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s

Dynamically update values of a chartjs chart

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

Best way to list files in Java, sorted by Date Modified?

You might also look at apache commons IO, it has a built in last modified comparator and many other nice utilities for working with files.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

None of the above worked for me (tomcat 7.0.62)... As Sensei_Shoh notes see the class above the message and add this to logging.properties. My logs were:

Jan 18, 2016 8:44:21 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

so I added

org.apache.catalina.startup.TldConfig.level = FINE

in conf/logging.properties

After that I got so many "offending" files that I did not bother skipping them (and also reverted to normal logging...)

SSH configuration: override the default username

Create a file called config inside ~/.ssh. Inside the file you can add:

Host *
    User buck

Or add

Host example
    HostName example.net
    User buck

The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net; ssh example will be enough.

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

npm ERR! network getaddrinfo ENOTFOUND

Just unset the proxy host using :

unset HOST

This worked for me.

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

Including a css file in a blade template?

@include directive allows you to include a Blade view from within another view, like this :

@include('another.view')

Include CSS or JS from master layout

asset()

The asset function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):

<link href="{{ asset('css/styles.css') }}" rel="stylesheet">
<script type="text/javascript" src="{{ asset('js/scripts.js') }}"></script>

mix()

If you are using versioned Mix file, you can also use mix() function. It will returns the path to a versioned Mix file:

<link href="{{ mix('css/styles.css') }}" rel="stylesheet">
<script type="text/javascript" src="{{ mix('js/scripts.js') }}"></script>

Incude CSS or JS from sub-view, use @push().

layout.blade.php

<html>
    <head>
        <!-- push target to head -->
        @stack('styles')
        @stack('scripts')
    </head>
    <body>

        <!-- or push target to footer -->
        @stack('scripts')
    </body>
</html

view.blade.php

@push('styles')
    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">
@endpush

@push('scripts')
    <script type="text/javascript" src="{{ asset('js/scripts.js') }}"></script>
@endpush

Creating a blocking Queue<T> in .NET?

I haven't fully explored the TPL but they might have something that fits your needs, or at the very least, some Reflector fodder to snag some inspiration from.

Hope that helps.

Getting the text that follows after the regex match

You can do this with "just the regular expression" as you asked for in a comment:

(?<=sentence).*

(?<=sentence) is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence without making that text itself part of the match. Consequently, (?<=sentence).* will match any text after sentence.

This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4}) is legal, but (?<=sentence\s*) isn't.

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

How to open a new HTML page using jQuery?

You need to use ajax.

http://api.jquery.com/jQuery.ajax/

<code>
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});
</code>

How to set a Javascript object values dynamically?

myObj.name=value

or

myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Difference between map, applymap and apply methods in Pandas

Probably simplest explanation the difference between apply and applymap:

apply takes the whole column as a parameter and then assign the result to this column

applymap takes the separate cell value as a parameter and assign the result back to this cell.

NB If apply returns the single value you will have this value instead of the column after assigning and eventually will have just a row instead of matrix.

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

how to use python2.7 pip instead of default pip

There should be a binary called "pip2.7" installed at some location included within your $PATH variable.

You can find that out by typing

which pip2.7

This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

Now, you should be all set, and

which pip2.7

should return the correct output.

What is the meaning of 'No bundle URL present' in react-native?

another thing that working for me , is to open the project in xcode, and then clean and build it. usually it reruns the packaging server and solve the problem.

NoClassDefFoundError on Maven dependency

For some reason, the lib is present while compiling, but missing while running.

My situation is, two versions of one lib conflict.

For example, A depends on B and C, while B depends on D:1.0, C depends on D:1.1, maven may just import D:1.0. If A uses one class which is in D:1.1 but not in D:1.0, a NoClassDefFoundError will be throwed.

If you are in this situation too, you need to resolve the dependency conflict.

Check if all values of array are equal

this might work , you can use the comment out code as well that also woks well with the given scenerio.

_x000D_
_x000D_
function isUniform(){_x000D_
 var arrayToMatch = [1,1,1,1,1];_x000D_
 var temp = arrayToMatch[0];_x000D_
 console.log(temp);_x000D_
  /* return arrayToMatch.every(function(check){_x000D_
    return check == temp;_x000D_
   });*/_x000D_
var bool;_x000D_
   arrayToMatch.forEach(function(check){_x000D_
    bool=(check == temp);_x000D_
   })_x000D_
  console.log(bool);_x000D_
}_x000D_
isUniform();
_x000D_
_x000D_
_x000D_

Python os.path.join() on a list

I stumbled over the situation where the list might be empty. In that case:

os.path.join('', *the_list_with_path_components)

Note the first argument, which will not alter the result.

PostgreSQL: Why psql can't connect to server?

I had the same problem. It seems that there is no socket when there is no cluster.

The default cluster creation failed during the installation because no default locale was set.

Encode html entities in javascript

If you're already using jQuery, try html().

$('<div>').text('<script>alert("gotcha!")</script>').html()
// "&lt;script&gt;alert("gotcha!")&lt;/script&gt;"

An in-memory text node is instantiated, and html() is called on it.

It's ugly, it wastes a bit of memory, and I have no idea if it's as thorough as something like the he library but if you're already using jQuery, maybe this is an option for you.

Taken from blog post Encode HTML entities with jQuery by Felix Geisendörfer.

Angular2 RC6: '<component> is not a known element'

I ran across this exact problem. Failed: Template parse errors: 'app-login' is not a known element... with ng test. I tried all of the above replies: nothing worked.

NG TEST SOLUTION:

Angular 2 Karma Test 'component-name' is not a known element

<= I added declarations for the offending components into beforEach(.. declarations[]) to app.component.spec.ts.

EXAMPLE app.component.spec.ts

...
import { LoginComponent } from './login/login.component';
...
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [
        AppComponent,
        LoginComponent
      ],
    }).compileComponents();
  ...

Skip certain tables with mysqldump

You can use the mysqlpump command with the

--exclude-tables=name

command. It specifies a comma-separated list of tables to exclude.

Syntax of mysqlpump is very similar to mysqldump, buts its way more performant. More information of how to use the exclude option you can read here: https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#mysqlpump-filtering

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

How can I get the ID of an element using jQuery?

$('#test') returns a jQuery object, so you can't use simply object.id to get its Id

you need to use $('#test').attr('id'), which returns your required ID of the element

This can also be done as follows ,

$('#test').get(0).id which is equal to document.getElementById('test').id

What's the difference between .bashrc, .bash_profile, and .environment?

That's simple. It's explained in man bash:

/bin/bash
       The bash executable
/etc/profile
       The systemwide initialization file, executed for login shells
~/.bash_profile
       The personal initialization file, executed for login shells
~/.bashrc
       The individual per-interactive-shell startup file
~/.bash_logout
       The individual login shell cleanup file, executed when a login shell exits
~/.inputrc
       Individual readline initialization file

Login shells are the ones that are read one you login (so, they are not executed when merely starting up xterm, for example). There are other ways to login. For example using an X display manager. Those have other ways to read and export environment variables at login time.

Also read the INVOCATION chapter in the manual. It says "The following paragraphs describe how bash executes its startup files.", i think that's a spot-on :) It explains what an "interactive" shell is too.

Bash does not know about .environment. I suspect that's a file of your distribution, to set environment variables independent of the shell that you drive.

Convert string to Color in C#

For transferring colors via xml-strings I've found out:

Color x = Color.Red; // for example
String s = x.ToArgb().ToString()
... to/from xml ...
Int32 argb = Convert.ToInt32(s);
Color red = Color.FromArgb(argb);

How do I extract the contents of an rpm?

In OpenSuse at least, the unrpm command comes with the build package.

In a suitable directory (because this is an archive bomb):

unrpm file.rpm

Using Jquery Datatable with AngularJs

visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda

<script>  
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
  $scope.data=[
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011\/04\/25",
            "$320,800"
        ],
        [
            "Garrett Winters",
            "Accountant",
            "Tokyo",
            "8422",
            "2011\/07\/25",
            "$170,750"
        ],
        [
            "Ashton Cox",
            "Junior Technical Author",
            "San Francisco",
            "1562",
            "2009\/01\/12",
            "$86,000"
        ],
        [
            "Cedric Kelly",
            "Senior Javascript Developer",
            "Edinburgh",
            "6224",
            "2012\/03\/29",
            "$433,060"
        ],
        [
            "Airi Satou",
            "Accountant",
            "Tokyo",
            "5407",
            "2008\/11\/28",
            "$162,700"
        ],
        [
            "Brielle Williamson",
            "Integration Specialist",
            "New York",
            "4804",
            "2012\/12\/02",
            "$372,000"
        ],
        [
            "Herrod Chandler",
            "Sales Assistant",
            "San Francisco",
            "9608",
            "2012\/08\/06",
            "$137,500"
        ],
        [
            "Rhona Davidson",
            "Integration Specialist",
            "Tokyo",
            "6200",
            "2010\/10\/14",
            "$327,900"
        ],
        [
            "Colleen Hurst",
            "Javascript Developer",
            "San Francisco",
            "2360",
            "2009\/09\/15",
            "$205,500"
        ],
        [
            "Sonya Frost",
            "Software Engineer",
            "Edinburgh",
            "1667",
            "2008\/12\/13",
            "$103,600"
        ],
        [
            "Jena Gaines",
            "Office Manager",
            "London",
            "3814",
            "2008\/12\/19",
            "$90,560"
        ],
        [
            "Quinn Flynn",
            "Support Lead",
            "Edinburgh",
            "9497",
            "2013\/03\/03",
            "$342,000"
        ],
        [
            "Charde Marshall",
            "Regional Director",
            "San Francisco",
            "6741",
            "2008\/10\/16",
            "$470,600"
        ],
        [
            "Haley Kennedy",
            "Senior Marketing Designer",
            "London",
            "3597",
            "2012\/12\/18",
            "$313,500"
        ],
        [
            "Tatyana Fitzpatrick",
            "Regional Director",
            "London",
            "1965",
            "2010\/03\/17",
            "$385,750"
        ],
        [
            "Michael Silva",
            "Marketing Designer",
            "London",
            "1581",
            "2012\/11\/27",
            "$198,500"
        ],
        [
            "Paul Byrd",
            "Chief Financial Officer (CFO)",
            "New York",
            "3059",
            "2010\/06\/09",
            "$725,000"
        ],
        [
            "Gloria Little",
            "Systems Administrator",
            "New York",
            "1721",
            "2009\/04\/10",
            "$237,500"
        ],
        [
            "Bradley Greer",
            "Software Engineer",
            "London",
            "2558",
            "2012\/10\/13",
            "$132,000"
        ],
        [
            "Dai Rios",
            "Personnel Lead",
            "Edinburgh",
            "2290",
            "2012\/09\/26",
            "$217,500"
        ],
        [
            "Jenette Caldwell",
            "Development Lead",
            "New York",
            "1937",
            "2011\/09\/03",
            "$345,000"
        ],
        [
            "Yuri Berry",
            "Chief Marketing Officer (CMO)",
            "New York",
            "6154",
            "2009\/06\/25",
            "$675,000"
        ],
        [
            "Caesar Vance",
            "Pre-Sales Support",
            "New York",
            "8330",
            "2011\/12\/12",
            "$106,450"
        ],
        [
            "Doris Wilder",
            "Sales Assistant",
            "Sidney",
            "3023",
            "2010\/09\/20",
            "$85,600"
        ],
        [
            "Angelica Ramos",
            "Chief Executive Officer (CEO)",
            "London",
            "5797",
            "2009\/10\/09",
            "$1,200,000"
        ],
        [
            "Gavin Joyce",
            "Developer",
            "Edinburgh",
            "8822",
            "2010\/12\/22",
            "$92,575"
        ],
        [
            "Jennifer Chang",
            "Regional Director",
            "Singapore",
            "9239",
            "2010\/11\/14",
            "$357,650"
        ],
        [
            "Brenden Wagner",
            "Software Engineer",
            "San Francisco",
            "1314",
            "2011\/06\/07",
            "$206,850"
        ],
        [
            "Fiona Green",
            "Chief Operating Officer (COO)",
            "San Francisco",
            "2947",
            "2010\/03\/11",
            "$850,000"
        ],
        [
            "Shou Itou",
            "Regional Marketing",
            "Tokyo",
            "8899",
            "2011\/08\/14",
            "$163,000"
        ],
        [
            "Michelle House",
            "Integration Specialist",
            "Sidney",
            "2769",
            "2011\/06\/02",
            "$95,400"
        ],
        [
            "Suki Burks",
            "Developer",
            "London",
            "6832",
            "2009\/10\/22",
            "$114,500"
        ],
        [
            "Prescott Bartlett",
            "Technical Author",
            "London",
            "3606",
            "2011\/05\/07",
            "$145,000"
        ],
        [
            "Gavin Cortez",
            "Team Leader",
            "San Francisco",
            "2860",
            "2008\/10\/26",
            "$235,500"
        ],
        [
            "Martena Mccray",
            "Post-Sales support",
            "Edinburgh",
            "8240",
            "2011\/03\/09",
            "$324,050"
        ],
        [
            "Unity Butler",
            "Marketing Designer",
            "San Francisco",
            "5384",
            "2009\/12\/09",
            "$85,675"
        ],
        [
            "Howard Hatfield",
            "Office Manager",
            "San Francisco",
            "7031",
            "2008\/12\/16",
            "$164,500"
        ],
        [
            "Hope Fuentes",
            "Secretary",
            "San Francisco",
            "6318",
            "2010\/02\/12",
            "$109,850"
        ],
        [
            "Vivian Harrell",
            "Financial Controller",
            "San Francisco",
            "9422",
            "2009\/02\/14",
            "$452,500"
        ],
        [
            "Timothy Mooney",
            "Office Manager",
            "London",
            "7580",
            "2008\/12\/11",
            "$136,200"
        ],
        [
            "Jackson Bradshaw",
            "Director",
            "New York",
            "1042",
            "2008\/09\/26",
            "$645,750"
        ],
        [
            "Olivia Liang",
            "Support Engineer",
            "Singapore",
            "2120",
            "2011\/02\/03",
            "$234,500"
        ],
        [
            "Bruno Nash",
            "Software Engineer",
            "London",
            "6222",
            "2011\/05\/03",
            "$163,500"
        ],
        [
            "Sakura Yamamoto",
            "Support Engineer",
            "Tokyo",
            "9383",
            "2009\/08\/19",
            "$139,575"
        ],
        [
            "Thor Walton",
            "Developer",
            "New York",
            "8327",
            "2013\/08\/11",
            "$98,540"
        ],
        [
            "Finn Camacho",
            "Support Engineer",
            "San Francisco",
            "2927",
            "2009\/07\/07",
            "$87,500"
        ],
        [
            "Serge Baldwin",
            "Data Coordinator",
            "Singapore",
            "8352",
            "2012\/04\/09",
            "$138,575"
        ],
        [
            "Zenaida Frank",
            "Software Engineer",
            "New York",
            "7439",
            "2010\/01\/04",
            "$125,250"
        ],
        [
            "Zorita Serrano",
            "Software Engineer",
            "San Francisco",
            "4389",
            "2012\/06\/01",
            "$115,000"
        ],
        [
            "Jennifer Acosta",
            "Junior Javascript Developer",
            "Edinburgh",
            "3431",
            "2013\/02\/01",
            "$75,650"
        ],
        [
            "Cara Stevens",
            "Sales Assistant",
            "New York",
            "3990",
            "2011\/12\/06",
            "$145,600"
        ],
        [
            "Hermione Butler",
            "Regional Director",
            "London",
            "1016",
            "2011\/03\/21",
            "$356,250"
        ],
        [
            "Lael Greer",
            "Systems Administrator",
            "London",
            "6733",
            "2009\/02\/27",
            "$103,500"
        ],
        [
            "Jonas Alexander",
            "Developer",
            "San Francisco",
            "8196",
            "2010\/07\/14",
            "$86,500"
        ],
        [
            "Shad Decker",
            "Regional Director",
            "Edinburgh",
            "6373",
            "2008\/11\/13",
            "$183,000"
        ],
        [
            "Michael Bruce",
            "Javascript Developer",
            "Singapore",
            "5384",
            "2011\/06\/27",
            "$183,000"
        ],
        [
            "Donna Snider",
            "Customer Support",
            "New York",
            "4226",
            "2011\/01\/25",
            "$112,000"
        ]
    ]


$scope.dataTableOpt = {
  //if any ajax call 
  };
});
</script>
<div class="container" ng-app="formvalid">
      <div class="panel" data-ng-controller="validationCtrl">
      <div class="panel-heading border">    
        <h2>Data table using jquery datatable in Angularjs </h2>
      </div>
      <div class="panel-body">
          <table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Position</th>
              <th>Office</th>
              <th>Age</th>
              <th>Start Date</th>
            </tr>
          </thead>
            <tbody>
              <tr ng-repeat="n in data">
                <td>{{$index+1}}</td>
                <td>{{n[0]}}</td>
                <td>{{n[1]}}</td>
                <td>{{n[2]}}</td>
                <td>{{n[3]}}</td>
                <td>{{n[4] | date:'dd/MM/yyyy'}}</td>
              </tr>
            </tbody>
        </table>
      </div>
    </div>
    </div>

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

How to drop a unique constraint from table column?

I had the same problem. I'm using DB2. What I have done is a bit not too professional solution, but it works in every DBMS:

  1. Add a column with the same definition without the unique contraint.
  2. Copy the values from the original column to the new
  3. Drop the original column (so DBMS will remove the constraint as well no matter what its name was)
  4. And finally rename the new one to the original
  5. And a reorg at the end (only in DB2)
ALTER TABLE USERS ADD COLUMN LOGIN_OLD VARCHAR(50) NOT NULL DEFAULT '';
UPDATE USERS SET LOGIN_OLD=LOGIN;
ALTER TABLE USERS DROP COLUMN LOGIN;
ALTER TABLE USERS RENAME COLUMN LOGIN_OLD TO LOGIN;

CALL SYSPROC.ADMIN_CMD('REORG TABLE USERS');

The syntax of the ALTER commands may be different in other DBMS

SQL Server Insert if not exists

The INSERT command doesn't have a WHERE clause - you'll have to write it like this:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   IF NOT EXISTS (SELECT * FROM EmailsRecebidos 
                   WHERE De = @_DE
                   AND Assunto = @_ASSUNTO
                   AND Data = @_DATA)
   BEGIN
       INSERT INTO EmailsRecebidos (De, Assunto, Data)
       VALUES (@_DE, @_ASSUNTO, @_DATA)
   END
END

Make: how to continue after a command fails?

Change clean to

rm -f .lambda .lambda_t .activity .activity_t_lambda

I.e. don't prompt for remove; don't complain if file doesn't exist.

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

This should do it:

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

Remember protractor's $ isn't jQuery and :visible is not yet a part of available CSS selectors + pseudo-selectors

More info at https://stackoverflow.com/a/13388700/511069

ViewDidAppear is not called when opening app from background

As per Apple's documentation:

(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;

Description:
Tells a child controller its appearance is about to change. If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:, viewWillDisappear:, viewDidAppear:, or viewDidDisappear: directly.

(void)endAppearanceTransition;

Description:

Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.

Sample code:

(void)applicationDidEnterBackground:(UIApplication *)application
{

    [self.window.rootViewController beginAppearanceTransition: NO animated: NO];  // I commented this line

    [self.window.rootViewController endAppearanceTransition]; // I commented this line

}

Question: How I fixed?

Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

Erase whole array Python

Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:

>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>

Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

How to display hexadecimal numbers in C?

Try:

printf("%04x",a);
  • 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified.
  • 4 (width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

Setting up SSL on a local xampp/apache server

Apache part - enabling you to open https://localhost/xyz

There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/. The files starts with <IfModule ssl_module>, so it only has an effect if the apache has been started with its mod_ssl module.

Open the file xampp/apache/conf/httpd.conf in an editor and search for the line

#LoadModule ssl_module modules/mod_ssl.so

remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.


PHP part - enabling adldap to use ldap over ssl

adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll in your php.ini
Run

echo 'ini: ', get_cfg_var('cfg_file_path');

It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for

;extension=php_openssl.dll

remove the semicolon, save the file and re-start the apache.

see also: http://docs.php.net/install.windows.extensions

How to configure log4j with a properties file

I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:

Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);

If the properties file is in the jar, then you could do something like this:

Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);

The above assumes that the log4j.properties is in the root folder of the jar file.

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.

You can read further on this URL: Securly download file inside browser with correct filename

This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.

In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.

I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf


routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
                new { controller = "ShoppingCart", action = "PrintQuote" }
                , new string[] { "x.x.x.Controllers" }
            );

This pretty much solved my issue. Hoping this helps someone!

Cheerz, Anup

How do I change the text of a span element using JavaScript?

EDIT: This was written in 2014. You probably don't care about IE8 anymore and can forget about using innerText. Just use textContent and be done with it, hooray.

If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML might be acceptable:

// * Fine for hardcoded text strings like this one or strings you otherwise 
//   control.
// * Not OK for user-supplied input or strings you don't control unless
//   you know what you are doing and have sanitized the string first.
document.getElementById('myspan').innerHTML = 'newtext';

However, as others note, if you are not the source for any part of the text string, using innerHTML can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.

If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:

var span = document.getElementById('myspan');
span.innerText = span.textContent = 'newtext';

Firefox doesn't support innerText and IE8 doesn't support textContent so you need to use both if you want to maintain cross-browser compatibility.

And if you want to avoid reflows (caused by innerText) where possible:

var span = document.getElementById('myspan');
if ('textContent' in span) {
    span.textContent = 'newtext';
} else {
    span.innerText = 'newtext';
}

Tree data structure in C#

Tree With Generic Data

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class Tree<T>
{
    public T Data { get; set; }
    public LinkedList<Tree<T>> Children { get; set; } = new LinkedList<Tree<T>>();
    public Task Traverse(Func<T, Task> actionOnNode, int maxDegreeOfParallelism = 1) => Traverse(actionOnNode, new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism));
    private async Task Traverse(Func<T, Task> actionOnNode, SemaphoreSlim semaphore)
    {
        await actionOnNode(Data);
        SafeRelease(semaphore);
        IEnumerable<Task> tasks = Children.Select(async input =>
        {
            await semaphore.WaitAsync().ConfigureAwait(false);
            try
            {
                await input.Traverse(actionOnNode, semaphore).ConfigureAwait(false);
            }
            finally
            {
                SafeRelease(semaphore);
            }
        });
        await Task.WhenAll(tasks);
    }
    private void SafeRelease(SemaphoreSlim semaphore)
    {
        try
        {
            semaphore.Release();
        }
        catch (Exception ex)
        {
            if (ex.Message.ToLower() != "Adding the specified count to the semaphore would cause it to exceed its maximum count.".ToLower())
            {
                throw;
            }
        }
    }

    public async Task<IEnumerable<T>> ToList()
    {
        ConcurrentBag<T> lst = new ConcurrentBag<T>();
        await Traverse(async (data) => lst.Add(data));
        return lst;
    }
    public async Task<int> Count() => (await ToList()).Count();
}



Unit Tests

using System.Threading.Tasks;
using Xunit;

public class Tree_Tests
{
    [Fact]
    public async Task Tree_ToList_Count()
    {
        Tree<int> head = new Tree<int>();

        Assert.NotEmpty(await head.ToList());
        Assert.True(await head.Count() == 1);

        // child
        var child = new Tree<int>();
        head.Children.AddFirst(child);
        Assert.True(await head.Count() == 2);
        Assert.NotEmpty(await head.ToList());

        // grandson
        child.Children.AddFirst(new Tree<int>());
        child.Children.AddFirst(new Tree<int>());
        Assert.True(await head.Count() == 4);
        Assert.NotEmpty(await head.ToList());
    }

    [Fact]
    public async Task Tree_Traverse()
    {
        Tree<int> head = new Tree<int>() { Data = 1 };

        // child
        var child = new Tree<int>() { Data = 2 };
        head.Children.AddFirst(child);

        // grandson
        child.Children.AddFirst(new Tree<int>() { Data = 3 });
        child.Children.AddLast(new Tree<int>() { Data = 4 });

        int counter = 0;
        await head.Traverse(async (data) => counter += data);
        Assert.True(counter == 10);

        counter = 0;
        await child.Traverse(async (data) => counter += data);
        Assert.True(counter == 9);

        counter = 0;
        await child.Children.First!.Value.Traverse(async (data) => counter += data);
        Assert.True(counter == 3);

        counter = 0;
        await child.Children.Last!.Value.Traverse(async (data) => counter += data);
        Assert.True(counter == 4);
    }
}

Can gcc output C code after preprocessing?

I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:

gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp

(Doesn't have to be 'cpp'.) There's an excellent description of this usage at http://www.cs.tut.fi/~jkorpela/html/cpre.html.

The "-traditional-cpp" preserves whitespace & tabs.

SQL Server convert select a column and convert it to a string

ALTER PROCEDURE [dbo].[spConvertir_CampoACadena]( @nomb_tabla   varchar(30),
                          @campo_tabla  varchar(30),
                          @delimitador  varchar(5),
                          @respuesta    varchar(max) OUTPUT
)
AS
DECLARE @query      varchar(1000),
    @cadena     varchar(500)
BEGIN
  SET @query = 'SELECT @cadena  = COALESCE(@cadena + '''+ @delimitador +''', '+ '''''' +') + '+ @campo_tabla + ' FROM '+@nomb_tabla
  --select @query
  EXEC(@query)
  SET @respuesta = @cadena  
END

error: src refspec master does not match any

For me, the fix appears to be "git ." (stages all current files). Apparently this is required after a git init? I followed it by "get reset" (unstages all files) and proceeded with the exact same commands to stage only a few files, which then pushed successfully.

   git . 
   git reset

Append integer to beginning of list in Python

>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li  # Don't use 'list' as variable name.
[5, 1, 2, 3]

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Using external images for CSS custom cursors

I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:

.test {
    cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}

How to pass a parameter like title, summary and image in a Facebook sharer URL

This works at the moment (Oct. 2016), but I can't guarantee how long it will last:

https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]

When should I use "this" in a class?

You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)

Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)

Error "can't load package: package my_prog: found packages my_prog and main"

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

What are the basic rules and idioms for operator overloading?

Why can't operator<< function for streaming objects to std::cout or to a file be a member function?

Let's say you have:

struct Foo
{
   int a;
   double b;

   std::ostream& operator<<(std::ostream& out) const
   {
      return out << a << " " << b;
   }
};

Given that, you cannot use:

Foo f = {10, 20.0};
std::cout << f;

Since operator<< is overloaded as a member function of Foo, the LHS of the operator must be a Foo object. Which means, you will be required to use:

Foo f = {10, 20.0};
f << std::cout

which is very non-intuitive.

If you define it as a non-member function,

struct Foo
{
   int a;
   double b;
};

std::ostream& operator<<(std::ostream& out, Foo const& f)
{
   return out << f.a << " " << f.b;
}

You will be able to use:

Foo f = {10, 20.0};
std::cout << f;

which is very intuitive.

How can I extract the folder path from file path in Python?

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder

What are the differences between json and simplejson Python modules?

json seems faster than simplejson in both cases of loads and dumps in latest version

Tested versions:

  • python: 3.6.8
  • json: 2.0.9
  • simplejson: 3.16.0

Results:

>>> def test(obj, call, data, times):
...   s = datetime.now()
...   print("calling: ", call, " in ", obj, " ", times, " times") 
...   for _ in range(times):
...     r = getattr(obj, call)(data)
...   e = datetime.now()
...   print("total time: ", str(e-s))
...   return r

>>> test(json, "dumps", data, 10000)
calling:  dumps  in  <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'>   10000  times
total time:  0:00:00.054857

>>> test(simplejson, "dumps", data, 10000)
calling:  dumps  in  <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'>   10000  times
total time:  0:00:00.419895
'{"1": 100, "2": "acs", "3.5": 3.5567, "d": [1, "23"], "e": {"a": "A"}}'

>>> test(json, "loads", strdata, 1000)
calling:  loads  in  <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'>   1000  times
total time:  0:00:00.004985
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}

>>> test(simplejson, "loads", strdata, 1000)
calling:  loads  in  <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'>   1000  times
total time:  0:00:00.040890
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}

For versions:

  • python: 3.7.4
  • json: 2.0.9
  • simplejson: 3.17.0

json was faster than simplejson during dumps operation but both maintained the same speed during loads operations

When is assembly faster than C?

The question is a bit misleading. The answer is there in your post itself. It is always possible to write assembly solution for a particular problem which executes faster than any generated by a compiler. The thing is you need to be an expert in assembly to overcome the limitations of a compiler. An experienced assembly programmer can write programs in any HLL which performs faster than one written by an inexperienced. The truth is you can always write assembly programs executing faster than one generated by a compiler.

How to disable and then enable onclick event on <div> with javascript

You can disable the event by applying following code:

with .attr() API

$('#your_id').attr("disabled", "disabled");

or with .prop() API

$('#your_id').prop('disabled', true);

How to use jQuery to select a dropdown option?

HTML select elements have a selectedIndex property that can be written to in order to select a particular option:

$('select').prop('selectedIndex', 3); // select 4th option

Using plain JavaScript this can be achieved by:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;

SQL multiple columns in IN clause

You could do like this:

SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));

The sqlfiddle.

CertificateException: No name matching ssl.someUrl.de found

In Java 8 you can skip server name checking with the following code:

HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);

However this should be used only in development!

What characters are valid for JavaScript variable names?

Here is one quick suggestion for creating variable names. If you want the variable not to conflict when being used in FireFox, do not use the variable name "_content" as this variable name is already being used by the browser. I found this out the hard way and had to change all of the places I used the variable "_content" in a large JavaScript application.

Cannot refer to a non-final variable inside an inner class defined in a different method

To solve the problem above, different languages make different decisions.

for Java, the solution is as what we see in this article.

for C#, the solution is allow side-effects and capture by reference is the only option.

for C++11, the solution is to allow the programmer make the decision. They can choose to capture by value or by reference. If capturing by value, no side-effects would occur because the variable referenced is actually different. If capture by reference, side-effects may occur but the programmer should realize it.

Making a <button> that's a link in HTML

A little bit easier and it looks exactly like the button in the form. Just use the input and wrap the anchor tag around it.

<a href="#"><input type="button" value="Button Text"></a>

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

How to get today's Date?

Use this code to easy get Date & Time :

package date.time;

import java.text.SimpleDateFormat;    
import java.util.Date;

public class DateTime {

    public static void main(String[] args) {
        SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
        Date date = new Date();
        System.out.println("Today Date & Time at Now :"+dnt.format(date));  
    } 
}

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

What is this weird colon-member (" : ") syntax in the constructor?

there is another 'benefit'

if the member variable type does not support null initialization or if its a reference (which cannot be null initialized) then you have no choice but to supply an initialization list

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Android SDK location

If you have downloaded sdk manager zip (from https://developer.android.com/studio/#downloads), then you have Android SDK Location as root of the extracted folder.

So silly, But it took time for me as a beginner.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

This is what I do:

  1. Right click on solution -> Add -> Existing Website...
  2. Choose the folder where your website is. Just the root folder of the site.

Then everything will be added on your solution from folders to files, and files inside those folders.

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

how to filter out a null value from spark dataframe

Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.

df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")

If you need to filter out rows that contain any null (OR connected) please use

df.na.drop()

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

Invalid Host Header when ngrok tries to connect to React dev server

I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:

module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.

const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such

if (ngrok) {
console.log('If nGronk')
ngrok.connect(
    {
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
    host_header:3000
  },
  (err, url) => {
    if (err) {

    } else {

    }
   }
  );
 }

Do not pass a subdomain if you do not have a custom domain

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

Draw a connecting line between two elements

js-graph.it supports this use case, as seen by its getting started guide, supporting dragging elements without connection overlaps. Doesn't seem like it supports editing/creating connections. Doesn't seem it is maintained anymore.

Annotation @Transactional. How to rollback?

For me rollbackFor was not enough, so I had to put this and it works as expected:

@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)

I hope it helps :-)

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

How to break lines at a specific character in Notepad++?

  1. Click Ctrl + h or Search -> Replace on the top menu
  2. Under the Search Mode group, select Regular expression
  3. In the Find what text field, type ],\s*
  4. In the Replace with text field, type ],\n
  5. Click Replace All

Finding the index of an item in a list

Let’s give the name lst to the list that you have. One can convert the list lst to a numpy array. And, then use numpy.where to get the index of the chosen item in the list. Following is the way in which you will implement it.

import numpy as np

lst = ["foo", "bar", "baz"]  #lst: : 'list' data type
print np.where( np.array(lst) == 'bar')[0][0]

>>> 1

Excel SUMIF between dates

You haven't got your SUMIF in the correct order - it needs to be range, criteria, sum range. Try:

=SUMIF(A:A,">="&DATE(2012,1,1),B:B)

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

How to set initial value and auto increment in MySQL?

Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.

Now, Set your values and then press Go under the Table Options Box.

What's the difference between import java.util.*; and import java.util.Date; ?

The toString() implementation of java.util.Date does not depend on the way the class is imported. It always returns a nice formatted date.

The toString() you see comes from another class.

Specific import have precedence over wildcard imports.

in this case

import other.Date
import java.util.*

new Date();

refers to other.Date and not java.util.Date.

The odd thing is that

import other.*
import java.util.*

Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date and java.util.Date matches.

How to get my activity context?

In Kotlin will be :

activity?.applicationContext?.let {
         it//<- you context
        }

basic authorization command for curl

One way, provide --user flag as part of curl, as follows:

curl --user username:password http://example.com

Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization header of curl as follows:

curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/

Here, dXNlcm5hbWU6cGFzc3dvcmQ= is Base64 encoded token of username:password.

Use space as a delimiter with cut command

You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.

echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2  #bar

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

After 7 long hours of searching I finally found the way!! None of the above solutions worked, only one of them pointed towards the issue!

If you are on Win7, then your Firewall blocks the SDK Manager from retrieving the addon list. You will have to add "android.bat" and "java.exe" to the trusted files and bingo! everything will start working!!

Specify path to node_modules in package.json

Yarn supports this feature:

# .yarnrc file in project root
--modules-folder /node_modules

But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

How to view AndroidManifest.xml from APK file?

The file needs to be decompiled (or deodex'd not sure which one). But here's another way to do it:

-Download free Tickle My Android tool on XDA: https://forum.xda-developers.com/showthread.php?t=1633333https://forum.xda-developers.com/showthread.php?t=1633333
-Unzip
-Copy APK into \_WorkArea1\_in\ folder
-Open "Tickle My Android.exe"
-Theming Menu
-Decompile Files->Any key to continue (ignore warning)
-Decompile Files->1->[Enter]->y[Enter]
-Wait for it to decompile in new window... Done when new window closes
-Decompiled/viewable files will be here: \_WorkArea3\_working\[App]\

AWS : The config profile (MyName) could not be found

can you check your config file under ~/.aws/config- you might have an invalid section called [myname], something like this (this is an example)

[default]
region=us-west-2
output=json

[myname]
region=us-east-1
output=text

Just remove the [myname] section (including all content for this profile) and you will be fine to run aws cli again

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

How do you do a ‘Pause’ with PowerShell 2.0?

I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.

<1> ReadKey (System.Console)

write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Disadvantage: Does not work in PS-ISE.

<2> ReadKey (RawUI)

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Does not exclude modifier keys.

<3> cmd

cmd /c Pause | Out-Null
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Visibly launches new shell/window on first use; not noticeable on subsequent use but still has the overhead

<4> Read-Host

Read-Host -Prompt "Press Enter to continue"
  • Advantage: Works in PS-ISE.
  • Disadvantage: Accepts only Enter key.

<5> ReadKey composite

This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.

Function Pause ($Message = "Press any key to continue . . . ") {
    if ((Test-Path variable:psISE) -and $psISE) {
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
    }
    else {     
        Write-Host -NoNewline $Message
        [void][System.Console]::ReadKey($true)
        Write-Host
    }
}
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE (though only with Enter or mouse click)
  • Disadvantage: Not a one-liner!

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Another way to do this is described below.

First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.

After doing this, use the following formula.

=If(D55="","",IF(C55="",NOW(),C55))

Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.

This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.

How SID is different from Service name in Oracle tnsnames.ora

I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:

mySID, mySID.whereever.com =
(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
  )
  (CONNECT_DATA =
    (SERVICE_NAME = mySID.whereever.com)
    (SID = mySID)
    (SERVER = DEDICATED)
  )
)

I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This can be fixed by inserting the respective records in the Parent table first and then we can insert records in the Child table's respective column. Also check the data type and size of the column. It should be same as the parent table column,even the engine and collation should also be the same. TRY THIS! This is how I solved mine. Correct me if am wrong.

how to change language for DataTable

Tradução para Português Brasil

    $('#table_id').DataTable({
    "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Exibir _MENU_ registros por página",
        "sZeroRecords":   "Nenhum resultado encontrado",
        "sEmptyTable":    "Nenhum resultado encontrado",
        "sInfo":          "Exibindo do _START_ até _END_ de um total de _TOTAL_ registros",
        "sInfoEmpty":     "Exibindo do 0 até 0 de um total de 0 registros",
        "sInfoFiltered":  "(Filtrado de um total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Próximo",
            "sPrevious": "Anterior"
        },
        "oAria": {
            "sSortAscending":  ": Ativar para ordenar a columna de maneira ascendente",
            "sSortDescending": ": Ativar para ordenar a columna de maneira descendente"
        }
    }
});

Google Chrome Full Black Screen

i have resolved this by following steps.

1) Go to customise icon in the top right corner chrome.
2) click on more tools option.
3) Click task manager.
4) Kill/end process GPU process

This has resolved my issue of black screen in chrome.

How can I change the color of AlertDialog title and the color of the line under it

Continuing from this answer: https://stackoverflow.com/a/15285514/1865860, I forked the nice github repo from @daniel-smith and made some improvements:

  • improved example Activity
  • improved layouts
  • fixed setItems method
  • added dividers into items_list
  • dismiss dialogs on click
  • support for disabled items in setItems methods
  • listItem touch feedback
  • scrollable dialog message

link: https://github.com/dentex/QustomDialog

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Signing a Windows EXE file

And yet another option, if you're developing on Windows 10 but don't have Microsoft's signtool.exe installed, you can use Bash on Ubuntu on Windows to sign your app. Here is a run down:

https://blog.synapp.nz/2017/06/16/code-signing-a-windows-application-on-linux-on-windows/

Reducing video size with same format and reducing frame size

There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php

Read each line of txt file to new array element

You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.

    <?php
        $file = fopen("members.txt", "r");
        $i = 0;
        while (!feof($file)) {
            $line_of_text .= fgets($file);
        }
        $members = explode("\n", $line_of_text);
        fclose($file);
        print_r($members);
    ?>

Asking the user for input until they give a valid response

The simple solution would be:

while True:
    age = int(input("Please enter your age: "))

    if (age<=0) or (age>120):
        print('Sorry, I did not understand that.Please try again')
        continue
    else:

        if age>=18:
            print("You are able to vote in the United States!")
        else:
            print("You are not able to vote in the United States.")
        break

Explanation of above code: In order for a valid age,it should be positive and should not be more than normal physical age,say for example maximum age is 120.

Then we can ask user for age and if age input is negative or more than 120,we consider it invalid input and ask the user to try again.

Once the valid input is entered, we perform a check (using nested if-else statement) whether the age is >=18 or vice versa and print a message whether the user is eligible to vote

How to search in a List of Java object

Using Java 8

With Java 8 you can simply convert your list to a stream allowing you to write:

import java.util.List;
import java.util.stream.Collectors;

List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
    .filter(a -> Objects.equals(a.value3, "three"))
    .collect(Collectors.toList());

Note that

  • a -> Objects.equals(a.value3, "three") is a lambda expression
  • result is a List with a Sample type
  • It's very fast, no cast at every iteration
  • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


Apache Commons

If you can't use Java 8, you can use Apache Commons library and write:

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

Collection result = CollectionUtils.select(list, new Predicate() {
     public boolean evaluate(Object a) {
         return Objects.equals(((Sample) a).value3, "three");
     }
 });

// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);

Note that:

  • There is a cast from Object to Sample at each iteration
  • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



Bonus: A nice blog article talking about how to find element in list.

Eclipse HotKey: how to switch between tabs?

On windows if you have a 5 button mouse, you can use forward and back in lieu of ALT+Left and ALT+Right.

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

You could override the equals() method, with title, author, url and description. (and the hashCode() since if you override one you should override the other). Then use a HashSet of type <blog>.

How to measure elapsed time

Per the Android docs SystemClock.elapsedRealtime() is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.

The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.

  • SystemClock.elapsedRealtime() and SystemClock.elapsedRealtimeNanos() are the best bet for calculating general purpose elapsed time.
  • SystemClock.uptimeMillis() and System.nanoTime() are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime().
  • Stay away from System.currentTimeMillis() as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis() to not always be accurate.

When the game starts:

long startTime = SystemClock.elapsedRealtime();

When the game ends:

long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;

Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis() as the basis of the time sent to setText(...).

Also, instead of using Timer, you might want to look into using TimerTask, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.

How to colorize diff on the command line?

With bat command:

diff file1 file2 | bat -l diff

Using NSPredicate to filter an NSArray based on NSDictionary keys

Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football) You want it to read (SPORT == 'Football'), so your format string needs to be @"(SPORT == '%@')".

What is the meaning of @_ in Perl?

Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...

my $size=1234;
sub sub1{
  $_[0]=500;
}
sub1 $size;

Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:

sub sub2{
  my @m=@_;
  ....
}

assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.

Apache Spark: The number of cores vs. the number of executors

I haven't played with these settings myself so this is just speculation but if we think about this issue as normal cores and threads in a distributed system then in your cluster you can use up to 12 cores (4 * 3 machines) and 24 threads (8 * 3 machines). In your first two examples you are giving your job a fair number of cores (potential computation space) but the number of threads (jobs) to run on those cores is so limited that you aren't able to use much of the processing power allocated and thus the job is slower even though there is more computation resources allocated.

you mention that your concern was in the shuffle step - while it is nice to limit the overhead in the shuffle step it is generally much more important to utilize the parallelization of the cluster. Think about the extreme case - a single threaded program with zero shuffle.

How to calculate a mod b in Python?

There's the % sign. It's not just for the remainder, it is the modulo operation.

jQuery Ajax requests are getting cancelled without being sent

I had the cancelled in Firefox. Some ajax-calls working perfectly fine for me, but it failed for the coworker who actually had to use it.

When I checked this out via the Chrome tricks mentioned above, I found nothing suspicious. When checking it in firebug, it showed the 'loading' animation after the two mallicous calls, and no result tab.

The solution was mega simple: go to history, find the website, rightclick -> forget website.
Forget, not delete.

After that, no problems anymore. My guess is it has something to do with the .htaccess.

PostgreSQL : cast string to date DD/MM/YYYY

In case you need to convert the returned date of a select statement to a specific format you may use the following:

select to_char(DATE (*date_you_want_to_select*)::date, 'DD/MM/YYYY') as "Formated Date"

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

How to transition to a new view controller with code only using Swift

Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.

Try something like:

secondViewController.view.backgroundColor = UIColor.redColor();

Now the view controller it shows should be red.

To actually do something with secondViewController, create a subclass of UIViewController and instead of

let secondViewController:UIViewController = UIViewController()

create an instance of your second view controller:

//If using code
let secondViewController = MyCustomViewController.alloc()

//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController

How can I convert a .jar to an .exe?

If your program is "publicly available non-commercial in nature" and has "a publicly available Web site that meets the basic quality standards", then you can try and get a free license of Excelsior. If its not then it's expensive, but still a viable option.

Program: https://www.excelsiorjet.com

As a side note: Here's a study of all existing Jar to EXE programs, which is a bit depressing - https://www.excelsior-usa.com/articles/java-to-exe.html

Wait until a process ends

Process.WaitForExit should be just what you're looking for I think.

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

Select entries between dates in doctrine 2

You can do either…

$qb->where('e.fecha BETWEEN :monday AND :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

or…

$qb->where('e.fecha > :monday')
   ->andWhere('e.fecha < :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

Javascript Confirm popup Yes, No button instead of OK and Cancel

the very specific answer to the point is confirm dialogue Js Function:

confirm('Do you really want to do so');

It show dialogue box with ok cancel buttons,to replace these button with yes no is not so simple task,for that you need to write jQuery function.

Javascript: How to loop through ALL DOM elements on a page?

i think this is really quick

document.querySelectorAll('body,body *').forEach(function(e) {

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

How to center body on a page?

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.