Programs & Examples On #Static order fiasco

How do I center an SVG in a div?

I had to use

display: inline-block;

How do you unit test private methods?

I don't agree with the "you should only be interested in testing the external interface" philosophy. It's a bit like saying that a car repair shop should only have tests to see if the wheels turn. Yes, ultimately I'm interested in the external behavior but I like my own, private, internal tests to be a bit more specific and to the point. Yes, if I refactor, I may have to change some of the tests, but unless it's a massive refactor, I'll only have to change a few and the fact that the other (unchanged) internal tests still work is a great indicator that the refactoring has been successful.

You can try to cover all internal cases using only the public interface and theoretically it's possible to test every internal method (or at least every one that matters) entirely by using the public interface but you may have to end up standing on your head to achieve this and the connection between the test cases being run through the public interface and the internal portion of the solution they're designed to test may be difficult or impossible to discern. Having pointed, individual tests that guarantee that the internal machinery is working properly is well worth the minor test changes that come about with refactoring - at least that's been my experience. If you have to make huge changes to your tests for every refactoring, then maybe this doesn't make sense, but in that case, maybe you ought to rethink your design entirely. A good design should be flexible enough to allow for most changes without massive redesigns.

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

Close application and launch home screen on Android

It is not recommended, but you can still use this. Better go with this solution in case you need to quit the app.

According to me, the best solution is to finish every activity in your app like below.

Step 1. Maintain a static variable in mainactivity. Say,

public static boolean isQuit = false;

Step 2. On click event of an button, set this variable to true.

mainactivity.isQuit = true;
finish();

Step 3. And in every activity of your application, have the onrestart method as below.

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    if(mainactivity.isQuit)
        finish();
}

bundle install returns "Could not locate Gemfile"

Search for the Gemfile file in your project, go to that directory and then run "bundle install". prior to running this command make sure you have installed the gem "sudo gem install bundler"

Best Way to read rss feed in .net Using C#

You're looking for the SyndicationFeed class, which does exactly that.

How to set default value for column of new created table from select statement in 11g

new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 as select * from t1;

This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax

create table t1 (id number default 1 unique);
insert into t1 (id) values (2);

create table t2 (id default 1 unique)
as select * from t1;

What does "javascript:void(0)" mean?

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

nodejs mysql Error: Connection lost The server closed the connection

I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.

Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.

tl;dr; Do not use this method.


A pragmatic solution is to force MySQL to keep the connection alive:

setInterval(function () {
    db.query('SELECT 1');
}, 5000);

I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST does not occur.

Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID() and mysql connection have been reset without you being aware about it?

However, this only ensures that connection time out (wait_timeout and interactive_timeout) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.

jQuery has deprecated synchronous XMLHTTPRequest

To avoid this warning, do not use:

async: false

in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.

The default is async: true, so if you never use this option at all, your code should be safe if the feature is ever really removed.

However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.

Notice that the Fetch API that's replacing XMLHttpRequest does not even offer a synchronous option.

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

What is the difference between square brackets and parentheses in a regex?

Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.

/^(7|8|9)\d{9}$/

What this does:

  • ^ and $ denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
  • () denotes a capturing group.
  • 7|8|9 denotes matching either of 7, 8, or 9. It does this with alternations, which is what the pipe operator | does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat

alternations

Pattern: [rf]at
Match string: carat

class

  • \d{9} matches nine digits. \d is a shorthanded metacharacter, which matches any digits.
/^[7|8|9][\d]{9}$/

Look at what it does:

  • ^ and $ denotes anchored matches as well.
  • [7|8|9] is a character class. Any characters from the list 7, |, 8, |, or 9 can be matched, thus the | was added in incorrectly. This matches without backtracking.
  • [\d] is a character class that inhabits the metacharacter \d. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
  • {9} indicates the previous single construct is repeated nine times in total.

The optimal regex is /^[789]\d{9}$/, because /^(7|8|9)\d{9}$/ captures unnecessarily which imposes a performance decrease on most regex implementations ( happens to be one, considering the question uses keyword var in code, this probably is JavaScript). The use of which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes [] instead of alternations | gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.

How to call a Parent Class's method from Child Class in Python?

This is a more abstract method:

super(self.__class__,self).baz(arg)

How do I get the XML SOAP request of an WCF Web service request?

There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.

In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.

Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.

How do you run JavaScript script through the Terminal?

I tried researching that too but instead ended up using jsconsole.com by Remy Sharp (he also created jsbin.com). I'm running on Ubuntu 12.10 so I had to create a special icon but if you're on Windows and use Chrome simply go to Tools>Create Application Shortcuts (note this doesn't work very well, or at all in my case, on Ubuntu). This site works very like the Mac jsc console: actually it has some cool features too (like loading libraries/code from a URL) that I guess jsc does not.

Hope this helps.

How can I roll back my last delete command in MySQL?

A "rollback" only works if you used transactions. That way you can group queries together and undo all queries if only one of them fails.

But if you already committed the transaction (or used a regular DELETE-query), the only way of getting your data back is to recover it from a previously made backup.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

Adding dictionaries together, Python

Here are quite a few ways to add dictionaries.

You can use Python3's dictionary unpacking feature.

ndic = {**dic0, **dic1}

Or create a new dict by adding both items.

ndic = dict(dic0.items() + dic1.items())

If your ok to modify dic0

dic0.update(dic1)

If your NOT ok to modify dic0

ndic = dic0.copy()
ndic.update(dic1)

If all the keys in one dict are ensured to be strings (dic1 in this case, of course args can be swapped)

ndic = dict(dic0, **dic1)

In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.

ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

Triggers cannot modify the changed data (Inserted or Deleted) otherwise you could get infinite recursion as the changes invoked the trigger again. One option would be for the trigger to roll back the transaction.

Edit: The reason for this is that the standard for SQL is that inserted and deleted rows cannot be modified by the trigger. The underlying reason for is that the modifications could cause infinite recursion. In the general case, this evaluation could involve multiple triggers in a mutually recursive cascade. Having a system intelligently decide whether to allow such updates is computationally intractable, essentially a variation on the halting problem.

The accepted solution to this is not to permit the trigger to alter the changing data, although it can roll back the transaction.

create table Foo (
       FooID int
      ,SomeField varchar (10)
)
go

create trigger FooInsert
    on Foo after insert as
    begin
        delete inserted
         where isnumeric (SomeField) = 1
    end
go


Msg 286, Level 16, State 1, Procedure FooInsert, Line 5
The logical tables INSERTED and DELETED cannot be updated.

Something like this will roll back the transaction.

create table Foo (
       FooID int
      ,SomeField varchar (10)
)
go

create trigger FooInsert
    on Foo for insert as
    if exists (
       select 1
         from inserted 
        where isnumeric (SomeField) = 1) begin
              rollback transaction
    end
go

insert Foo values (1, '1')

Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

How to convert AAR to JAR

 The 'aar' bundle is the binary distribution of an Android Library Project. .aar file 
 consists a JAR file and some resource files. You can convert it
 as .jar file using this steps

1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using 
 any winrar or zip Extractor software.

2) Now you will get a .zip file. Right click on the .zip file and select "Extract files". 
 Will get a folder which contains "classes.jar, resource, manifest, R.java,
 proguard(optional), libs(optional), assets(optional)".

3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.

Note: If you want to get only .jar file from your .aar file use the above way. Suppose If you want to include the manifest.xml and resources with your .jar file means you can just right click on your .aar file and save it as .jar file directly instead of saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.

enter image description here enter image description here

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

SHA-256 or MD5 for file integrity

To 1): Yes, on most CPUs, SHA-256 is about only 40% as fast as MD5.

