Programs & Examples On #Sql calc found rows

RuntimeError on windows trying python multiprocessing

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.

How Can I Remove “public/index.php” in the URL Generated Laravel?

This likely has very little to do with Laravel and everything to do with your Apache configs.

Do you have access to your Apache server config? If so, check this out, from the docs:

In general, you should only use .htaccess files when you don't have access to the main server configuration file. There is, for example, a common misconception that user authentication should always be done in .htaccess files, and, in more recent years, another misconception that mod_rewrite directives must go in .htaccess files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things. Likewise, mod_rewrite directives work better, in many respects, in the main server configuration.

... In general, use of .htaccess files should be avoided when possible. Any configuration that you would consider putting in a .htaccess file, can just as effectively be made in a section in your main server configuration file.

Source: Apache documentation.

The reason why I mention this first is because it is best to get rid of .htaccess completely if you can,and use a Directory tag inside a VirtualHost tag. That being said, the rest of this is going to assume you are sticking with the .htaccess route for whatever reason.

To break this down, a couple things could be happening:

  1. I note, perhaps pointlessly, that your file is named .htacces in your question. My guess is that it is a typo but on the off chance you overlooked it and it is in fact just missing the second s, this is exactly the sort of minor error that would leave me banging my head against the wall looking for something more challenging.

  2. Your server could not be allowing .htaccess. To check this, go to your Apache configuration file. In modern Apache builds this is usually not in one config file so make sure you're using the one that points to your app, wherever it exists. Change

    AllowOverride none
    

    to

    AllowOverride all
    

    As a followup, the Apache documents also recommend that, for security purposes, you don't do this for every folder if you are going to go for .htaccess for rewriting. Instead, do it for the folders you need to add .htaccess to.

  3. Do you have mod_rewrite enabled? That could be causing the issues. I notice you have the tag at the top <IfModule mod_rewrite.c>. Try commenting out those tags and restart Apache. If you get an error then it is probably because you need to enable mod_rewrite: How to enable mod_rewrite for Apache 2.2

Hope this helps. I've named some of the most common issues but there are several others that could be more mundane or unique. Another suggestion on a dev server? Re-install Apache. If possible, do so from a different source with a good tutorial.

Sort hash by key, return hash in Ruby

You gave the best answer to yourself in the OP: Hash[h.sort] If you crave for more possibilities, here is in-place modification of the original hash to make it sorted:

h.keys.sort.each { |k| h[k] = h.delete k }

How do I find the install time and date of Windows?

I find the creation date of c:\pagefile.sys can be pretty reliable in most cases. It can easily be obtained using this command (assuming Windows is installed on C:):

dir /as /t:c c:\pagefile.sys

The '/as' specifies 'system files', otherwise it will not be found. The '/t:c' sets the time field to display 'creation'.

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

Enabling error display in PHP via htaccess only

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess. This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

How to write MySQL query where A contains ( "a" or "b" )

You can write your query like so:

SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')

The % is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

How do I directly modify a Google Chrome Extension File? (.CRX)

If you have installed the Portable version of Chrome, or have it installed in a custom directory - the extensions won't be available in directory referenced in above answers.

Try right-clicking on Chrome's shortcut & Check the "Target" directory. From there, navigate to one directory above and you should be able to see the User Data folder and then can use the answers mentioned above

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.

However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.

Bootstrap 3 - How to load content in modal body via AJAX?

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

How do you check if a certain index exists in a table?

Wrote the below function that allows me to quickly check to see if an index exists; works just like OBJECT_ID.

CREATE FUNCTION INDEX_OBJECT_ID (
    @tableName VARCHAR(128),
    @indexName VARCHAR(128)
    )
RETURNS INT
AS
BEGIN
    DECLARE @objectId INT

    SELECT @objectId = i.object_id
    FROM sys.indexes i
    WHERE i.object_id = OBJECT_ID(@tableName)
    AND i.name = @indexName

    RETURN @objectId
END
GO

EDIT: This just returns the OBJECT_ID of the table, but it will be NULL if the index doesn't exist. I suppose you could set this to return index_id, but that isn't super useful.

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

Very very minified version of http://www.featureblend.com/javascript-flash-detection-library.html (only boolean flash detection)

var isFlashInstalled = (function(){
var b=new function(){var n=this;n.c=!1;var a="ShockwaveFlash.ShockwaveFlash",r=[{name:a+".7",version:function(n){return e(n)}},{name:a+".6",version:function(n){var a="6,0,21";try{n.AllowScriptAccess="always",a=e(n)}catch(r){}return a}},{name:a,version:function(n){return e(n)}}],e=function(n){var a=-1;try{a=n.GetVariable("$version")}catch(r){}return a},i=function(n){var a=-1;try{a=new ActiveXObject(n)}catch(r){a={activeXError:!0}}return a};n.b=function(){if(navigator.plugins&&navigator.plugins.length>0){var a="application/x-shockwave-flash",e=navigator.mimeTypes;e&&e[a]&&e[a].enabledPlugin&&e[a].enabledPlugin.description&&(n.c=!0)}else if(-1==navigator.appVersion.indexOf("Mac")&&window.execScript)for(var t=-1,c=0;c<r.length&&-1==t;c++){var o=i(r[c].name);o.activeXError||(n.c=!0)}}()};  
return b.c;
    })();

if(isFlashInstalled){
    // Do something with flash
    }else{
    // Don't use flash  
        }

MySQL - how to front pad zip code with "0"?

I know this is well after the OP. One way you can go with that keeps the table storing the zipcode data as an unsigned INT but displayed with zeros is as follows.

select LPAD(cast(zipcode_int as char), 5, '0') as zipcode from table;

While this preserves the original data as INT and can save some space in storage you will be having the server perform the INT to CHAR conversion for you. This can be thrown into a view and the person who needs this data can be directed there vs the table itself.

Two onClick actions one button

Try it:

<input type="button" value="Dont show this again! " onClick="fbLikeDump();WriteCookie();" />

Or also

<script>
function clickEvent(){
    fbLikeDump();
    WriteCookie();
}
</script>
<input type="button" value="Dont show this again! " onClick="clickEvent();" />

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

Regex for string not ending with given suffix

Anything that matches something ending with a --- .*a$ So when you match the regex, negate the condition or alternatively you can also do .*[^a]$ where [^a] means anything which is not a

Base 64 encode and decode example code

First:

  • Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.

Transmitting end:

  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

Receiving end:

  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

So something like:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

Or with StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

How to set button click effect in Android?

Create bounce.xml file for animation

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        android:duration="100"
        android:fromXScale="0.9"
        android:fromYScale="0.9"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" />

</set>

Add this line in onClick to initialize

final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce); button.startAnimation(myAnim);

You get the shrink effect in a button click.

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

How can I do time/hours arithmetic in Google Spreadsheet?

Example of calculating time:

work-start   work-stop   lunchbreak    effective time

  07:30:00    17:00:00          1.5                 8  [=((A2-A1)*24)-A3]

