Programs & Examples On #Gdbserver

GDB remote application debugging through gdbserver

Check string length in PHP

[0]=> string(141) means that $message is an array, not string, and $message[0] is a string with 141 characters in length.

libstdc++-6.dll not found

useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"

4 ways to solve it

  1. Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)

  2. Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.

  3. Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.

  4. Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)

Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'

Basic HTTP and Bearer Token Authentication

Standard (https://tools.ietf.org/html/rfc6750) says you can use:

  • Form-Encoded Body Parameter: Authorization: Bearer mytoken123
  • URI Query Parameter: access_token=mytoken123

So it's possible to pass many Bearer Token with URI, but doing this is discouraged (see section 5 in the standard).

In AVD emulator how to see sdcard folder? and Install apk to AVD?

DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

call javascript function onchange event of dropdown list

You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to set Oracle's Java as the default Java in Ubuntu?

If you want this environment variable available to all users and on system start then you can add the following to /etc/profile.d/java.sh (create it if necessary):

export JDK_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME=/usr/lib/jvm/java-7-oracle

Then in a terminal run:

sudo chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh

My second question is - should it point to java-6-sun or java-6-sun-1.6.0.24 ?

It should always point to java-7-oracle as that symlinks to the latest installed one (assuming you installed Java from the Ubuntu repositories and now from the download available at oracle.com).

Overlapping Views in Android

Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

Hiding elements in responsive layout?

Bootstrap 4 Beta Answer:

d-block d-md-none to hide on medium, large and extra large devices.

d-none d-md-block to hide on small and extra-small devices.

enter image description here

Note that you can also inline by replacing d-*-block with d-*-inline-block


Old answer: Bootstrap 4 Alpha

  • You can use the classes .hidden-*-up to hide on a given size and larger devices

    .hidden-md-up to hide on medium, large and extra large devices.

  • The same goes with .hidden-*-down to hide on a given size and smaller devices

    .hidden-md-down to hide on medium, small and extra-small devices

  • visible-* is no longer an option with bootstrap 4

  • To display only on medium devices, you can combine the two:

    hidden-sm-down and hidden-xl-up

The valid sizes are:

  • xs for phones in portrait mode (<34em)
  • sm for phones in landscape mode (=34em)
  • md for tablets (=48em)
  • lg for desktops (=62em)
  • xl for desktops (=75em)

This was as of Bootstrap 4, alpha 5 (January 2017). More details here: http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

On Bootstrap 4.3.x: https://getbootstrap.com/docs/4.3/utilities/display/

Split string on the first white space occurrence

Late to the game, I know but there seems to be a very simple way to do this:

_x000D_
_x000D_
const str = "72 tocirah sneab";_x000D_
const arr = str.split(/ (.*)/);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

This will leave arr[0] with "72" and arr[1] with "tocirah sneab". Note that arr[2] will be empty, but you can just ignore it.

For reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses

How to delete SQLite database from Android programmatically

context.deleteDatabase(DATABASE_NAME); will delete the database only if all the connections are closed. If you are maintaining singleton instance for handling your database helper - it is easy to close the opened Connection.

Incase the databasehelper is used in multiple place by instantiating directly, the deleteDatabase + killProcess will do the job even if some connections are open. This can be used if the application scenario doesn't have any issues in restarting the app.

The pipe ' ' could not be found angular2 custom pipe

Note : Only if you are not using angular modules

For some reason this is not in the docs but I had to import the custom pipe in the component

import {UsersPipe} from './users-filter.pipe'

@Component({
    ...
    pipes:      [UsersPipe]
})

Why Does OAuth v2 Have Both Access and Refresh Tokens?

While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation. Another point missing in discussion is from rfc6749#page-55

"For example, the authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response.The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).

enter image description here

Passing parameters on button action:@selector

You can set tag of the button and access it from sender in action

[btnHome addTarget:self action:@selector(btnMenuClicked:)     forControlEvents:UIControlEventTouchUpInside];
                    btnHome.userInteractionEnabled = YES;
                    btnHome.tag = 123;

In the called function

-(void)btnMenuClicked:(id)sender
{
[sender tag];

    if ([sender tag] == 123) {
        // Do Anything
    }
}

Enabling CORS in Cloud Functions for Firebase

Changing true by "*" did the trick for me, so this is how it looks like:

const cors = require('cors')({ origin: "*" })

I tried this approach because in general, this is how this response header is set:

'Access-Control-Allow-Origin', '*'

Be aware that this will allow any domain to call your endpoints therefore it's NOT secure.

Additionally, you can read more on the docs: https://github.com/expressjs/cors

How to get a list of all files that changed between two Git commits?

To find the names of all files modified since your last commit:

git diff --name-only

Or (for a bit more information, including untracked files):

git status

regular expression for finding 'href' value of a <a> link

I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.

<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

You can view a full explanation of this regex at here.

Snippet playground:

_x000D_
_x000D_
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
  console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
  Text to match:_x000D_
  <input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
  _x000D_
  <button>Match</button>_x000D_
 </label>
_x000D_
_x000D_
_x000D_

MIT vs GPL license

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

FFmpeg: How to split video efficiently?

http://ffmpeg.org/trac/ffmpeg/wiki/Seeking%20with%20FFmpeg may also be useful to you. Also ffmpeg has a segment muxer that might work.

Anyway my guess is that combining them into one command would save time.

Why do we always prefer using parameters in SQL statements?

Two years after my first go, I'm recidivating...

Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates.

Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "@myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way?

jQuery find and replace string

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.

HTML:

<div>
    <div>
        <p>
           <h1>
             <a class="swapText">lollipops</a>
           </h1>
        </p>
        <span class="swapText">lollipops</span>
    </div>
</div>
<p>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
    $('.swapText').text("marshmallows");
});

Git vs Team Foundation Server

On top of everything that's been said (

https://stackoverflow.com/a/4416666/172109

https://stackoverflow.com/a/4894099/172109

https://stackoverflow.com/a/4415234/172109

), which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.

Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

How do I do an OR filter in a Django query?

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

Start an external application from a Google Chrome Extension?

There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/

Using Html.ActionLink to call action on different controller

I would recommend writing these helpers using named parameters for the sake of clarity as follows:

@Html.ActionLink(
    linkText: "Details",
    actionName: "Details",
    controllerName: "Product",
    routeValues: new {
        id = item.ID
    },
    htmlAttributes: null
)

How to debug Ruby scripts

I strongly recommend this video, in order to pick the proper tool at the moment to debug our code.

https://www.youtube.com/watch?v=GwgF8GcynV0

Personally, I'd highlight two big topics in this video.

  • Pry is awesome for debug data, "pry is a data explorer" (sic)
  • Debugger seems to be better to debug step by step.

That's my two cents!

How to find text in a column and saving the row number where it is first found - Excel VBA

Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....