To 2): I would argue for a different algorithm than MD5 in such a case. I would definitely prefer an algorithm that is considered safe. However, this is more a feeling. Cases where this matters would be rather constructed than realistic, e.g. if your backup system encounters an example case of an attack on an MD5-based certificate, you are likely to have two files in such an example with different data, but identical MD5 checksums. For the rest of the cases, it doesn't matter, because MD5 checksums have a collision (= same checksums for different data) virtually only when provoked intentionally. I'm not an expert on the various hashing (checksum generating) algorithms, so I can not suggest another algorithm. Hence this part of the question is still open. Suggested further reading is Cryptographic Hash Function - File or Data Identifier on Wikipedia. Also further down on that page there is a list of cryptographic hash algorithms.

To 3): MD5 is an algorithm to calculate checksums. A checksum calculated using this algorithm is then called an MD5 checksum.

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

SimpleXml to string

Probably depending on the XML feed you may/may not need to use __toString(); I had to use the __toString() otherwise it is returning the string inside an SimpleXMLElement. Maybe I need to drill down the object further ...

Ruby replace string with captured regex pattern

def get_code(str)
  str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Synchronized method is used for lock all the objects Synchronized block is used to lock specific object

Can't update data-attribute value

Had a similar problem, I propose this solution althought is not supported in IE 10 and under.

Given

<div id='example' data-example-update='1'></div>

The Javascript standard defines a property called dataset to update data-example-update.

document.getElementById('example').dataset.exampleUpdate = 2;

Note: use camel case notation to access the correct data attribute.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Why Git is not allowing me to commit even after configuration?

Do you have a local user.name or user.email that's overriding the global one?

git config --list --global | grep user
  user.name=YOUR NAME
  user.email=YOUR@EMAIL
git config --list --local | grep user
  user.name=YOUR NAME
  user.email=

If so, remove them

git config --unset --local user.name
git config --unset --local user.email

The local settings are per-clone, so you'll have to unset the local user.name and user.email for each of the repos on your machine.

Change the column label? e.g.: change column "A" to column "Name"

If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok

How to configure custom PYTHONPATH with VM and PyCharm?

In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.

Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.

See e.g. this SO question for more details on .pth files....

Java: how to use UrlConnection to post request with authorization?

To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me

Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback

BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work. Inside my servlet to do GET using url like e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked

Thanks to all contributors

        URL url = new URL(httpurl);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("client_id", id);
        params.put("client_secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", redirect);
        params.put("code", code);  // your INSTAGRAM code received 
        Set set = params.entrySet();
        Iterator i = set.iterator();
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        reader.close();
        conn.disconnect();
        System.out.println("INSTAGRAM token returned: "+builder.toString());

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

ImportError: No module named PIL

I had the same issue while importing PIL and further importing the ImageTk and Image modules. I also tried installing PIL directly through pip. but not success could be achieved. As in between it has been suggested that PIL has been deprectaed, thus, tried to install pillow through pip only. pillow was successfully installed, further, the PIL package was made under the path : python27/Lib/site-packages/.

Now both Image and ImageTk could be imported.

Environment variable substitution in sed

In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).

So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.

sed 's/foo/$BAR/g'
sed "s/foo/$BAR/g"

In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.

How to get the top 10 values in postgresql?

For this you can use limit

select *
from scores
order by score desc
limit 10

If performance is important (when is it not ;-) look for an index on score.


Starting with version 8.4, you can also use the standard (SQL:2008) fetch first

select *
from scores
order by score desc
fetch first 10 rows only

As @Raphvanns pointed out, this will give you the first 10 rows literally. To remove duplicate values, you have to select distinct rows, e.g.

select distinct *
from scores
order by score desc
fetch first 10 rows only

SQL Fiddle

Delaying a jquery script until everything else has loaded

From here:

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

// Check if jQuery's loaded 
function GM_wait() 
{ 
    if(typeof unsafeWindow.jQuery == 'undefined') 
    { 
        window.setTimeout(GM_wait,100); 
    } 
    else 
    { 
        $ = unsafeWindow.jQuery; 
        letsJQuery(); 
    } 
} 

GM_wait(); 

// All your GM code must be inside this function 
function letsJQuery() 
{
    // Do your jQuery stuff in here    
} 

This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.

For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:

<script type="text/javascript" language="JavaScript"> 
    function js(url){
        s = document.createElement("script");
        s.type = "text/javascript";
        s.src = url;
        document.getElementsByTagName("head")[0].appendChild(s);
    }       

    js("/js/jquery-ui.js");
    js("/js/jrails.js");
    js("/js/jquery.jgrowl-min.js");
    js("/js/jquery.scrollTo-min.js");
    js("/js/jquery.corner-min.js");
    js("/js/jquery.cookie-min.js");
    js("/js/application-min.js");

    function JS_wait() {
        if (typeof $.cookie == 'undefined' || // set in jquery.cookie-min.js
            typeof getLastViewedAnchor == 'undefined' || // set in application-min.js
            typeof getLastViewedArchive == 'undefined' || // set in application-min.js 
            typeof getAntiSpamValue == 'undefined') // set in application-min.js
        { 
            window.setTimeout(JS_wait, 100); 
        }
        else 
        { 
            JS_ready(); 
        }
    }

    function JS_ready() {
        // snipped
    };

    $(document).ready(JS_wait);
</script> 

Can't find out where does a node.js app running and can't kill it

If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.

I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID] command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.

How to copy a dictionary and only edit the copy

When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copy

dict2 = copy.deepcopy(dict1)

Proper usage of Optional.ifPresent()

Why write complicated code when you could make it simple?

Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...

if (user.isPresent())
{
    doSomethingWithUser(user.get());
}

This code has the advantages of being

  1. readable
  2. easy to debug (breakpoint)
  3. not tricky

Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.

How to scroll to bottom in react?

thank you 'metakermit' for his good answer, but I think we can make it a bit better, for scroll to bottom, we should use this:

scrollToBottom = () => {
   this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
}

but if you want to scroll top, you should use this:

scrollToTop = () => {
   this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
}   

and this codes are common:

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}


render () {
  return (
    <div>
      <div className="MessageContainer" >
        <div className="MessagesList">
          {this.renderMessages()}
        </div>
        <div style={{ float:"left", clear: "both" }}
             ref={(el) => { this.messagesEnd = el; }}>
        </div>
      </div>
    </div>
  );
}

Loop through checkboxes and count each one checked or unchecked

To build a result string exactly in the format you show, you can use this:

var sList = "";
$('input[type=checkbox]').each(function () {
    sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
});
console.log (sList);

However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.

EDIT: Sorry, I mis-read the output format you were looking for. Here is an update:

var sList = "";
$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? "1" : "0");
    sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);

Redirect output of mongo query to a csv file

I use the following technique. It makes it easy to keep the column names in sync with the content:

var cursor = db.getCollection('Employees.Details').find({})

var header = []
var rows = []

var firstRow = true
cursor.forEach((doc) => 
{
    var cells = []
    
    if (firstRow) header.push("employee_number")
    cells.push(doc.EmpNum.valueOf())

    if (firstRow) header.push("name")
    cells.push(doc.FullName.valueOf())    

    if (firstRow) header.push("dob")
    cells.push(doc.DateOfBirth.valueOf())   
    
    row = cells.join(',')
    rows.push(row)    

    firstRow =  false
})

print(header.join(','))
print(rows.join('\n'))

Command to get nth line of STDOUT

Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:

set -o pipefail                        # cf. help set
time -p ls -l | sed -n -e '2{p;q;}'    # only print the second line & quit (on Mac OS X)
echo "$?: ${PIPESTATUS[*]}"            # cf. man bash | less -p 'PIPESTATUS'

How to clear mysql screen console in windows?

