Programs & Examples On #Evolutionary algorithm

Evolutionary algorithms (EAs) are inspired by the biological model of evolution and natural selection. In the natural world, evolution helps species adapt to their environments. Evolutionary algorithms are based on a simplified model of this biological evolution. To solve a particular problem we create an environment in which potential solutions can evolve. The environment is shaped by the parameters of the problem and encourages the evolution of good

What are good examples of genetic algorithms/genetic programming solutions?

I used a GA to optimize seating assignments at my wedding reception. 80 guests over 10 tables. Evaluation function was based on keeping people with their dates, putting people with something in common together, and keeping people with extreme opposite views at separate tables.

I ran it several times. Each time, I got nine good tables, and one with all the odd balls. In the end, my wife did the seating assignments.

My traveling salesman optimizer used a novel mapping of chromosome to itinerary, which made it trivial to breed and mutate the chromosomes without any risk of generating invalid tours.

Update: Because a couple people have asked how ...

Start with an array of guests (or cities) in some arbitrary but consistent ordering, e.g., alphabetized. Call this the reference solution. Think of a guest's index as his/her seat number.

Instead of trying to encode this ordering directly in the chromosome, we encode instructions for transforming the reference solution into a new solution. Specifically, we treat the chromosomes as lists of indexes in the array to swap. To get decode a chromosome, we start with the reference solution and apply all the swaps indicated by the chromosome. Swapping two entries in the array always results in a valid solution: every guest (or city) still appears exactly once.

Thus chromosomes can be randomly generated, mutated, and crossed with others and will always produce a valid solution.

Incrementing in C++ - When to use x++ or ++x?

Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.

"More Effective C++" item #6 - that's sufficient authority for me.

For those who don't own the book, here are the pertinent quotes. From page 32:

From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...

And on page 34:

If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

How do you install GLUT and OpenGL in Visual Studio 2012?

For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.

I copied some important parts of that package here:

... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...

... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...

Permission denied error on Github Push

See the github help on cloning URL. With HTTPS, if you are not authorized to push, you would basically have a read-only access. So yes, you need to ask the author to give you permission.

If the author doesn't give you permission, you can always fork (clone) his repository and work on your own. Once you made a nice and tested feature, you can then send a pull request to the original author.

space between divs - display table-cell

Use transparent borders if possible.

JSFiddle Demo

https://jsfiddle.net/74q3na62/

HTML

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
        <div class="cell">Cell 3</div>
    </div>
</div>

CSS

.table {
  display: table;
  border: 1px solid black;
}

.row { display:table-row; }

.cell {
  display: table-cell;
  background-clip: padding-box;
  background-color: gold;
  border-right: 10px solid transparent;
}

.cell:last-child {
  border-right: 0 none;
}

Explanation

You could use the border-spacing property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.

If you don't need visible borders on your table cells you should therefore use transparent borders to generate cell margins. Transparent borders require setting background-clip: padding-box; because otherwise the background color of the table cells is displayed on the border.

Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip out.

How to list the files inside a JAR file?

I would like to expand on acheron55's answer, since it is a very non-safe solution, for several reasons:

  1. It doesn't close the FileSystem object.
  2. It doesn't check if the FileSystem object already exists.
  3. It isn't thread-safe.

This is somewhat a safer solution:

private static ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();

public void walk(String path) throws Exception {

    URI uri = getClass().getResource(path).toURI();
    if ("jar".equals(uri.getScheme()) {
        safeWalkJar(path, uri);
    } else {
        Files.walk(Paths.get(path));
    }
}

private void safeWalkJar(String path, URI uri) throws Exception {

    synchronized (getLock(uri)) {    
        // this'll close the FileSystem object at the end
        try (FileSystem fs = getFileSystem(uri)) {
            Files.walk(fs.getPath(path));
        }
    }
}

private Object getLock(URI uri) {

    String fileName = parseFileName(uri);  
    locks.computeIfAbsent(fileName, s -> new Object());
    return locks.get(fileName);
}

private String parseFileName(URI uri) {

    String schemeSpecificPart = uri.getSchemeSpecificPart();
    return schemeSpecificPart.substring(0, schemeSpecificPart.indexOf("!"));
}

private FileSystem getFileSystem(URI uri) throws IOException {

    try {
        return FileSystems.getFileSystem(uri);
    } catch (FileSystemNotFoundException e) {
        return FileSystems.newFileSystem(uri, Collections.<String, String>emptyMap());
    }
}   

There's no real need to synchronize over the file name; one could simply synchronize on the same object every time (or make the method synchronized), it's purely an optimization.

I would say that this is still a problematic solution, since there might be other parts in the code that use the FileSystem interface over the same files, and it could interfere with them (even in a single threaded application).
Also, it doesn't check for nulls (for instance, on getClass().getResource().

This particular Java NIO interface is kind of horrible, since it introduces a global/singleton non thread-safe resource, and its documentation is extremely vague (a lot of unknowns due to provider specific implementations). Results may vary for other FileSystem providers (not JAR). Maybe there's a good reason for it being that way; I don't know, I haven't researched the implementations.

Difference between $(this) and event.target?

http://api.jquery.com/on/ states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">
    </div>
</div>

Check the below output:

<script>
    $(function(){
        $(".btn").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        });


        $("#outer").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        })
    })
</script>

Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget,event.target are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, event.target would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/

There is already an open DataReader associated with this Command which must be closed first

I am using web service in my tool, where those service fetch the stored procedure. while more number of client tool fetches the web service, this problem arises. I have fixed by specifying the Synchronized attribute for those function fetches the stored procedure. now it is working fine, the error never showed up in my tool.

 [MethodImpl(MethodImplOptions.Synchronized)]
 public static List<t> MyDBFunction(string parameter1)
  {
  }

This attribute allows to process one request at a time. so this solves the Issue.

How to call window.alert("message"); from C#?

It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:

try
{
  ...
}
catch(ApplicationException ex){
  Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

How to split string using delimiter char using T-SQL?

For your specific data, you can use

Select col1, col2, LTRIM(RTRIM(SUBSTRING(
    STUFF(col3, CHARINDEX('|', col3,
    PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
    PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01

EDIT - charindex vs patindex

Test

select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)

set statistics time on

dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1

dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2

set statistics time off

Timings

CHARINDEX:

 SQL Server Execution Times (1):
   CPU time = 5656 ms,  elapsed time = 6418 ms.
 SQL Server Execution Times (2):
   CPU time = 5813 ms,  elapsed time = 6114 ms.
 SQL Server Execution Times (3):
   CPU time = 5672 ms,  elapsed time = 6108 ms.

PATINDEX:

 SQL Server Execution Times (1):
   CPU time = 5906 ms,  elapsed time = 6296 ms.
 SQL Server Execution Times (2):
   CPU time = 5860 ms,  elapsed time = 6404 ms.
 SQL Server Execution Times (3):
   CPU time = 6109 ms,  elapsed time = 6301 ms.

Conclusion

The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

Bootstrap Align Image with text

i am a new bee ;p . And i faced the same problem. And the solution is BS Media objects. please see the code..

<div class="media">
   <div class="media-left media-top">
    <img src="something.png" alt="@l!" class="media-object" width="20" height="50"/>
    </div>
   <div class="media-body">
      <h2 class="media-heading">Beside Image</h2>
   </div>
</div>

How to rollback a specific migration?

Well in rails 5 it's quite easy rake db:migrate:status or rails db:migrate:status

It was modified to handle both the same way Then just pick which Version you want to roll back and then run rake db:migrate VERSION=2013424230423

Make sure VERSION is all capital letters

If you have a problem with any step of the migration or stuck in the middle simply go to the migration file and comment out the lines that were already migrated.

Hope that helps

Rename MySQL database

I don't think you can do this. Basic answers will work in many cases, and in others cause data corruptions. A strategy needs to be chosen based on heuristic analysis of your database. That is the reason this feature was implemented, and then removed. [doc]

You'll need to dump all object types in that database, create the newly named one and then import the dump. If this is a live system you'll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.

If you want to see the commands that could do this, @satishD has the details, which conveys some of the challenges around which you'll need to build a strategy that matches your target database.

How to make asynchronous HTTP requests in PHP

I find this package quite useful and very simple: https://github.com/amphp/parallel-functions

<?php

use function Amp\ParallelFunctions\parallelMap;
use function Amp\Promise\wait;

$responses = wait(parallelMap([
    'https://google.com/',
    'https://github.com/',
    'https://stackoverflow.com/',
], function ($url) {
    return file_get_contents($url);
}));

It will load all 3 urls in parallel. You can also use class instance methods in the closure.

For example I use Laravel extension based on this package https://github.com/spatie/laravel-collection-macros#parallelmap

Here is my code:

    /**
     * Get domains with all needed data
     */
    protected function getDomainsWithdata(): Collection
    {
        return $this->opensrs->getDomains()->parallelMap(function ($domain) {
            $contact = $this->opensrs->getDomainContact($domain);
            $contact['domain'] = $domain;
            return $contact;
        }, 10);
    }

It loads all needed data in 10 parallel threads and instead of 50 secs without async it finished in just 8 secs.

Show hide fragment in android

I may be way way too late but it could help someone in the future.
This answer is a modification to mangu23 answer
I only added a for loop to avoid repetition and to easily add more fragments without boilerplate code.

We first need a list of the fragments that should be displayed

public class MainActivity extends AppCompatActivity{
    //...
    List<Fragment> fragmentList = new ArrayList<>();
}

Then we need to fill it with our fragments

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    HomeFragment homeFragment = new HomeFragment();
    MessagesFragment messagesFragment = new MessagesFragment();
    UserFragment userFragment = new UserFragment();
    FavoriteFragment favoriteFragment = new FavoriteFragment();
    MapFragment mapFragment = new MapFragment();

    fragmentList.add(homeFragment);
    fragmentList.add(messagesFragment);
    fragmentList.add(userFragment);
    fragmentList.add(favoriteFragment);
    fragmentList.add(mapFragment);
}

And we need a way to know which fragment were selected from the list, so we need getFragmentIndex function

private int getFragmentIndex(Fragment fragment) {
    int index = -1;
    for (int i = 0; i < fragmentList.size(); i++) {
        if (fragment.hashCode() == fragmentList.get(i).hashCode()){
            return i;
        }
    }
    return index;
}

And finally, the displayFragment method will like this:

private void displayFragment(Fragment fragment) {
        int index = getFragmentIndex(fragment);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragment.isAdded()) { // if the fragment is already in container
            transaction.show(fragment);
        } else { // fragment needs to be added to frame container
            transaction.add(R.id.placeholder, fragment);
        }
        // hiding the other fragments
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i).isAdded() && i != index) {
                transaction.hide(fragmentList.get(i));
            }
        }
        transaction.commit();
    }