If you subtract one time value from another the result you get will represent the fraction of 24 hours, so if you multiply the result with 24 you get the value represented in hours.

In other words: the operation is mutiply, but the meaning is to change the format of the number (from days to hours).

Python safe method to get value of nested dictionary

A recursive solution. It's not the most efficient but I find it a bit more readable than the other examples and it doesn't rely on functools.

def deep_get(d, keys):
    if not keys or d is None:
        return d
    return deep_get(d.get(keys[0]), keys[1:])

Example

d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code'])     # => 200
deep_get(d, ['garbage', 'status_code'])  # => None

A more polished version

def deep_get(d, keys, default=None):
    """
    Example:
        d = {'meta': {'status': 'OK', 'status_code': 200}}
        deep_get(d, ['meta', 'status_code'])          # => 200
        deep_get(d, ['garbage', 'status_code'])       # => None
        deep_get(d, ['meta', 'garbage'], default='-') # => '-'
    """
    assert type(keys) is list
    if d is None:
        return default
    if not keys:
        return d
    return deep_get(d.get(keys[0]), keys[1:], default)

Wait till a Function with animations is finished until running another Function

Along with Yoshi's answer, I have found another very simple (callback type) solution for animations.

jQuery has an exposed variable (that for some reason isn't listed anywhere in the jQuery docs) called $.timers, which holds the array of animations currently taking place.

function animationsTest (callback) {
    // Test if ANY/ALL page animations are currently active

    var testAnimationInterval = setInterval(function () {
        if (! $.timers.length) { // any page animations finished
            clearInterval(testAnimationInterval);
            callback();
        }
    }, 25);
};

Basic useage:

functionOne(); // one with animations

animationsTest(functionTwo);

Hope this helps some people out!

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

Capture event onclose browser

Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.

The only working solution is How to capture the browser window close event?

ASP.NET Web Site or ASP.NET Web Application?

Web Application project model

  • Provides the same Web project semantics as Visual Studio .NET Web projects. Has a project file (structure based on project files). Build model - all code in the project is compiled into a single assembly. Supports both IIS and the built-in ASP.NET Development Server. Supports all the features of Visual Studio 2005 (refactoring, generics, etc.) and of ASP.NET (master pages, membership and login, site navigation, themes, etc). Using FrontPage Server Extensions (FPSE) are no longer a requirement.

Web Site project model

  • No project file (Based on file system).
  • New compilation model.
  • Dynamic compilation and working on pages without building entire site on each page view.
  • Supports both IIS and the built-in ASP.NET Development Server.
  • Each page has it's own assembly.
  • Defferent code model.

How to kill/stop a long SQL query immediately?

A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.

If you are running SQL Server on Linux, there is an app you can add to your systray called "killall" Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program. Hope that helps.

Setting width/height as percentage minus pixels

I use Jquery for this

function setSizes() {
   var containerHeight = $("#listContainer").height();
   $("#myList").height(containerHeight - 18);
}

then I bind the window resize to recalc it whenever the browser window is resized (if container's size changed with window resize)

$(window).resize(function() { setSizes(); });

How can I remove the first line of a text file using bash/sed script?

Try tail:

tail -n +2 "$FILE"

-n x: Just print the last x lines. tail -n 5 would give you the last 5 lines of the input. The + sign kind of inverts the argument and make tail print anything but the first x-1 lines. tail -n +1 would print the whole file, tail -n +2 everything but the first line, etc.

GNU tail is much faster than sed. tail is also available on BSD and the -n +2 flag is consistent across both tools. Check the FreeBSD or OS X man pages for more.

The BSD version can be much slower than sed, though. I wonder how they managed that; tail should just read a file line by line while sed does pretty complex operations involving interpreting a script, applying regular expressions and the like.

Note: You may be tempted to use

# THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"

but this will give you an empty file. The reason is that the redirection (>) happens before tail is invoked by the shell:

  1. Shell truncates file $FILE
  2. Shell creates a new process for tail
  3. Shell redirects stdout of the tail process to $FILE
  4. tail reads from the now empty $FILE

If you want to remove the first line inside the file, you should use:

tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"

The && will make sure that the file doesn't get overwritten when there is a problem.

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

How to skip over an element in .map()?

TLDR: You can first filter your array and then perform your map but this would require two passes on the array (filter returns an array to map). Since this array is small, it is a very small performance cost. You can also do a simple reduce. However if you want to re-imagine how this can be done with a single pass over the array (or any datatype), you can use an idea called "transducers" made popular by Rich Hickey.

Answer:

We should not require increasing dot chaining and operating on the array [].map(fn1).filter(f2)... since this approach creates intermediate arrays in memory on every reducing function.

The best approach operates on the actual reducing function so there is only one pass of data and no extra arrays.

The reducing function is the function passed into reduce and takes an accumulator and input from the source and returns something that looks like the accumulator

// 1. create a concat reducing function that can be passed into `reduce`
const concat = (acc, input) => acc.concat([input])

// note that [1,2,3].reduce(concat, []) would return [1,2,3]

// transforming your reducing function by mapping
// 2. create a generic mapping function that can take a reducing function and return another reducing function
const mapping = (changeInput) => (reducing) => (acc, input) => reducing(acc, changeInput(input))

// 3. create your map function that operates on an input
const getSrc = (x) => x.src
const mappingSrc = mapping(getSrc)

// 4. now we can use our `mapSrc` function to transform our original function `concat` to get another reducing function
const inputSources = [{src:'one.html'}, {src:'two.txt'}, {src:'three.json'}]
inputSources.reduce(mappingSrc(concat), [])
// -> ['one.html', 'two.txt', 'three.json']

// remember this is really essentially just
// inputSources.reduce((acc, x) => acc.concat([x.src]), [])


// transforming your reducing function by filtering
// 5. create a generic filtering function that can take a reducing function and return another reducing function
const filtering = (predicate) => (reducing) => (acc, input) => (predicate(input) ? reducing(acc, input): acc)

// 6. create your filter function that operate on an input
const filterJsonAndLoad = (img) => {
  console.log(img)
  if(img.src.split('.').pop() === 'json') {
    // game.loadSprite(...);
    return false;
  } else {
    return true;
  }
}
const filteringJson = filtering(filterJsonAndLoad)

// 7. notice the type of input and output of these functions
// concat is a reducing function,
// mapSrc transforms and returns a reducing function
// filterJsonAndLoad transforms and returns a reducing function
// these functions that transform reducing functions are "transducers", termed by Rich Hickey
// source: http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
// we can pass this all into reduce! and without any intermediate arrays

const sources = inputSources.reduce(filteringJson(mappingSrc(concat)), []);
// [ 'one.html', 'two.txt' ]

// ==================================
// 8. BONUS: compose all the functions
// You can decide to create a composing function which takes an infinite number of transducers to
// operate on your reducing function to compose a computed accumulator without ever creating that
// intermediate array
const composeAll = (...args) => (x) => {
  const fns = args
  var i = fns.length
  while (i--) {
    x = fns[i].call(this, x);
  }
  return x
}

const doABunchOfStuff = composeAll(
    filtering((x) => x.src.split('.').pop() !== 'json'),
    mapping((x) => x.src),
    mapping((x) => x.toUpperCase()),
    mapping((x) => x + '!!!')
)

const sources2 = inputSources.reduce(doABunchOfStuff(concat), [])
// ['ONE.HTML!!!', 'TWO.TXT!!!']

Resources: rich hickey transducers post

Accessing inventory host variable in Ansible playbook

You should be able to use the variable name directly

ansible_ssh_host

Or you can go through hostvars without having to specify the host literally by using the magic variable inventory_hostname

hostvars[inventory_hostname].ansible_ssh_host

Bring element to front using CSS

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Use one of those.

VB.NET Empty String Array

You don't have to include String twice, and you don't have to use New.
Either of the following will work...

Dim strings() as String = {}
Dim strings as String() = {}

How to connect android emulator to the internet

If you are behind a proxy in the SDK Manager, under Tools -> Options, do NOT configure the proxy settings. When you run from the command line add -http-proxy:

emulator.exe -avd YOUR_AVD_NAME_HERE -http-proxy PROXY:PORT

Worked for me.

Visual Studio SignTool.exe Not Found

No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)

How do you stop tracking a remote branch in Git?

git branch --unset-upstream stops tracking all the local branches, which is not desirable.

Remove the [branch "branch-name"] section from the .git/config file followed by

git branch -D 'branch-name' && git branch -D -r 'origin/branch-name'

works out the best for me.

document.getElementById('btnid').disabled is not working in firefox and chrome

There are always weird issues with browser support of getElementById, try using the following instead:

// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/

function disbtn(e) { 
    if ( someCondition == true ) {
        document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled");
    } else {
        document.getElementsBySelector("#btn1")[0].removeAttribute("disabled");
    }    
}

Alternatively, embrace jQuery where you could simply do this:

function disbtn(e) { 
    if ( someCondition == true ) {
        $("#btn1").attr("disabled", "disabled");
    } else {
        $("#btn1").removeAttr("disabled");
    }    
}

Complexities of binary tree traversals

Travesal is O(n) for any order - because you are hitting each node once. Lookup is where it can be less than O(n) IF the tree has some sort of organizing schema (ie binary search tree).

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Find stored procedure by name

You can use:

select * 
from 
   sys.procedures 
where 
   name like '%name_of_proc%'

if you need the code you can look in the syscomments table

select text 
from 
    syscomments c
    inner join sys.procedures p on p.object_id = c.object_id
where 
    p.name like '%name_of_proc%'

Edit Update:

you can can also use the ansi standard version

SELECT * 
FROM 
    INFORMATION_SCHEMA.ROUTINES 
WHERE 
    ROUTINE_NAME LIKE '%name_of_proc%'

Android - SMS Broadcast receiver

Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.

Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:

<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

Hive ParseException - cannot recognize input near 'end' 'string'

I solved this issue by doing like that:

insert into my_table(my_field_0, ..., my_field_n) values(my_value_0, ..., my_value_n)

Java collections maintaining insertion order

Depends on what you need the implementation to do well. Insertion order usually is not interesting so there is no need to maintain it so you can rearrange to get better performance.

For Maps it is usually HashMap and TreeMap that is used. By using hash codes, the entries can be put in small groups easy to search in. The TreeMap maintains a sorted order of the inserted entries at the cost of slower search, but easier to sort than a HashMap.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

.htaccess rewrite to redirect root URL to subdirectory

I don't understand your question...

If you want to redirect every request to a subfolder:

RewriteRule ^(.*)$ shop/$1 [L,QSA]

http://www.example.com/* -> wwwroot/store/*

If you want to redirect to a subfolder which has the domain name

RewriteCond %{HTTP_HOST} ([^\.]+\.[^\.]+)$
RewriteRule ^(.*)$ %1/$1 [L,QSA]

http://www.example.com/* -> wwwroot/example.com/*

While variable is not defined - wait

async, await implementation, improvement over @Toprak's answer

(async() => {
    console.log("waiting for variable");
    while(!window.hasOwnProperty("myVar")) // define the condition as you like
        await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("variable is defined");
})();
console.log("above code doesn't block main function stack");

After revisiting the OP's question. There is actually a better way to implement what was intended: "variable set callback". Although the below code only works if the desired variable is encapsulated by an object (or window) instead of declared by let or var (I left the first answer because I was just doing improvement over existing answers without actually reading the original question):

let obj = encapsulatedObject || window;
Object.defineProperty(obj, "myVar", {
    configurable: true,
    set(v){
        Object.defineProperty(obj, "myVar", {
            configurable: true, enumerable: true, writable: true, value: v });
        console.log("window.myVar is defined");
    }
});
    

see Object.defineProperty or use es6 proxy (which is probably overkill)


If you are looking for more:

_x000D_
_x000D_
/**
 * combining the two as suggested by @Emmanuel Mahuni,
 * and showing an alternative to handle defineProperty setter and getter
 */


let obj = {} || window;
(async() => {
  let _foo = await new Promise(res => {
    Object.defineProperty(obj, "foo", { set: res });
  });
  console.log("obj.foo is defined with value:", _foo);
})();
/*
IMPORTANT: note that obj.foo is still undefined
the reason is out of scope of this question/answer
take a research of Object.defineProperty to see more
*/

// TEST CODE

console.log("test start");
setTimeout(async () => {
  console.log("about to assign obj.foo");
  obj.foo = "Hello World!";
  // try uncomment the following line and compare the output
  // await new Promise(res => setTimeout(res));
  console.log("finished assigning obj.foo");
  console.log("value of obj.foo:", obj.foo); // undefined
  // console: obj.foo is defined with value: Hello World!
}, 2000);
_x000D_
_x000D_
_x000D_

How to subtract a day from a date?

Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...

The relativedelta function from dateutil function (a powerful extension to the datetime lib)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

How do you convert a C++ string to an int?

in "stdapi.h"

StrToInt

This function tells you the result, and how many characters participated in the conversion.

Print the contents of a DIV

Here is an IFrame solution that works for IE and Chrome:

function printHTML(htmlString) {
    var newIframe = document.createElement('iframe');
    newIframe.width = '1px';
    newIframe.height = '1px';
    newIframe.src = 'about:blank';

    // for IE wait for the IFrame to load so we can access contentWindow.document.body
    newIframe.onload = function() {
        var script_tag = newIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
        script_tag.appendChild(script);

        newIframe.contentWindow.document.body.innerHTML = htmlString;
        newIframe.contentWindow.document.body.appendChild(script_tag);

        // for chrome, a timeout for loading large amounts of content
        setTimeout(function() {
            newIframe.contentWindow.Print();
            newIframe.contentWindow.document.body.removeChild(script_tag);
            newIframe.parentElement.removeChild(newIframe);
        }, 200);
    };
    document.body.appendChild(newIframe);
}

jQuery find and replace string

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

What jar should I include to use javax.persistence package in a hibernate based application?

In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.

Add a dependency with API classes for full JavaEE profile:

<properties>
    <javaee-api.version>7.0</javaee-api.version>
    <hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>

<depencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee-api.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Also add dependency with particular JPA provider like antonycc suggested:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate-entitymanager.version}</version>
</dependency>