Click with contextMenu button on Mysql prompt and choose "Scroll", because I didn't find any way to clean too. =P

Check if one list contains element from the other

Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

How to find day of week in php in a specific timezone

I think this is the correct answer, just change Europe/Stockholm to the users time-zone.

$dateTime = new \DateTime(
    'now',
    new \DateTimeZone('Europe/Stockholm')
);
$day = $dateTime->format('N');

ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)

http://php.net/manual/en/function.date.php

For a list of supported time-zones, see http://php.net/manual/en/timezones.php

Pan & Zoom Image

One addition to the superb solution provided by @Wieslaw Šoltés answer above

The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (child != null)
        {
            var tt = GetTranslateTransform(child);
            start = e.GetPosition(this);
            origin = new Point(tt.X, tt.Y);
            this.Cursor = Cursors.Hand;
            child.CaptureMouse();
        }
    }

With this:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
        {
            if (child != null)
            {
                var tt = GetTranslateTransform(child);
                start = e.GetPosition(this);
                origin = new Point(tt.X, tt.Y);
                this.Cursor = Cursors.Hand;
                child.CaptureMouse();
            }
        }

        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
        {
            this.Reset();
        }
    }

Creating a .dll file in C#.Net

You need to make a class library and not a Console Application. The console application is translated into an .exe whereas the class library will then be compiled into a dll which you can reference in your windows project.

  • Right click on your Console Application -> Properties -> Change the Output type to Class Library

enter image description here

MySQL OPTIMIZE all tables?

You can optimize/check and repair all the tables of database, using mysql client.

First, you should get all the tables list, separated with ',':

mysql -u[USERNAME] -p[PASSWORD] -Bse 'show tables' [DB_NAME]|xargs|perl -pe 's/ /,/g'

Now, when you have all the tables list for optimization:

mysql -u[USERNAME] -p[PASSWORD] -Bse 'optimize tables [tables list]' [DB_NAME]

Using 'make' on OS X

There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:

  • GCC
  • LLVM
  • Clang
  • Developer CLI Tools (purge, make, etc)
  • DevSDK (headers, etc)

The download is 282MB vs 3GB for Xcode.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.

Decoding the bytes while adding to the list should work. The changed code should look as follows:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

>>> s=bytes('hello')
>>> type(s)
<type 'str'>

Can anyone recommend a simple Java web-app framework?

try Wavemaker http://wavemaker.com Free, easy to use. The learning curve to build great-looking Java applications with WaveMaker isjust a few weeks!

Powershell script to locate specific file/file name?

From a powershell prompt, use the gci cmdlet (alias for Get-ChildItem) and -filter option:

gci -recurse -filter "hosts"

This will return an exact match to filename "hosts".


SteveMustafa points out with current versions of powershell you can use the -File switch to give the following to recursively search for only files named "hosts" (and not directories or other miscellaneous file-system entities):

gci -recurse -filter "hosts" -File 


The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.".

If you want to avoid the error messages then set the -ErrorAction to be silent.

gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue


An additional helper is that you can set the root to search from using -Path. The resulting command to search explicitly search from, for example, the root of the C drive would be

gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

How do I get elapsed time in milliseconds in Ruby?

DateTime.now.strftime("%Q")

Example usage:

>> DateTime.now.strftime("%Q")
=> "1541433332357"

>> DateTime.now.strftime("%Q").to_i
=> 1541433332357

What's the difference between size_t and int in C++?

The size_t type is defined as the unsigned integral type of the sizeof operator. In the real world, you will often see int defined as 32 bits (for backward compatibility) but size_t defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int is also 64-bits, this is called the LP64 convention; if long int is 32 bits but long long int and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int is signed and size_t is unsigned.

There were historically a number of other platforms where addresses were wider or shorter than the native size of int. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.

Any time int is smaller than size_t, and you try to store the size or offset of a very large file or object in an unsigned int, there is the possibility that it could overflow and cause a bug. With an int, there is also the possibility of getting a negative number. If an int or unsigned int is wider, the program will run correctly but waste memory.

You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3). For that purpose, the standard library defines ptrdiff_t in <stddef.h> as the signed type of the result of subtracting a pointer from another.

That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX and either 0 or INT_MIN as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.

ORA-00060: deadlock detected while waiting for resource

I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.

How to turn off gcc compiler optimization to enable buffer overflow

You don't need to disable ASLR in order to do a buffer overflow! Although ASLR is enabled (kernel_randomize_va_space = 2), it will not take effect unless the compiled executable is PIE. So unless you compiled your file with -fPIC -pie flag, ASLR will not take effect.

I think only disabling the canaries with -fno-stack-protector is enough. If you want to check if ASLR is working or not (Position independent code must be set), use:

hardening-check executable_name

How can I change the thickness of my <hr> tag

I believe the best achievement for styling <hr> tag is as follow:

hr {
color:#ddd;
background-color:
#ddd; height:1px;
border:none;
max-width:100%;
}

And for the HTML code just add: <hr>.

Regex replace uppercase with lowercase letters

In BBEdit works this (ex.: changing the ID values to lowercase):

Search any value: <a id="(?P<x>.*?)"></a> Replace with the same in lowercase: <a id="\L\P<x>\E"></a>

Was: <a id="VALUE"></a> Became: <a id="value"></a>

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

CSS background-image - What is the correct usage?

You don't need to use quotes and you can use any path you like!

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

Submit form on pressing Enter with AngularJS

Use ng-submit and just wrap both inputs in separate form tags:

<div ng-controller="mycontroller">

  <form ng-submit="myFunc()">
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
  </form>

  <br />

  <form ng-submit="myFunc()">
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
  </form>

</div>

Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.

Lombok annotations do not compile under Intellij idea

IDEA 2016.1:

  • Install lombok plugin
  • Settings -> Compiler -> Annotation Processors -> Enable annotation processing: checked (default configuration)
  • Settings -> Compiler -> Annotation Processors -> Annotation Processors add "lombok.launch.AnnotationProcessorHider$AnnotationProcessor"
  • Also if you are using maven add to maven-compiler-plugin configuration -> annotationProcessors -> annotationProcessor: lombok.launch.AnnotationProcessorHider$AnnotationProcessor

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>${maven.plugin.compiler.version}</version>
      <configuration>
        <compilerVersion>${java.version}</compilerVersion>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <annotationProcessors>
          <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
        </annotationProcessors>
      </configuration>
    </plugin>
    

Create random list of integers in Python

Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

You could use

[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]

to generate 10,000 numbers in the range using sample 10 times.