In this way, we can call displayFragment(homeFragment) for example.
This will automatically show the HomeFragment and hide any other fragment in the list.
This solution allows you to append more fragments to the fragmentList without having to repeat the if statements in the old displayFragment version.
I hope someone will find this useful.

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

How do I REALLY reset the Visual Studio window layout?

Try devenv.exe /resetuserdata. I think it's more aggressive than the Tools > Import and Export options suggested.

Also check Tools > Add In Manager and make sure there aren't any orphans there.

Set object property using reflection

I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.

Here is the package

Sets the value of a property of an object by its path from the root.

The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.

Usage:

For setting up the properties directly under the object root:

Ie. LineItem class has an int property called ItemId

LineItem lineItem = new LineItem();

ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);

For setting up nested property multiple levels below the object root:

Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.

To make things even more complex, the State property is not a reference type, it is a struct.

Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.

Invite invite = new Invite();

ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

How do I set the selected item in a comboBox to match my string using C#?

I have created a Function which will return the Index of the Value

        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

jQuery preventDefault() not triggered

Update

And there's your problem - you do have to click event handlers for some a elements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.

Here's a working fiddle that shows the behaviour you want.

This should be your code:

$(document).ready(function(){


    $('#tabs div.tab').hide();
    $('#tabs div.tab:first').show();
    $('#tabs ul li:first').addClass('active');

    $("div.subtab_left li.notebook a").click(function(e) {
        e.stopImmediatePropagation();
        alert("asdasdad");
        return false;
    });

    $('#tabs ul li a').click(function(){
        alert("Handling link click");
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div.tab').hide();
        $(currentTab).show();
        return false;
    });

});

Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation() is used to stop the other click handler from firing while return false is used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation).

Play around with this, if you remove the e.stopImmediatePropagation() you'll find that the second click handler's alert will fire after the first alert. Removing the return false will have no effect on this behaviour but will cause links to be followed by the browser.

Note

A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.


  1. I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?

    If you've attached other event handlers to the link, you should look into event.stopPropagation() and event.stopImmediatePropagation() instead. Note that return false is equivalent to calling both event.preventDefault and event.stopPropagation()ref

  2. In your second code snippet, e is not defined. So an error would thrown at e.preventDefault() and the next lines never execute. In other words

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    should be

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

Here's a working example showing that this code indeed does work and that return false is not really required if you only want to stop the following of a link.

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }

Simplest way to do a recursive self-join?

SQL 2005 or later, CTEs are the standard way to go as per the examples shown.

SQL 2000, you can do it using UDFs -

CREATE FUNCTION udfPersonAndChildren
(
    @PersonID int
)
RETURNS @t TABLE (personid int, initials nchar(10), parentid int null)
AS
begin
    insert into @t 
    select * from people p      
    where personID=@PersonID

    while @@rowcount > 0
    begin
      insert into @t 
      select p.*
      from people p
        inner join @t o on p.parentid=o.personid
        left join @t o2 on p.personid=o2.personid
      where o2.personid is null
    end

    return
end