Note <scope>provided</scope> in API dependency section: this means that corresponding jar will not be exported into artifact's lib/, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.

What does 'git remote add upstream' help achieve?

I think it could be used for "retroactively forking"

If you have a Git repo, and have now decided that it should have forked another repo. Retroactively you would like it to become a fork, without disrupting the team that uses the repo by needing them to target a new repo.

But I could be wrong.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call command, and the second one would share the first one's window.

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit command at the end of your second batch file, or you'll be within a second cmd shell once everything is done.

How to save/restore serializable object to/from file?

You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.

Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.

So, with your code, if I were using XML Serialization:

var path = @"C:\Test\myserializationtest.xml";
using(FileStream fs = new FileStream(path, FileMode.Create))
{
    XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));

    xSer.Serialize(fs, serializableObject);
}

Then, to deserialize:

using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
{
    XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));

    var myObject = _xSer.Deserialize(fs);
}

NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

NSOperation vs Grand Central Dispatch

GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.

The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

multiple prints on the same line in Python

Most simple:

Python 3

    print('\r' + 'something to be override', end='')

It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.

Passing structs to functions

Passing structs to functions by reference: simply :)

#define maxn 1000

struct solotion
{
    int sol[maxn];
    int arry_h[maxn];
    int cat[maxn];
    int scor[maxn];

};