(Of course this won't beat NumPy.)

$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop

$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
100 loops, best of 3: 9.24 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop

$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
>   a = range(x)
>   shuffle(a)
>   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop

$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop

But since you don't care about the distribution of numbers, why not just use:

range(1000)*(10000/1000)

?

Export to CSV using jQuery and html

From what I understand, you have your data on a table and you want to create the CSV from that data. However, you have problem creating the CSV.

My thoughts would be to iterate and parse the contents of the table and generate a string from the parsed data. You can check How to convert JSON to CSV format and store in a variable for an example. You are using jQuery in your example so that would not count as an external plugin. Then, you just have to serve the resulting string using window.open and use application/octetstream as suggested.

How to access to the parent object in c#

Why not change the constructor on Production to let you pass in a reference at construction time:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

libpthread.so.0: error adding symbols: DSO missing from command line

I also encountered same problem. I do not know why, i just add -lpthread option to compiler and everything ok.

Old:

$ g++ -rdynamic -m64 -fPIE -pie  -o /tmp/node/out/Release/mksnapshot ...*.o *.a -ldl -lrt

got following error. If i append -lpthread option to above command then OK.

/usr/bin/ld: /tmp/node/out/Release/obj.host/v8_libbase/deps/v8/src/base/platform/condition-variable.o: undefined reference to symbol 'pthread_condattr_setclock@@GLIBC_2.3.3'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

What does PermGen actually stand for?

PermGen stands for Permanent Generation.

Here is a brief blurb on DDJ

How to find and turn on USB debugging mode on Nexus 4

Step 1 : Go to Settings >> About Phone >> scroll to the bottom >> tap Build number seven times; this message will appear “You are now 3 steps away from being a developer.”

Step 2 : Now go to Settings >> Developer Options >> Check USB Debugging

this is great article will help you to enable this mode on your phone

Enable USB Debugging Mode on Android

How to validate a credit card number

http://www.w3resource.com/javascript/form/credit-card-validation.php + the Luhn algorithm:

var checkLuhn = function (cardNo) {
    var s = 0;
    var doubleDigit = false;
    for (var i = cardNo.length - 1; i >= 0; i--) {
        var digit = +cardNo[i];
        if (doubleDigit) {
            digit *= 2;
            if (digit > 9)
                digit -= 9;
        }
        s += digit;
        doubleDigit = !doubleDigit;
    }
    return s % 10 == 0;
}

P.S.: Do not use regex for this, as it is done by the link. But it is useful to use text definitions of each card. Here it is:

American Express: Starting with 34 or 37, length 15 digits.

Visa: Starting with 4, length 13 or 16 digits.

MasterCard: Starting with 51 through 55, length 16 digits.

Discover: Starting with 6011, length 16 digits or starting with 5, length 15 digits.

Diners Club: Starting with 300 through 305, 36, or 38, length 14 digits.

JCB: Starting with 2131 or 1800, length 15 digits or starting with 35, length 16 digits.

I have it done like this:

var validateCardNo = function (no) {
    return (no && checkLuhn(no) &&
        no.length == 16 && (no[0] == 4 || no[0] == 5 && no[1] >= 1 && no[1] <= 5 ||
        (no.indexOf("6011") == 0 || no.indexOf("65") == 0)) ||
        no.length == 15 && (no.indexOf("34") == 0 || no.indexOf("37") == 0) ||
        no.length == 13 && no[0] == 4)
}

Spring @PropertySource using YAML

Spring-boot has a helper for this, just add

@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)

at the top of your test classes or an abstract test superclass.

Edit: I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):

@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
        initializers=[ConfigFileApplicationContextInitializer::class]
)

is added to the top, then

    @Configuration
    open class TestConfig {

        @Bean
        open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
            return PropertySourcesPlaceholderConfigurer()
        }
    }

to the context.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

I got the same message. After looking for a code related source it got to me that running the application on a local machine interferes with the dev stage, because the share the same DB. So sometimes one server has deleted an entry already while the other just wanted to do the same.

Skip certain tables with mysqldump

You can use the --ignore-table option. So you could do

mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql

There is no whitespace after -p (this is not a typo).

To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.

If you want an alternative way to ignore multiple tables you can use a script like this:

#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN   
)
 
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}

How to load html string in a webview?

I had the same requirement and I have done this in following way.You also can try out this..

Use loadData method

web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

movDirector movProducer like all are my string variable.

In short i retain custom styling for my url.

Excel CSV - Number cell format

This works for Microsoft Office 2010, Excel Version 14

I misread the OP's preference "to do something to the file itself." I'm still keeping this for those who want a solution to format the import directly

  1. Open a blank (new) file (File -> New from workbook)
  2. Open the Import Wizard (Data -> From Text)
  3. Select your .csv file and Import
  4. In the dialogue box, choose 'Delimited', and click Next.
  5. Choose your delimiters (uncheck everything but 'comma'), choose your Text qualifiers (likely {None}), click Next
  6. In the Data preview field select the column you want to be text. It should highlight.
  7. In the Column data format field, select 'Text'.
  8. Click finished.

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

Position: absolute and parent height?

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array

E.g.:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

VB.NET - How to move to next item a For Each Loop?

I'd use the Continue statement instead:

For Each I As Item In Items

    If I = x Then
        Continue For
    End If

    ' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

PostgreSQL - max number of parameters in "IN" clause?

If you have query like:

SELECT * FROM user WHERE id IN (1, 2, 3, 4 -- and thousands of another keys)

you may increase performace if rewrite your query like:

SELECT * FROM user WHERE id = ANY(VALUES (1), (2), (3), (4) -- and thousands of another keys)

Connecting to a network folder with username/password in Powershell

PowerShell 3 supports this out of the box now.

If you're stuck on PowerShell 2, you basically have to use the legacy net use command (as suggested earlier).

Removing character in list of strings

Try this:

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s 

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Inserting the same value multiple times when formatting a string

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

Fragment transaction animation: slide in and slide out

This is another solution which I use:

public class CustomAnimator {
    private static final String TAG = "com.example.CustomAnimator";

    private static Stack<AnimationEntry> animation_stack    = new Stack<>();

    public static final int                 DIRECTION_LEFT  = 1;
    public static final int                 DIRECTION_RIGHT = -1;
    public static final int                 DIRECTION_UP    = 2;
    public static final int                 DIRECTION_DOWN  = -2;

    static class AnimationEntry {
        View in;
        View    out;
        int     direction;
        long    duration;
    }

    public static boolean hasHistory() {
        return !animation_stack.empty();
    }

    public static void reversePrevious() {
        if (!animation_stack.empty()) {
            AnimationEntry entry = animation_stack.pop();
            slide(entry.out, entry.in, -entry.direction, entry.duration, false);
        }
    }

    public static void clearHistory() {
        animation_stack.clear();
    }

    public static void slide(final View in, View out, final int direction, long duration) {
        slide(in, out, direction, duration, true);
    }

    private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {

        ViewGroup in_parent = (ViewGroup) in.getParent();
        ViewGroup out_parent = (ViewGroup) out.getParent();

        if (!in_parent.equals(out_parent)) {
            return;
        }

        int parent_width = in_parent.getWidth();
        int parent_height = in_parent.getHeight();

        ObjectAnimator slide_out;
        ObjectAnimator slide_in;

        switch (direction) {
            case DIRECTION_LEFT:
            default:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
                break;
            case DIRECTION_RIGHT:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
                break;
            case DIRECTION_UP:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
                break;
            case DIRECTION_DOWN:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
                break;
        }

        AnimatorSet animations = new AnimatorSet();
        animations.setDuration(duration);
        animations.playTogether(slide_in, slide_out);
        animations.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                out.setVisibility(View.INVISIBLE);
                if (save) {
                    AnimationEntry ae = new AnimationEntry();
                    ae.in = in;
                    ae.out = out;
                    ae.direction = direction;
                    ae.duration = duration;
                    animation_stack.push(ae);
                }
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {
                in.setVisibility(View.VISIBLE);
            }
        });
        animations.start();
    }
}

The usage of class. Let's say you have two fragments (list and details fragments)as shown below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/list_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/details_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</FrameLayout>

Usage

View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);

You can use the function CustomAnimator.reversePrevious();to get the previous view when the user pressed back.

What is the App_Data folder used for in Visual Studio?

It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How do you round a number to two decimal places in C#?

One thing you may want to check is the Rounding Mechanism of Math.Round:

http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

Java generics - get class?