(which will work in 2005, it's just not the standard way of doing it. That said, if you find that the easier way to work, run with it)

If you really need to do this in SQL7, you can do roughly the above in a sproc but couldn't select from it - SQL7 doesn't support UDFs.

simple Jquery hover enlarge

If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:

$(document).ready(function() {
    $("[id^=content]").hover(function() {
        $(this).addClass('transition');
    }, function() {
        $(this).removeClass('transition');
    });
});

Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.

var self = this?

One solution to this is to bind all your callback to your object with javascript's bind method.

You can do this with a named method,

function MyNamedMethod() {
  // You can now call methods on "this" here 
}

doCallBack(MyNamedMethod.bind(this)); 

Or with an anonymous callback

doCallBack(function () {
  // You can now call methods on "this" here
}.bind(this));

Doing these instead of resorting to var self = this shows you understand how the binding of this behaves in javascript and doesn't rely on a closure reference.

Also, the fat arrow operator in ES6 basically is the same a calling .bind(this) on an anonymous function:

doCallback( () => {
  // You can reference "this" here now
});

sql ORDER BY multiple values in specific order?

The CASE and ORDER BY suggestions should all work, but I'm going to suggest a horse of a different color. Assuming that there are only a reasonable number of values for x_field and you already know what they are, create an enumerated type with F, P, A, and I as the values (plus whatever other possible values apply). Enums will sort in the order implied by their CREATE statement. Also, you can use meaninful value names—your real application probably does and you have just masked them for confidentiality—without wasted space, since only the ordinal position is stored.

When should I use semicolons in SQL Server?

Personal opinion: Use them only where they are required. (See TheTXI's answer above for the required list.)

Since the compiler doesn't require them, you can put them all over, but why? The compiler won't tell you where you forgot one, so you'll end up with inconsistent use.

[This opinion is specific to SQL Server. Other databases may have more-stringent requirements. If you're writing SQL to run on multiple databases, your requirements may vary.]

tpdi stated above, "in a script, as you're sending more than one statement, you need it." That's actually not correct. You don't need them.

PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional'
PRINT 'Semicolons are optional';
PRINT 'Semicolons are optional';

Output:

Semicolons are optional
Semicolons are optional
Semicolons are optional
Semicolons are optional

Why does SSL handshake give 'Could not generate DH keypair' exception?

The problem is the prime size. The maximum-acceptable size that Java accepts is 1024 bits. This is a known issue (see JDK-6521495).

The bug report that I linked to mentions a workaround using BouncyCastle's JCE implementation. Hopefully that should work for you.

UPDATE

This was reported as bug JDK-7044060 and fixed recently.

Note, however, that the limit was only raised to 2048 bit. For sizes > 2048 bit, there is JDK-8072452 - Remove the maximum prime size of DH Keys; the fix appears to be for 9.

How to scroll to specific item using jQuery?

I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.

 var scrollDownTo =$("#show_question_" + nQueId).position().top;
        console.log(scrollDownTo);
        $('#slider_light_box_container').animate({
            scrollTop: scrollDownTo
            }, 1000, function(){
        });

        }

Populating a ListView using an ArrayList?

tutorial

Also look up ArrayAdapter interface:

ArrayAdapter(Context context, int textViewResourceId, List<T> objects)

How to echo or print an array in PHP?

Human readable: (eg. can be log to text file..)

print_r( $arr_name , TRUE);

How to show grep result with complete path or file name

I fall here when I was looking exactly for the same problem and maybe it can help other.

I think the real solution is:

cat *.log | grep -H somethingtosearch

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

Java - get the current class name?

In your example, this probably refers to an anonymous class instance. Java gives a name to those classes by appending a $number to the name of the enclosing class.

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

Catching FULL exception message

I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.

But I've found it immensely helpful to dump the entire object with ConvertTo-Json so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.

    try {
        Invoke-WebRequest...
    }
    catch {
        Write-Host ($_ | ConvertTo-Json)
    }

Use ConvertTo-Json's -Depth parameter to expand deeper values, but use extreme caution going past the default depth of 2 :P

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

Make sure the config file at .git is correct...Check URL & Make sure your using the correct protocol for your keys ...ProjectWorkspace/.git/config

  ~Wrong url for git@bitbucket
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = gitbucket.org:Prezyack/project-one-hello.git
    fetch = +refs/heads/*:refs/remotes/origin/*

 ~Wrong URL for SSH...
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = https://[email protected]/emmap1/bitbucketspacestation.git
[branch "master"]
    remote = origin
    merge = refs/heads/master

We are looking at the URL... e.g: For bitbucket, expect [email protected] its gitbucket.org. make the necessary changes.. SAVE Try pushing again.

Ignore .pyc files in git repository

i try to use the sentence of a prior post and don't work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore

Enjoy.

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

I had the same problem. I use Ubuntu 12.04. I tried disabling ipv6.

Modify the /etc/sysctl.conf and add the following:
#disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

Then restart the machine and check. I think this may be a ipv6 issue even in Windows OS.

How to pass a vector to a function?

found = binarySearch(first, last, search4, &random);

Notice the &.

IntelliJ and Tomcat.. Howto..?

Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.

For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and was solved by running the following in run

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Convert all first letter to upper case, rest lower for each word

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I had this part enabled in my php.ini

 extension=php_memcache.dll
    [Memcache]
    memcache.allow_failover = 1
    memcache.max_failover_attempts=20
    memcache.chunk_size =8192
    memcache.default_port = 11211

After commenting these lines composer was installed in my windows 10

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Appending a line to a file only if it does not already exist

use awk

awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file file

How do I write a bash script to restart a process if it dies?

I've used the following script with great success on numerous servers:

pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid 
while [ -e /proc/$pid ]; do sleep 0.1; done

notes:

  • It's looking for a java process, so I can use jps, this is much more consistent across distributions than ps
  • $INSTALLATION contains enough of the process path that's it's totally unambiguous
  • Use sleep while waiting for the process to die, avoid hogging resources :)

This script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.

Add some word to all or some rows in Excel?

Save a copy of your spreadsheet first (just in case).

  1. Insert two new columns to the left of the numbered column.

  2. Put a k in the first row of the first (new) column.

  3. Copy it (the k).

  4. Go to the original first column (now the third column) and leave your cursor on the first row that has data.

  5. Hit ctrl and down arrow (at the same time) to jump to the bottom of the populated data range for your original first column.

  6. Left arrow twice to get to the new first column, the one with a k at the very top.

  7. Hit Ctrl-shift-up arrow to go to the first cell with data populated (the original k you put in), highlighting all the cells in-between your starting and ending point.

  8. Use paste (ctrl-v, right-click or whatever your preferred method), and it'll fill all those cells with a k.

  9. Then use the "Concatenate" formula in the second column. Its two arguments will be the column of Ks (column A, first column) and the column with the numbers in it.

  10. This will get you a column with the results of the K column and your numbers.

Hope this helps! The ctrl-shift-arrow and ctrl-arrow shortcuts are amazing for working with large datasets in Excel.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

You need to apply 3d transform to the element, so it will get its own composite layer. For instance:

.element{
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
}

or

.element{
    -webkit-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}

More about layer creation criteria you can read right here: Accelerated Rendering in Chrome


An explanation:

Examples (hover green box):

When you use any transition on your element it cause browser to recalculate styles, then re-layout your content even if transition property is visual (in my examples it is an opacity) and finaly paint an element:

screenshot

The issue here is re-layout of the content that can make an effect of "dancing" or "blinking" elements on the page while transition happens. If you will go to settings, check "Show composite layers" checkbox and then apply 3d transform to an element, you will see that it gets it's own layer which outlined with orange border.

screenshot

After element gets its own layer, browser just needs to composite layers on transition without re-layout or even paint operations so problem have to be solved:

screenshot

Closing Application with Exit button

You cannot exit your application. Using android.finish() won't exit the application, it just kills the activity. It's used when we don't want to see the previous activity on back button click. The application automatically exits when you switch off the device. The Android architecture does not support exiting the app. If you want, you can forcefully exit the app, but that's not considered good practice.

How to master AngularJS?

Please keep an eye on the mailing list for problems/solutions discussed by community members. https://groups.google.com/forum/?fromgroups#!forum/angular . It's been really useful to me.

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

How do I sort a VARCHAR column in SQL server that contains numbers?

I solved it in a very simple way writing this in the "order" part

ORDER BY (
sr.codice +0
)
ASC

This seems to work very well, in fact I had the following sorting:

16079   Customer X 
016082  Customer Y
16413   Customer Z

So the 0 in front of 16082 is considered correctly.

How can I get javascript to read from a .json file?

Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.

_x000D_
_x000D_
window.portalData = [_x000D_
  {_x000D_
    "kpi" : "NDAR",_x000D_
    "data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "NTI",_x000D_
     "data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "BS",_x000D_
     "data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
  },_x000D_
  {_x000D_
     "kpi" : "SISS",_x000D_
     "data" :  [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
  },_x000D_
  {_x000D_
 "kpi" : "MID",_x000D_
 "data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_
  }_x000D_
];
_x000D_
_x000D_
_x000D_

You can then do the following in your HTML

<script src="server_data.js"> </script>


function getServerData(kpiCode)
{
    var elem = $(window.portalData).filter(function(idx){
        return window.portalData[idx].kpi == kpiCode;
     });

    return elem[0].data;
};

var defData = getServerData('NDAR');

Submit form without page reloading

Here is some jQuery for posting to a php page and getting html back:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});

How to convert hex to rgb using Java?

For Android Kotlin users:

"#FFF".longARGB()?.let{ Color.parceColor(it) }
"#FFFF".longARGB()?.let{ Color.parceColor(it) }
fun String?.longARGB(): String? {
    if (this == null || !startsWith("#")) return null
    
//    #RRGGBB or #AARRGGBB
    if (length == 7 || length == 9) return this

//    #RGB or #ARGB
    if (length in 4..5) {
        val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
        if (length == 5) {
            return "$rgb${this[4]}${this[4]}"
        }
        return rgb
    }

    return null
}

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

How to get multiline input from user

In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n

To get multi-line input from the user you can go like:

no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
    lines+=input()+"\n"

print(lines)

Or

lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)

How to iterate std::set?

Just use the * before it:

set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
    cout << *it;
}

This dereferences it and allows you to access the element the iterator is currently on.

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

Remote branch is not showing up in "git branch -r"

Unfortunately, git branch -a and git branch -r do not show you all remote branches, if you haven't executed a "git fetch".

git remote show origin works consistently all the time. Also git show-ref shows all references in the Git repository. However, it works just like the git branch command.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

This is what I've used:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

How to retrieve the current value of an oracle sequence without increment it?

This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:

Why would you want it?

Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.

In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.

RonK's Query:

select MY_SEQ_NAME.currval from DUAL;

In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.

Add row to query result using select

In SQL Server, you would say:

Select name from users
UNION [ALL]
SELECT 'JASON'

In Oracle, you would say

Select name from user
UNION [ALL]
Select 'JASON' from DUAL

How to declare a constant map in Golang?

As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

var romanNumeralDict = struct {
    m map[int]string
}{m: map[int]string {
    1000: "M",
    900: "CM",
    //YOUR VALUES HERE
}}

func main() {
    d := 1000
    fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}

Object reference not set to an instance of an object.

All versions of .Net:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

.Net 4.0 or later:

if (String.IsNullOrWhitespace(strSearch))

Can I specify multiple users for myself in .gitconfig?

Something like Rob W's answer, but allowing different a different ssh key, and works with older git versions (which don't have e.g. a core.sshCommand config).

I created the file ~/bin/git_poweruser, with executable permission, and in the PATH:

#!/bin/bash

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

cat > $TMPDIR/ssh << 'EOF'
#!/bin/bash
ssh -i $HOME/.ssh/poweruserprivatekey $@
EOF

chmod +x $TMPDIR/ssh
export GIT_SSH=$TMPDIR/ssh

git -c user.name="Power User name" -c user.email="[email protected]" $@

Whenever I want to commit or push something as "Power User", I use git_poweruser instead of git. It should work on any directory, and does not require changes in .gitconfig or .ssh/config, at least not in mine.

When to throw an exception?

Some useful things to think about when deciding whether an exception is appropriate:

  1. what level of code you want to have run after the exception candidate occurs - that is, how many layers of the call stack should unwind. You generally want to handle an exception as close as possible to where it occurs. For username/password validation, you would normally handle failures in the same block of code, rather than letting an exception bubble up. So an exception is probably not appropriate. (OTOH, after three failed login attempts, control flow may shift elsewhere, and an exception may be appropriate here.)

  2. Is this event something you would want to see in an error log? Not every exception is written to an error log, but it's useful to ask whether this entry in an error log would be useful - i.e., you would try to do something about it, or would be the garbage you ignore.

ClientScript.RegisterClientScriptBlock?

The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.

Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )

Guessing the problem

If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.

Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.

MySQL OPTIMIZE all tables?

Do all the necessary procedures for fixing all tables in all the databases with a simple shell script:

#!/bin/bash
mysqlcheck --all-databases
mysqlcheck --all-databases -o
mysqlcheck --all-databases --auto-repair
mysqlcheck --all-databases --analyze

How to remove specific substrings from a set of strings in Python?

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

.replace doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

Calculating difference between two timestamps in Oracle in milliseconds

I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.

CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
    FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
        day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
        hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
        minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
        second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
        msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
        d1_ NUMBER;
        h1_ NUMBER;
        m1_ NUMBER;
        s1_ NUMBER;
        ms_ NUMBER;
        /* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
        precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
        format_ VARCHAR2(2) := ', ';
        return_ VARCHAR2(50);
    BEGIN
        IF (syntax_ IS NULL) THEN
            precision_ := 0;
        ELSE
            IF (syntax_ = 0) THEN
                precision_ := 0;
            ELSIF (syntax_ = 1) THEN
                precision_ := 1;
            ELSIF (syntax_ = 2) THEN
                precision_ := 2;
            ELSIF (syntax_ = 3) THEN
                precision_ := 3;
            ELSIF (syntax_ = 4) THEN
                precision_ := 4;
            ELSE 
                precision_ := 0;
            END IF;
        END IF;
        SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
        SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
        SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
        SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
        IF (precision_ = 4) THEN
            IF (d1_ = 1) THEN
                day_ := ' day';
            ELSE
                day_ := ' days';
            END IF;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 3) THEN
            h1_ := (d1_ * 24) + h1_;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 2) THEN
            m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 1) THEN
            s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := s1_ || second_;
            RETURN return_;
        ELSE
            ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
            IF (ms_ = 1) THEN
                msecond_ := ' millisecond';
            ELSE
                msecond_ := ' milliseconds';
            END IF;
            return_ := ms_ || msecond_;
            RETURN return_;
        END IF;
    END Core;
BEGIN
    RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;

For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:

47344620000 milliseconds

How to display list items on console window in C#

Assuming the items override ToString appropriately:

public void WriteToConsole(IEnumerable items)
{
    foreach (object o in items)
    {
        Console.WriteLine(o);
    }
}

(There'd be no advantage in using generics in this loop - we'd end up calling Console.WriteLine(object) anyway, so it would still box just as it does in the foreach part in this case.)

EDIT: The answers using List<T>.ForEach are very good.

My loop above is more flexible in the case where you have an arbitrary sequence (e.g. as the result of a LINQ expression), but if you definitely have a List<T> I'd say that List<T>.ForEach is a better option.

One advantage of List<T>.ForEach is that if you have a concrete list type, it will use the most appropriate overload. For example:

List<int> integers = new List<int> { 1, 2, 3 };
List<string> strings = new List<string> { "a", "b", "c" };

integers.ForEach(Console.WriteLine);
strings.ForEach(Console.WriteLine);

When writing out the integers, this will use Console.WriteLine(int), whereas when writing out the strings it will use Console.WriteLine(string). If no specific overload is available (or if you're just using a generic List<T> and the compiler doesn't know what T is) it will use Console.WriteLine(object).

Note the use of Console.WriteLine as a method group, by the way. This is more concise than using a lambda expression, and actually slightly more efficient (as the delegate will just be a call to Console.WriteLine, rather than a call to a method which in turn just calls Console.WriteLine).

Getting a union of two arrays in JavaScript

Simple way to deal with merging single array values.

var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}

var object=null;
var first=values[0];
for (var i in values) 
 if(i>0)    
 object= $.merge(values[i],first)

What is sharding and why is it important?

Sharding is just another name for "horizontal partitioning" of a database. You might want to search for that term to get it clearer.

From Wikipedia:

Horizontal partitioning is a design principle whereby rows of a database table are held separately, rather than splitting by columns (as for normalization). Each partition forms part of a shard, which may in turn be located on a separate database server or physical location. The advantage is the number of rows in each table is reduced (this reduces index size, thus improves search performance). If the sharding is based on some real-world aspect of the data (e.g. European customers vs. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard.

Some more information about sharding:

Firstly, each database server is identical, having the same table structure. Secondly, the data records are logically split up in a sharded database. Unlike the partitioned database, each complete data record exists in only one shard (unless there's mirroring for backup/redundancy) with all CRUD operations performed just in that database. You may not like the terminology used, but this does represent a different way of organizing a logical database into smaller parts.

Update: You wont break MVC. The work of determining the correct shard where to store the data would be transparently done by your data access layer. There you would have to determine the correct shard based on the criteria which you used to shard your database. (As you have to manually shard the database into some different shards based on some concrete aspects of your application.) Then you have to take care when loading and storing the data from/into the database to use the correct shard.

Maybe this example with Java code makes it somewhat clearer (it's about the Hibernate Shards project), how this would work in a real world scenario.

To address the "why sharding": It's mainly only for very large scale applications, with lots of data. First, it helps minimizing response times for database queries. Second, you can use more cheaper, "lower-end" machines to host your data on, instead of one big server, which might not suffice anymore.

How to Check byte array empty or not?

You must swap the order of your test:

From:

if (Attachment.Length > 0 && Attachment != null)

To:

if (Attachment != null && Attachment.Length > 0 )

The first version attempts to dereference Attachment first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").


[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:

if (Attachment?.Length > 0)
        

Put content in HttpResponseMessage object?

Apparently the new way to do it is detailed here:

http://aspnetwebstack.codeplex.com/discussions/350492

To quote Henrik,

HttpResponseMessage response = new HttpResponseMessage();

response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");

So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object.

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Prevent Android activity dialog from closing on outside touch

builder.setCancelable(false);


public void Mensaje(View v){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("¿Quieres ir a el Menú principal?");
    builder.setMessage("Al presionar SI iras a el menú y saldras de la materia.");
    builder.setPositiveButton("SI", null);
    builder.setNegativeButton("NO", null);
    builder.setCancelable(false);
    builder.show();
}

Recursively find files with a specific extension

My preference:

find . -name '*.jpg' -o -name '*.png' -print | grep Robert

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Convert integer to binary in C#

    static void convertToBinary(int n)
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(n);
        // step 1 : Push the element on the stack
        while (n > 1)
        {
            n = n / 2;
            stack.Push(n);
        }

        // step 2 : Pop the element and print the value
        foreach(var val in stack)
        {
            Console.Write(val % 2);
        }
     }

Version of Apache installed on a Debian machine

dlocate -s apache2 | grep '^Version:'

Sorting a tab delimited file

If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:

tr " " "\t" < <file> | sort <options>

EF 5 Enable-Migrations : No context type was found in the assembly

I got this problem first: PM> add-migration first

No migrations configuration type was found in the assembly 'MyProjectName'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

then i tried this:

PM> Enable-Migrations No context type was found in the assembly 'MyProjectName'.

Then the right command for me :

PM> Enable-Migrations -ProjectName MyProjectName -ContextTypeName MyProjectName.Data.Context

After that i got this error message even though Context inherits from DbContext

The type 'Context' does not inherit from DbContext. The DbMigrationsConfiguration.ContextType property must be set to a type that inherits from DbContext.

Then i Installed Microsoft.EntityFrameworkCore.Tools

ITS OK NOW but the message is funny. i already tried add migrations at first :D

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework6\Enable-Migrations' for Entity Framework 6. Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.

Find out free space on tablespace

column pct_free format 999.99
select
     used.tablespace_name,
     (reserv.maxbytes - used.bytes)*100/reserv.maxbytes pct_free,
     used.bytes/1024/1024/1024 used_gb,
     reserv.maxbytes/1024/1024/1024 maxgb,
     reserv.bytes/1024/1024/1024 gb,
     (reserv.maxbytes - used.bytes)/1024/1024/1024 "max free bytes",
     reserv.datafiles
from
    (select tablespace_name, count(1) datafiles, sum(greatest(maxbytes,bytes)) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_segments group by tablespace_name) used
where used.tablespace_name = reserv.tablespace_name
order by 2
/

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

textarea {
width: 700px;  
height: 100px;
resize: none; }

assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.

Python - Extracting and Saving Video Frames

The previous answers have lost the first frame. And it will be nice to store the images in a folder.

# create a folder to store extracted images
import os
folder = 'test'  
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__)  # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
    success,image = vidcap.read()
    if not success:
        break
    cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image)     # save frame as JPEG file
    count += 1
print("{} images are extacted in {}.".format(count,folder))

By the way, you can check the frame rate by VLC. Go to windows -> media information -> codec details

How to enable curl in xampp?

First, make sure you have libcurl (see: http://curl.haxx.se) installed. Then make sure your copy of PHP has been compiled with the --with-curl[=DIR] flag. For more info see:

If XAMPP comes pre-compiled with cURL you may just need to enable the extension in your php.ini file (usually by removing a semicolon at the start of the line which includes the extension).

Text editor to open big (giant, huge, large) text files

Tips and tricks

less

Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.

Perl

Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

logparser

This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

When should I use Async Controllers in ASP.NET MVC?

As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.

Take a look here for excellent advise.

"unexpected token import" in Nodejs5 and babel?

I have done the following to overcome the problem (ex.js script)

problem

$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");

$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:152:10)
    at Module._compile (module.js:624:28)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:194:16)
    at bootstrap_node.js:618:3

solution

# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections

# .babelrc setup
$ cat .babelrc
{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported

# or execution with babel-node
$ babel-node ex.js
Successfully Imported

How to use sha256 in php5.3.0

Could this be a typo? (two Ps in ppasscode, intended?)

$_POST['ppasscode'];

I would make sure and do:

print_r($_POST);

and make sure the data is accurate there, and then echo out what it should look like:

echo hash('sha256', $_POST['ppasscode']);

Compare this output to what you have in the database (manually). By doing this you're exploring your possible points of failure:

  1. Getting password from form
  2. hashing the password
  3. stored password
  4. comparison of the two.

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

How to use refs in React with Typescript

One way (which I've been doing) is to setup manually :

refs: {
    [string: string]: any;
    stepInput:any;
}

then you can even wrap this up in a nicer getter function (e.g. here):

stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

The simplest solution that I could find using Typescript 3.1 in 3 steps is:

1) Make interface

interface IOriginal {
    original: { [key: string]: any }
}

2) Make a typed copy

let copy: IOriginal = (original as any)[key];

3) Use anywhere (JSX included)

<input customProp={copy} />

How do I fill arrays in Java?

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};

clear javascript console in Google Chrome

Instead of typing command just press:

CLTRL + L

to clear chrome console

Understanding React-Redux and mapStateToProps()

Yes, you can do this. You can also even process the state and return the object.

function mapStateToProps(state){  
  let completed = someFunction (state);
   return {
     completed : completed,  
   }
}
 

This would be useful if you want to shift the logic related to state from render function to outside of it.

Uninstall mongoDB from ubuntu

use command with sudo,

sudo apt-get autoremove --purge mongodb

OR

sudo apt-get remove mongodb* --purge

It will remove complete mongodb

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

Can't access Tomcat using IP address

Very strange because the firewall caused the issue.

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

How can I read SMS messages from the device programmatically in Android?

It is a trivial process. You can see a good example in the source code SMSPopup

Examine the following methods:

SmsMmsMessage getSmsDetails(Context context, long ignoreThreadId, boolean unreadOnly)
long findMessageId(Context context, long threadId, long _timestamp, int messageType
void setMessageRead(Context context, long messageId, int messageType)
void deleteMessage(Context context, long messageId, long threadId, int messageType)

this is the method for reading:

SmsMmsMessage getSmsDetails(Context context,
                            long ignoreThreadId, boolean unreadOnly)
{
   String SMS_READ_COLUMN = "read";
   String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null;
   String SORT_ORDER = "date DESC";
   int count = 0;
   // Log.v(WHERE_CONDITION);
   if (ignoreThreadId > 0) {
      // Log.v("Ignoring sms threadId = " + ignoreThreadId);
      WHERE_CONDITION += " AND thread_id != " + ignoreThreadId;
   }
   Cursor cursor = context.getContentResolver().query(
                      SMS_INBOX_CONTENT_URI,
                      new String[] { "_id", "thread_id", "address", "person", "date", "body" },
                      WHERE_CONDITION,
                      null,
                      SORT_ORDER);
   if (cursor != null) {
      try {
         count = cursor.getCount();
         if (count > 0) {
            cursor.moveToFirst();
            // String[] columns = cursor.getColumnNames();
            // for (int i=0; i<columns.length; i++) {
            // Log.v("columns " + i + ": " + columns[i] + ": " + cursor.getString(i));
            // }                                         
            long messageId = cursor.getLong(0);
            long threadId = cursor.getLong(1);
            String address = cursor.getString(2);
            long contactId = cursor.getLong(3);
            String contactId_string = String.valueOf(contactId);
            long timestamp = cursor.getLong(4);

            String body = cursor.getString(5);                             
            if (!unreadOnly) {
                count = 0;
            }

            SmsMmsMessage smsMessage = new SmsMmsMessage(context, address,
                          contactId_string, body, timestamp,
                          threadId, count, messageId, SmsMmsMessage.MESSAGE_TYPE_SMS);
            return smsMessage;
         }
      } finally {
         cursor.close();
      }
   }               
   return null;
}

Use ffmpeg to add text subtitles

NOTE: This solution "burns the subtitles" into the video, so that every viewer of the video will be forced to see them.

If your ffmpeg has libass enabled at compile time, you can directly do:

ffmpeg -i mymovie.mp4 -vf subtitles=subtitles.srt mysubtitledmovie.mp4

This is the case e.g. for Ubuntu 20.10, you can check if ffmpeg --version has --enable-libass.

Otherwise, you can the libass library (make sure your ffmpeg install has the library in the configuration --enable-libass).

First convert the subtitles to .ass format:

ffmpeg -i subtitles.srt subtitles.ass

Then add them using a video filter:

ffmpeg -i mymovie.mp4 -vf ass=subtitles.ass mysubtitledmovie.mp4

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

In Git, what is the difference between origin/master vs origin master?

I suggest merging develop and master with that command

git checkout master

git merge --commit --no-ff --no-edit develop

For more information, check https://git-scm.com/docs/git-merge

problem with <select> and :after with CSS in WebKit

<div class="select">
<select name="you_are" id="dropdown" class="selection">
<option value="0" disabled selected>Select</option>
<option value="1">Student</option>
<option value="2">Full-time Job</option>
<option value="2">Part-time Job</option>
<option value="3">Job-Seeker</option>
<option value="4">Nothing Yet</option>
</select>
</div>

Insted of styling the select why dont you add a div out-side the select.

and style then in CSS

.select{
    width: 100%;
    height: 45px;
    position: relative;
}
.select::after{
    content: '\f0d7';
    position: absolute;
    top: 0px;
    right: 10px;
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    color: #0b660b;
    font-size: 45px;
    z-index: 2;

}
#dropdown{
    -webkit-appearance: button;
       -moz-appearance: button;
            appearance: button;
            height: 45px;
            width: 100%;
        outline: none;
        border: none;
        border-bottom: 2px solid #0b660b;
        font-size: 20px;
        background-color: #0b660b23;
        box-sizing: border-box;
        padding-left: 10px;
        padding-right: 10px;
}

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

SQL query for extracting year from a date

Edit: due to post-tag 'oracle', the first two queries become irrelevant, leaving 3rd query for oracle.

For MySQL:

SELECT YEAR(ASOFDATE) FROM PASOFDATE

Editted: In anycase if your date is a String, let's convert it into a proper date format. And select the year out of it.

SELECT YEAR(STR_TO_DATE(ASOFDATE, '%d-%b-%Y')) FROM PSASOFDATE

Since you are trying Toad, can you check the following code:

For Oracle:

SELECT EXTRACT (TO_DATE(YEAR, 'MM/DD/YY') FROM ASOFDATE) FROM PSASOFDATE;

Reference:

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S on some versions of env to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).

Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

How to apply CSS page-break to print a table with lots of rows?

You can use the following:

<style type="text/css">
   table { page-break-inside:auto }
   tr    { page-break-inside:avoid; page-break-after:auto }
</style>

Refer the W3C's CSS Print Profile specification for details.

And also refer the Salesforce developer forums.

How to set Spring profile from system variable?

My solution is to set the environment variable as spring.profiles.active=development. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows

application.properties
system properties
environment variable

jQuery get value of select onChange

Let me share an example which I developed with BS4, thymeleaf and Spring boot.

I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").

First, the thymeleaf snippet:

 <div class="form-group">
     <label th:for="topicId" th:text="#{label.topic}">Topic</label>
     <select class="custom-select"
             th:id="topicId" th:name="topicId"
             th:field="*{topicId}"
             th:errorclass="is-invalid" required>
         <option value="" selected
                 th:text="#{option.select}">Select
         </option>
         <optgroup th:each="topicGroup : ${topicGroups}"
                   th:label="${topicGroup}">
             <option th:each="topicItem : ${topics}"
                     th:if="${topicGroup == topicItem.grp} "
                     th:value="${{topicItem.baseIdentity.id}}"
                     th:text="${topicItem.name}"
                     th:selected="${{topicItem.baseIdentity.id==topicId}}">
             </option>
         </optgroup>
         <option th:each="topicIter : ${topics}"
                 th:if="${topicIter.grp == ''} "
                 th:value="${{topicIter.baseIdentity.id}}"
                 th:text="${topicIter.name}"
                 th:selected="${{topicIter.baseIdentity?.id==topicId}}">
         </option>
     </select>
     <small id="topicHelp" class="form-text text-muted"
            th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->

<div class="form-group">
    <label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
    <select class="custom-select"
            id="subtopicsId" name="subtopicsId"
            th:field="*{subtopicsId}"
            th:errorclass="is-invalid" multiple="multiple">
        <option value="" disabled
                th:text="#{option.multiple.optional}">Select
        </option>
        <option th:each="subtopicsIter : ${subtopicsList}"
                th:value="${{subtopicsIter.baseIdentity.id}}"
                th:text="${subtopicsIter.name}">
        </option>
    </select>
    <small id="subtopicsHelp" class="form-text text-muted"
           th:unless="${#fields.hasErrors('subtopicsId')}"
           th:text="#{label.subtopics.tt}">select</small>
    <small id="subtopicsIdError" class="invalid-feedback"
           th:if="${#fields.hasErrors('subtopicsId')}"
           th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->

I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.

Now, here's the jQuery that handles changes:

$('#topicId').change(function () {
    selectedOption = $(this).val();
    if (selectedOption === "") {
        $('#subtopicsId').prop('disabled', 'disabled').val('');
        $("#subtopicsId option").slice(1).remove(); // keep first
    } else {
        $('#subtopicsId').prop('disabled', false)
        var orig = $(location).attr('origin');
        var url = orig + "/getsubtopics/" + selectedOption;
        $.ajax({
            url: url,
           success: function (response) {
                  var len = response.length;
                    $("#subtopicsId option[value!='']").remove(); // keep first 
                    for (var i = 0; i < len; i++) {
                        var id = response[i]['baseIdentity']['id'];
                        var name = response[i]['name'];
                        $("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
                    }
                },
                error: function (e) {
                    console.log("ERROR : ", e);
                }
        });
    }
}).change(); // and call it once defined

The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.

BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.

Laravel Update Query

It is very simple to do. Code are given below :

 DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));  

How to rotate the background image in the container?

CSS:

.reverse {
  transform: rotate(180deg);
}

.rotate {
  animation-duration: .5s;
  animation-iteration-count: 1;
  animation-name: yoyo;
  animation-timing-function: linear;
}

@keyframes yoyo {
  from { transform: rotate(  0deg); }
  to   { transform: rotate(360deg); }
}

Javascript:

$(buttonElement).click(function () {
  $(".arrow").toggleClass("reverse")

  return false
})

$(buttonElement).hover(function () {
  $(".arrow").addClass("rotate")
}, function() {
  $(".arrow").removeClass("rotate")
})

PS: I've found this somewhere else but don't remember the source

Django CSRF Cookie Not Set

If you're using the HTML5 Fetch API to make POST requests as a logged in user and getting Forbidden (CSRF cookie not set.), it could be because by default fetch does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.

You can include the session token by passing the option credentials: 'include' to fetch:

var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
    method: 'POST',
    body: payload,
    headers: headers,
    credentials: 'include'
})

Spring Boot Multiple Datasource

Using two datasources you need their own transaction managers.

@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction

@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

MySQL - select data from database between two dates

Have you tried before and after rather than >= and <=? Also, is this a date or a timestamp?

Create a menu Bar in WPF?

<StackPanel VerticalAlignment="Top">
    <Menu Width="Auto" Height="20">
        <MenuItem Header="_File">
            <MenuItem x:Name="AppExit" Header="E_xit" HorizontalAlignment="Left" Width="140" Click="AppExit_Click"/>
        </MenuItem>
        <MenuItem Header="_Tools">
            <MenuItem x:Name="Options" Header="_Options" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
        <MenuItem Header="_Help">
            <MenuItem x:Name="About" Header="&amp;About" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
    </Menu>
    <Label Content="Label"/>
</StackPanel>

Applying styles to tables with Twitter Bootstrap

You can also apply TR classes: info, error, warning, or success.

jQuery / Javascript code check, if not undefined

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

Padding between ActionBar's home icon and title

I used \t before the title and worked for me.

Returning multiple values from a C++ function

The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.

Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.

I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.

Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.

Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..

Convert .pfx to .cer

I wanted to add a method which I think was simplest of all.

  1. Simply right click the pfx file, click "Install" follow the wizard, and add it to a store (I added to the Personal store).

  2. In start menu type certmgr.msc and go to CertManager program.

  3. Find your pfx certificate (tabs at top are the various stores), click the export button and follow the wizard (there is an option to export as .CER)

Essentially it does the same thing as Andrew's answer, but it avoids using Windows Management Console (goes straight to the import/export).

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

Importing csv file into R - numeric values read as characters

version for data.table based on code from dmanuge :

convNumValues<-function(ds){
  ds<-data.table(ds)
  dsnum<-data.table(data.matrix(ds))
  num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
  nds <- data.table(  dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
                        ,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}

how to find host name from IP with out login to the host

Use nslookup

nslookup 208.77.188.166 
...
Non-authoritative answer:
166.188.77.208.in-addr.arpa     name = www.example.com.

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Ruby array to string conversion

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

bash string compare to multiple correct values

As @Renich suggests (but with an important typo that has not been fixed unfortunately), you can also use extended globbing for pattern matching. So you can use the same patterns you use to match files in command arguments (e.g. ls *.pdf) inside of bash comparisons.

For your particular case you can do the following.

if [[ "${cms}" != @(wordpress|magento|typo3) ]]

The @ means "Matches one of the given patterns". So this is basically saying cms is not equal to 'wordpress' OR 'magento' OR 'typo3'. In normal regular expression syntax @ is similar to just ^(wordpress|magento|typo3)$.

Mitch Frazier has two good articles in the Linux Journal on this Pattern Matching In Bash and Bash Extended Globbing.

For more background on extended globbing see Pattern Matching (Bash Reference Manual).

Extract subset of key-value pairs from Python dictionary object?

Okay, this is something that has bothered me a few times, so thank you Jayesh for asking it.

The answers above seem like as good a solution as any, but if you are using this all over your code, it makes sense to wrap the functionality IMHO. Also, there are two possible use cases here: one where you care about whether all keywords are in the original dictionary. and one where you don't. It would be nice to treat both equally.

So, for my two-penneth worth, I suggest writing a sub-class of dictionary, e.g.

class my_dict(dict):
    def subdict(self, keywords, fragile=False):
        d = {}
        for k in keywords:
            try:
                d[k] = self[k]
            except KeyError:
                if fragile:
                    raise
        return d

Now you can pull out a sub-dictionary with

orig_dict.subdict(keywords)

Usage examples:

#
## our keywords are letters of the alphabet
keywords = 'abcdefghijklmnopqrstuvwxyz'
#
## our dictionary maps letters to their index
d = my_dict([(k,i) for i,k in enumerate(keywords)])
print('Original dictionary:\n%r\n\n' % (d,))
#
## constructing a sub-dictionary with good keywords
oddkeywords = keywords[::2]
subd = d.subdict(oddkeywords)
print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,))
#
## constructing a sub-dictionary with mixture of good and bad keywords
somebadkeywords = keywords[1::2] + 'A'
try:
    subd2 = d.subdict(somebadkeywords)
    print("We shouldn't see this message")
except KeyError:
    print("subd2 construction fails:")
    print("\toriginal dictionary doesn't contain some keys\n\n")
#
## Trying again with fragile set to false
try:
    subd3 = d.subdict(somebadkeywords, fragile=False)
    print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,))
except KeyError:
    print("We shouldn't see this message")

If you run all the above code, you should see (something like) the following output (sorry for the formatting):

Original dictionary:
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}

Dictionary from odd numbered keys:
{'a': 0, 'c': 2, 'e': 4, 'g': 6, 'i': 8, 'k': 10, 'm': 12, 'o': 14, 'q': 16, 's': 18, 'u': 20, 'w': 22, 'y': 24}

subd2 construction fails:
original dictionary doesn't contain some keys

Dictionary constructed using some bad keys:
{'b': 1, 'd': 3, 'f': 5, 'h': 7, 'j': 9, 'l': 11, 'n': 13, 'p': 15, 'r': 17, 't': 19, 'v': 21, 'x': 23, 'z': 25}

sudo: docker-compose: command not found

Or, just add your binary path into the PATH. At the end of the bashrc:

... 
export PATH=$PATH:/home/user/.local/bin/

save the file and run:

source .bashrc

and the command will work.

What is .htaccess file?

.htaccess file create in directory /var/www/html/.htaccess

<IfModule mod_rewrite.c>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>

Is log(n!) = T(n·log(n))?

See Stirling's Approximation:

ln(n!) = n*ln(n) - n + O(ln(n))

where the last 2 terms are less significant than the first one.

Dynamic WHERE clause in LINQ

I have similar scenario where I need to add filters based on the user input and I chain the where clause.

Here is the sample code.

var votes = db.Votes.Where(r => r.SurveyID == surveyId);
if (fromDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value >= fromDate);
}
if (toDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value <= toDate);
}
votes = votes.Take(LimitRows).OrderByDescending(r => r.VoteDate);

How do I measure a time interval in C?

If your Linux system supports it, clock_gettime(CLOCK_MONOTONIC) should be a high resolution timer that is unaffected by system date changes (e.g. NTP daemons).

Groovy write to file (newline)

It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

IIS: Idle Timeout vs Recycle

I have inherited a desktop app that makes calls to a series of Web Services on IIS. The web services (also) have to be able to run timed processes, independently (without having the client on). Hence they all have timers. The web service timers were shutting down (memory leak?) so we set the Idle time out to 0 and timers stay on.

What are metaclasses in Python?

In addition to the published answers I can say that a metaclass defines the behaviour for a class. So, you can explicitly set your metaclass. Whenever Python gets a keyword class then it starts searching for the metaclass. If it's not found – the default metaclass type is used to create the class's object. Using the __metaclass__ attribute, you can set metaclass of your class:

class MyClass:
   __metaclass__ = type
   # write here other method
   # write here one more method

print(MyClass.__metaclass__)

It'll produce the output like this:

class 'type'

And, of course, you can create your own metaclass to define the behaviour of any class that are created using your class.

For doing that, your default metaclass type class must be inherited as this is the main metaclass:

class MyMetaClass(type):
   __metaclass__ = type
   # you can write here any behaviour you want

class MyTestClass:
   __metaclass__ = MyMetaClass

Obj = MyTestClass()
print(Obj.__metaclass__)
print(MyMetaClass.__metaclass__)

The output will be:

class '__main__.MyMetaClass'
class 'type'

Android Gradle Could not reserve enough space for object heap

in gradle.properties, you can even delete

org.gradle.jvmargs=-Xmx1536m

such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

For Cordova OR Ionic Hybrid App

I have the very similar problem with my Ionic 1 Cordova Build after Integrating the Firebase Cloud Messaging ( FCM )

I fixed this issue by the following steps

So one fix will be: inside platforms/android open project.properties (Its a file ) , you will have something like this

cordova.system.library.1=com.google.android.gms:play-services-ads:+
cordova.system.library.2=com.google.firebase:firebase-core:+
cordova.system.library.3=com.google.firebase:firebase-messaging:+

Replace the

+

Sign with your target version number - like the following

cordova.system.library.1=com.google.android.gms:play-services-ads:9.0.0
cordova.system.library.2=com.google.firebase:firebase-core:9.0.0
cordova.system.library.3=com.google.firebase:firebase-messaging:9.0.0

Save the file

Then take build using

 ionic cordova run android

I hope this will work for everyone

Setting DIV width and height in JavaScript

Fix the typos in your code ("document" is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and then you'll be fine. You should really follow jmort's advice and simply set up 2 css classes that you switch between in javascript -- it would make your life a lot easier and save yourself from all the extra typing. The typos you've committed are a perfect example of why this is the better approach.

For brownie points, you should also check out element.addEventListener for assigning event handlers to your elements.

Update TextView Every Second

You can use Timer instead of Thread. This is whole my code

package dk.tellwork.tellworklite.tabs;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import dk.tellwork.tellworklite.MainActivity;
import dk.tellwork.tellworklite.R;

@SuppressLint("HandlerLeak")
public class HomeActivity extends Activity {
    Button chooseYourAcitivity, startBtn, stopBtn;
    TextView labelTimer;
    int passedSenconds;
    Boolean isActivityRunning = false;
    Timer timer;
    TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_home);

        chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);
        chooseYourAcitivity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //move to Activities tab
                switchTabInActivity(1);
            }
        });

        labelTimer = (TextView)findViewById(R.id.labelTime);
        passedSenconds = 0;

        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isActivityRunning) {
                    //pause running activity
                    timer.cancel();
                    startBtn.setText(getString(R.string.homeStartBtn));
                    isActivityRunning = false;
                } else {
                    reScheduleTimer();
                    startBtn.setText(getString(R.string.homePauseBtn));
                    isActivityRunning = true;
                }
            }
        });

        stopBtn = (Button)findViewById(R.id.stopBtn);
        stopBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                timer.cancel();
                passedSenconds = 0;
                labelTimer.setText("00 : 00 : 00");
                startBtn.setText(getString(R.string.homeStartBtn));
                isActivityRunning = false;
            }
        });
    }

    public void reScheduleTimer(){
        timer = new Timer();
        timerTask = new myTimerTask();
        timer.schedule(timerTask, 0, 1000);
    }

    private class myTimerTask extends TimerTask{
        @Override
        public void run() {
            // TODO Auto-generated method stub
            passedSenconds++;
            updateLabel.sendEmptyMessage(0);
        }
    }

    private Handler updateLabel = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            //super.handleMessage(msg);

            int seconds = passedSenconds % 60;
            int minutes = (passedSenconds / 60) % 60;
            int hours = (passedSenconds / 3600);
            labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));
        }
    };

    public void switchTabInActivity(int indexTabToSwitchTo){
        MainActivity parentActivity;
        parentActivity = (MainActivity) this.getParent();
        parentActivity.switchTab(indexTabToSwitchTo);
    }
}

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

Foreign Key naming scheme

The standard convention in SQL Server is:

FK_ForeignKeyTable_PrimaryKeyTable

So, for example, the key between notes and tasks would be:

FK_note_task

And the key between tasks and users would be:

FK_task_user

This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:

FK_task_user
FK_note_task
FK_note_user

So you can see that tasks depend on users, and notes depend on both tasks and users.

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I was also having the same problem, looked for phpinfo.ini, php.ini or .htaccess files to no avail. Finally I have looked at some php files, opened them and checked the codes inside for memory. Finally this solution was what I come out with and it worked for me. I was using wordpress, so this solution might only work for wordpress memory size limit problem. My solution, open default-constants.php file in /public_html/wp-includes folder. Open that file with code editor, and find memory settings under wp_initial_constants scope, or just Ctrl+F it to find the word "memory". There you will come over WP_MEMORY_LIMIT and WP_MAX_MEMORY_LIMIT. Just increase it, it was 64 MB in my case, I increased it to 128 MB and then to 200 MB.

// Define memory limits.
if ( ! defined( 'WP_MEMORY_LIMIT' ) ) {
    if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
        define( 'WP_MEMORY_LIMIT', $current_limit );
    } elseif ( is_multisite() ) {
        define( 'WP_MEMORY_LIMIT', '200M' );
    } else {
        define( 'WP_MEMORY_LIMIT', '128M' );
    }
}

if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) {
    if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
        define( 'WP_MAX_MEMORY_LIMIT', $current_limit );
    } elseif ( -1 === $current_limit_int || $current_limit_int > 268435456 /* = 256M */ ) {
        define( 'WP_MAX_MEMORY_LIMIT', $current_limit );
    } else {
        define( 'WP_MAX_MEMORY_LIMIT', '256M' );
    }
}