and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...

Where will log4net create this log file?

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

WCF Service Returning "Method Not Allowed"

Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address

You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

Select count(*) from multiple tables

JOIN with different tables

SELECT COUNT(*) FROM (  
SELECT DISTINCT table_a.ID  FROM table_a JOIN table_c ON table_a.ID  = table_c.ID   );

How to use JNDI DataSource provided by Tomcat in Spring?

In your spring class, You can inject a bean annotated like as

@Autowired
@Qualifier("dbDataSource")
private DataSource dataSource;

and You add this in your context.xml

<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>

You can declare the JNDI resource in tomcat's server.xml using

<Resource name="jdbc/TestDB" 
  global="jdbc/TestDB" 
  auth="Container" 
  type="javax.sql.DataSource" 
  driverClassName="com.mysql.jdbc.Driver" 
  url="jdbc:mysql://localhost:3306/TestDB" 
  username="pankaj" 
  password="pankaj123" 

  maxActive="100" 
  maxIdle="20" 
  minIdle="5" 
  maxWait="10000"/>

back to context.xml de spring add this

<ResourceLink name="jdbc/MyLocalDB"
                global="jdbc/TestDB"
                auth="Container"
                type="javax.sql.DataSource" />

if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.

How to use HttpWebRequest (.NET) asynchronously?

Use HttpWebRequest.BeginGetResponse()

HttpWebRequest webRequest;

void StartWebRequest()
{
    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}

void FinishWebRequest(IAsyncResult result)
{
    webRequest.EndGetResponse(result);
}

The callback function is called when the asynchronous operation is complete. You need to at least call EndGetResponse() from this function.

Get yesterday's date in bash on Linux, DST-safe

You can use:

date -d "yesterday 13:55" '+%Y-%m-%d'

Or whatever time you want to retrieve will retrieved by bash.

For month:

date -d "30 days ago" '+%Y-%m-%d'

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

Detect Click into Iframe using JavaScript

I ran into a situation where I had to track clicks on a social media button pulled in through an iframe. A new window would be opened when the button was clicked. Here was my solution:

var iframeClick = function () {
    var isOverIframe = false,
    windowLostBlur = function () {
        if (isOverIframe === true) {
            // DO STUFF
            isOverIframe = false;
        }
    };
    jQuery(window).focus();
    jQuery('#iframe').mouseenter(function(){
        isOverIframe = true;
        console.log(isOverIframe);
    });
    jQuery('#iframe').mouseleave(function(){
        isOverIframe = false;
        console.log(isOverIframe);
    });
    jQuery(window).blur(function () {
        windowLostBlur();
    });
};
iframeClick();

How to create a DateTime equal to 15 minutes ago?

only the below code in Python 3.7 worked for me

from datetime import datetime,timedelta    
print(datetime.now()-timedelta(seconds=900))

Running Windows batch file commands asynchronously

Create a batch file with the following lines:

start foo.exe
start bar.exe
start baz.exe 

The start command runs your command in a new window, so all 3 commands would run asynchronously.

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error. Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

Jupyter/IPython Notebooks: Shortcut for "run all"?

As of 5.5 you can run Kernel > Restart and Run All

How to make the division of 2 ints produce a float instead of another int?

To lessen the impact on code readabilty, I'd suggest:

v = 1d* s/t;

Replace the single quote (') character from a string

Do you mean like this?

>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'

How can I get the current array index in a foreach loop?

You can get the index value with this

foreach ($arr as $key => $val)
{
    $key = (int) $key;
    //With the variable $key you can get access to the current array index
    //You can use $val[$key] to

}

Not Equal to This OR That in Lua

Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.

When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.

However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.

As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.

The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.

Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.

There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:

if x ~= 1 and x ~= 0 then
    print( "X must be equal to 1 or 0" )
    return
end

Alternatively, you can use a loop to check these values:

local x_is_ok = false
for i = 0,1 do 
    if x == i then
        x_is_ok = true
    end
end
if not x_is_ok then
    print( "X must be equal to 1 or 0" )
    return
end

Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)

if not (x >= 0 and x <= 1 and math.floor(x) == x) then
    print( "X must be equal to 1 or 0" )
    return
end

Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

How to remove an element slowly with jQuery?

target.fadeOut(300, function(){ $(this).remove();});

or

$('#target_id').fadeOut(300, function(){ $(this).remove();});

Duplicate: How to "fadeOut" & "remove" a div in jQuery?

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

TS1086: An accessor cannot be declared in ambient context

Quick solution: Update package.json

"devDependencies": {
   ...
   "typescript": "~3.7.4",
 }

In tsconfig.json

{
    ...,
    "angularCompilerOptions": {
       ...,
       "disableTypeScriptVersionCheck": true
    }
}

then remove node_modules folder and reinstall with

npm install

For more visit here

How do I make a <div> move up and down when I'm scrolling the page?

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.

if($(window).scrollTop() > Height_of_Header){
    //begin to scroll
    $("#div").css("position","fixed");
    $("#div").css("top",0);
}
else{
    //lock it back into place
    $("#div").css("position","relative");
}

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

How to catch exception output from Python subprocess.check_output()?

Trying to "transfer an amount larger than my bitcoin balance" is not an unexpected error. You could use Popen.communicate() directly instead of check_output() to avoid raising an exception unnecessarily:

from subprocess import Popen, PIPE

p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE)
output = p.communicate()[0]
if p.returncode != 0: 
   print("bitcoin failed %d %s" % (p.returncode, output))

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Read XML Attribute using XmlDocument

I have an Xml File books.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

Program:

XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["Definition"].Value;
}

Now, attrVal has the value of ID.

How to update Android Studio automatically?

These steps are for the people who already have Android Studio installed on their Windows machine >>>

Steps to download the update:

  1. Google for “Update android studio”
  2. Choose the result from “tools.android.com”
  3. Download the zip file (it’s around 500 MB).

Steps to install Android Studio from a .zip folder:

  1. Open the .zip folder using Windows Explorer.
  2. click on 'Extract all' (or 'Extract all files') option in the ribbon.
  3. Go to the extract location. And then to android-studio\bin and run studio.exe ifyou’re on 32bit OS, or studio64.exe if you’re on 64bit OS.

By then, the Andriod Studio should open and configure your uppdates enter image description here

Comparison of DES, Triple DES, AES, blowfish encryption for data

enter image description here

DES is the old "data encryption standard" from the seventies.

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

What is the syntax to insert one list into another list in python?

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 

How to Convert an int to a String?

You have two options:

1) Using String.valueOf() method:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2) adding an empty string:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

Casting is not an option, will throw a ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!

Getting a count of rows in a datatable that meet certain criteria

One easy way to accomplish this is combining what was posted in the original post into a single statement:

int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Length;

Another way to accomplish this is using Linq methods:

int numberOfRecords = dtFoo.AsEnumerable().Where(x => x["IsActive"].ToString() == "Y").ToList().Count;

Note this requires including System.Linq.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

how to inherit Constructor from super class to sub class

Say if you have

/**
 * 
 */
public KKSSocket(final KKSApp app, final String name) {
    this.app = app;
    this.name = name;
    ...
}

then a sub-class named KKSUDPSocket extending KKSSocket could have:

/**
 * @param app
 * @param path
 * @param remoteAddr
 */
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
    super(app, path, remoteAddr);
}

and

/**
 * @param app
 * @param path
 */
public KKSUDPSocket(KKSApp app, String path) {
    super(app, path);
}

You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.

How do you change the value inside of a textfield flutter?

If you simply want to replace the entire text inside the text editing controller, then the other answers here work. However, if you want to programmatically insert, replace a selection, or delete, then you need to have a little more code.

Making your own custom keyboard is one use case for this. All of the inserts and deletions below are done programmatically:

enter image description here

Inserting text

The _controller here is a TextEditingController for the TextField.

void _insertText(String myText) {
  final text = _controller.text;
  final textSelection = _controller.selection;
  final newText = text.replaceRange(
    textSelection.start,
    textSelection.end,
    myText,
  );
  final myTextLength = myText.length;
  _controller.text = newText;
  _controller.selection = textSelection.copyWith(
    baseOffset: textSelection.start + myTextLength,
    extentOffset: textSelection.start + myTextLength,
  );
}

Thanks to this Stack Overflow answer for help with this.

Deleting text

There are a few different situations to think about:

  1. There is a selection (delete the selection)
  2. The cursor is at the beginning (don’t do anything)
  3. Anything else (delete the previous character)

Here is the implementation:

void _backspace() {
  final text = _controller.text;
  final textSelection = _controller.selection;
  final selectionLength = textSelection.end - textSelection.start;

  // There is a selection.
  if (selectionLength > 0) {
    final newText = text.replaceRange(
      textSelection.start,
      textSelection.end,
      '',
    );
    _controller.text = newText;
    _controller.selection = textSelection.copyWith(
      baseOffset: textSelection.start,
      extentOffset: textSelection.start,
    );
    return;
  }

  // The cursor is at the beginning.
  if (textSelection.start == 0) {
    return;
  }

  // Delete the previous character
  final newStart = textSelection.start - 1;
  final newEnd = textSelection.start;
  final newText = text.replaceRange(
    newStart,
    newEnd,
    '',
  );
  _controller.text = newText;
  _controller.selection = textSelection.copyWith(
    baseOffset: newStart,
    extentOffset: newStart,
  );
}

Full code

You can find the full code and more explanation in my article Custom In-App Keyboard in Flutter.

Update just one gem with bundler

It appears that with newer versions of bundler (>= 1.14) it's:

bundle update --conservative gem-name

Ansible - Use default if a variable is not defined

If you are assigning default value for boolean fact then ensure that no quotes is used inside default().

- name: create bool default
  set_fact:
    name: "{{ my_bool | default(true) }}"

For other variables used the same method given in verified answer.

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

Margin-Top not working for span element?

span is an inline element that doesn't support vertical margins. Put the margin on the outer div instead.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

Java generics: multiple generic parameters?

Even more, you can inherit generics :)

@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
        return (T) somethingHolderMap.get(clazz);
    }

Disable clipboard prompt in Excel VBA on workbook close

Just clear the clipboard before closing.

Application.CutCopyMode=False
ActiveWindow.Close

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

Google Play on Android 4.0 emulator

Have you ever tried Genymotion? I've read about it last week and it is great. They have several Android Images that you run (with their own software). The images are INCREDIBLY fast and they have Google Play installed on them. Check it out if it is the kind of thing that you need.

http://www.genymotion.com/

How to printf "unsigned long" in C?

The format is %lu.

Please check about the various other datatypes and their usage in printf here

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Keras, How to get the output of each layer?

In case you have one of the following cases:

  • error: InvalidArgumentError: input_X:Y is both fed and fetched
  • case of multiple inputs

You need to do the following changes:

  • add filter out for input layers in outputs variable
  • minnor change on functors loop

Minimum example:

from keras.engine.input_layer import InputLayer
inp = model.input
outputs = [layer.output for layer in model.layers if not isinstance(layer, InputLayer)]
functors = [K.function(inp + [K.learning_phase()], [x]) for x in outputs]
layer_outputs = [fun([x1, x2, xn, 1]) for fun in functors]

In Swift how to call method with parameters on GCD main thread?

Modern versions of Swift use DispatchQueue.main.async to dispatch to the main thread:

DispatchQueue.main.async { 
  // your code here
}

To dispatch after on the main queue, use:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  // your code here
}

Older versions of Swift used:

dispatch_async(dispatch_get_main_queue(), {
  let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass
  delegateObj.addUIImage("yourstring")
})

loading json data from local file into React JS

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:

function reqListener(e) {
    data = JSON.parse(this.responseText);
    console.log(data);
}

I'm not seeing the use of data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

Checking if an object is null in C#

in C# > 7.0 use

if (obj is null) ...

This will ignore any == or != defined by the object (unless of course you want to use them ...)

For not null use if (obj is object) and from C# 9 you can also use if (obj is not null)

Is there a performance difference between a for loop and a for-each loop?

All these loops do the exact same, I just want to show these before throwing in my two cents.

First, the classic way of looping through List:

for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }

Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).

for (String s : strings) { /* do something using s */ }

Third, the micro-optimized for loop:

int size = strings.size();
for (int i = -1; ++i < size;) { /* do something using strings.get(i) */ }

Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.

While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java for-each loop (some refer to it as Iterator loop and others as for-in loop) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.

If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.

Rails DB Migration - How To Drop a Table?

Run

rake db:migrate:down VERSION=<version>

Where <version> is the version number of your migration file you want to revert.

Example:-

rake db:migrate:down VERSION=3846656238

Adding values to Arraylist

in the first you don't define the type that will be held and linked within your arraylist construct

this is the preferred method to do so, you define the type of list and the ide will handle the rest

in the third one you will better just define List for shorter code

What does void mean in C, C++, and C#?

It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.

How can I find script's directory?

Try this:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

How do I create a copy of an object in PHP?

According to previous comment, if you have another object as a member variable, do following:

class MyClass {
  private $someObject;

  public function __construct() {
    $this->someObject = new SomeClass();
  }

  public function __clone() {
    $this->someObject = clone $this->someObject;
  }

}

Now you can do cloning:

$bar = new MyClass();
$foo = clone $bar;

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The activity must be exported or contain an intent-filter

Sometimes if you change the starting activity you have to click edit in the run dropdown play button and in app change the Launch Options Activity to the one you have set the LAUNCHER intent filter in the manifest.