I'm not 100% sure if this works in all cases (needs at least Java 1.5):

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main 
{
    public class A
    {   
    }

    public class B extends A
    {       
    }


    public Map<A, B> map = new HashMap<Main.A, Main.B>();

    public static void main(String[] args) 
    {

        try
        {
            Field field = Main.class.getField("map");           
            System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());

            Type genericType = field.getGenericType();

            if(genericType instanceof ParameterizedType)
            {
                ParameterizedType type = (ParameterizedType) genericType;               
                Type[] typeArguments = type.getActualTypeArguments();

                for(Type typeArgument : typeArguments) 
                {   
                    Class<?> classType = ((Class<?>)typeArgument);                  
                    System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }    
}

This will output:

Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B

GET and POST methods with the same Action name in the same Controller

You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:

    public ActionResult Index(int i)
    {
        Some Code--Some Code---Some Code
        return View();
    }

There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:

  [GET("Resources")]
  public ActionResult Index()
  {
      return View();
  }

  [POST("Resources")]
  public ActionResult Create()
  {
      return RedirectToAction("Index");
  }

In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.

The package can be installed using NuGet like this:

PM> Install-Package AttributeRouting

If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

In Windows 10 preview build with PowerShell 5, I can see that you can do:

$info = Get-Package -Name YourInstalledProduct
$info.Metadata["ProductCode"]

Not familiar with even not sure if all products has UpgradeCode, but according to this post you need to search UpgradeCode from this registry path:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes

Unfortunately, the registry key values are the ProductCode and the registry keys are the UpgradeCode.

"The page has expired due to inactivity" - Laravel 5.5

Solution:

use incognito new tab then test it again.

reason:

in my case another user logged in with my admin panel

Last Key in Python Dictionary

There's a definite need to get the last element of a dictionary, for example to confirm whether the latest element has been appended to the dictionary object or not.

We need to convert the dictionary keys to a list object, and use an index of -1 to print out the last element.

mydict = {'John':'apple','Mat':'orange','Jane':'guava','Kim':'apple','Kate': 'grapes'}

mydict.keys()

output: dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])

list(mydict.keys())

output: ['John', 'Mat', 'Jane', 'Kim', 'Kate']

list(mydict.keys())[-1]

output: 'Kate'

Resize image proportionally with CSS?

To resize the image proportionally using CSS:

img.resize {
    width:540px; /* you can use % */
    height: auto;
}

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I had this issue when I added react-router-dom to the new CRA app using typescript. After I added @types/react-router, the issue was fixed.

How to get Linux console window width in Python

Try "blessings"

I was looking for the very same thing. It is very easy to use and offers tools for coloring, styling and positioning in the terminal. What you need is as easy as:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

Works like a charm in Linux. (I'm not sure about MacOSX and Windows)

Download and documentation here

or you can install it with pip:

pip install blessings

Measuring execution time of a function in C++

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from <chrono> header.

Use it like so:

#include <iostream>
#include <chrono>

void function()
{
    long long number = 0;

    for( long long i = 0; i != 2000000; ++i )
    {
       number += 5;
    }
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration;
    return 0;
}

This will measure the duration of the function.

NOTE: You will not always get the same timing for a function. This is because the CPU of your machine can be less or more used by other processes running on your computer, just as your mind can be more or less concentrated when you solve a math exercise. In the human mind, we can remember the solution of a math problem, but for a computer the same process will always be something new; thus, as I said, you will not always get the same result!

Find document with array that contains a specific value

I know this topic is old, but for future people who could wonder the same question, another incredibly inefficient solution could be to do:

PersonModel.find({$where : 'this.favouriteFoods.indexOf("sushi") != -1'});

This avoids all optimisations by MongoDB so do not use in production code.

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

How to find/identify large commits in git history?

A blazingly fast shell one-liner

This shell script displays all blob objects in the repository, sorted from smallest to largest.

For my sample repo, it ran about 100 times faster than the other ones found here.
On my trusty Athlon II X4 system, it handles the Linux Kernel repository with its 5.6 million objects in just over a minute.

The Base Script

git rev-list --objects --all |
  git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' |
  sed -n 's/^blob //p' |
  sort --numeric-sort --key=2 |
  cut -c 1-12,41- |
  $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest

When you run above code, you will get nice human-readable output like this:

...
0d99bb931299  530KiB path/to/some-image.jpg
2ba44098e28f   12MiB path/to/hires-image.png
bd1741ddce0d   63MiB path/to/some-video-1080p.mp4

macOS users: Since numfmt is not available on macOS, you can either omit the last line and deal with raw byte sizes or brew install coreutils.

Filtering

To achieve further filtering, insert any of the following lines before the sort line.

To exclude files that are present in HEAD, insert the following line:

grep -vF --file=<(git ls-tree -r HEAD | awk '{print $3}') |

To show only files exceeding given size (e.g. 1 MiB = 220 B), insert the following line:

awk '$2 >= 2^20' |

Output for Computers

To generate output that's more suitable for further processing by computers, omit the last two lines of the base script. They do all the formatting. This will leave you with something like this:

...
0d99bb93129939b72069df14af0d0dbda7eb6dba 542455 path/to/some-image.jpg
2ba44098e28f8f66bac5e21210c2774085d2319b 12446815 path/to/hires-image.png
bd1741ddce0d07b72ccf69ed281e09bf8a2d0b2f 65183843 path/to/some-video-1080p.mp4

File Removal

For the actual file removal, check out this SO question on the topic.

libstdc++-6.dll not found

I use Eclipse under Fedora 20 with MinGW for cross compile. Use these settings and the program won't ask for libstdc++-6.dll any more.

Project type - Cross GCC

Cross Settings

  • Prefix: x86_64-w64-mingw32-
  • Path: /usr/bin

Cross GCC Compiler

  • Command: gcc

  • All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0

  • Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include

Cross G++ Compiler

  • Command: g++

  • All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0

  • Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include

Cross G++ Linker

  • Command: g++ -static-libstdc++ -static-libgcc

  • All Options: -L/usr/x86_64-w64-mingw32/sys-root/mingw/lib -L/usr/x86_64-w64-mingw32/sys-root/mingw/bin

  • Library search path (-L):

    /usr/x86_64-w64-mingw32/sys-root/mingw/lib

    /usr/x86_64-w64-mingw32/sys-root/mingw/bin

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The IIS inbound rules as shown in the question DO work. I had to clear the browser cache and add the following line in the top of my <head> section of the index.html page:

<base href="/myApplication/app/" />

This is because I have more than one application in localhost and so requests to other partials were being taken to localhost/app/view1 instead of localhost/myApplication/app/view1

Hopefully this helps someone!

How do I download/extract font from chrome developers tools?

Right-click, then "Open link in new tab"

edit : you can also double-click, it has the same effect

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

All other answers may answer your query, but I faced same issue which was due to stray , which I added at the end of my json string like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf",
}

I finally got it working when I removed extra , like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf"
}

Hope this help! cheers.

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

How permission can be checked at runtime without throwing SecurityException?

You can use Context.checkCallingorSelfPermission() function for this. Here is an example:

private boolean checkWriteExternalPermission()
{
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);            
}

How to implement a material design circular progress bar in android

With the Material Components library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
      android:indeterminate="true"          
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:indicatorColor="@array/progress_colors"
      app:indicatorSize="xxdp"
      app:showAnimationBehavior="inward"/>

where array/progress_colors is an array with the colors:

  <integer-array name="progress_colors">
    <item>@color/yellow_500</item>
    <item>@color/blue_700</item>
    <item>@color/red_500</item>
  </integer-array>

enter image description here

Note: it requires at least the version 1.3.0

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Refer to a cell in another worksheet by referencing the current worksheet's name?

Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:

=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))

Then you will have the 'Jan Item'!J3 value.

String comparison in Python: is vs. ==

See This question

Your logic in reading

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

is slightly flawed.

If is applies then == will be True, but it does NOT apply in reverse. == may yield True while is yields False.

MySQL vs MySQLi when using PHP

for me, prepared statements is a must-have feature. more exactly, parameter binding (which only works on prepared statements). it's the only really sane way to insert strings into SQL commands. i really don't trust the 'escaping' functions. the DB connection is a binary protocol, why use an ASCII-limited sub-protocol for parameters?