void inser(solotion &come){
    come.sol[0]=2;
}

void initial(solotion &come){
    for(int i=0;i<maxn;i++)
        come.sol[i]=0;
}

int main()
{
    solotion sol1;
    inser(sol1);
    solotion sol2;
    initial(sol2);
}

Download file of any type in Asp.Net MVC using FileResult?

GetFile should be closing the file (or opening it within a using). Then you can delete the file after conversion to bytes-- the download will be done on that byte buffer.

    byte[] GetFile(string s)
    {
        byte[] data;
        using (System.IO.FileStream fs = System.IO.File.OpenRead(s))
        {
            data = new byte[fs.Length];
            int br = fs.Read(data, 0, data.Length);
            if (br != fs.Length)
                throw new System.IO.IOException(s);
        }
        return data;
    }

So in your download method...

        byte[] fileBytes = GetFile(file);
        // delete the file after conversion to bytes
        System.IO.File.Delete(file);
        // have the file download dialog only display the base name of the file            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(file));

Use awk to find average of a column

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'

Add the numbers in $2 (second column) in sum (variables are auto-initialized to zero by awk) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'

If you want to use the shebang notation, you could write:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

You can also control the format of the average with printf() and a suitable format ("%13.6e\n", for example).

You can also generalize the code to average the Nth column (with N=2 in this sample) using:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState)
{

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

ORA-01438: value larger than specified precision allows for this column

One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g

Adding external library into Qt Creator project

I would like to add for the sake of completeness that you can also add just the LIBRARY PATH where it will look for a dependent library (which may not be directly referenced in your code but a library you use may need it).

For comparison, this would correspond to what LIBPATH environment does but its kind of obscure in Qt Creator and not well documented.

The way i came around this is following:

LIBS += -L"$$_PRO_FILE_PWD_/Path_to_Psapi_lib/"

Essentially if you don't provide the actual library name, it adds the path to where it will search dependent libraries. The difference in syntax is small but this is very useful to supply just the PATH where to look for dependent libraries. It sometime is just a pain to supply each path individual library where you know they are all in certain folder and Qt Creator will pick them up.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

After fixing the build.gradle version, It started working 4.0.0 to 3.5.0

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

Best approach to remove time part of datetime in SQL Server

select CONVERT(char(10), GetDate(),126)

How to show soft-keyboard when edittext is focused

I am agree with raukodraug therefor using in a swithview you must request/clear focus like this :

    final ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
    final View btn = viewSwitcher.findViewById(R.id.address_btn);
    final View title = viewSwitcher.findViewById(R.id.address_value);

    title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            viewSwitcher.showPrevious();
            btn.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(btn, InputMethodManager.SHOW_IMPLICIT);
        }
    });

    // EditText affiche le titre evenement click
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btn.clearFocus();
            viewSwitcher.showNext();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(btn.getWindowToken(), 0);
            // Enregistre l'adresse.
            addAddress(view);
        }
    });

Regards.

Remove an item from array using UnderscoreJS

I used to try this method

_.filter(data, function(d) { return d.name != 'a' });

There might be better methods too like the above solutions provided by users

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

I'm using the following trick:

I select the declaration of the class with the data-members and press:

Ctrl+C, Shift+Ctrl+C, Ctrl+V.

  • The first command copies the declaration to the clipboard,
  • The second command is a shortcut that invokes the PROGRAM
  • The last command overwrites the selection by text from the clipboard.

The PROGRAM gets the declaration from the clipboard, finds the name of the class, finds all members and their types, generates constructor and copies it all back into the clipboard.

We are doing it with freshmen on my "Programming-I" practice (Charles University, Prague) and most of students gets it done till the end of the hour.

If you want to see the source code, let me know.

How to convert UTF-8 byte[] to string?

I saw some answers at this post and it's possible to be considered completed base knowledge, because have a several approaches in C# Programming to resolve the same problem. Only one thing that is necessary to be considered is about a difference between Pure UTF-8 and UTF-8 with B.O.M..

In last week, at my job, I need to develop one functionality that outputs CSV files with B.O.M. and other CSVs with pure UTF-8 (without B.O.M.), each CSV file Encoding type will be consumed by different non-standardized APIs, that one API read UTF-8 with B.O.M. and the other API read without B.O.M.. I need to research the references about this concept, reading "What's the difference between UTF-8 and UTF-8 without B.O.M.?" Stack Overflow discussion and this Wikipedia link "Byte order mark" to build my approach.

Finally, my C# Programming for the both UTF-8 encoding types (with B.O.M. and pure) needed to be similar like this example bellow:

//for UTF-8 with B.O.M., equals shared by Zanoni (at top)
string result = System.Text.Encoding.UTF8.GetString(byteArray);

//for Pure UTF-8 (without B.O.M.)
string result = (new UTF8Encoding(false)).GetString(byteArray);

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

How to send PUT, DELETE HTTP request in HttpURLConnection?

Even Rest Template can be an option :

String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<RequestDAO>....";
    RestTemplate rest = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/xml");
    headers.add("Accept", "*/*");
    HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
    ResponseEntity<String> responseEntity =
            rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);

     responseEntity.getBody().toString();

Remove element by id