Btw, please don't do the following code, because that's bad practice:

ini_set('memory_limit', '-1');

How do I get the current GPS location programmatically in Android?

I have got very accurate location using FusedLocationProviderClient
(Google Play services required)

Permissions Required

android.permission.ACCESS_FINE_LOCATION

android.permission.ACCESS_COARSE_LOCATION

Dependency

'com.google.android.gms:play-services-location:15.0.0'

Kotlin Code

val client = FusedLocationProviderClient(this)
val location = client.lastLocation
location.addOnCompleteListener {
    // this is a lambda expression and we get an 'it' iterator to access the 'result'
    // it.result.latitude gives the latitude
    // it.result.longitude gives the longitude 
    val geocoder = Geocoder(applicationContext, Locale.getDefault())
    val address = geocoder.getFromLocation(it.result.latitude, it.result.longitude, 1)
    if (address != null && address.size > 0) {
        // Get the current city
        city = address[0].locality
    }
}
location.addOnFailureListener {
    // Some error in getting the location, let's log it
    Log.d("xtraces", it.message)
}

jQuery selector for inputs with square brackets in the name attribute

The attribute selector syntax is [name=value] where name is the attribute name and value is the attribute value.

So if you want to select all input elements with the attribute name having the value inputName[]:

$('input[name="inputName[]"]')