SQL Server Group By Month

Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.

SELECT 
      SUM( case when DateDiff(m, PaymentDate, @start) = 0 
           then Amount else 0 end ) AS "Apr",
      SUM( case when DateDiff(m, PaymentDate, @start) = 1 
           then Amount else 0 end ) AS "May",
      SUM( case when DateDiff(m, PaymentDate, @start) = 2 
           then Amount else 0 end ) AS "June",
      SUM( case when DateDiff(m, PaymentDate, @start) = 3 
           then Amount else 0 end ) AS "July",
      SUM( case when DateDiff(m, PaymentDate, @start) = 4 
           then Amount else 0 end ) AS "Aug",
      SUM( case when DateDiff(m, PaymentDate, @start) = 5 
           then Amount else 0 end ) AS "Sep",
      SUM( case when DateDiff(m, PaymentDate, @start) = 6 
           then Amount else 0 end ) AS "Oct",
      SUM( case when DateDiff(m, PaymentDate, @start) = 7 
           then Amount else 0 end ) AS "Nov",
      SUM( case when DateDiff(m, PaymentDate, @start) = 8 
           then Amount else 0 end ) AS "Dec",
      SUM( case when DateDiff(m, PaymentDate, @start) = 9 
           then Amount else 0 end ) AS "Jan",
      SUM( case when DateDiff(m, PaymentDate, @start) = 10 
           then Amount else 0 end ) AS "Feb",
      SUM( case when DateDiff(m, PaymentDate, @start) = 11 
           then Amount else 0 end ) AS "Mar"
   FROM 
      Payments I
         JOIN Live L
            on I.LiveID = L.Record_Key
   WHERE 
          Year = 2010 
      AND UserID = 100

How to download a Nuget package without nuget.exe or Visual Studio extension?

I haven't tried it yet, but it looks like NuGet Package Explorer should be able to do it:

https://github.com/NuGetPackageExplorer/NuGetPackageExplorer

NuGet Package Explorer

(or like Colonel Panic says, 7-zip should probably do it)

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

For mongo v3.6.3+ (or 2019 versions)

rm /var/lib/mongodb/mongod.lock
service mongodb restart

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

"Permission Denied" trying to run Python on Windows 10

As far as I can tell, this was caused by a conflict with the version of Python 3.7 that was recently added into the Windows Store. It looks like this added two "stubs" called python.exe and python3.exe into the %USERPROFILE%\AppData\Local\Microsoft\WindowsApps folder, and in my case, this was inserted before my existing Python executable's entry in the PATH.

Moving this entry below the correct Python folder (partially) corrected the issue.

The second part of correcting it is to type manage app execution aliases into the Windows search prompt and disable the store versions of Python altogether.

manage app execution aliases

It's possible that you'll only need to do the second part, but on my system I made both changes and everything is back to normal now.

How do I add a library project to Android Studio?

I also encountered the same problem then I did following things.

  1. I import the library project into my AndroidStudio IDE as a module using menu File -> Import module menus

  2. Then I went to my main module in which I want the library project as a dependent project

  3. Right click on the main module (in my case its name is app) -> open module setting -> go into dependencies tab -> click on + button (you will get it on right side of window) -> click on module dependency -> select your library project from list

Apply the changes and click the OK button.

It worked for me. I hope it will help others too.

"import datetime" v.s. "from datetime import datetime"

The difference between from datetime import datetime and normal import datetime is that , you are dealing with a module at one time and a class at other.

The strptime function only exists in the datetime class so you have to import the class with the module otherwise you have to specify datetime twice when calling this function.

The thing here is that , the class name and the module name has been given the same name so it creates a bit of confusuion.

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

Free FTP Library

I've just posted an article that presents both an FTP client class and an FTP user control.

They are simple and aren't very fast, but are very easy to use and all source code is included. Just drop the user control onto a form to allow users to navigate FTP directories from your application.

C: What is the difference between ++i and i++?

Here is the example to understand the difference

int i=10;
printf("%d %d",i++,++i);

output: 10 12/11 11 (depending on the order of evaluation of arguments to the printf function, which varies across compilers and architectures)

Explanation: i++->i is printed, and then increments. (Prints 10, but i will become 11) ++i->i value increments and prints the value. (Prints 12, and the value of i also 12)

How to use Comparator in Java to sort

Two corrections:

  1. You have to make an ArrayList of People objects:

    ArrayList<People> preps = new ArrayList<People>(); 
    
  2. After adding the objects to the preps, use:

    Collections.sort(preps, new CompareId());
    

Also, add a CompareId class as:

class CompareId implements Comparator {  
    public int compare(Object obj1, Object obj2) {  
        People t1 = (People)obj1;  
        People t2 = (People)obj2;  

        if (t1.marks > t2.marks)  
            return 1;   
        else  
            return -1;
    }  
}

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

How can I confirm a database is Oracle & what version it is using SQL?

This will work starting from Oracle 10

select version
      , regexp_substr(banner, '[^[:space:]]+', 1, 4) as edition 
from    v$instance
     ,  v$version where regexp_like(banner, 'edition', 'i');

How to replace a string in multiple files in linux command line

In case your string has a forward slash(/) in it, you could change the delimiter to '+'.

find . -type f -exec sed -i 's+http://example.com+https://example.com+g' {} +

This command would run recursively in the current directory.

Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How to Set AllowOverride all

If you are using Linux you may edit the code in the directory of

/etc/httpd/conf/httpd.conf

now, here find the code line kinda like

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride None
#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

Change the AllowOveride None to AllowOveride All

Now now you can set any kind of rule in your .httacess file inside your directories if any other operating system just try to find the file of httpd.conf and edit it.

Converting a date in MySQL from string field

Yes, there's str_to_date

mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03                           |
+--------------------------------------+
1 row in set (0.00 sec)

Adding Git-Bash to the new Windows Terminal

If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here

C:\Program Files\Git\mingw64\share\git\git-for-windows I copied it into.

%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

and named it git-bash_32px as suggested above.

Control the opacity with CTRL + SHIFT + scrolling.

        {
            "acrylicOpacity" : 0.75,
            "closeOnExit" : true,
            "colorScheme" : "Campbell",
            "commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l",
            "cursorColor" : "#FFFFFF",
            "cursorShape" : "bar",
            "fontFace" : "Consolas",
            "fontSize" : 10,
            "guid" : "{73225108-7633-47ae-80c1-5d00111ef646}",
            "historySize" : 9001,
            "icon" : "ms-appdata:///roaming/git-bash_32px.ico",
            "name" : "Bash",
            "padding" : "0, 0, 0, 0",
            "snapOnInput" : true,
            "startingDirectory" : "%USERPROFILE%",
            "useAcrylic" : true
        },

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Reading Xml with XmlReader in C#

We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account> element, after parsing the reader will index the </Accounts> closing tag.

The parsing code looks something like this:

public class Account
{
    string _accountId;
    string _nameOfKin;
    Statements _statmentsAvailable;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read node attributes
        _accountId = reader.GetAttribute( "accountId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                switch( reader.Name )
                {
                    // Read element for a property of this class
                    case "NameOfKin":
                        _nameOfKin = reader.ReadElementContentAsString();
                        break;

                    // Starting sub-list
                case "StatementsAvailable":
                    _statementsAvailable = new Statements();
                    _statementsAvailable.Read( reader );
                    break;

                    default:
                        reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }       
    }
}

The Statements class just reads in the <StatementsAvailable> node

public class Statements
{
    List<Statement> _statements = new List<Statement>();

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();
        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                if( reader.Name == "Statement" )
                {
                    var statement = new Statement();
                    statement.ReadFromXml( reader );
                    _statements.Add( statement );               
                }
                else
                {
                    reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }
    }
}