This one actually comes from Firefox... for once, IE was ahead of the pack and allowed the removal of an element directly.

This is just my assumption, but I believe the reason that you must remove a child through the parent is due to an issue with the way Firefox handled the reference.

If you call an object to commit hari-kari directly, then immediately after it dies, you are still holding that reference to it. This has the potential to create several nasty bugs... such as failing to remove it, removing it but keeping references to it that appear valid, or simply a memory leak.

I believe that when they realized the issue, the workaround was to remove an element through its parent because when the element is gone, you are now simply holding a reference to the parent. This would stop all that unpleasantness, and (if closing down a tree node by node, for example) would 'zip-up' rather nicely.

It should be an easily fixable bug, but as with many other things in web programming, the release was probably rushed, leading to this... and by the time the next version came around, enough people were using it that changing this would lead to breaking a bunch of code.

Again, all of this is simply my guesswork.

I do, however, look forward to the day when web programming finally gets a full spring cleaning, all these strange little idiosyncracies get cleaned up, and everyone starts playing by the same rules.

Probably the day after my robot servant sues me for back wages.

How to check if NSString begins with a certain character

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

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

I had this problem with chrome when I was working on a WordPress site. I added this code

$_SERVER['HTTPS'] = false;

into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

HTML5 Video not working in IE 11

It was due to IE Document-mode version too low. Press 'F12' and using higher version( My case, above version 9 is OK)

show/hide a div on hover and hover out

I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.

JS fiddle Demo

CSS

#stuff {
    opacity: 0.0;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
}
#hover {
    width:80px;
    height:20px;
    background-color:green;
    margin-bottom:15px;
}
#hover:hover + #stuff {
    opacity: 1.0;
}

HTML

<div id="hover">Hover</div>
<div id="stuff">stuff</div>

How to make a PHP SOAP call using the SoapClient class

First initialize webservices:

$client = new SoapClient("http://example.com/webservices?wsdl");

Then set and pass the parameters:

$params = array (
    "arg0" => $contactid,
    "arg1" => $desc,
    "arg2" => $contactname
);

$response = $client->__soapCall('methodname', array($params));

Note that the method name is available in WSDL as operation name, e.g.:

<operation name="methodname">

Testing Private method using mockito

  1. By using reflection, private methods can be called from test classes. In this case,

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        // invoke the private method for test
        privateMethod.invoke(A, null);
    
        }
    }
    
  2. If the private method calls any other private method, then we need to spy the object and stub the another method.The test class will be like ...

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        A spyA = spy(a);
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        doReturn("Test").when(spyA, "method2"); // if private method2 is returning string data
        // invoke the private method for test
        privateMethod.invoke(spyA , null);
    
        }
    }
    

**The approach is to combine reflection and spying the object. **method1 and **method2 are private methods and method1 calls method2.

Calculate date from week number

The free Time Period Library for .NET includes the ISO 8601 conform class Week:

// ----------------------------------------------------------------------
public static DateTime GetFirstDayOfWeek( int year, int weekOfYear )
{
  return new Week( year, weekOfYear ).FirstDayStart;
} // GetFirstDayOfWeek

Changing file permission in Python

All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444 permissions -- but we can do better!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

As John La Rooy pointed out,stat.S_IWUSR basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~ operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITING bit constant).

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

Write objects into file with Node.js

could you try doing JSON.stringify(obj);

Like this

 var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8'); 

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

jQuery: Best practice to populate drop down?

$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });

How can I see the entire HTTP request that's being sent by my Python application?

r = requests.get('https://api.github.com', auth=('user', 'pass'))

r is a response. It has a request attribute which has the information you need.

r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

r.request.headers gives the headers:

{'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

Then r.request.data has the body as a mapping. You can convert this with urllib.urlencode if they prefer:

import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

depending on the type of the response the .data-attribute may be missing and a .body-attribute be there instead.

Dropping connected users in Oracle database

I had the same problem, Oracle config in default affects letter register. In exact my Scheme_Name was written all Capital letters. You can see your Scheme_Name on "Other Users" tab, if you are using Oracle S

How to use multiple @RequestMapping annotations in spring?

From my test (spring 3.0.5), @RequestMapping(value={"", "/"}) - only "/" works, "" does not. However I found out this works: @RequestMapping(value={"/", " * "}), the " * " matches anything, so it will be the default handler in case no others.

support FragmentPagerAdapter holds reference to old fragments

You are running into a problem because you are instantiating and keeping references to your fragments outside of PagerAdapter.getItem, and are trying to use those references independently of the ViewPager. As Seraph says, you do have guarantees that a fragment has been instantiated/added in a ViewPager at a particular time - this should be considered an implementation detail. A ViewPager does lazy loading of its pages; by default it only loads the current page, and the one to the left and right.

If you put your app into the background, the fragments that have been added to the fragment manager are saved automatically. Even if your app is killed, this information is restored when you relaunch your app.

Now consider that you have viewed a few pages, Fragments A, B and C. You know that these have been added to the fragment manager. Because you are using FragmentPagerAdapter and not FragmentStatePagerAdapter, these fragments will still be added (but potentially detached) when you scroll to other pages.

Consider that you then background your application, and then it gets killed. When you come back, Android will remember that you used to have Fragments A, B and C in the fragment manager and so it recreates them for you and then adds them. However, the ones that are added to the fragment manager now are NOT the ones you have in your fragments list in your Activity.

The FragmentPagerAdapter will not try to call getPosition if there is already a fragment added for that particular page position. In fact, since the fragment recreated by Android will never be removed, you have no hope of replacing it with a call to getPosition. Getting a handle on it is also pretty difficult to obtain a reference to it because it was added with a tag that is unknown to you. This is by design; you are discouraged from messing with the fragments that the view pager is managing. You should be performing all your actions within a fragment, communicating with the activity, and requesting to switch to a particular page, if necessary.

Now, back to your problem with the missing activity. Calling pagerAdapter.getItem(1)).update(id, name) after all of this has happened returns you the fragment in your list, which has yet to be added to the fragment manager, and so it will not have an Activity reference. I would that suggest your update method should modify some shared data structure (possibly managed by the activity), and then when you move to a particular page it can draw itself based on this updated data.

Calling a method every x minutes

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);

Core dumped, but core file is not in the current directory?

My efforts in WSL have been unsuccessful.

For those running on Windows Subsystem for Linux (WSL) there seems to be an open issue at this time for missing core dump files.

The comments indicate that

This is a known issue that we are aware of, it is something we are investigating.

Github issue

Windows Developer Feedback

regex pattern to match the end of a string

Use the $ metacharacter to match the end of a string.

In Perl, this looks like:

my $str = 'red/white/blue';
my($last_match) = $str =~ m/.*\/(.*)$/;

Written in JavaScript, this looks like:

var str = 'red/white/blue'.match(/.*\/(.*)$/);

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

AngularJS: How to clear query parameters in the URL?