How to get to a particular element in a List in java?

String[] is an array of Strings. Such an array is internally a class. Like all classes that don't explicitly extend some other class, it extends Object implicitly. The method toString() of class Object, by default, gives you the representation you see: the class name, followed by @, followed by the hash code in hex. Since the String[] class doesn't override the toString() method, you get that as a result.

Create some method that outputs the array elements for you. Iterate over the array and use System.out.print() (not print*ln*) on the elements.

Send email using java

You can find a complete and very simple java class for sending emails using Google(gmail) account here,

Send email using java and Google account

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

Git Pull is Not Possible, Unmerged Files

There is a solution even if you don't want to remove your local changes. Just fix the unmerged files (by git add or git remove). Then do git pull.

Call PHP function from jQuery?

This is exactly what ajax is for. See here:

http://api.jquery.com/load/

Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.

$('#result').load('ajax/test.php');

Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).

Sorting Directory.GetFiles()

Just an idea. I like to find an easy way out and try re use already available resources. if I were to sort files I would've just create a process and make syscal to "DIR [x:\Folders\SubFolders*.*] /s /b /on" and capture the output.

With system's DIR command you can sort by :

/O          List by files in sorted order.
sortorder    N  By name (alphabetic)       S  By size (smallest first)
             E  By extension (alphabetic)  D  By date/time (oldest first)
             G  Group directories first    -  Prefix to reverse order

The /S switch includes sub folders

I AM NOT SURE IF D = By Date/Time is using LastModifiedDate or FileCreateDate. But if the needed sort order is already built-in in the DIR command, I will get that by calling syscall. And it's FAST. I am just the lazy guy ;)

After a little googling I found switch to sort by particular date/time:-

/t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField. 

Value Description 
c : Creation
a : Last access
w : Last written

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

Get contentEditable caret index position

As this took me forever to figure out using the new window.getSelection API I am going to share for posterity. Note that MDN suggests there is wider support for window.getSelection, however, your mileage may vary.

const getSelectionCaretAndLine = () => {
    // our editable div
    const editable = document.getElementById('editable');

    // collapse selection to end
    window.getSelection().collapseToEnd();

    const sel = window.getSelection();
    const range = sel.getRangeAt(0);

    // get anchor node if startContainer parent is editable
    let selectedNode = editable === range.startContainer.parentNode
      ? sel.anchorNode 
      : range.startContainer.parentNode;

    if (!selectedNode) {
        return {
            caret: -1,
            line: -1,
        };
    }

    // select to top of editable
    range.setStart(editable.firstChild, 0);

    // do not use 'this' sel anymore since the selection has changed
    const content = window.getSelection().toString();
    const text = JSON.stringify(content);
    const lines = (text.match(/\\n/g) || []).length + 1;

    // clear selection
    window.getSelection().collapseToEnd();

    // minus 2 because of strange text formatting
    return {
        caret: text.length - 2, 
        line: lines,
    }
} 

Here is a jsfiddle that fires on keyup. Note however, that rapid directional key presses, as well as rapid deletion seems to be skip events.

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

Unable to install packages in latest version of RStudio and R Version.3.1.1

As @Pascal said, it is likely that you encounter problem with the firewall or/and proxy issue. As a first step, go through FAQ on the CRAN web page. After that, try to flag R with --internet2.

Sometimes it could be useful to check global options in R studio and uncheck "Use Internet Explorer library/proxy for HTTP". Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option.

Hope this helps.

How to delete session cookie in Postman?

In the Native Postman app there is "Cookie manager", so that is not a problem at all,

But in the Postman extension for Chrome there is not

So the solution is just in the installing native Postman

Postman for Linux, Mac & Windows

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

Bash script to run php script

I found php-cgi on my server. And its on environment path so I was able to run from anywhere. I executed succesfuly file.php in my bash script.

#!/bin/bash
php-cgi ../path/file.php

And the script returned this after php script was executed:

X-Powered-By: PHP/7.1.1 Content-type: text/html; charset=UTF-8

done!

By the way, check first if it works by checking the version issuing the command php-cgi -v

Changing iframe src with Javascript

Maybe this can be helpful... It's plain html - no javascript:

_x000D_
_x000D_
<p>Click on link bellow to change iframe content:</p>_x000D_
<a href="http://www.bing.com" target="search_iframe">Bing</a> -_x000D_
<a href="http://en.wikipedia.org" target="search_iframe">Wikipedia</a> -_x000D_
<a href="http://google.com" target="search_iframe">Google</a> (not allowed in inframe)_x000D_
_x000D_
<iframe src="http://en.wikipedia.org" width="100%" height="100%" name="search_iframe"></iframe>
_x000D_
_x000D_
_x000D_

By the way some sites do not allow you to open them in iframe (security reasons - clickjacking)

How to set an image as a background for Frame in Swing GUI of java?

if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator

how to align img inside the div to the right?

<style type="text/css">
>> .imgTop {
>>  display: block;
>>  text-align: right;
>>  }
>> </style>

<img class="imgTop" src="imgName.gif" alt="image description" height="100" width="100">

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

Fake "click" to activate an onclick method

For IE there is fireEvent() method. Don't know if that works for other browsers.

How to automatically insert a blank row after a group of data

This does exactly what you are asking, checks the rows, and inserts a blank empty row at each change in column A:

sub AddBlankRows()
'
dim iRow as integer, iCol as integer
dim oRng as range

set oRng=range("a1")

irow=oRng.row
icol=oRng.column

do 
'
if cells(irow+1, iCol)<>cells(irow,iCol) then
    cells(irow+1,iCol).entirerow.insert shift:=xldown
    irow=irow+2
else
    irow=irow+1
end if
'
loop while not cells (irow,iCol).text=""
'
end sub

I hope that gets you started, let us know!

Philip

Length of the String without using length() method

Hidden length() usage:

    String s = "foobar";

    int i = 0;
    for(char c: s.toCharArray())
    {
        i++;
    }

HTML input field hint

This is exactly what you want

_x000D_
_x000D_
$(document).tooltip({ selector: "[title]",_x000D_
                              placement: "top",_x000D_
                              trigger: "focus",_x000D_
                              animation: false}); 
_x000D_
<form id="form">_x000D_
    <label for="myinput1">Browser tooltip appears on hover but disappears on clicking the input field. But this one persists while user is typing within the field</label>_x000D_
    <input id="myinput1" type="text" title="This tooltip persists" />_x000D_
    <input id="myinput2" type="text" title="This one also" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

[ref]

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Close pre-existing figures in matplotlib when running from eclipse

See Bi Rico's answer for the general Eclipse case.

For anybody - like me - who lands here because you have lots of windows and you're struggling to close them all, just killing python can be effective, depending on your circumstances. It probably works under almost any circumstances - including with Eclipse.