And if you want to check for two attributes (here: name and value):

$('input[name="inputName[]"][value=someValue]')

How to obfuscate Python code effectively?

Well if you want to make a semi-obfuscated code you make code like this:

import base64
import zlib
def run(code): exec(zlib.decompress(base64.b16decode(code)))
def enc(code): return base64.b16encode(zlib.compress(code))

and make a file like this (using the above code):

f = open('something.py','w')
f.write("code=" + enc("""
print("test program")
print(raw_input("> "))"""))
f.close()

file "something.py":

code = '789CE352008282A2CCBC120DA592D4E212203B3FBD28315749930B215394581E9F9957500A5463A7A0A4A90900ADFB0FF9'

just import "something.py" and run run(something.code) to run the code in the file.

One trick is to make the code hard to read by design: never document anything, if you must, just give the output of a function, not how it works. Make variable names very broad, movie references, or opposites example: btmnsfavclr = 16777215 where as "btmnsfavclr" means "Batman's Favorite Color" and the value is 16777215 or the decimal form of "ffffff" or white. Remember to mix different styles of naming to keep those pesky people of of your code. Also, use tips on this site: Top 11 Tips to Develop Unmaintainable Code.

How do I iterate over an NSArray?

The generally-preferred code for 10.5+/iOS.

for (id object in array) {
    // do something with object
}