At the time of writing, and as previously mentioned by @Bosh, html5mode must be true in order to be able to set $location.search() and have it be reflected back into the window’s visual URL.

See https://github.com/angular/angular.js/issues/1521 for more info.

But if html5mode is true you can easily clear the URL’s query string with:

$location.search('');

or

$location.search({});

This will also alter the window’s visual URL.

(Tested in AngularJS version 1.3.0-rc.1 with html5Mode(true).)

Android Failed to install HelloWorld.apk on device (null) Error

I had the same problem and solved it by adding the paths of Android SDK folder tools and platform-tools to system PATH variable then restarting the device.

php error: Class 'Imagick' not found

Install Imagic in PHP7:

sudo apt-get install php-imagick

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

What is the 'new' keyword in JavaScript?

It does 5 things:

  1. It creates a new object. The type of this object is simply object.
  2. It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
  3. It makes the this variable point to the newly created object.
  4. It executes the constructor function, using the newly created object whenever this is mentioned.
  5. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

Note: constructor function refers to the function after the new keyword, as in

new ConstructorFunction(arg1, arg2)

Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.

The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to set or read this value.

Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.


Here is an example:

ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes 
// it a constructor.

ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that 
// we can alter. I just added a property called 'b' to it. Like 
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with

obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1.  At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.

obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks 
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'

It's like class inheritance because now, any objects you make using new ObjMaker() will also appear to have inherited the 'b' property.

If you want something like a subclass, then you do this:

SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);

SubObjMaker.prototype.c = 'third';  
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype

obj2.c;
// returns 'third', from SubObjMaker.prototype

obj2.b;
// returns 'second', from ObjMaker.prototype

obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype 
// was created with the ObjMaker function, which assigned a for us

I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.

How to run a cronjob every X minutes?

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

To set for x minutes we need to set x minutes in the 1st argument and then the path of your script

For 15 mins

*/15 * * * *  /usr/bin/php /mydomain.in/cromail.php > /dev/null 2>&1

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

Stop jQuery .load response from being cached

Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.

'?_='+Math.round(Math.random()*10000)

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

Renaming files in a folder to sequential numbers

Again using Pero's solution with little modifying, because find will be traversing the directory tree in the order items are stored within the directory entries. This will (mostly) be consistent from run to run, on the same machine and will essentially be "file/directory creation order" if there have been no deletes.

However, in some case you need to get some logical order, say, by name, which is used in this example.

find -name '*.jpg' | sort -n | # find jpegs
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command 

Overflow:hidden dots at the end

Hopefully it's helpful for you:

_x000D_
_x000D_
.text-with-dots {_x000D_
    display: block;_x000D_
    max-width: 98%;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden !important;_x000D_
    text-overflow: ellipsis;_x000D_
}
_x000D_
<div class='text-with-dots'>Some texts here Some texts here Some texts here Some texts here Some texts here Some texts here </div>
_x000D_
_x000D_
_x000D_

How to print a dictionary's key?

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

MySQL wait_timeout Variable - GLOBAL vs SESSION

As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.

For example, if you have 100 connections and you lower the global wait_timeout then it will not affect the existing connections, only new ones after the variable was changed.

Specifically for the wait_timeout variable though, there is a twist. If you are using the mysql client in the interactive mode, or the connector with CLIENT_INTERACTIVE set via mysql_real_connect() then you will see the interactive_timeout set for @@session.wait_timeout

Here you can see this demonstrated:

> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout' 
70      60      70      60

> ./bin/mysql -Bsse 'select @@wait_timeout'                                                                                                 
70

> ./bin/mysql                                                                                                                               
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)

Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|             60 |
+----------------+
1 row in set (0.00 sec)

So, if you are testing this using the client it is the interactive_timeout that you will see when connecting and not the value of wait_timeout

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

Stop mouse event propagation

Adding false after function will stop event propagation

<a (click)="foo(); false">click with stop propagation</a>

Why is the Android emulator so slow? How can we speed up the Android emulator?

To reduce your emulator start-up time you need to check the "Disable Boot Animation" before starting the emulator. Refer to the Android documentation.

If in case you don't know, you do not need to close the emulator every-time you run/debug your app. If you click run/debug when it's already open, your APK file will get uploaded to the emulator and start pretty much immediately. Emulator takes annoyingly long time only when it started the first time.

Here are some tips to speed up the Android emulator: How to speed up the Android Emulator by up to 400%.

How to include scripts located inside the node_modules folder?

If you want a quick and easy solution (and you have gulp installed).

In my gulpfile.js I run a simple copy paste task that puts any files I might need into ./public/modules/ directory.

gulp.task('modules', function() {
    sources = [
      './node_modules/prismjs/prism.js',
      './node_modules/prismjs/themes/prism-dark.css',
    ]
    gulp.src( sources ).pipe(gulp.dest('./public/modules/'));
});

gulp.task('copy-modules', ['modules']);

The downside to this is that it isn't automated. However, if all you need is a few scripts and styles copied over (and kept in a list), this should do the job.

Android Endless List

Best solution so far that I have seen is in FastAdapter library for recycler views. It has a EndlessRecyclerOnScrollListener.

Here is an example usage: EndlessScrollListActivity

Once I used it for endless scrolling list I have realised that the setup is a very robust. I'd definitely recommend it.

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

Add JavaScript object to JavaScript object

var jsonIssues = [
 {ID:'1',Name:'Some name',Notes:'NOTES'},
 {ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];

If you want to add to the array then you can do this

jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};

Or you can use the push technique that the other guy posted, which is also good.

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

Default SecurityProtocol in .NET 4.5

You can override the default behavior in following registry:

Key  : HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 
Value: SchUseStrongCrypto
Type: REG_DWORD
Data : 1

and

Key  : HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
Type: REG_DWORD
Data : 1

For details, please see the implementation of ServicePointManager.

Where to place JavaScript in an HTML file?

The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]
    

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

Why can't static methods be abstract in Java?

Poor language design. It would be much more effective to call directly a static abstract method than creating an instance just for using that abstract method. Especially true when using an abstract class as a workaround for enum inability to extend, which is another poor design example. Hope they solve those limitations in a next release.

Remove querystring from URL

If you need to perform complex operation on URL, you can take a look to the jQuery url parser plugin.

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

Steps:

  1. Connect the phone to a different computer (slave-machine)
  2. Run adb usb && adb tcpip 5555 from there
  3. On master machine

    deko$: adb devices
    List of devices attached
    
    deko$: adb connect 10.0.20.153:5555
    connected to 10.0.20.153:5555
    
  4. Now Android Studio or Xamarin can install and run app on the phone


Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

How can I get the current PowerShell executing file?

As noted in previous responses, using "$MyInvocation" is subject to scoping issues and doesn't necessarily provide consistent data (return value vs. direct access value). I've found that the "cleanest" (most consistent) method for getting script info like script path, name, parms, command line, etc. regardless of scope (in main or subsequent/nested function calls) is to use "Get-Variable" on "MyInvocation"...

# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value

# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path

# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath

# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name

# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName

So, you can get the same info as $PSCommandPath, but a whole lot more in the deal. Not sure, but it looks like "Get-Variable" was not available until PS3 so not a lot of help for really old (not updated) systems.

There are also some interesting aspects when using "-Scope" as you can backtrack to get the names, etc. of the calling function(s). 0=current, 1=parent, etc.

Hope this is somewhat helpful.

Ref, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable

Laravel requires the Mcrypt PHP extension

If you are using Z Shell, just do the following:

  1. Open terminal
  2. sudo nano ~/.zshrc
  3. Paste this; export PATH=/Applications/MAMP/bin/php/php5.6.10/bin:$PATH
  4. Save
  5. Run source ~/.zshrc
  6. Run which php - you should get the MAMP 5.6.10 path

5.6.10 is the version of PHP you set in your MAMP.

Python: Assign Value if None Exists

Here is the easiest way I use, hope works for you,

var1 = var1 or 4

This assigns 4 to var1 only if var1 is None , False or 0

How to connect to SQL Server database from JavaScript in the browser?

As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.

Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.

Resizing UITableView to fit content

There is a much better way to do it if you use AutoLayout: change the constraint that determines the height. Just calculate the height of your table contents, then find the constraint and change it. Here's an example (assuming that the constraint that determines your table's height is actually a height constraint with relation "Equal"):

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    for constraint in tableView.constraints {
        if constraint.firstItem as? UITableView == tableView {
            if constraint.firstAttribute == .height {
                constraint.constant = tableView.contentSize.height
            }
        }
    }
}

SQL Server: Examples of PIVOTing String data

From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:

SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO

How do I get this javascript to run every second?

Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

var t=setInterval(runFunction,1000);

And to stop it, you can run:

clearInterval(t);

How to rollback just one step using rake db:migrate

Other people have already answered you how to rollback, but you also asked how you could identify the version number of a migration.

  • rake db:migrate:status gives a list of your migrations version, name and status (up or down)
  • Your can also find the migration file, which contain a timestamp in the filename, that is the version number. Migrations are located in folder: /db/migrate

How to close existing connections to a DB

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

ASP.NET Core Web API Authentication

ASP.NET Core 2.0 with Angular

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Make sure to use type of authentication filter

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

How to create a CPU spike with a bash command

You can also do

dd if=/dev/zero of=/dev/null

To run more of those to put load on more cores, try to fork it:

fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd

Repeat the command in the curly brackets as many times as the number of threads you want to produce (here 4 threads). Simple enter hit will stop it (just make sure no other dd is running on this user or you kill it too).

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

String or binary data would be truncated. The statement has been terminated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.

Query level

INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO

Server Level

DBCC TRACEON(460, -1);
GO

From SQL Server 2019 you can enable it at database level:

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

The old output message is:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

The new output message is:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.

In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

How to store NULL values in datetime fields in MySQL?

I just discovered that MySQL will take null provided the default for the field is null and I write specific if statements and leave off the quotes. This works for update as well.

if(empty($odate) AND empty($ddate))
{
  $query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
};

Formula to determine brightness of RGB color

I think what you are looking for is the RGB -> Luma conversion formula.

Photometric/digital ITU BT.709:

Y = 0.2126 R + 0.7152 G + 0.0722 B

Digital ITU BT.601 (gives more weight to the R and B components):

Y = 0.299 R + 0.587 G + 0.114 B

If you are willing to trade accuracy for perfomance, there are two approximation formulas for this one:

Y = 0.33 R + 0.5 G + 0.16 B

Y = 0.375 R + 0.5 G + 0.125 B

These can be calculated quickly as

Y = (R+R+B+G+G+G)/6

Y = (R+R+R+B+G+G+G+G)>>3

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Convert string with comma to integer

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.

-Rick

Adding an external directory to Tomcat classpath

I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.

1. run the application using IDE's tomcat run config. 
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too. 

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

How do I create an executable in Visual Studio 2013 w/ C++?

All executable files from Visual Studio should be located in the debug folder of your project, e.g:

Visual Studio Directory: c:\users\me\documents\visual studio

Then the project which was called 'hello world' would be in the directory:

c:\users\me\documents\visual studio\hello world

And your exe would be located in:

c:\users\me\documents\visual studio\hello world\Debug\hello world.exe

Note the exe being named the same as the project.

Otherwise, you could publish it to a specified folder of your choice which comes with an installation, which would be good if you wanted to distribute it quickly

EDIT:

Everytime you build your project in VS, the exe is updated with the new one according to the code (as long as it builds without errors). When you publish it, you can choose the location, aswell as other factors, and the setup exe will be in that location, aswell as some manifest files and other files about the project.

How to Import 1GB .sql file to WAMP/phpmyadmin

If you will try to load such a large file through phpmyadmin then you would need to change upload_file_size in php.ini to your requirements and then after uploading you will have to revert it back. What will happen? If you would like to load a 3GB file. You will have to change those parameters in php.ini again.

The best solution to solve this issue to open command prompt in windows.

Find path of wamp mysql directory.

Usually, it is C:/wamp64/bin/mysql/mysqlversion/bin/mysql.exe

Execute mysql -u root

You will be in mysql command prompt

Switch database with use command.

mysql> use database_name
mysql> source [file_path]

In case of Windows, here is the example.

mysql> source C:/sqls/sql1GB.sql

That's it. If you will have a database over 10GB or 1000GB. This method will still work for you.

PHP check if date between two dates

You can use the mktime(hour, minute, seconds, month, day, year) function

$paymentDate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$contractDateBegin = mktime(0, 0, 0, 1, 1, 2001); 
$contractDateEnd =  mktime(0, 0, 0, 1, 1, 2012);

if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd){
    echo "is between";
}else{
    echo "NO GO!";  
}

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

How to find memory leak in a C++ code/project?

Answering the second part of your question,

Is there any standard or procedure one should follow to ensure there is no memory leak in the program.

Yes, there is. And this is one of the key differences between C and C++.