I just spawned 60 plots from emacs (I prefer that to eclipse) and then I thought my script had exited. Running close('all') in my ipython window did not work for me because the plots did not come from ipython, so I resorted to looking for running python processes.

When I killed the interpreter running the script, then all 60 plots were closed - e.g.,

$ ps aux | grep python
rsage    11665  0.1  0.6 649904 109692 ?       SNl  10:54   0:03 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
rsage    12111  0.9  0.5 390956 88212 pts/30   Sl+  11:08   0:17 /usr/bin/python /usr/bin/ipython -pylab
rsage    12410 31.8  2.4 576640 406304 pts/33  Sl+  11:38   0:06 python3 ../plot_motor_data.py
rsage    12431  0.0  0.0   8860   648 pts/32   S+   11:38   0:00 grep python

$ kill 12410

Note that I did not kill my ipython/pylab, nor did I kill the update manager (killing the update manager is probably a bad idea)...

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Created a base class based on @sky-dev implementation. So this can be easily applied to multiple contexts, and entities.

public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
    public BaseDbContext(string connectionString)
        : base(connectionString)
    {
    }
    public override int SaveChanges()
    {

        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries<TEntity>())
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Usage:

public class MyContext: BaseDbContext<MyEntities>
{

    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    public MyContext()
        : base("name=MyConnectionString")
    {
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    public MyContext(string connectionString)
        : base(connectionString)
    {
    }

     //DBcontext class body here (methods, overrides, etc.)
 }

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

Vuejs: Event on route change

Just incase if anyone is looking for how to do it in typescript here is the solution

   @Watch('$route', { immediate: true, deep: true })
   onUrlChange(newVal: Route) {
      // Some action
    }

And yes as mentioned by @Coops below, please do not forget to include

import { Watch } from 'vue-property-decorator';

Edit: Alcalyn made a very good point of using Route type instead of using any

import { Watch } from 'vue-property-decorator';    
import { Route } from 'vue-router';

right click context menu for datagridview

  • Put a context menu on your form, name it, set captions etc. using the built-in editor
  • Link it to your grid using the grid property ContextMenuStrip
  • For your grid, create an event to handle CellContextMenuStripNeeded
  • The Event Args e has useful properties e.ColumnIndex, e.RowIndex.

I believe that e.RowIndex is what you are asking for.

Suggestion: when user causes your event CellContextMenuStripNeeded to fire, use e.RowIndex to get data from your grid, such as the ID. Store the ID as the menu event's tag item.

Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.

downloading all the files in a directory with cURL

Oh, I have just the thing you need!

$host = "ftp://example.com/dir/";
$savePath = "downloadedFiles";
if($check = isFtpUp($host)){

    echo $ip." -is alive<br />";

    $check = trim($check);
    $files = explode("\n",$check);

    foreach($files as $n=>$file){
        $file = trim($file);
        if($file !== "." || $file !== ".."){
            if(!saveFtpFile($file, $host.$file, $savePath)){
                // downloading failed. possible reason: $file is a folder name.
                // echo "Error downloading file.<br />";
            }else{
                echo "File: ".$file." - saved!<br />";
            }
        }else{
            // do nothing
        }
    }
}else{
    echo $ip." - is down.<br />";
}

and functions isFtpUp and saveFtpFile are as follows:

function isFtpUp($host){
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_USERPWD, "anonymous:[email protected]");
curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

$result = curl_exec($ch);

return $result;

}

function saveFtpFile( $targetFile = null, $sourceFile = null, $savePath){

// function settings
set_time_limit(60);
$timeout = 60;
$ftpuser = "anonymous";
$ftppassword = "[email protected]";
$savePath = "downloadedFiles"; // should exist!
$curl = curl_init();
$file = @fopen ($savePath.'/'.$targetFile, 'w');

if(!$file){
    return false;
}

curl_setopt($curl, CURLOPT_URL, $sourceFile);
curl_setopt($curl, CURLOPT_USERPWD, $ftpuser.':'.$ftppassword);

// curl settings

// curl_setopt($curl, CURLOPT_FAILONERROR, 1);
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FILE, $file);

$result = curl_exec($curl);


if(!$result){
    return false;
}

curl_close($curl);
fclose($file);

return $result;
}

EDIT:

it's a php script. save it as a .php file, put it on your webserver, change $ip to address(need not be ip) of ftp server you want to download files from, create a directory named downloadedFiles on the same directory as this file.

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Solution for me without reinstalling or creating a new project:

Step 1: Change line in build.gradle from:

dependencies {
    classpath 'com.android.tools.build:gradle:0.4'
}

to

dependencies {
    classpath 'com.android.tools.build:gradle:0.5.+'
}

Note: for newer versions of gradle you may need to change it to 0.6.+ instead.

Step 2: In the <YourProject>.iml file, delete the entire<component name="FacetManager">[...]</component> tag.

Step 3 (Maybe not necessary): In the Android SDK manager, install (if not already installed) Android Support Repository under Extras.


Info found here

DataSet panel (Report Data) in SSRS designer is gone

If you are working with SQL 2008 R2 then from View---->Report Data option at bottom

TypeError: window.initMap is not a function

In my case, I had to load the Map on my Wordpress website and the problem was that the Google's api script was loading before the initMap(). Therefore, I solved the problem with a delay:

<script>
function initMap() {
     // Your Javascript Codes for the map
     ...
}

<?php
// Delay for 5 seconds
sleep(5);
?>

</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap"></script>

Read/write files within a Linux kernel module

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);

# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
            loff_t *pos);

Also, filp_open no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs).

How can we print line numbers to the log in java

I use this little method that outputs the trace and line number of the method that called it.

 Log.d(TAG, "Where did i put this debug code again?   " + Utils.lineOut());

Double click the output to go to that source code line!

You might need to adjust the level value depending on where you put your code.

public static String lineOut() {
    int level = 3;
    StackTraceElement[] traces;
    traces = Thread.currentThread().getStackTrace();
    return (" at "  + traces[level] + " " );
}

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

How to delete all data from solr and hbase

Solr I am not sure but you can delete all the data from hbase using truncate command like below:

truncate 'table_name'

It will delete all row-keys from hbase table.

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

How to detect if a stored procedure already exists

A better option might be to use a tool like Red-Gate SQL Compare or SQL Examiner to automatically compare the differences and generate a migration script.

How to restrict the selectable date ranges in Bootstrap Datepicker?

Another possibility is to use the options with data attributes, like this(minimum date 1 week before):

<input class='datepicker' data-date-start-date="-1w">

More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

How to export MySQL database with triggers and procedures?

I've created the following script and it worked for me just fine.