This construct is used to enumerate objects in a collection which conforms to the NSFastEnumeration protocol. This approach has a speed advantage because it stores pointers to several objects (obtained via a single method call) in a buffer and iterates through them by advancing through the buffer using pointer arithmetic. This is much faster than calling -objectAtIndex: each time through the loop.

It's also worth noting that while you technically can use a for-in loop to step through an NSEnumerator, I have found that this nullifies virtually all of the speed advantage of fast enumeration. The reason is that the default NSEnumerator implementation of -countByEnumeratingWithState:objects:count: places only one object in the buffer on each call.

I reported this in radar://6296108 (Fast enumeration of NSEnumerators is sluggish) but it was returned as Not To Be Fixed. The reason is that fast enumeration pre-fetches a group of objects, and if you want to enumerate only to a given point in the enumerator (e.g. until a particular object is found, or condition is met) and use the same enumerator after breaking out of the loop, it would often be the case that several objects would be skipped.

If you are coding for OS X 10.6 / iOS 4.0 and above, you also have the option of using block-based APIs to enumerate arrays and other collections:

[array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
    // do something with object
}];

You can also use -enumerateObjectsWithOptions:usingBlock: and pass NSEnumerationConcurrent and/or NSEnumerationReverse as the options argument.


10.4 or earlier