In C++, you should never call new or delete in your user code. RAII is a very commonly used technique, which pretty much solves the resource management problem. Every resource in your program (a resource is anything that has to be acquired, and then later on, released: file handles, network sockets, database connections, but also plain memory allocations, and in some cases, pairs of API calls (BeginX()/EndX(), LockY(), UnlockY()), should be wrapped in a class, where:

  • the constructor acquires the resource (by calling new if the resource is a memroy allocation)
  • the destructor releases the resource,
  • copying and assignment is either prevented (by making the copy constructor and assignment operators private), or are implemented to work correctly (for example by cloning the underlying resource)

This class is then instantiated locally, on the stack, or as a class member, and not by calling new and storing a pointer.

You often don't need to define these classes yourself. The standard library containers behave in this way as well, so that any object stored into a std::vector gets freed when the vector is destroyed. So again, don't store a pointer into the container (which would require you to call new and delete), but rather the object itself (which gives you memory management for free). Likewise, smart pointer classes can be used to easily wrap objects that just have to be allocated with new, and control their lifetimes.

This means that when the object goes out of scope, it is automatically destroyed, and its resource released and cleaned up.

If you do this consistently throughout your code, you simply won't have any memory leaks. Everything that could get leaked is tied to a destructor which is guaranteed to be called when control leaves the scope in which the object was declared.

How do I share a global variable between c files?

In the second .c file use extern keyword with the same variable name.

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

How can I decrease the size of Ratingbar?

<RatingBar
  style="?android:attr/ratingBarStyleIndicator"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
/>

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

Oracle - How to generate script from sql developer

This worked for me:

  • In SQL Developer, right click the object that you want to generate a script for. i.e. the table name
  • Select Quick DLL > Save To File
  • This will then write the create statement to an external sql file.

Note, you can also highlight multiple objects at the same time, so you could generate one script that contains create statements for all tables within the database.

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

There's an ELSE in the DOS batch language? Back in the days when I did more of this kinda thing, there wasn't.

If my theory is correct and your ELSE is being ignored, you may be better off doing

IF NOT EXIST file GOTO label

...which will also save you a line of code (the one right after your IF).

Second, I vaguely remember some kind of bug with testing for the existence of directories. Life would be easier if you could test for the existence of a file in that directory. If there's no file you can be sure of, something to try (this used to work up to Win95, IIRC) would be to append the device file name NUL to your directory name, e.g.

IF NOT EXIST C:\dir\NUL GOTO ...

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

Enable Hibernate logging

Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:

MyProject
¦   build.xml
¦   
+---build
¦   ¦   capitolo2-ejb.jar
¦   ¦   capitolo2-war.war
¦   ¦   JBoss4.dpf
¦   ¦   log4j.properties

Copy values from one column to another in the same table

BEWARE : Order of update columns is critical

GOOD: What I want saves existing Value of Status to PrevStatus

UPDATE Collections SET  PrevStatus=Status, Status=44 WHERE ID=1487496;

BAD: Status & PrevStatus both end up as 44

UPDATE Collections SET  Status=44, PrevStatus=Status WHERE ID=1487496;

Calculate text width with JavaScript

I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in impressivewebs page

(function($){

        $.fn.autofit = function() {             

            var hiddenDiv = $(document.createElement('div')),
            content = null;

            hiddenDiv.css('display','none');

            $('body').append(hiddenDiv);

            $(this).bind('fit keyup keydown blur update focus',function () {
                content = $(this).val();

                content = content.replace(/\n/g, '<br>');
                hiddenDiv.html(content);

                $(this).css('width', hiddenDiv.width());

            });

            return this;

        };
    })(jQuery);

The fit event is used to execute the function call inmediatly after the function is asociated to the control.

e.g.: $('input').autofit().trigger("fit");

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

CSS strikethrough different color from text?

Single Property solution is:

.className {
    text-decoration: line-through red;
};

Define your color after line through property.

Create a directory if it doesn't exist

You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>

How to set Toolbar text and back arrow color

Inside Activity, you can use

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));

If you love to choose xml for both title color & back arrow white just add this style in style.xml .

 <style name="ToolBarStyle" parent="Theme.AppCompat">
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:textColorSecondary">@android:color/white</item>
    <item name="actionMenuTextColor">@android:color/white</item>
</style>

And toolbar look like :

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        app:theme="@style/ToolBarStyle"
        android:layout_height="?attr/actionBarSize"
  />

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

You're probably trying to run Python 3 file with Python 2 interpreter. Currently (as of 2019), python command defaults to Python 2 when both versions are installed, on Windows and most Linux distributions.

But in case you're indeed working on a Python 2 script, a not yet mentioned on this page solution is to resave the file in UTF-8+BOM encoding, that will add three special bytes to the start of the file, they will explicitly inform the Python interpreter (and your text editor) about the file encoding.

Can I catch multiple Java exceptions in the same catch clause?

Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.

How to open the Google Play Store directly from my Android application?

This link will open the app automatically in market:// if you are on Android and in browser if you are on PC.

https://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.app.id&ddl=1&pcampaignid=web_ddl_1

Box-Shadow on the left side of the element only

box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);

The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.

The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.

reference: CSS Box Shadow Property

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Passing 'this' to an onclick event

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

How to shut down the computer from C#

Note that shutdown.exe is just a wrapper around InitiateSystemShutdownEx, which provides some niceties missing in ExitWindowsEx

How can I enable the MySQLi extension in PHP 7?

I got the solution. I am able to enable MySQLi extension in php.ini. I just uncommented this line in php.ini:

extension=php_mysqli.dll

Now MySQLi is working well. Here is the php.ini file path in an Apache 2, PHP 7, and Ubuntu 14.04 environment:

/etc/php/7.0/apache2/php.ini

By default, the MySQLi extension is disabled in PHP 7.

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

What is the "__v" field in Mongoose

It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .

Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?

Get week day name from a given month, day and year individually in SQL Server

I used

select
case
when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

Node.js quick file server (static files over HTTP)

For the benefit of searchers, I liked Jakub g's answer, but wanted a little error handling. Obviously it's best to handle errors properly, but this should help prevent a site stopping if an error occurs. Code below:

var http = require('http');
var express = require('express');

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});

MySQL WHERE: how to write "!=" or "not equals"?

You may be using old version of Mysql but surely you can use

 DELETE FROM konta WHERE taken <> ''

But there are many other options available. You can try the following ones

DELETE * from konta WHERE strcmp(taken, '') <> 0;

DELETE * from konta where NOT (taken = '');

ASP.NET custom error page - Server.GetLastError() is null

Try using something like Server.Transfer("~/ErrorPage.aspx"); from within the Application_Error() method of global.asax.cs

Then from within Page_Load() of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();

Server.Transfer() seems to keep the exception hanging around.

Read a XML (from a string) and get some fields - Problems reading XML

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML); 

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
} 

How to detect if JavaScript is disabled?

Might sound a strange solution, but you can give it a try :

<?php $jsEnabledVar = 0; ?>    

<script type="text/javascript">
var jsenabled = 1;
if(jsenabled == 1)
{
   <?php $jsEnabledVar = 1; ?>
}
</script>

<noscript>
var jsenabled = 0;
if(jsenabled == 0)
{
   <?php $jsEnabledVar = 0; ?>
}
</noscript>

Now use the value of '$jsEnabledVar' throughout the page. You may also use it to display a block indicating the user that JS is turned off.

hope this will help

Setting the target version of Java in ant javac

To find the version of the java in the classfiles I used:

javap -verbose <classname>

which announces the version at the start as

minor version: 0
major version: 49

which corresponds to Java 1.5

100% width background image with an 'auto' height

It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size but on the element itself, and on any element including images.

.your-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

Format numbers to strings in Python

You can use C style string formatting:

"%d:%d:d" % (hours, minutes, seconds)

See here, especially: https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html