#! /bin/sh
cd $(dirname $0)
DB=$1
DBUSER=$2
DBPASSWD=$3
FILE=$DB-$(date +%F).sql
mysqldump --routines "--user=${DBUSER}"  --password=$DBPASSWD $DB > $PWD/$FILE
gzip $FILE
echo Created $PWD/$FILE*

and you call the script using command line arguments.

backupdb.sh my_db dev_user dev_password

How to get post slug from post in WordPress?

I came across this method and I use it to make div IDs the slug name inside the loop:

<?php $slug = basename( get_permalink() ); echo $slug;?>

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

How to add a right button to a UINavigationController?

You Can use this:

Objective-C

UIBarButtonItem *rightSideOptionButton = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(rightSideOptionButtonClicked:)];          
self.navigationItem.rightBarButtonItem = rightSideOptionButton;

Swift

let rightSideOptionButton = UIBarButtonItem()
rightSideOptionButton.title = "Right"
self.navigationItem.rightBarButtonItem = rightSideOptionButton

Understanding .get() method in Python

If d is a dictionary, then d.get(k, v) means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.

How to get video duration, dimension and size in PHP?

If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):

wp_get_attachment_metadata($videoID);

helped me a lot. thats why i'm posting it, although its just for wordpress users.

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.:

def product(xs):
    return reduce(operator.mul, xs, 1)

Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, there's no builtin foldr, and actually using reduce with non-associative operators is considered bad style.

Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.

How to read embedded resource text file

I know it is an old thread, but this is what worked for me :

  1. add the text file to the project resources
  2. set the access modifier to public, as showed above by Andrew Hill
  3. read the text like this :

    textBox1 = new TextBox();
    textBox1.Text = Properties.Resources.SomeText;
    

The text that I added to the resources: 'SomeText.txt'

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

How do I use Maven through a proxy?

To set Maven Proxy :

Edit the proxies session in your ~/.m2/settings.xml file. If you cant find the file, create one.

<settings>
<proxies>
    <proxy>
        <id>httpproxy</id>
        <active>true</active>
        <protocol>http</protocol>
        <host>your-proxy-host</host>
        <port>your-proxy-port</port>
        <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
<proxy>
        <id>httpsproxy</id>
        <active>true</active>
        <protocol>https</protocol>
        <host>your-proxy-host</host>
        <port>your-proxy-port</port>
        <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>

</proxies>
</settings>

or

Edit the proxies session in your {M2_HOME}/conf/settings.xml

Hope it Helps.. :)

Build an iOS app without owning a mac?

You can use Phonegap (Cordova) to develop iOS Apps without a Mac, but yout would still need a Mac to submit your application to the App Store. We developed a cloud application which also can publish your app without a Mac https://www.wenz.io/ApplicationLoader. Currently we are in beta and you can use the service for free.

Best regards, Steffen Wenz

(I'm the creator of the site)

How do I show the schema of a table in a MySQL database?

SELECT COLUMN_NAME, TABLE_NAME,table_schema
FROM INFORMATION_SCHEMA.COLUMNS;

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I could find this solution and is working fine:

cd /Applications/Python\ 3.7/
./Install\ Certificates.command

Can't install laravel installer via composer

On centos 7 I have used:

yum install php-pecl-zip

because any other solution didn't work for me.

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

On Fedora 28, just pay attention to the line

security.useSystemPropertiesFile=true

of the java.security file, found at:

$(dirname $(readlink -f $(which java)))/../lib/security/java.security

Fedora 28 introduced external file of disabledAlgorithms control at

/etc/crypto-policies/back-ends/java.config

You can edit this external file or you can exclude it from java.security by setting

security.useSystemPropertiesFile=false

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

Try wrapping expression with:

$scope.$apply(function() {
   $scope.foo.bar=true;
})

How can I create a table with borders in Android?

My solution for this problem is to put an xml drawable resource on the background field of every cell. In this manner you could define a shape with the border you want for all cells. The only inconvenience is that the borders of the extreme cells have half the width of the others but it's no problem if your table fills the entire screen.

An Example:

drawable/cell_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#000"/>
        <stroke android:width="1dp"  android:color="#ff9"/>
</shape>

layout/my_table.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TableRow
        android:id="@+id/tabla_cabecera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></TableRow>

    <TableLayout
        android:id="@+id/tabla_cuerpo"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>
    </TableLayout>


</LinearLayout>

Edit: An example

enter image description here

Edit2: Another example (with more elements: circle corners, gradients...) enter image description here

I have explained this issue with more details in http://blog.intelligenia.com/2012/02/programacion-movil-en-android.html#more. It's in spanish but there are some codes and images of more complex tables.

How do I pass data between Activities in Android application?

You can use SharedPreferences...

  1. Logging. Time store session id in SharedPreferences

    SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("sessionId", sessionId);
    editor.commit();
    
  2. Signout. Time fetch session id in sharedpreferences

    SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    

If you don't have the required session id, then remove sharedpreferences:

SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();

That is very useful, because one time you save the value and then retrieve anywhere of activity.

What algorithms compute directions from point A to point B on a map?

Speaking of GraphHopper, a fast Open Source route planner based on OpenStreetMap, I have read a bit literature and implemented some methods. The simplest solution is a Dijkstra and a simple improvement is a bidirectional Dijkstra which explores roughly only the half of the nodes. With bidirctional Dijkstra a route through entire Germany takes already 1sec (for car mode), in C it would be probably only 0.5s or so ;)

I've created an animated gif of a real path search with bidirectional Dijkstra here. Also there are some more ideas to make Dijkstra faster like doing A*, which is a "goal-oriented Dijkstra". Also I've create a gif-animation for it.

But how to do it (a lot) faster?

The problem is that for a path search all nodes between the locations have to be explored and this is really costly as already in Germany there are several millions of them. But an additional pain point of Dijkstra etc is that such searches uses lots of RAM.

There are heuristic solutions but also exact solutions which organzize the graph (road network) in hierarchical layers, both have pro&cons and mainly solve the speed and RAM problem. I've listed some of them in this answer.

For GraphHopper I decided to use Contraction Hierarchies because it is relative 'easy' to implement and does not take ages for preparation of the graph. It still results in very fast response times like you can test at our online instance GraphHopper Maps. E.g. from south Africa to east China which results in a 23000km distance and nearly 14 days driving time for car and took only ~0.1s on the server.

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

Force download a pdf link using javascript/ajax/jquery

Here is a Javascript solution (for folks like me who were looking for an answer to the title):

function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var evt = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': false
        });
        save.dispatchEvent(evt);

        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}

source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html

Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:

//...
try {
    var evt = new MouseEvent(...);
} catch (e) {
    window.open(fileURL, fileName);
}
//...

What is the purpose of the single underscore "_" variable in Python?

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

Any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

App.Config Transformation for projects which are not Web Projects in Visual Studio?