The standard idiom for pre-10.5 is to use an NSEnumerator and a while loop, like so:

NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
  // do something with object
}

I recommend keeping it simple. Tying yourself to an array type is inflexible, and the purported speed increase of using -objectAtIndex: is insignificant to the improvement with fast enumeration on 10.5+ anyway. (Fast enumeration actually uses pointer arithmetic on the underlying data structure, and removes most of the method call overhead.) Premature optimization is never a good idea — it results in messier code to solve a problem that isn't your bottleneck anyway.

When using -objectEnumerator, you very easily change to another enumerable collection (like an NSSet, keys in an NSDictionary, etc.), or even switch to -reverseObjectEnumerator to enumerate an array backwards, all with no other code changes. If the iteration code is in a method, you could even pass in any NSEnumerator and the code doesn't even have to care about what it's iterating. Further, an NSEnumerator (at least those provided by Apple code) retains the collection it's enumerating as long as there are more objects, so you don't have to worry about how long an autoreleased object will exist.

Perhaps the biggest thing an NSEnumerator (or fast enumeration) protects you from is having a mutable collection (array or otherwise) change underneath you without your knowledge while you're enumerating it. If you access the objects by index, you can run into strange exceptions or off-by-one errors (often long after the problem has occurred) that can be horrific to debug. Enumeration using one of the standard idioms has a "fail-fast" behavior, so the problem (caused by incorrect code) will manifest itself immediately when you try to access the next object after the mutation has occurred. As programs get more complex and multi-threaded, or even depend on something that third-party code may modify, fragile enumeration code becomes increasingly problematic. Encapsulation and abstraction FTW! :-)


Difference between java.exe and javaw.exe

The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

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

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Random number from a range in a Bash Script

Same with ruby:

echo $(ruby -e 'puts rand(20..65)') #=> 65 (inclusive ending)
echo $(ruby -e 'puts rand(20...65)') #=> 37 (exclusive ending)

How do I pass along variables with XMLHTTPRequest

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
const params = new URLSearchParams();_x000D_
params.set('var1', 'foo');_x000D_
params.set('var2', 'bar');_x000D_
target.search = params.toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

Or to convert an entire object's worth of parameters:

_x000D_
_x000D_
const paramsObject = {_x000D_
  var1: 'foo',_x000D_
  var2: 'bar'_x000D_
};_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
target.search = new URLSearchParams(paramsObject).toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

How to validate phone number in laravel 5.2?

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:

 'phone' => 'required|numeric|phone' 

De-obfuscate Javascript code to make it readable again

From the first link on google;