The Statement class would look very much the same

public class Statement
{
    string _satementId;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read noe attributes
        _statementId = reader.GetAttribute( "statementId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {           
            ....same basic loop
        }       
    }
}

Exit while loop by user hitting ENTER key

The exact thing you want ;)

https://stackoverflow.com/a/22391379/3394391

import sys, select, os

i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        break
    i += 1

Split string into array of character strings

To sum up the other answers...

This works on all Java versions:

"cat".split("(?!^)")

This only works on Java 8 and up:

"cat".split("")

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

PHP replacing special characters like à->a, è->e

Here is a way to have some flexibility in what should be discarded and what should be replaced. This is how I currently do it.

$string = 'À some string with junk I Ä ';

$replace = [
    '&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
    '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae',
    '&Auml;' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
    'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
    'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
    'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
    'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
    'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
    'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
    'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
    'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
    'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
    'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
    'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
    '?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
    '&Uuml;' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
    'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
    'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
    'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
    'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
    'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
    'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
    'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
    'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
    'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
    'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
    '?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
    '?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
    '&ouml;' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
    'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
    'û' => 'u', 'ü' => 'ue', 'u' => 'u', '&uuml;' => 'ue', 'u' => 'u', 'u' => 'u',
    'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
    'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
    '?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
    '?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
    '?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
    '?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
    '?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
    '?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
    '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
    '?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
    '?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
    '?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
    '?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
    '?' => 'yu', '?' => 'ya'
];

echo str_replace(array_keys($replace), $replace, $string);  

Angular/RxJs When should I unsubscribe from `Subscription`

--- Update Angular 9 and Rxjs 6 Solution

  1. Using unsubscribe at ngDestroy lifecycle of Angular Component
class SampleComponent implements OnInit, OnDestroy {
  private subscriptions: Subscription;
  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$.subscribe( ... );
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}
  1. Using takeUntil in Rxjs
class SampleComponent implements OnInit, OnDestroy {
  private unsubscribe$: new Subject<void>;
  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$
    .pipe(takeUntil(this.unsubscribe$))
    .subscribe( ... );
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}
  1. for some action that you call at ngOnInit that just happen only one time when component init.
class SampleComponent implements OnInit {

  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$
    .pipe(take(1))
    .subscribe( ... );
  }
}

We also have async pipe. But, this one use on the template (not in Angular component).

How to get a complete list of object's methods and attributes?

Here is a practical addition to the answers of PierreBdR and Moe:

  • For Python >= 2.6 and new-style classes, dir() seems to be enough.
  • For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir(), look for __class__, and then to go for its __bases__:

    # code borrowed from the rlcompleter module
    # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
    
    # or: from rlcompleter import get_class_members
    def get_class_members(klass):
        ret = dir(klass)
        if hasattr(klass,'__bases__'):
            for base in klass.__bases__:
                ret = ret + get_class_members(base)
        return ret
    
    
    def uniq( seq ): 
        """ the 'set()' way ( use dict when there's no set ) """
        return list(set(seq))
    
    
    def get_object_attrs( obj ):
        # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
        ret = dir( obj )
        ## if "__builtins__" in ret:
        ##    ret.remove("__builtins__")
    
        if hasattr( obj, '__class__'):
            ret.append('__class__')
            ret.extend( get_class_members(obj.__class__) )
    
            ret = uniq( ret )
    
        return ret
    

(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs() as for dir(), and for old-style classes the main addition to the dir() output seem to be the __class__ attribute.)

Skip rows during csv import pandas

You can try yourself:

>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
   0  1
0  1  2
1  5  6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
   0  1
0  3  4
1  5  6

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I tried this and it works without any issues to validate if the field is empty. I have answered your question partially as I haven't personally tried to add default values to attributes

if(field.getText()!= null && !field.getText().isEmpty())

Hope it helps

How do I install the babel-polyfill library?

Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.

So this worked for me:

npm install --save [email protected]
npm install regenerator-runtime

then add to the very top of your initial js file:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

How can I send the "&" (ampersand) character via AJAX?

You can use encodeURIComponent().

It will escape all the characters that cannot occur verbatim in URLs:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

In this example, the ampersand character & will be replaced by the escape sequence %26, which is valid in URLs.

try/catch blocks with async/await

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
  apiClient.getCurrentUser()
);

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

it is wrong. correct will be

P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these

Waiting Time (0+3+4+6+10)/5 = 4.6

Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf

Is there a way to word-wrap long words in a div?

You can try specifying a width for the div, whether it be in pixels, percentages or ems, and at that point the div will remain that width and the text will wrap automatically then within the div.

Combine Date and Time columns using python pandas

You can also convert to datetime without string concatenation, by combining datetime and timedelta objects. Combined with pd.DataFrame.pop, you can remove the source series simultaneously:

df['DateTime'] = pd.to_datetime(df.pop('Date')) + pd.to_timedelta(df.pop('Time'))

print(df)

             DateTime
0 2013-01-06 23:00:00
1 2013-02-06 01:00:00
2 2013-02-06 21:00:00
3 2013-02-06 22:00:00
4 2013-02-06 23:00:00
5 2013-03-06 01:00:00
6 2013-03-06 21:00:00
7 2013-03-06 22:00:00
8 2013-03-06 23:00:00
9 2013-04-06 01:00:00

print(df.dtypes)

DateTime    datetime64[ns]
dtype: object

Invalid default value for 'dateAdded'

I have mysql version 5.6.27 on my LEMP and CURRENT_TIMESTAMP as default value works fine.

How do you POST to a page using the PHP header() function?

The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.

May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.

To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.

How to clear a data grid view

You can assign the datasource as null of your data grid and then rebind it.

dg.DataSource = null;
dg.DataBind();

Why do we always prefer using parameters in SQL statements?

You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:

Her daughter is named Help I'm trapped in a driver's license factory.


In your example, if you just use:

var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query

You are open to SQL injection. For example, say someone enters txtSalary:

1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.

When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.


The correct way is to use parameterized queries, eg (C#):

SqlCommand query =  new SqlCommand("SELECT empSalary FROM employee 
                                    WHERE salary = @sal;");
query.Parameters.AddWithValue("@sal", txtSalary.Text);

With that, you can safely execute the query.

For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

How to use jQuery Plugin with Angular 4?

Yes you can use jquery with Angular 4

Steps:

1) In index.html put below line in tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

2) In component ts file below you have to declare var like this

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular 4 with jquery';
  toggleTitle(){
    $('.title').slideToggle(); //
  }

}

And use this code for corresponding html file like this:

<h1 class="title" style="display:none">
  {{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>

This will work for you. Thanks

How to add a button dynamically using jquery

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Convert String to Double - VB

The international versions:

    Public Shared Function GetDouble(ByVal doublestring As String) As Double
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
        Return retval
    End Function

    ' NULLABLE VERSION:
    Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
            Return retval
        Else
            Return Nothing
        End If
    End Function

Results:

        ' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)

        ' Clean Double.TryParse
        ' -------------------------------------------------
        Double.TryParse("1.12", d1)     ' Type: DOUBLE     Value: d1 = 0.0
        Double.TryParse("1,12", d2)     ' Type: DOUBLE     Value: d2 = 1.12
        Double.TryParse("abcd", d3)     ' Type: DOUBLE     Value: d3 = 0.0

        ' GetDouble() method
        ' -------------------------------------------------
        d1 = GetDouble("1.12")          ' Type: DOUBLE     Value: d1 = 1.12
        d2 = GetDouble("1,12")          ' Type: DOUBLE     Value: d2 = 1.12
        d3 = GetDouble("abcd")          ' Type: DOUBLE     Value: d3 = 0.0

        ' Nullable version - GetDoubleNullable() method
        ' -------------------------------------------------
        d1n = GetDoubleNullable("1.12") ' Type: DOUBLE?    Value: d1n = 1.12
        d2n = GetDoubleNullable("1,12") ' Type: DOUBLE?    Value: d2n = 1.12
        d3n = GetDoubleNullable("abcd") ' Type: DOUBLE?    Value: d3n = Nothing

How to use enums as flags in C++?

As above(Kai) or do the following. Really enums are "Enumerations", what you want to do is have a set, therefore you should really use stl::set

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

int main(void)
{
    AnimalFlags seahawk;
    //seahawk= CanFly | EatsFish | Endangered;
    seahawk= static_cast<AnimalFlags>(CanFly | EatsFish | Endangered);
}

How do I get the directory that a program is running from?

Boost Filesystem's initial_path() behaves like POSIX's getcwd(), and neither does what you want by itself, but appending argv[0] to either of them should do it.

You may note that the result is not always pretty--you may get things like /foo/bar/../../baz/a.out or /foo/bar//baz/a.out, but I believe that it always results in a valid path which names the executable (note that consecutive slashes in a path are collapsed to one).

I previously wrote a solution using envp (the third argument to main() which worked on Linux but didn't seem workable on Windows, so I'm essentially recommending the same solution as someone else did previously, but with the additional explanation of why it is actually correct even if the results are not pretty.

Intro to GPU programming

If you use MATLAB, it becomes pretty simple to use GPU's for technical computing (matrix computations and heavy math/number crunching). I find it useful for uses of GPU cards outside of gaming. Check out the link below:

http://www.mathworks.com/discovery/matlab-gpu.html

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

I have got the same issue when tried to get users information without auth.

Check if you have loggen in before any request.

 $uid = $facebook->getUser();

 if ($uid){
      $me = $facebook->api('/me');
 }

The code above should solve your issue.

How to iterate over a column vector in Matlab?

for i=1:length(list)
  elm = list(i);
  //do something with elm.

Reactjs - Form input validation

Try powerform-react . It is based upon powerform which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.

Checkout this simple form that uses powerform-react

There is also a complex example.

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

Twitter Bootstrap Datepicker within modal window

add z-index above 1051 in class datepicker

add something like this in page or css

<style>
.datepicker{z-index:1151 !important;}
</style>

Changing Underline color

Best way I came across doing is like this:

HTML5:

<p>Initial Colors <a id="new-color">Different Colors</a></p>

CSS3:

p {
    color: #000000;
    text-decoration-line: underline;
    text-decoration-color: #a11015;
}

p #new-color{
    color: #a11015;
    text-decoration-line: underline;
    text-decoration-color: #000000;
}

Fatal error: Call to undefined function mb_detect_encoding()

When I opened my php.ini file, "extension_dir" line looked like following :

extension_dir = "C:/wamp/bin/php/php5.4.16/ext/"

which i changed to:

extension_dir = "C:\wamp\bin\php\php5.4.16\ext\"

and it worked.

WPF Datagrid Get Selected Cell Value

Worked For me

object item = dgwLoadItems.SelectedItem;
string ID = (dgwLoadItems.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBox.Show(ID);

<hr> tag in Twitter Bootstrap not functioning correctly?

I think it would look better if we add border-color : transparent as per below:

<hr style="width: 100%; background-color: black; height: 1px; border-color : transparent;" />

If you don't put the border transparent it will be white and i don't think that is good all time.

lexical or preprocessor issue file not found occurs while archiving?

I know this is old, but I'm gonna chime in anyway because it may be useful to someone. If you can still see the file in Finder, then click on the file in your project and delete it, selecting "remove references" and not "move to trash".

Once the reference is removed, drag and drop the file from finder into your project again and it should sort itself out.

Change status bar color with AppCompat ActionBarActivity

Applying

    <item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

in Theme.AppCompat.Light.DarkActionBar didn't worked for me. What did the trick is , giving colorPrimaryDark as usual along with android:colorPrimary in styles.xml

<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>

and in setting

if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    Window window = this.Window;
                    Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                }

didn't had to set statusbar color in code .

Adding backslashes without escaping [Python]

There is no extra backslash, it's just formatted that way in the interactive environment. Try:

print string

Then you can see that there really is no extra backslash.

How to get selected value from Dropdown list in JavaScript

Direct value should work just fine:

var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

Get nth character of a string in Swift programming language

Best way which worked for me is:

var firstName = "Olivia"
var lastName = "Pope"

var nameInitials.text = "\(firstName.prefix(1))" + "\    (lastName.prefix(1))"

Output:"OP"

check if command was successful in a batch file

This likely doesn't work with start, as that starts a new window, but to answer your question:

If the command returns a error level you can check the following ways

By Specific Error Level

commandhere
if %errorlevel%==131 echo do something

By If Any Error

commandhere || echo what to do if error level ISN'T 0

By If No Error

commandhere && echo what to do if error level IS 0

If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)

By Parsing Full Output

for /f "tokens=* delims=" %%a in ('somecommand') do set output=%%a
if %output%==whateveritwouldsayinerror echo error

Or you could just look for a single phrase in the output like the word Error

By Checking For String

commandhere | find "Error" || echo There was no error!
commandhere | find "Error" && echo There was an error!

And you could even mix together (just remember to escape | with ^| if in a for statement)

Hope this helps.

Automatically pass $event with ng-click?

As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).

The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:

<clickable>
  <h1>Hello World!</h1>
</clickable>

Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):

app.directive('clickable', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div ng-transclude ng-click="handleClick($event)"></div>'
    };
});

Finally in my controller I have the click event ready to go:

$scope.handleClick = function($event) {
    var i = 0;
};

Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.

Hope that helps!

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to find minimum value from vector?

#include <iostream>
int main()
{
    int v[100] = {5,14,2,4,6};
    int n = 5;
    int mic = v[0];
    for(int i = 0; i != n; ++i)
    {
        if(v[i] < mic)
        mic = v[i];
    }
    std:cout << mic << std::endl;;
}

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

It has 3 solutions that other guys told upper... but when try Application_Start solution, My other jQuery library like Pickup_Date_and_Time doesn't work... so I test second way and it's answered: 1- set the Target FrameWork to Pre 4.5 2- Use " UnobtrusiveValidationMode="None" " in your page header =>

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Master/MasteOfHotel.Master" 
    UnobtrusiveValidationMode="None" %>

it works for me and doesn't disrupt my other jQuery function.

Number prime test in JavaScript

You can try this one

_x000D_
_x000D_
function isPrime(num){_x000D_
    _x000D_
    // Less than or equal to 1 are not prime_x000D_
    if (num<=1) return false;_x000D_
    _x000D_
    // 2 and 3 are prime, so no calculations_x000D_
    if (num==2 || num==3 ) return true; _x000D_
    _x000D_
    // If mod with square root is zero then its not prime _x000D_
    if (num % Math.sqrt(num)==0 ) return false;_x000D_
    _x000D_
    // Run loop till square root_x000D_
    for(let i = 2, sqrt = Math.sqrt(num); i <= sqrt; i++) {_x000D_
    _x000D_
        // If mod is zero then its not prime_x000D_
        if(num % i === 0) return false; _x000D_
    }_x000D_
    _x000D_
    // Otherwise the number is prime_x000D_
    return true;_x000D_
   }_x000D_
   _x000D_
   _x000D_
   for(let i=-2; i <= 35; i++) { _x000D_
    console.log(`${i} is${isPrime(i) ? '' : ' not'} prime`);_x000D_
   }
_x000D_
_x000D_
_x000D_