In my experience, the things I need to make environment-specific are things like connection strings, appsettings and often smpt settings. The config system allows to specify these things in separate files. So you can use this in your app.config/web.config:

 <appSettings configSource="appsettings.config" />
 <connectionStrings configSource="connection.config" />
 <system.net>
    <mailSettings>
       <smtp configSource="smtp.config"/>
    </mailSettings>
 </system.net>

What I typically do is to put these config-specific sections in separate files, in a subfolder called ConfigFiles (either in the solution root or at the project level, depends). I define a file per configuration, e.g. smtp.config.Debug and smtp.config.Release.

Then you can define a pre-build event like so:

copy $(ProjectDir)ConfigFiles\smtp.config.$(ConfigurationName) $(TargetDir)smtp.config

In team development, you can tweak this further by including the %COMPUTERNAME% and/or %USERNAME% in the convention.

Of course, this implies that the target files (x.config) should NOT be put in source control (since they are generated). You should still add them to the project file and set their output type property to 'copy always' or 'copy if newer' though.

Simple, extensible, and it works for all types of Visual Studio projects (console, winforms, wpf, web).

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

Convert JSON array to an HTML table in jQuery

A still shorter way

$.makeTable = function (mydata) {
            if (mydata.length <= 0) return "";
           return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
                return "<th>" + key + "</th>";
            }).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
                return "<tr>" + $.map(index, function (val, key) {
                    return "<td>" + val + "</td>";
                }).join("\n") + "</tr>";
            }).join("\n"));
        };

How to implement a FSM - Finite State Machine in Java

You can implement Finite State Machine in two different ways.

Option 1:

Finite State machine with a pre-defined workflow : Recommended if you know all states in advance and state machine is almost fixed without any changes in future

  1. Identify all possible states in your application

  2. Identify all the events in your application

  3. Identify all the conditions in your application, which may lead state transition

  4. Occurrence of an event may cause transitions of state

  5. Build a finite state machine by deciding a workflow of states & transitions.

    e.g If an event 1 occurs at State 1, the state will be updated and machine state may still be in state 1.

    If an event 2 occurs at State 1, on some condition evaluation, the system will move from State 1 to State 2

This design is based on State and Context patterns.

Have a look at Finite State Machine prototype classes.

Option 2:

Behavioural trees: Recommended if there are frequent changes to state machine workflow. You can dynamically add new behaviour without breaking the tree.

enter image description here

The base Task class provides a interface for all these tasks, the leaf tasks are the ones just mentioned, and the parent tasks are the interior nodes that decide which task to execute next.

The Tasks have only the logic they need to actually do what is required of them, all the decision logic of whether a task has started or not, if it needs to update, if it has finished with success, etc. is grouped in the TaskController class, and added by composition.

The decorators are tasks that “decorate” another class by wrapping over it and giving it additional logic.

Finally, the Blackboard class is a class owned by the parent AI that every task has a reference to. It works as a knowledge database for all the leaf tasks

Have a look at this article by Jaime Barrachina Verdia for more details