function call_func(_0x41dcx2) {
 var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
 var _0x41dcx4 = document['createElement']('div');
 var _0x41dcx5 = _0x41dcx3['id'];
 var _0x41dcx6 = _0x41dcx3['Student_name'];
 var _0x41dcx7 = _0x41dcx3['student_dob'];
 var _0x41dcx8 = '<b>ID:</b>';
 _0x41dcx8 += '<a href="/learningyii/index.php?r=student/view&amp; id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student Name:</b>';
 _0x41dcx8 += _0x41dcx6;
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student DOB:</b>';
 _0x41dcx8 += _0x41dcx7;
 _0x41dcx8 += '<br/>';
 _0x41dcx4['innerHTML'] = _0x41dcx8;
 _0x41dcx4['setAttribute']('class', 'view');
 $('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};

It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

"Error: Main method not found in class MyClass, please define the main method as..."

The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.

It

  • must be static
  • must have exactly one String array argument (which may be named anything)
  • must be spelled m-a-i-n in lowercase.

Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.

Select2 open dropdown on focus

Somehow select2Focus didn't work here with empty selection, couldn't figured out the issue, therefore I added manual control when after focus event auto open get's triggered.

Here is coffeescript:

$("#myid").select2()
  .on 'select2-blur', ->
    $(this).data('select2-auto-open', 'true')
  .on 'select2-focus', ->
    $(this).data('select2').open() if $(this).data('select2-auto-open') != 'false'
  .on 'select2-selecting', ->
    $(this).data('select2-auto-open', 'false')

Linux command for extracting war file?

Extracting a specific folder (directory) within war file:

# unzip <war file> '<folder to extract/*>' -d <destination path> 
unzip app##123.war 'some-dir/*' -d extracted/

You get ./extracted/some-dir/ as a result.

Create an empty list in python with certain size

One simple way to create a 2D matrix of size n using nested list comprehensions:

m = [[None for _ in range(n)] for _ in range(n)]

Postgresql GROUP_CONCAT equivalent?

and the version to work on the array type:

select
  array_to_string(
    array(select distinct unnest(zip_codes) from table),
    ', '
);

How can I validate google reCAPTCHA v2 using javascript/jQuery?

If you render the Recaptcha on a callback

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

using an empty DIV as a placeholder

<div id='html_element'></div>

then you can specify an optional function call on a successful CAPTCHA response

var onloadCallback = function() {
    grecaptcha.render('html_element', {
      'sitekey' : 'your_site_key',
      'callback' : correctCaptcha
    });
  };

The recaptcha response will then be sent to the 'correctCaptcha' function.

var correctCaptcha = function(response) {
    alert(response);
};

All of this was from the Google API notes :

Google Recaptcha v2 API Notes

I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.

Hope this helps.

Paul

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

How do I use extern to share variables between source files?

extern tells the compiler to trust you that the memory for this variable is declared elsewhere, so it doesnt try to allocate/check memory.

Therefore, you can compile a file that has reference to an extern, but you can not link if that memory is not declared somewhere.

Useful for global variables and libraries, but dangerous because the linker does not type check.

Android replace the current fragment with another fragment

Use android.support.v4.app for FragmentManager & FragmentTransaction in your code, it has worked for me.

DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

Detect whether Office is 32bit or 64bit via the registry

I found the way for checking office bitness .

We can check office 365 and 2016 bitness using this registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRun\Configuration

Platform x86 for 32 bit.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRun\Configuration

Platform x64 for 64 bit.

Please check...

Search File And Find Exact Match And Print Line?

Build lists of matched lines - several flavors:

def lines_that_equal(line_to_match, fp):
    return [line for line in fp if line == line_to_match]

def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

def lines_that_start_with(string, fp):
    return [line for line in fp if line.startswith(string)]

def lines_that_end_with(string, fp):
    return [line for line in fp if line.endswith(string)]

Build generator of matched lines (memory efficient):

def generate_lines_that_equal(string, fp):
    for line in fp:
        if line == string:
            yield line

Print all matching lines (find all matches first, then print them):

with open("file.txt", "r") as fp:
    for line in lines_that_equal("my_string", fp):
        print line

Print all matching lines (print them lazily, as we find them)

with open("file.txt", "r") as fp:
    for line in generate_lines_that_equal("my_string", fp):
        print line

Generators (produced by yield) are your friends, especially with large files that don't fit into memory.

Scanner vs. BufferedReader

Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.

In fact you can pass a BufferedReader to a scanner as the source of characters to parse.

maven compilation failure

It COULD be due to insufficient heap memory.

It sounds strange, but try it, it might just work:

export MAVEN_OPTS='-Xms384M -Xmx512M -XX:MaxPermSize=256M'

Source: https://groups.google.com/group/neo4j/msg/e208be9ee1c101d7)

what is Promotional and Feature graphic in Android Market/Play Store?

I found this nice write-up that clears it up pretty nicely:

The different graphic assets we request are used to highlight and promote your application in Android Market, and possibly other Google-owned properties. If you’d like to restrict the marketing of your app to just Android Market, you have the option of opting-out of marketing by selecting the "Marketing Opt-Out" in the Developer Console.

Screenshots (Required):
We require 2 screenshots.
Use: Displayed on the details page for your application in Android Market.
You may upload up to 8 screenshots.
Specs: 320w x 480h, 480w x 800h, or 480w x 854h; 24 bit PNG or JPEG (no alpha) Full bleed, no border in art.
Tips:
Landscape thumbnails are cropped, but we preserve the image’s full size and aspect ratio if the user opens it up on market client.
High Resolution Application Icon (Required):
Use: In various locations in Android Market.
Does not replace your launcher icon.
Specs: 512x512, 32-bit PNG with alpha; Max size of 1024KB.
Tips:
This does not replace your launcher icon, but should be a higher-fidelity, higher-resolution version of your application icon.
Same safe-frame as current launcher guidelines, just scaled up:
Full Asset: 512 x 512 px.
Circle or non-square icons: 426 x 426 px, centered within the PNG.
Square Icons: 398 x 398 px.
Drop shadow: black, 75% opaque, 90 degrees down, distance of 14px, size of 36px.
Tweak as necessary to fit icon style (e.g., Google Maps icon has a drop shadow of varying height).
Promotional Graphic (Optional):
Use: In various locations in Android Market.
Specs: 180w x 120h, 24 bit PNG or JPEG (no alpha), Full bleed, no border in art.
Feature Graphic (Optional):
Use: The featured section in Android Market. Will be downsized to mini or micro.
Specs: 1024w x 500h, 24 bit PNG or JPEG (no alpha) with no transparency
Tips:
Use a safe frame of 924x400 (50 pixel of safe padding on each side). All the important content of the graphic should be within this safe frame. Pixels outside of this safe frame may be cropped for stylistic purposes.
If incorporating text, use large font sizes, and keep the graphic simple, as this graphic may be scaled down from its original size.
This graphic may be displayed alone without the app icon.
Video Link (Optional):
Specs: Enter the URL to a YouTube video showcasing your app.
Tip:
Short videos (30 seconds - 2 minutes) highlighting the top features of your app work best.

Printing pointers in C

If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.

For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another.

  • void* p; says p is a memory address, but I don't know what's in the memory
  • char* s; says s is a memory address, and the first byte contains a character
  • char** ps; says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.

cf http://www.oberon2005.ru/paper/kr_c.pdf (e-book version of K&R)

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Setting format and value in input type="date"

new Date().toISOString().split('T')[0];

Global keyboard capture in C# application

My rep is too low to comment, but concerning the CallbackOnCollectedDelegate exception, I modified the public void SetupKeyboardHooks() in C4d's answer to look like this:

public void SetupKeyboardHooks(out object hookProc)
{
  _globalKeyboardHook = new GlobalKeyboardHook();
  _globalKeyboardHook.KeyboardPressed += OnKeyPressed;


  hookProc = _globalKeyboardHook.GcSafeHookProc;
}

where GcSafeHookProc is just a public getter for _hookProc in OPs

_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

and stored the hookProc as a private field in the class calling the SetupKeyboardHooks(...), therefore keeping the reference alive, save from garbage collection, no more CallbackOnCollectedDelegate exception. Seems having this additional reference in the GlobalKeyboardHook class is not sufficient. Maybe make sure that this reference is also disposed when closing your app.

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

pip3: command not found but python3-pip is already installed

Run

locate pip3

it should give you a list of results like this

/<path>/pip3
/<path>/pip3.x

go to /usr/local/bin to make a symbolic link to where your pip3 is located

ln -s /<path>/pip3.x /usr/local/bin/pip3

How to change default format at created_at and updated_at value laravel

If anyone is looking for a simple solution in Laravel 5.3:

  1. Let default timestamps() be saved as is i.e. '2016-11-14 12:19:49'
  2. In your views, format the field as below (or as required):

    date('F d, Y', strtotime($list->created_at))
    

It worked for me very well for me.

Install tkinter for Python

tk-devel also needs to be installed in my case

yum install -y tkinter tk-devel

install these and rebuild python

Qt jpg image display

#include ...

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    QGraphicsView view(&scene);
    QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
    scene.addItem(&item);
    view.show();
    return a.exec();
}

This should work. :) List of supported formats can be found here

How to set fake GPS location on IOS real device

Working with GPX files with Xcode compatibility

I followed the link given by AlexWien and it was extremely useful: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html

But, I spent quite some time searching for how to generate .gpx files with waypoints (wpt tags), as Xcode only accepts wpt tags.

The following tool converts a Google Maps link (also works with Google Maps Directions) to a .gpx file.

https://mapstogpx.com/mobiledev.php

Simulating a trip duration is supported, custom durations can be specified. Just select Xcode and it gets the route as waypoints.

How to copy sheets to another workbook using vba?

Someone over at Ozgrid answered a similar question. Basically, you just copy each sheet one at a time from Workbook1 to Workbook2.

Sub CopyWorkbook()

    Dim currentSheet as Worksheet
    Dim sheetIndex as Integer
    sheetIndex = 1

    For Each currentSheet in Worksheets

        Windows("SOURCE WORKBOOK").Activate 
        currentSheet.Select
        currentSheet.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(sheetIndex) 

        sheetIndex = sheetIndex + 1

    Next currentSheet

End Sub

Disclaimer: I haven't tried this code out and instead just adopted the linked example to your problem. If nothing else, it should lead you towards your intended solution.