jQuery: How to get the HTTP status code from within the $.ajax.error method?

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {     
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

[Ljava.lang.Object; cannot be cast to

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource

Problem is

(List<SwitcherServiceSource>) LoadSource.list();

This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

Solution

List<Object> result = (List<Object>) LoadSource.list(); 
Iterator itr = result.iterator();
while(itr.hasNext()){
   Object[] obj = (Object[]) itr.next();
   //now you have one array of Object for each row
   String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String 
   Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
   //same way for all obj[2], obj[3], obj[4]
}

Related link

How do I create an array of strings in C?

If you don't want to change the strings, then you could simply do

const char *a[2];
a[0] = "blah";
a[1] = "hmm";

When you do it like this you will allocate an array of two pointers to const char. These pointers will then be set to the addresses of the static strings "blah" and "hmm".

If you do want to be able to change the actual string content, the you have to do something like

char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");

This will allocate two consecutive arrays of 14 chars each, after which the content of the static strings will be copied into them.

How to replace captured groups only?

With two capturing groups would have been also possible; I would have also included two dashes, as additional left and right boundaries, before and after the digits, and the modified expression would have looked like:

(.*name=".+_)\d+(_[^"]+".*)

_x000D_
_x000D_
const regex = /(.*name=".+_)\d+(_[^"]+".*)/g;_x000D_
const str = `some_data_before name="some_text_0_some_text" and then some_data after`;_x000D_
const subst = `$1!NEW_ID!$2`;_x000D_
const result = str.replace(regex, subst);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Copying an array of objects into another array in javascript

Easy way to get this working is using:

var cloneArray = JSON.parse(JSON.stringify(originalArray));

I have issues with getting arr.concat() or arr.splice(0) to give a deep copy. Above snippet works perfectly.

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

Including dependencies in a jar with Maven

http://fiji.sc/Uber-JAR provides an excellent explanation of the alternatives:

There are three common methods for constructing an uber-JAR:

  1. Unshaded. Unpack all JAR files, then repack them into a single JAR.
    • Pro: Works with Java's default class loader.
    • Con: Files present in multiple JAR files with the same path (e.g., META-INF/services/javax.script.ScriptEngineFactory) will overwrite one another, resulting in faulty behavior.
    • Tools: Maven Assembly Plugin, Classworlds Uberjar
  2. Shaded. Same as unshaded, but rename (i.e., "shade") all packages of all dependencies.
    • Pro: Works with Java's default class loader. Avoids some (not all) dependency version clashes.
    • Con: Files present in multiple JAR files with the same path (e.g., META-INF/services/javax.script.ScriptEngineFactory) will overwrite one another, resulting in faulty behavior.
    • Tools: Maven Shade Plugin
  3. JAR of JARs. The final JAR file contains the other JAR files embedded within.
    • Pro: Avoids dependency version clashes. All resource files are preserved.
    • Con: Needs to bundle a special "bootstrap" classloader to enable Java to load classes from the wrapped JAR files. Debugging class loader issues becomes more complex.
    • Tools: Eclipse JAR File Exporter, One-JAR.

Could not load type from assembly error

Just run into this with another cause:

running unit tests in release mode but the library being loaded was the debug mode version which had not been updated

How can I get the IP address from NIC in Python?

Since most of the answers use ifconfig to extract the IPv4 from the eth0 interface, which is deprecated in favor of ip addr, the following code could be used instead:

import os

ipv4 = os.popen('ip addr show eth0 | grep "\<inet\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()
ipv6 = os.popen('ip addr show eth0 | grep "\<inet6\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()

UPDATE:

Alternatively, you can shift part of the parsing task to the python interpreter by using split() instead of grep and awk, as @serg points out in the comment:

import os

ipv4 = os.popen('ip addr show eth0').read().split("inet ")[1].split("/")[0]
ipv6 = os.popen('ip addr show eth0').read().split("inet6 ")[1].split("/")[0]

But in this case you have to check the bounds of the array returned by each split() call.

UPDATE 2:

Another version using regex:

import os
import re

ipv4 = re.search(re.compile(r'(?<=inet )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]
ipv6 = re.search(re.compile(r'(?<=inet6 )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]

Clicking a checkbox with ng-click does not update the model

It is kind of a hack but wrapping it in a timeout seems to accomplish what you are looking for:

angular.module('myApp', [])
    .controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $scope.todos = [{
        'text': "get milk",
        'done': true
    }, {
        'text': "get milk2",
            'done': false
    }];

    $scope.onCompleteTodo = function (todo) {
        $timeout(function(){
            console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
            $scope.doneAfterClick = todo.done;
            $scope.todoText = todo.text;
        });
    };
}]);

Sort a Custom Class List<T>

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

JavaScript: replace last occurrence of text in a string

I know this is silly, but I'm feeling creative this morning:

'one two, one three, one four, one'
.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
.reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
.join(' ') // string: "one four, one three, one two, one"
.replace(/one/, 'finish') // string: "finish four, one three, one two, one"
.split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
.reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
.join(' '); // final string: "one two, one three, one four, finish"

So really, all you'd need to do is add this function to the String prototype:

String.prototype.replaceLast = function (what, replacement) {
    return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};

Then run it like so: str = str.replaceLast('one', 'finish');

One limitation you should know is that, since the function is splitting by space, you probably can't find/replace anything with a space.

Actually, now that I think of it, you could get around the 'space' problem by splitting with an empty token.

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
};

String.prototype.replaceLast = function (what, replacement) {
    return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};

str = str.replaceLast('one', 'finish');

Best way to randomize an array with .NET

Random r = new Random();
List<string> list = new List(originalArray);
List<string> randomStrings = new List();

while(list.Count > 0)
{
int i = r.Random(list.Count);
randomStrings.Add(list[i]);
list.RemoveAt(i);
}

Pyspark: display a spark data frame in a table format

The show method does what you're looking for.

For example, given the following dataframe of 3 rows, I can print just the first two rows like this:

df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)

which yields:

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|bar|  2|
+---+---+
only showing top 2 rows

Kill python interpeter in linux from the terminal

pkill with script path

pkill -9 -f path/to/my_script.py

is a short and selective method that is more likely to only kill the interpreter running a given script.

See also: https://unix.stackexchange.com/questions/31107/linux-kill-process-based-on-arguments

javac error: Class names are only accepted if annotation processing is explicitly requested

How you can reproduce this cryptic error on the Ubuntu terminal:

Put this in a file called Main.java:

public Main{
    public static void main(String[] args){
        System.out.println("ok");
    }
}

Then compile it like this:

user@defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if 
annotation processing is explicitly requested
1 error

It's because you didn't specify .java at the end of Main.

Do it like this, and it works:

user@defiant /home/user $ javac Main.java
user@defiant /home/user $

Slap your forehead now and grumble that the error message is so cryptic.

How to include JavaScript file or library in Chrome console?

Do you use some AJAX framework? Using jQuery it would be:

$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.

(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById() doesn't work consistently on all browsers - see this answer for details.)

UPDATE:

It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:

to dynamically load scripts. Those may be relevant to people reading this question.

See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.

Install dependencies globally and locally using package.json

Build your own script to install global dependencies. It doesn't take much. package.json is quite expandable.

const {execSync} = require('child_process');

JSON.parse(fs.readFileSync('package.json'))
     .globalDependencies.foreach(
         globaldep => execSync('npm i -g ' + globaldep)
     );

Using the above, you can even make it inline, below!

Look at preinstall below:

{
  "name": "Project Name",
  "version": "0.1.0",
  "description": "Project Description",
  "main": "app.js",
  "scripts": {
    "preinstall": "node -e \"const {execSync} = require('child_process'); JSON.parse(fs.readFileSync('package.json')).globalDependencies.foreach(globaldep => execSync('npm i -g ' + globaldep));\"",
    "build": "your transpile/compile script",
    "start": "node app.js",
    "test": "./node_modules/.bin/mocha --reporter spec",
    "patch-release": "npm version patch && npm publish && git add . && git commit -m \"auto-commit\" && git push --follow-tags"
  },
  "dependencies": [
  },
  "globalDependencies": [
    "[email protected]",
    "ionic",
    "potato"
  ],
  "author": "author",
  "license": "MIT",
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^5.2.0"
  },
  "bin": {
    "app": "app.js"
  }
}

The authors of node may not admit package.json is a project file. But it is.

Java Reflection: How to get the name of a variable?

You can do like this:

Field[] fields = YourClass.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);         
for (Field field : fields) {
    //gives the names of the fields
    System.out.println(field.getName());   
}

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

What is the meaning of "$" sign in JavaScript

That is most likely jQuery code (more precisely, JavaScript using the jQuery library).

The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).

iPhone 5 CSS media query

You can get your answer fairly easily for the iPhone5 along with other smartphones on the media feature database for mobile devices:

http://pieroxy.net/blog/2012/10/18/media_features_of_the_most_common_devices.html

You can even get your own device values on the test page on the same website.

(Disclaimer: This is my website)

Redirect non-www to www in .htaccess

Add the following code in .htaccess file.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file

How to detect Esc Key Press in React and how to handle it

React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:

handleOnKeyDown = (e) => {
  if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
    // select item
    e.preventDefault();
  } else if (e.key === 'ArrowUp') {
    // go to top item
    e.preventDefault();
  } else if (e.key === 'ArrowDown') {
    // go to bottom item
    e.preventDefault();
  } else if (e.key === 'Escape') {
    // escape
    e.preventDefault();
  }
};

What is wrong with my SQL here? #1089 - Incorrect prefix key

In your PRIMARY KEY definition you've used (id(11)), which defines a prefix key - i.e. the first 11 characters only should be used to create an index. Prefix keys are only valid for CHAR, VARCHAR, BINARY and VARBINARY types and your id field is an int, hence the error.

Use PRIMARY KEY (id) instead and you should be fine.

MySQL reference here and read from paragraph 4.

Moment.js - how do I get the number of years since a date, not rounded up?

http://jsfiddle.net/xR8t5/27/

if you do not want fraction values:

var years = moment().diff('1981-01-01', 'years',false);
alert( years);

if you want fraction values:

var years = moment().diff('1981-01-01', 'years',true);
alert( years);

Units can be [seconds, minutes, hours, days, weeks, months, years]

How to remove RVM (Ruby Version Manager) from my system

In addition to @tadman's answer I removed the wrappers in /usr/local/bin as well as the file /etc/profile.d/rvm.

The wrappers include:

erb
gem
irb
rake
rdoc
ri
ruby
testrb

Converting from byte to int in java

Bytes are transparently converted to ints.

Just say

int i= rno[0];

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});