Programs & Examples On #Optimizely

Optimizely provides A/B testing, Multivariate Testing and optimizations for websites and mobile apps via software as a service

Android Studio Run/Debug configuration error: Module not specified

I realized following line was missing in settings.gradle file

include ':app'

make sure you include ":app" module

Fatal error: "No Target Architecture" in Visual Studio

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

How to customize Bootstrap 3 tab color

I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important (to override the default style on bootstrap.css).

Example code

_x000D_
_x000D_
.nav {_x000D_
    background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
    background-color: #666 !important;_x000D_
    color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
  <!-- Nav tabs -->_x000D_
  <ul class="nav nav-tabs" role="tablist">_x000D_
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
    <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
  </ul>_x000D_
_x000D_
  <!-- Tab panes -->_x000D_
  <div class="tab-content">_x000D_
    <div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/zjjpocv6/2/

The type arguments for method cannot be inferred from the usage

Now my aim was to have one pair with an base type and a type definition (Requirement A). For the type definition I want to use inheritance (Requirement B). The use should be possible, without explicite knowledge over the base type (Requirement C).

After I know now that the gernic constraints are not used for solving the generic return type, I experimented a little bit:

Ok let's introducte Get2:

class ServiceGate
{
    public IAccess<C, T> Get1<C, T>(C control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

    public IAccess<ISignatur<T>, T> Get2<T>(ISignatur<T> control)
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
    }
}

Fine, but this solution reaches not requriement B.

Next try:

class ServiceGate
{
    public IAccess<C, T> Get3<C, T>(C control, ISignatur<T> iControl) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!! 
    }
}

Nice! Now the compiler can infer the generic return types. But i don't like it. Other try:

class IC<A, B>
{
    public IC(A a, B b)
    {
        Value1 = a;
        Value2 = b;
    }

    public A Value1 { get; set; }

    public B Value2 { get; set; }
}

class Signatur : ISignatur<bool>
{
    public string Test { get; set; }

    public IC<Signatur, ISignatur<bool>> Get()
    {
        return new IC<Signatur, ISignatur<bool>>(this, this);
    }
}

class ServiceGate
{
    public IAccess<C, T> Get4<C, T>(IC<C, ISignatur<T>> control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!!
        var bla4 = service.Get4((new Signatur()).Get()); // Better...
    }
}

My final solution is to have something like ISignature<B, C>, where B ist the base type and C the definition...

TypeError: $ is not a function when calling jQuery function

Try this:

<script language="JavaScript" type="text/javascript" src="jquery/jquery.js"></script>
<script>
    jQuery.noConflict();
    (function ($) {
        function readyFn() {
            // Set your code here!!
        }

        $(document).ready(readyFn); 
    })(jQuery);

</script>

Comparing object properties in c#

Make sure objects aren't null.

Having obj1 and obj2:

if(obj1 == null )
{
   return false;
}
return obj1.Equals( obj2 );

Wget output document and headers to STDOUT

Try the following, no extra headers

wget -qO- www.google.com

Note the trailing -. This is part of the normal command argument for -O to cat out to a file, but since we don't use > to direct to a file, it goes out to the shell. You can use -qO- or -qO -.

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

Webpack how to build production code and how to use it

You can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below

plugins: [
    new webpack.DefinePlugin({
        'process.env':{
            'NODE_ENV': argv.p ? JSON.stringify('production') : JSON.stringify('development')
        }
    })
]

And thats it.

Filter output in logcat by tagname

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

If you just want to set the log levels for some tags you can do it on a tag by tag basis.

The located assembly's manifest definition does not match the assembly reference

You can do a couple of things to troubleshoot this issue. First, use Windows file search to search your hard drive for your assembly (.dll). Once you have a list of results, do View->Choose Details... and then check "File Version". This will display the version number in the list of results, so you can see where the old version might be coming from.

Also, like Lars said, check your GAC to see what version is listed there. This Microsoft article states that assemblies found in the GAC are not copied locally during a build, so you might need to remove the old version before doing a rebuild all. (See my answer to this question for notes on creating a batch file to do this for you)

If you still can't figure out where the old version is coming from, you can use the fuslogvw.exe application that ships with Visual Studio to get more information about the binding failures. Microsoft has information about this tool here. Note that you'll have to enable logging by setting the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\EnableLog registry key to 1.

What is the difference between task and thread?

I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

private async void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    await Task.Run(() => {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
    })
    buttonDownload.Enabled = true;
}

VS

private void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    Thread t = new Thread(() =>
    {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
        this.Invoke((MethodInvoker)delegate()
        {
            buttonDownload.Enabled = true;
        });
    });
    t.IsBackground = true;
    t.Start();
}

the difference is you don't need to use MethodInvoker and shorter code.

How to open mail app from Swift

Swift 2, with availability check:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["[email protected]"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    presentViewController(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}


// MARK: - MFMailComposeViewControllerDelegate

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    switch result.rawValue {
    case MFMailComposeResultCancelled.rawValue:
        print("Cancelled")
    case MFMailComposeResultSaved.rawValue:
        print("Saved")
    case MFMailComposeResultSent.rawValue:
        print("Sent")
    case MFMailComposeResultFailed.rawValue:
        print("Error: \(error?.localizedDescription)")
    default:
        break
    }
    controller.dismissViewControllerAnimated(true, completion: nil)
}

Display Back Arrow on Toolbar

In your manifest file for the activity where you want to add a back button, we will use the property android:parentActivityName

        <activity
        android:name=".WebActivity"
        android:screenOrientation="portrait"
        android:parentActivityName=".MainActivity"
        />

P.S. This attribute was introduced in API Level 16.

PHP: trying to create a new line with "\n"

$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"&lt;br/>";

How to clean old dependencies from maven repositories?

  1. Download all actual dependencies of your projects

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  2. Move your local maven repository to temporary location

    mv ~/.m2 ~/saved-m2
    
  3. Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*

    find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
    
  4. To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):

    <settings>
     <mirrors>
      <mirror>
       <id>mycentral</id>
       <name>My Central</name>
       <url>file:/home/user/saved-m2/</url>
       <mirrorOf>central</mirrorOf>
      </mirror>
     </mirrors>
    </settings>
    
  5. Resolve your projects dependencies again:

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  6. Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.

Understanding colors on Android (six characters)

On Android, colors are can be specified as RGB or ARGB.

http://en.wikipedia.org/wiki/ARGB

In RGB you have two characters for every color (red, green, blue), and in ARGB you have two additional chars for the alpha channel.

So, if you have 8 characters, it's ARGB, with the first two characters specifying the alpha channel. If you remove the leading two characters it's only RGB (solid colors, no alpha/transparency). If you want to specify a color in your Java source code, you have to use:

int Color.argb (int alpha, int red, int green, int blue)

alpha  Alpha component [0..255] of the color
red    Red component [0..255] of the color
green  Green component [0..255] of the color
blue   Blue component [0..255] of the color

Reference: argb

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

How to check for an active Internet connection on iOS or macOS?

You could use Reachability by ? (available here).

#import "Reachability.h"

- (BOOL)networkConnection {
    return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}

if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

Check if String / Record exists in DataTable

Use the Find method if item_manuf_id is a primary key:

var result = dtPs.Rows.Find("some value");

If you only want to know if the value is in there then use the Contains method.

if (dtPs.Rows.Contains("some value"))
{
  ...
}

Primary key restriction applies to Contains aswell.

Creating a JSON response using Django and Python

You'll want to use the django serializer to help with unicode stuff:

from django.core import serializers

json_serializer = serializers.get_serializer("json")()
    response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
    return HttpResponse(response, mimetype="application/json")

What is the best way to add options to a select from a JavaScript object with jQuery?

There's a sorting problem with this solution in Chrome (jQuery 1.7.1) (Chrome sorts object properties by name/number?) So to keep the order (yes, it's object abusing), I changed this:

optionValues0 = {"4321": "option 1", "1234": "option 2"};

to this

optionValues0 = {"1": {id: "4321", value: "option 1"}, "2": {id: "1234", value: "option 2"}};

and then the $.each will look like:

$.each(optionValues0, function(order, object) {
  key = object.id;
  value = object.value;
  $('#mySelect').append($('<option>', { value : key }).text(value));
}); 

How to empty a list in C#?

You need the Clear() function on the list, like so.

List<object> myList = new List<object>();

myList.Add(new object()); // Add something to the list

myList.Clear() // Our list is now empty

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

Make a DIV fill an entire table cell

if <table> <tr> <td> <div> all have height: 100%; set, then the div will fill the dynamic cell height in all browsers.

How can I one hot encode in Python?

Short Answer

Here is a function to do one-hot-encoding without using numpy, pandas, or other packages. It takes a list of integers, booleans, or strings (and perhaps other types too).

import typing


def one_hot_encode(items: list) -> typing.List[list]:
    results = []
    # find the unique items (we want to unique items b/c duplicate items will have the same encoding)
    unique_items = list(set(items))
    # sort the unique items
    sorted_items = sorted(unique_items)
    # find how long the list of each item should be
    max_index = len(unique_items)

    for item in items:
        # create a list of zeros the appropriate length
        one_hot_encoded_result = [0 for i in range(0, max_index)]
        # find the index of the item
        one_hot_index = sorted_items.index(item)
        # change the zero at the index from the previous line to a one
        one_hot_encoded_result[one_hot_index] = 1
        # add the result
        results.append(one_hot_encoded_result)

    return results

Example:

one_hot_encode([2, 1, 1, 2, 5, 3])

# [[0, 1, 0, 0],
#  [1, 0, 0, 0],
#  [1, 0, 0, 0],
#  [0, 1, 0, 0],
#  [0, 0, 0, 1],
#  [0, 0, 1, 0]]
one_hot_encode([True, False, True])

# [[0, 1], [1, 0], [0, 1]]
one_hot_encode(['a', 'b', 'c', 'a', 'e'])

# [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1]]

Long(er) Answer

I know there are already a lot of answers to this question, but I noticed two things. First, most of the answers use packages like numpy and/or pandas. And this is a good thing. If you are writing production code, you should probably be using robust, fast algorithms like those provided in the numpy/pandas packages. But, for the sake of education, I think someone should provide an answer which has a transparent algorithm and not just an implementation of someone else's algorithm. Second, I noticed that many of the answers do not provide a robust implementation of one-hot encoding because they do not meet one of the requirements below. Below are some of the requirements (as I see them) for a useful, accurate, and robust one-hot encoding function:

A one-hot encoding function must:

  • handle list of various types (e.g. integers, strings, floats, etc.) as input
  • handle an input list with duplicates
  • return a list of lists corresponding (in the same order as) to the inputs
  • return a list of lists where each list is as short as possible

I tested many of the answers to this question and most of them fail on one of the requirements above.

How to recover closed output window in netbeans?

shorter way: 1-Alt + Shift + R 2-Ctrl + 4 second way:(in menus of netBeans) 1-go to window tab 2-go to IDE tools 3-click on Test Result 4-again in window tab click on Output

Enable Hibernate logging

Hibernate logging has to be also enabled in hibernate configuration.

Add lines

hibernate.show_sql=true
hibernate.format_sql=true

either to

server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml

or to application's persistence.xml in <persistence-unit><properties> tag.

Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.

There is an alternative way of using log4jdbc for any kind of sql logging.

The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.

Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:

   <logger category="org.hibernate">
     <level name="DEBUG"/>
   </logger>

Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.

If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.

Conversion from List<T> to array T[]

Try using

MyClass[] myArray = list.ToArray();

How to set image in imageview in android?

1> You can add image from layout itself:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

OR

2> Programmatically in java class:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

OR for fragments:

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

How to return only the Date from a SQL Server DateTime datatype

You can simply use the code below to get only the date part and avoid the time part in SQL:

SELECT SYSDATE TODAY FROM DUAL; 

How to draw circle in html page?

You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:

<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;">&nbsp;</div>

(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)

There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

After making above improvement such as checking if mysql service is running or not, you just need to give a small password while creating connection, it is ' ' or 1 time press on space-bar in case of GUI or workbench. After which you just need to validate your machine with server (validated HOST). For that purpose click on 'New Server Instance' and it will configure server/HOST on your behalf itself.

I have done this successfully just a few couple of minutes ago. My workbench software is able to show all pre-installed databases etc now.

hope it will work for you as well.

Thanks!!!

Width equal to content

Despite using display: inline-block. My div would fill the screen width when the children elements had their widths set to % of parent. If anyone else is looking for a solution to this and doesn't mind using screen proportion instead of parent proportion, replace the % with vw for width (Viewport Width), or vh for height (Viewport Height).

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Express.js Response Timeout

In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});

.htaccess redirect http to https

In cases where the HTTPS/SSL connection is ended at the load balancer and all traffic is sent to instances on port 80, the following rule works to redirect non-secure traffic.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Ensure the mod_rewrite module is loaded.

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

How to determine the content size of a UIWebView?

I have another solution that works great.

On one hand, Ortwin's approach & solution works only with iOS 6.0 and later, but fails to work correctly on iOS 5.0, 5.1 and 5.1.1, and on the other hand there is something that I don't like and can't understand with Ortwin's approach, it's the use of the method [webView sizeThatFits:CGSizeZero] with the parameter CGSizeZero : If you read Apple Official documentation about this methods and its parameter, it says clearly :

The default implementation of this method returns the size portion of the view’s bounds rectangle. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.

What I mean is that it's like he came across his solution without any logic, because reading the documentation, the parameter passed to [webView sizeThatFits: ...] should at least have the desired width. With his solution, the desired width is set to the webView's frame before calling sizeThatFits with a CGSizeZero parameter. So I maintain this solution is working on iOS 6 by "chance".

I imagined a more rational approach, which has the advantage of working for iOS 5.0 and later... And also in complex situations where more than one webView (With its property webView.scrollView.scrollEnabled = NO is embedded in a scrollView.

Here is my code to force the Layout of the webView to the desired width and get the corresponding height set back to the webView itself:

Obj-C

- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{   
    aWebView.scrollView.scrollEnabled = NO;    // Property available in iOS 5.0 and later 
    CGRect frame = aWebView.frame;

    frame.size.width = 200;       // Your desired width here.
    frame.size.height = 1;        // Set the height to a small one.

    aWebView.frame = frame;       // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).

    frame.size.height = aWebView.scrollView.contentSize.height;  // Get the corresponding height from the webView's embedded scrollView.

    aWebView.frame = frame;       // Set the scrollView contentHeight back to the frame itself.
}

Swift 4.x

func webViewDidFinishLoad(_ aWebView: UIWebView) {

    aWebView.scrollView.isScrollEnabled = false
    var frame = aWebView.frame

    frame.size.width = 200
    frame.size.height = 1

    aWebView.frame = frame
    frame.size.height = aWebView.scrollView.contentSize.height

    aWebView.frame = frame;
}

Note that in my example, the webView was embedded in a custom scrollView having other webViews... All these webViews had their webView.scrollView.scrollEnabled = NO, and the last piece of code I had to add was the calculation of the height of the contentSize of my custom scrollView embedding these webViews, but it was as easy as summing my webView's frame.size.height computed with the trick described above...

Call break in nested if statements

no it doesnt. break is for loops, not ifs.

nested if statements are just terrible. If you can avoid them, avoid them. Can you rewrite your code to be something like

if (c1 && c2) {
    //sequence 1
} else if (c3 && c2) {
   // sequence 3
}

that way you don't need any control logic to 'break out' of the loop.

How do I get a file's directory using the File object?

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

Selecting only first-level elements in jquery

As stated in other answers, the simplest method is to uniquely identify the root element (by ID or class name) and use the direct descendent selector.

$('ul.topMenu > li > a')

However, I came across this question in search of a solution which would work on unnamed elements at varying depths of the DOM.

This can be achieved by checking each element, and ensuring it does not have a parent in the list of matched elements. Here is my solution, wrapped in a jQuery selector 'topmost'.

jQuery.extend(jQuery.expr[':'], {
  topmost: function (e, index, match, array) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] !== false && $(e).parents().index(array[i]) >= 0) {
        return false;
      }
    }
    return true;
  }
});

Utilizing this, the solution to the original post is:

$('ul:topmost > li > a')

// Or, more simply:
$('li:topmost > a')

Complete jsFiddle available here.

How can I pass variable to ansible playbook in the command line?

ansible-playbok -i <inventory> <playbook-name> -e "proc_name=sshd"

You can use the above command in below playbooks.

---
- name: Service Status
gather_facts: False
tasks:
- name: Check Service Status (Linux)
shell: pgrep "{{ proc_name }}"
register: service_status
ignore_errors: yes
debug: var=service_status.rc`

HttpContext.Current.Session is null when routing requests

I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.

How do I display a decimal value to 2 decimal places?

Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.

In .NET Core, I had to use:

decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);

A hacky method, including conversion to string, is:

public string FormatTo2Dp(decimal myNumber)
{
    // Use schoolboy rounding, not bankers.
    myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);

    return string.Format("{0:0.00}", myNumber);
}

Removing an item from a select box

Just to augment this for anyone looking, you are also able to just:

$("#selectBox option[value='option1']").hide();

and

$("#selectBox option[value='option1']").show();

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

What about:

def dict_merge_and_sum( d1, d2 ):
    ret = d1
    ret.update({ k:v + d2[k] for k,v in d1.items() if k in d2 })
    ret.update({ k:v for k,v in d2.items() if k not in d1 })
    return ret

A = {'a': 1, 'b': 2, 'c': 3}
B = {'b': 3, 'c': 4, 'd': 5}

print( dict_merge_and_sum( A, B ) )

Output:

{'d': 5, 'a': 1, 'c': 7, 'b': 5}

Best approach to real time http streaming to HTML5 video client

Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.

SQL: ... WHERE X IN (SELECT Y FROM ...)

SELECT Customers.* 
  FROM Customers 
 WHERE NOT EXISTS (
       SELECT *
         FROM SUBSCRIBERS AS s
         JOIN s.Cust_ID = Customers.Customer_ID) 

When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, the query can use an index within the sub-query.

SQL sum with condition

Try moving ValueDate:

select sum(CASE  
             WHEN ValueDate > @startMonthDate THEN cash 
              ELSE 0 
           END) 
 from Table a
where a.branch = p.branch 
  and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

Check empty string in Swift?

You can use this extension:

extension String {

    static func isNilOrEmpty(string: String?) -> Bool {
        guard let value = string else { return true }

        return value.trimmingCharacters(in: .whitespaces).isEmpty
    }

}

and then use it like this:

let isMyStringEmptyOrNil = String.isNilOrEmpty(string: myString)

UICollectionView - dynamic cell height?

I just ran into this problem on a UICollectionView and the way that i solved it similar to the answer above but in a pure UICollectionView way.

  1. Create a custom UICollectionViewCell that contains whatever you will be filling it with to make it dynamic. I created its own .xib for it as it seems like the easiest approach.

  2. Add constraints in that .xib that allow for the cell to be calculated from top to bottom. The re-sizing won't work if you haven't accounted for all of the height. Say you have a view on top, then a label underneath it, and another label underneath that. You would need to connect constraints to the top of the cell to the top of that view, then the bottom of the view to the top of the first label, bottom of first label to the top of the second label, and bottom of second label to bottom of cell.

  3. Load the .xib into the viewcontroller and register it with the collectionView on viewDidLoad

    let nib = UINib(nibName: CustomCellName, bundle: nil)
    self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "customCellID")`
    
  4. Load a second copy of that xib into the class and store it as a property so you can use it to determine the size of what that cell should be

    let sizingNibNew = NSBundle.mainBundle().loadNibNamed(CustomCellName, owner: CustomCellName.self, options: nil) as NSArray
    self.sizingNibNew = (sizingNibNew.objectAtIndex(0) as? CustomViewCell)!
    
  5. Implement the UICollectionViewFlowLayoutDelegate in your view controller. The method that matters is called sizeForItemAtIndexPath. Inside that method you will need to pull the data from the datasource that is associated with that cell from the indexPath. Then configure the sizingCell and call preferredLayoutSizeFittingSize. The method returns a CGSize which will consist of the width minus the content insets and the height that is returned from self.sizingCell.preferredLayoutSizeFittingSize(targetSize).

    override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        guard let data = datasourceArray?[indexPath.item] else {
            return CGSizeZero
        }
        let sectionInset = self.collectionView?.collectionViewLayout.sectionInset
        let widthToSubtract = sectionInset!.left + sectionInset!.right
    
        let requiredWidth = collectionView.bounds.size.width
    
    
        let targetSize = CGSize(width: requiredWidth, height: 0)
    
        sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
        let adequateSize = self.sizingNibNew.preferredLayoutSizeFittingSize(targetSize)
        return CGSize(width: (self.collectionView?.bounds.width)! - widthToSubtract, height: adequateSize.height)
     }
    
  6. In the class of the custom cell itself you will need to override awakeFromNib and tell the contentView that its size needs to be flexible

     override func awakeFromNib() {
        super.awakeFromNib()
        self.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight]
     }
    
  7. In the custom cell override layoutSubviews

     override func layoutSubviews() {
       self.layoutIfNeeded()
      }
    
  8. In the class of the custom cell implement preferredLayoutSizeFittingSize. This is where you will need to do any trickery on the items that are being laid out. If its a label you will need to tell it what its preferredMaxWidth should be.

    func preferredLayoutSizeFittingSize(_ targetSize: CGSize)-> CGSize {
    
        let originalFrame = self.frame
        let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth
    
    
        var frame = self.frame
        frame.size = targetSize
        self.frame = frame
    
        self.setNeedsLayout()
        self.layoutIfNeeded()
        self.label.preferredMaxLayoutWidth = self.questionLabel.bounds.size.width
    
    
        // calling this tells the cell to figure out a size for it based on the current items set
        let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    
        let newSize = CGSize(width:targetSize.width, height:computedSize.height)
    
        self.frame = originalFrame
        self.questionLabel.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth
    
        return newSize
    }
    

All those steps should give you the correct sizes. If your getting 0 or other funky numbers than you haven't set up your constraints properly.

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

What is HTML5 ARIA?

I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them

What is ARIA?

If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.

ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.

And see this you tube video for ARIA live.

How to make HTML table cell editable?

HTML5 supports contenteditable,

<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>

3rd party edit

To quote the mdn entry on contenteditable

The attribute must take one of the following values:

  • true or the empty string, which indicates that the element must be editable;

  • false, which indicates that the element must not be editable.

If this attribute is not set, its default value is inherited from its parent element.

This attribute is an enumerated one and not a Boolean one. This means that the explicit usage of one of the values true, false or the empty string is mandatory and that a shorthand ... is not allowed.

// wrong not allowed
<label contenteditable>Example Label</label> 

// correct usage
<label contenteditable="true">Example Label</label>.

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));
}

What is the difference between :focus and :active?

Active is when the user activating that point (Like mouse clicking, if we use tab from field-to-field there is no sign from active style. Maybe clicking need more time, just try hold click on that point), focus is happened after the point is activated. Try this :

<style type="text/css">
  input { font-weight: normal; color: black; }
  input:focus { color: green; outline: 1px solid green; }
  input:active { color: red; outline: 1px solid red; }
</style>

<input type="text"/>
<input type="text"/>

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Cross-Origin Read Blocking (CORB)

You have to add CORS on the server side:

If you are using nodeJS then:

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

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

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

What is the C# equivalent of friend?

Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.

In C++, make the Factory a friend of Widget class.

In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.

This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.

Adding a Scrollable JTextArea (Java)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Opening a CHM file produces: "navigation to the webpage was canceled"

other way is to use different third party software. This link shows more third party software to view chm files...

I tried with SumatraPDF and it work fine.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

The short version of the most voted answer has problems with TB values.

I adjusted it appropriately to handle also tb values and still without a loop and also added a little error checking for negative values. Here's my solution:

static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(long value, int decimalPlaces = 0)
{
    if (value < 0)
    {
        throw new ArgumentException("Bytes should not be negative", "value");
    }
    var mag = (int)Math.Max(0, Math.Log(value, 1024));
    var adjustedSize = Math.Round(value / Math.Pow(1024, mag), decimalPlaces);
    return String.Format("{0} {1}", adjustedSize, SizeSuffixes[mag]);
}

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

You can also fit a set of a data to whatever function you like using curve_fit from scipy.optimize. For example if you want to fit an exponential function (from the documentation):

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn)

And then if you want to plot, you could do:

plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()

(Note: the * in front of popt when you plot will expand out the terms into the a, b, and c that func is expecting.)

How to pass a variable to the SelectCommand of a SqlDataSource?

to attach to a GUID:

 SqlDataSource1.SelectParameters.Add("userId",  System.Data.DbType.Guid, userID);

Change the name of a key in dictionary

If you have a complex dict, it means there is a dict or list within the dict:

myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict

Output
{1: 'one', 2: {3: 'three', 5: 'four'}}

How to press back button in android programmatically?

You don't need to override onBackPressed() - it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed() whenever you want to "programatically press" the back button.

That would only result to finish() being called, though ;)

I think you're confused with what the back button does. By default, it's just a call to finish(), so it just exits the current activity. If you have something behind that activity, that screen will show.

What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.

C non-blocking keyboard input

As already stated, you can use sigaction to trap ctrl-c, or select to trap any standard input.

Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode. The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.

You'd need to use the tcsetattr() function to turn off ICANON mode, and probably also disable ECHO too. From memory, you also have to set the terminal back into ICANON mode when the program exits!

Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h> functions kbhit() and getch():

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv);
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}

Initializing data.frames()

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

Mongoose: Find, modify, save

I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.

User.findOne({username: oldUsername}, function (err, user) {
   user.username = newUser.username;
   user.password = newUser.password;
   user.rights = newUser.rights;

   user.markModified(username)
   user.markModified(password)
   user.markModified(rights)
    user.save(function (err) {
    if(err) {
        console.error('ERROR!');
    }
});
});

tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

How do I use floating-point division in bash?

i know it's old, but too tempting. so, the answer is: you can't... but you kind of can. let's try this:

$IMG_WIDTH=1024
$IMG2_WIDTH=2048

$RATIO="$(( IMG_WIDTH / $IMG2_WIDTH )).$(( (IMG_WIDTH * 100 / IMG2_WIDTH) % 100 ))

like that you get 2 digits after the point, truncated (call it rounding to the lower, haha) in pure bash (no need to launch other processes). of course, if you only need one digit after the point you multiply by 10 and do modulo 10.

what this does:

  • first $((...)) does integer division;
  • second $((...)) does integer division on something 100 times larger, essentially moving your 2 digits to the left of the point, then (%) getting you only those 2 digits by doing modulo.

bonus track: bc version x 1000 took 1,8 seconds on my laptop, while the pure bash one took 0,016 seconds.

capture div into image using html2canvas

you can try this code to capture a div When the div is very wide or offset relative to the screen

var div = $("#div")[0];
var rect = div.getBoundingClientRect();

var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;

var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);

html2canvas(div, {
    canvas:canvas,
    height:rect.height,
    width:rect.width,
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        var pHtml = "<img src="+image+" />";
        $("#parent").append(pHtml);
    }
});

HTML5 Local storage vs. Session storage

The advantage of the session storage over local storage, in my opinion, is that it has unlimited capacity in Firefox, and won't persist longer than the session. (Of course it depends on what your goal is.)

ASP.NET Core configuration for .NET Core console application

If you use .netcore 3.1 the simplest way use new configuration system to call CreateDefaultBuilder method of static class Host and configure application

public class Program
{
    public static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                IHostEnvironment env = context.HostingEnvironment;
                config.AddEnvironmentVariables()
                    // copy configuration files to output directory
                    .AddJsonFile("appsettings.json")
                    // default prefix for environment variables is DOTNET_
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddCommandLine(args);
            })
            .ConfigureServices(services =>
            {
                services.AddSingleton<IHostedService, MySimpleService>();
            })
            .Build()
            .Run();
    }
}

class MySimpleService : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StartAsync");
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StopAsync");
        return Task.CompletedTask;
    }
}

You need set Copy to Output Directory = 'Copy if newer' for the files appsettings.json and appsettings.{environment}.json Also you can set environment variable {prefix}ENVIRONMENT (default prefix is DOTNET) to allow choose specific configuration parameters.

.csproj file:

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <RootNamespace>ConsoleApplication3</RootNamespace>
  <AssemblyName>ConsoleApplication3</AssemblyName>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.7" />
  <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
</ItemGroup>

<ItemGroup>
  <None Update="appsettings.Development.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

more details .NET Generic Host

PreparedStatement with list of parameters in a IN clause

You could use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Code:

PreparedStatement statement = connection.prepareStatement("Select * from test where field in (?)");
Array array = statement.getConnection().createArrayOf("VARCHAR", new Object[]{"A1", "B2","C3"});
statement.setArray(1, array);
ResultSet rs = statement.executeQuery();

Why use pip over easy_install?

UPDATE: setuptools has absorbed distribute as opposed to the other way around, as some thought. setuptools is up-to-date with the latest distutils changes and the wheel format. Hence, easy_install and pip are more or less on equal footing now.

Source: http://pythonhosted.org/setuptools/merge-faq.html#why-setuptools-and-not-distribute-or-another-name

Using curl POST with variables defined in bash script functions

Existing answers point out that curl can post data from a file, and employ heredocs to avoid excessive quote escaping and clearly break the JSON out onto new lines. However there is no need to define a function or capture output from cat, because curl can post data from standard input. I find this form very readable:

curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the default library path which is accessed to check for available dynamic and shared libraries. It is specific to linux distributions.

It is similar to environment variable PATH in windows that linker checks for possible implementations during linking time.

Using Gradle to build a jar with dependencies

I use task shadowJar by plugin . com.github.jengelman.gradle.plugins:shadow:5.2.0

Usage just run ./gradlew app::shadowJar result file will be at MyProject/app/build/libs/shadow.jar

top level build.gradle file :

 apply plugin: 'kotlin'

buildscript {
    ext.kotlin_version = '1.3.61'

    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

app module level build.gradle file

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'

sourceCompatibility = 1.8

kapt {
    generateStubs = true
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"
    shadow "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"

    implementation project(":module_remote")
    shadow project(":module_remote")
}

jar {
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
    manifest {
        attributes(
                'Main-Class': 'com.github.kolyall.TheApplication',
                'Class-Path': configurations.compile.files.collect { "lib/$it.name" }.join(' ')
        )
    }
}

shadowJar {
    baseName = 'shadow'
    classifier = ''
    archiveVersion = ''
    mainClassName = 'com.github.kolyall.TheApplication'

    mergeServiceFiles()
}

How to group subarrays by a column value?

for($i = 0 ; $i < count($arr)  ; $i++ )
{
    $tmpArr[$arr[$i]['id']] = $arr[$i]['id'];
}
$vmpArr = array_keys($tmpArr);
print_r($vmpArr);

Xcode 'CodeSign error: code signing is required'

Maybe your mac's date and time are incorrect. Just correct them.

reducing number of plot ticks

The solution @raphael gave is straightforward and quite helpful.

Still, the displayed tick labels will not be values sampled from the original distribution but from the indexes of the array returned by np.linspace(ymin, ymax, N).

To display N values evenly spaced from your original tick labels, use the set_yticklabels() method. Here is a snippet for the y axis, with integer labels:

import numpy as np
import matplotlib.pyplot as plt

ax = plt.gca()

ymin, ymax = ax.get_ylim()
custom_ticks = np.linspace(ymin, ymax, N, dtype=int)
ax.set_yticks(custom_ticks)
ax.set_yticklabels(custom_ticks)

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

How can I strip HTML tags from a string in ASP.NET?

For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:

public static string StripTags(this string markup)
{
    try
    {
        StringReader sr = new StringReader(markup);
        XPathDocument doc;
        using (XmlReader xr = XmlReader.Create(sr,
                           new XmlReaderSettings()
                           {
                               ConformanceLevel = ConformanceLevel.Fragment
                               // for multiple roots
                           }))
        {
            doc = new XPathDocument(xr);
        }

        return doc.CreateNavigator().Value; // .Value is similar to .InnerText of  
                                           //  XmlDocument or JavaScript's innerText
    }
    catch
    {
        return string.Empty;
    }
}

font awesome icon in select option

When using a <select> tag that shows all options, here's a work around using <div> instead:

HTML

<div id='sectionOptionsSelect' size='5' class='block1'
        style='visibility: hidden; border: 1px solid gray; padding: 5px; '>
    <span class='addPageBreakAbove'>Add Page Break Above</span>
    <span class='addPageBreakBelow'>Add Page Break Below</span>
    <span class='removeSection'>
        <label class='fa fa-window-close'
               style='font-size: 25px; color: red; background: white; '></label>
        Remove Section</span>
</div>

Supporting JS

$('#sectionOptionsSelect span').hover(function () {

    $(this).css('background', '#c0ec67');

}, function () {

    $(this).css('background', 'transparent');
});

$('.removeSection').click(function () {

    alert('removeSection');
});

CSS

#sectionOptionsSelect span {
    display: block;
}

Rebuild all indexes in a Database

Replace the "YOUR DATABASE NAME" in the query below.

    DECLARE @Database NVARCHAR(255)   
    DECLARE @Table NVARCHAR(255)  
    DECLARE @cmd NVARCHAR(1000)  

    DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
    SELECT name FROM master.sys.databases   
    WHERE name IN ('YOUR DATABASE NAME')  -- databases
    AND state = 0 -- database is online
    AND is_in_standby = 0 -- database is not read only for log shipping
    ORDER BY 1  

    OPEN DatabaseCursor  

    FETCH NEXT FROM DatabaseCursor INTO @Database  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  

       SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
       table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

       -- create table cursor  
       EXEC (@cmd)  
       OPEN TableCursor   

       FETCH NEXT FROM TableCursor INTO @Table   
       WHILE @@FETCH_STATUS = 0   
       BEGIN
          BEGIN TRY   
             SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
             PRINT @cmd -- uncomment if you want to see commands
             EXEC (@cmd) 
          END TRY
          BEGIN CATCH
             PRINT '---'
             PRINT @cmd
             PRINT ERROR_MESSAGE() 
             PRINT '---'
          END CATCH

          FETCH NEXT FROM TableCursor INTO @Table   
       END   

       CLOSE TableCursor   
       DEALLOCATE TableCursor  

       FETCH NEXT FROM DatabaseCursor INTO @Database  
    END  
    CLOSE DatabaseCursor   
    DEALLOCATE DatabaseCursor

Uncaught SyntaxError: Unexpected token < On Chrome

You can check your Network (console) and See the answer from the Server ... The "<" will be the first letter of your response. Something like "<"undefined index XY in line Z>"

Comparing strings in Java

You can compare the values using equals() of Java :

public void onClick(View v) {
    // TODO Auto-generated method stub

    s1=text1.getText().toString();
    s2=text2.getText().toString();

    if(s1.equals(s2))
        Show.setText("Are Equal");
    else
        Show.setText("Not Equal");
}

Cycles in an Undirected Graph

By the way, if you happen to know that it is connected, then simply it is a tree (thus no cycles) if and only if |E|=|V|-1. Of course that's not a small amount of information :)

Adding the "Clear" Button to an iPhone UITextField

Swift 4 (adapted from Kristopher Johnson's answer)

textfield.clearButtonMode = .always

textfield.clearButtonMode = .whileEditing

textfield.clearButtonMode = .unlessEditing

textfield.clearButtonMode = .never

What do the different readystates in XMLHttpRequest mean, and how can I use them?

kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,

so here is the original documentation quoted to rightly understand what readystate represents :

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)
The object has been constructed.

OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)
The response entity body is being received.

DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

Please Read here : W3C Explaination Of ReadyState

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

What is the difference between URI, URL and URN?

URI (Uniform Resource Identifier) according to Wikipedia:

a string of characters used to identify a resource.

URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.

URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax

IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.

How do you uninstall MySQL from Mac OS X?

I also found

/Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

after using all of the other answers here to uninstall MySQL Community Server 8.0.15 from OS X 10.10.

Removing "http://" from a string

Use look behinds in preg_replace to remove anything before //.

preg_replace('(^[a-z]+:\/\/)', '', $url); 

This will only replace if found in the beginning of the string, and will ignore if found later

Jenkins Pipeline Wipe Out Workspace

I used deleteDir() as follows:

  post {
        always {
            deleteDir() /* clean up our workspace */
        }
    }

However, I then had to also run a Success or Failure AFTER always but you cannot order the post conditions. The current order is always, changed, aborted, failure, success and then unstable.

However, there is a very useful post condition, cleanup which always runs last, see https://jenkins.io/doc/book/pipeline/syntax/

So in the end my post was as follows :

post {
    always {

    }
    success{

    }
    failure {

    }
    cleanup{
        deleteDir()
    }
}

Hopefully this may be helpful for some corner cases

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How to make the overflow CSS property work with hidden as value

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

Differences between JDK and Java SDK

The JDK (Java Development Kit) is an SDK (Software Dev Kit).

It is used to build software/applications on Java and of course it includes the JRE (Java Runtime Edition) to execute that software. If you just want to execute a Java application, download only the JRE.

By the way, Java EE (Enterprise Edition) contains libraries of packages of classes "with methods (functions)" to build apps for the WEB environment and Java ME (Micro Edition) for mobile devices. If you are interested in it (Java ME) I would recommend to take a look at Google's Android DevKit and API.

Take a look here: it's gonna explain bit more.. http://www.oracle.com/technetwork/java/archive-139210.html

window.location.reload with clear cache

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};

Best way to compare dates in Android

You can use compareTo()

CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime); 
// getCurrentDateTime: 05/23/2016 18:49 PM

if (getCurrentDateTime.compareTo(getMyTime) < 0)
{

}
else
{
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
}

Connecting to SQL Server Express - What is my server name?

All of the following services should be running,for successful connectivity: SQL Full test filter Daemon, SQL server(SQLEXPRESS), SQL Server Agent(SQLEXPRESS), SQL Server Browser, SQL server reporting service and SQL Server VSS Writer

Using only CSS, show div on hover over <a>

For me, if I want to interact with the hidden div without seeing it disappear each time I leave the triggering element (a in that case) I must add:

div:hover {
    display: block;
}

HTML5 record audio to file

There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html

It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.

You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder object that contains an exportWAV method, and a forceDownload method.

HTML/CSS: Making two floating divs the same height

Using Javascript, you can make the two div tags the same height. The smaller div will adjust to be the same height as the tallest div tag using the code shown below:

var rightHeight = document.getElementById('right').clientHeight;
var leftHeight = document.getElementById('left').clientHeight;
if (leftHeight > rightHeight) {
document.getElementById('right').style.height=leftHeight+'px';
} else {
document.getElementById('left').style.height=rightHeight+'px';
}

With "left" and "right" being the id's of the div tags.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

Passing html values into javascript functions

Simply put id attribute in your input text field -

<input type="text" maxlength="3" name="value" id="value" />

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Splitting on first occurrence

For me the better approach is that:

s.split('mango', 1)[-1]

...because if happens that occurrence is not in the string you'll get "IndexError: list index out of range".

Therefore -1 will not get any harm cause number of occurrences is already set to one.

Temporarily change current working directory in bash to run a command

Something like this should work:

sh -c 'cd /tmp && exec pwd'

Access camera from a browser

You can use HTML5 for this:

<video autoplay></video>
<script>
  var onFailSoHard = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, onFailSoHard);
</script>

Source

How to start IIS Express Manually

Once you have IIS Express installed (the easiest way is through Microsoft Web Platform Installer), you will find the executable file in %PROGRAMFILES%\IIS Express (%PROGRAMFILES(x86)%\IIS Express on x64 architectures) and its called iisexpress.exe.

To see all the possible command-line options, just run:

iisexpress /?

and the program detailed help will show up.

If executed without parameters, all the sites defined in the configuration file and marked to run at startup will be launched. An icon in the system tray will show which sites are running.

There are a couple of useful options once you have some sites created in the configuration file (found in %USERPROFILE%\Documents\IISExpress\config\applicationhost.config): the /site and /siteId.

With the first one, you can launch a specific site by name:

iisexpress /site:SiteName

And with the latter, you can launch by specifying the ID:

iisexpress /siteId:SiteId

With this, if IISExpress is launched from the command-line, a list of all the requests made to the server will be shown, which can be quite useful when debugging.

Finally, a site can be launched by specifying the full directory path. IIS Express will create a virtual configuration file and launch the site (remember to quote the path if it contains spaces):

iisexpress /path:FullSitePath

This covers the basic IISExpress usage from the command line.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Is it bad practice to use break to exit a loop in Java?

Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.

However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.

How to convert a string from uppercase to lowercase in Bash?

This worked for me. Thank you Rody!

y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"

one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.

string="${val}_world"

String to list in Python

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']

split:

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

Android webview launches browser when calling loadurl

Make your Activity like this.

public class MainActivity extends Activity {
WebView browser;

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // find the WebView by name in the main.xml of step 2
    browser=(WebView)findViewById(R.id.wvwMain);

    // Enable javascript
    browser.getSettings().setJavaScriptEnabled(true);  

    // Set WebView client
    browser.setWebChromeClient(new WebChromeClient());

    browser.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                }
        });
     // Load the webpage
    browser.loadUrl("http://google.com/");
   }
}

Find if a textbox is disabled or not using jquery

You can check if a element is disabled or not with this:

if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice 
}

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

How to use Typescript with native ES6 Promises

If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:

tsc a.ts --target es6 --module commonjs

More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

If you use tsconfig.json, then like this:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
    }
}

More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

Open popup and refresh parent page on close popup

Following code will manage to refresh parent window post close :

function ManageQB_PopUp() {
            $(document).ready(function () {
                window.close();
            });
            window.onunload = function () {
                var win = window.opener;
                if (!win.closed) {
                    window.opener.location.reload();
                }
            };
        }

How to add a jar in External Libraries in android studio

Please provide the jar file location in build.gradle

implementation fileTree(dir: '<DirName>', include: ['*.jar'])

Example:

implementation fileTree(dir: 'C:\Downloads', include: ['*.jar'])

To add single jar file

implementation files('libs/foo.jar')

Note: compile is deprecated in latest gradle, hence use implementation instead.

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

Adding the following two lines in the script solved the issue for me.

# !/usr/bin/python
# coding=utf-8

Hope it helps !

How to set data attributes in HTML elements

If you're using jQuery, use .data():

div.data('myval', 20);

You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().

What does "<>" mean in Oracle

It just means "different of", some languages uses !=, others (like SQL) <>

Recursive mkdir() system call on Unix

hmm I thought that mkdir -p does that?

mkdir -p this/is/a/full/path/of/stuff

Finding whether a point lies inside a rectangle or not

The easiest way I thought of was to just project the point onto the axis of the rectangle. Let me explain:

If you can get the vector from the center of the rectangle to the top or bottom edge and the left or right edge. And you also have a vector from the center of the rectangle to your point, you can project that point onto your width and height vectors.

P = point vector, H = height vector, W = width vector

Get Unit vector W', H' by dividing the vectors by their magnitude

proj_P,H = P - (P.H')H' proj_P,W = P - (P.W')W'

Unless im mistaken, which I don't think I am... (Correct me if I'm wrong) but if the magnitude of the projection of your point on the height vector is less then the magnitude of the height vector (which is half of the height of the rectangle) and the magnitude of the projection of your point on the width vector is, then you have a point inside of your rectangle.

If you have a universal coordinate system, you might have to figure out the height/width/point vectors using vector subtraction. Vector projections are amazing! remember that.

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

Spring Test & Security: How to mock authentication?

Create a class TestUserDetailsImpl on your test package:

@Service
@Primary
@Profile("test")
public class TestUserDetailsImpl implements UserDetailsService {
    public static final String API_USER = "[email protected]";

    private User getAdminUser() {
        User user = new User();
        user.setUsername(API_USER);

        SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_API_USER");
        user.setAuthorities(Collections.singletonList(role));

        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) 
                                         throws UsernameNotFoundException {
        if (Objects.equals(username, ADMIN_USERNAME))
            return getAdminUser();
        throw new UsernameNotFoundException(username);
    }
}

Rest endpoint:

@GetMapping("/invoice")
@Secured("ROLE_API_USER")
public Page<InvoiceDTO> getInvoices(){
   ...
}

Test endpoint:

@Test
@WithUserDetails("[email protected]")
public void testApi() throws Exception {
     ...
}

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Definition of a Balanced Tree

There's no difference between these two things. Think about it.

Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?

There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.

It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).

Register DLL file on Windows Server 2008 R2

This is what has to occur.

You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\

Then in the Run dialog, type this in: C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll

and you will get the message:

DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

Spring MVC - HttpMediaTypeNotAcceptableException

in my case favorPathExtension(false) helped me

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer
            .setUseSuffixPatternMatch(false);  // to use special character in path variables, for example, `[email protected]`
}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .favorPathExtension(false); // to  avoid HttpMediaTypeNotAcceptableException on standalone tomcat
}

}

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

Font size relative to the user's screen resolution?

New Way

There are several ways to achieve this.

CSS3 supports new dimensions that are relative to view port. But this doesn't work in android.

  1. 3.2vw = 3.2% of width of viewport
  2. 3.2vh = 3.2% of height of viewport
  3. 3.2vmin = Smaller of 3.2vw or 3.2vh
  4. 3.2vmax = Bigger of 3.2vw or 3.2vh

    body
    {
        font-size: 3.2vw;
    }
    

see css-tricks.com/.... and also look at caniuse.com/....

Old Way

  1. Use media query but requires font sizes for several breakpoints

    body
    {
        font-size: 22px; 
    }
    h1
    {
       font-size:44px;
    }
    
    @media (min-width: 768px) 
    {
       body
       {
           font-size: 17px; 
       }
       h1
       {
           font-size:24px;
       }
    }
    
  2. Use dimensions in % or rem. Just change the base font size everything will change. Unlike previous one you could just change the body font and not h1 everytime or let base font size to default of the device and rest all in em.

    • “Root Ems”(rem): The “rem” is a scalable unit. 1rem is equal to the font-size of the body/html, for instance, if the font-size of the document is 12pt, 1em is equal to 12pt. Root Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc..

    • Percent (%): The percent unit is much like the “em” unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.

see kyleschaeffer.com/....

Making an svg image object clickable with onclick, avoiding absolute positioning

I got this working accross the latest versions of Firefox, Chrome, Safari and Opera.

It relies on a transparent div before the object that has absolute position and set width and height so it covers the object tag below.

Here it is, I've been a bit lazy and used inline styes:

<div id="toolbar" style="width: 600px; height: 100px; position: absolute; z-index: 1;"></div>
<object data="interface.svg" width="600" height="100" type="image/svg+xml">
</object>

I used the following JavaScript to hook up an event to it:

<script type="text/javascript">
    var toolbar = document.getElementById("toolbar");
    toolbar.onclick = function (e) {
        alert("Hello");
    };
</script>

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

How to add a "sleep" or "wait" to my Lua Script?

function wait(time)
    local duration = os.time() + time
    while os.time() < duration do end
end

This is probably one of the easiest ways to add a wait/sleep function to your script

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:

TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();

How to get jSON response into variable from a jquery script

Here's the script, rewritten to use the suggestions above and a change to your no-cache method.

<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>

//the script above returns this:
{"response":"error","comment":"test comment here"}

<script type="text/javascript">
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    dataType: "json",
    success: function (data) {
        if (data.response == 'captcha') {
            alert('captcha');
        } else if (data.response == 'success') {
            alert('success');
        } else {
            alert('sorry there was an error');
        }
    }

}); // Semi-colons after all declarations, IE is picky on these things.
</script>

The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log the value of data and make sure the property you are looking for is there.

Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Add new value to an existing array in JavaScript

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

Can I multiply strings in Java to repeat sequences?

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));

How do I delete unpushed git commits?

Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.

git reset --hard origin

Get the current time in C

To extend the answer from @mingos above, I wrote the below function to format my time to a specific format ([dd mm yyyy hh:mm:ss]).

// Store the formatted string of time in the output
void format_time(char *output){
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    sprintf(output, "[%d %d %d %d:%d:%d]",timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
}

More information about struct tm can be found here.

Render HTML to an image

You can use an HTML to PDF tool like wkhtmltopdf. And then you can use a PDF to image tool like imagemagick. Admittedly this is server side and a very convoluted process...

How to output loop.counter in python jinja template?

change this {% if loop.counter == 1 %} to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}

and this from {{ user }} {{loop.counter}} to {{ user }} {{forloop.counter}}

How do I convert a string to a number in PHP?

You can use:

((int) $var)   ( but in big number it return 2147483647 :-) )

But the best solution is to use:

if (is_numeric($var))
    $var = (isset($var)) ? $var : 0;
else
    $var = 0;

Or

if (is_numeric($var))
    $var = (trim($var) == '') ? 0 : $var;
else
    $var = 0;

The most efficient way to remove first N elements in a list?

l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.

Trusting all certificates using HttpClient over HTTPS

You basically have four potential solutions to fix a "Not Trusted" exception on Android using httpclient:

  1. Trust all certificates. Don't do this, unless you really know what you're doing.
  2. Create a custom SSLSocketFactory that trusts only your certificate. This works as long as you know exactly which servers you're going to connect to, but as soon as you need to connect to a new server with a different SSL certificate, you'll need to update your app.
  3. Create a keystore file that contains Android's "master list" of certificates, then add your own. If any of those certs expire down the road, you are responsible for updating them in your app. I can't think of a reason to do this.
  4. Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default.

This answer uses solution #4, which seems to me to be the most robust.

The solution is to use an SSLSocketFactory that can accept multiple KeyStores, allowing you to supply your own KeyStore with your own certificates. This allows you to load additional top-level certificates such as Thawte that might be missing on some Android devices. It also allows you to load your own self-signed certificates as well. It will use the built-in default device certificates first, and fall back on your additional certificates only as necessary.

First, you'll want to determine which cert you are missing in your KeyStore. Run the following command:

openssl s_client -connect www.yourserver.com:443

And you'll see output like the following:

Certificate chain
 0 s:/O=www.yourserver.com/OU=Go to 
   https://www.thawte.com/repository/index.html/OU=Thawte SSL123 
   certificate/OU=Domain Validated/CN=www.yourserver.com
   i:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
 1 s:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
   i:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 
   2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA

As you can see, our root certificate is from Thawte. Go to your provider's website and find the corresponding certificate. For us, it was here, and you can see that the one we needed was the one Copyright 2006.

If you're using a self-signed certificate, you didn't need to do the previous step since you already have your signing certificate.

Then, create a keystore file containing the missing signing certificate. Crazybob has details how to do this on Android, but the idea is to do the following:

If you don't have it already, download the bouncy castle provider library from: http://www.bouncycastle.org/latest_releases.html. This will go on your classpath below.

Run a command to extract the certificate from the server and create a pem file. In this case, mycert.pem.

echo | openssl s_client -connect ${MY_SERVER}:443 2>&1 | \
 sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

Then run the following commands to create the keystore.

export CLASSPATH=/path/to/bouncycastle/bcprov-jdk15on-155.jar
CERTSTORE=res/raw/mystore.bks
if [ -a $CERTSTORE ]; then
    rm $CERTSTORE || exit 1
fi
keytool \
      -import \
      -v \
      -trustcacerts \
      -alias 0 \
      -file <(openssl x509 -in mycert.pem) \
      -keystore $CERTSTORE \
      -storetype BKS \
      -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath /path/to/bouncycastle/bcprov-jdk15on-155.jar \
      -storepass some-password

You'll notice that the above script places the result in res/raw/mystore.bks. Now you have a file that you'll load into your Android app that provides the missing certificate(s).

To do this, register your SSLSocketFactory for the SSL scheme:

final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443));

// and then however you create your connection manager, I use ThreadSafeClientConnManager
final HttpParams params = new BasicHttpParams();
...
final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,schemeRegistry);

To create your SSLSocketFactory:

protected org.apache.http.conn.ssl.SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {
        final KeyStore ks = KeyStore.getInstance("BKS");

        // the bks file we generated above
        final InputStream in = context.getResources().openRawResource( R.raw.mystore);  
        try {
            // don't forget to put the password used above in strings.xml/mystore_password
            ks.load(in, context.getString( R.string.mystore_password ).toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(ks);

    } catch( Exception e ) {
        throw new RuntimeException(e);
    }
}

And finally, the AdditionalKeyStoresSSLSocketFactory code, which accepts your new KeyStore and checks if the built-in KeyStore fails to validate an SSL certificate:

/**
 * Allows you to trust certificates from additional KeyStores in addition to
 * the default KeyStore
 */
public class AdditionalKeyStoresSSLSocketFactory extends SSLSocketFactory {
    protected SSLContext sslContext = SSLContext.getInstance("TLS");

    public AdditionalKeyStoresSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(null, null, null, null, null, null);
        sslContext.init(null, new TrustManager[]{new AdditionalKeyStoresTrustManager(keyStore)}, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }



    /**
     * Based on http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#X509TrustManager
     */
    public static class AdditionalKeyStoresTrustManager implements X509TrustManager {

        protected ArrayList<X509TrustManager> x509TrustManagers = new ArrayList<X509TrustManager>();


        protected AdditionalKeyStoresTrustManager(KeyStore... additionalkeyStores) {
            final ArrayList<TrustManagerFactory> factories = new ArrayList<TrustManagerFactory>();

            try {
                // The default Trustmanager with default keystore
                final TrustManagerFactory original = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                original.init((KeyStore) null);
                factories.add(original);

                for( KeyStore keyStore : additionalkeyStores ) {
                    final TrustManagerFactory additionalCerts = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    additionalCerts.init(keyStore);
                    factories.add(additionalCerts);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }



            /*
             * Iterate over the returned trustmanagers, and hold on
             * to any that are X509TrustManagers
             */
            for (TrustManagerFactory tmf : factories)
                for( TrustManager tm : tmf.getTrustManagers() )
                    if (tm instanceof X509TrustManager)
                        x509TrustManagers.add( (X509TrustManager)tm );


            if( x509TrustManagers.size()==0 )
                throw new RuntimeException("Couldn't find any X509TrustManagers");

        }

        /*
         * Delegate to the default trust manager.
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            final X509TrustManager defaultX509TrustManager = x509TrustManagers.get(0);
            defaultX509TrustManager.checkClientTrusted(chain, authType);
        }

        /*
         * Loop over the trustmanagers until we find one that accepts our server
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for( X509TrustManager tm : x509TrustManagers ) {
                try {
                    tm.checkServerTrusted(chain,authType);
                    return;
                } catch( CertificateException e ) {
                    // ignore
                }
            }
            throw new CertificateException();
        }

        public X509Certificate[] getAcceptedIssuers() {
            final ArrayList<X509Certificate> list = new ArrayList<X509Certificate>();
            for( X509TrustManager tm : x509TrustManagers )
                list.addAll(Arrays.asList(tm.getAcceptedIssuers()));
            return list.toArray(new X509Certificate[list.size()]);
        }
    }

}

Is there an equivalent of 'which' on the Windows command line?

I am using GOW (GNU on Windows) which is a light version of Cygwin. You can grab it from GitHub here.

GOW (GNU on Windows) is the lightweight alternative to Cygwin. It uses a convenient Windows installer that installs about 130 extremely useful open source UNIX applications compiled as native win32 binaries. It is designed to be as small as possible, about 10 MB, as opposed to Cygwin which can run well over 100 MB depending upon options. - About Description(Brent R. Matzelle)

A screenshot of a list of commands included in GOW:

Enter image description here

Taking the record with the max date

If date and col_date are the same columns you should simply do:

SELECT A, MAX(date) FROM t GROUP BY A

Why not use:

WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date

Otherwise:

SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
  FROM TABLENAME
 GROUP BY A

Add some word to all or some rows in Excel?

  1. Insert a column left to the column in question(adding column A beside column B).
  2. Provide the value you want to append in 1st cell of column A
  3. Insert a column right to the column in question ( column C)
  4. Add this formula -> =CONCATENATE("A1","B1")
  5. Drag it down to apply to all values in column
  6. You will find concatenated values in column C

This worked for me !

array of string with unknown size

You can't create an array without a size. You'd need to use a list for that.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Deleting/commenting

- (void)viewWillAppear:(BOOL)animated {[super viewWillAppear:YES];}

function solved the problem for me.

XCode (11.3.1)

importing external ".txt" file in python

You can import modules but not text files. If you want to print the content do the following:

Open a text file for reading:

f = open('words.txt', 'r')

Store content in a variable:

content = f.read()

Print content of this file:

print(content)

After you're done close a file:

f.close()

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

Animate the transition between fragments

Here's a slide in/out animation between fragments:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.listFragment, new YourFragment());
transaction.commit();

We are using an objectAnimator.

Here are the two xml files in the animator subfolder.

enter_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
     <objectAnimator
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:duration="1000"
         android:propertyName="x"
         android:valueFrom="2000"
         android:valueTo="0"
         android:valueType="floatType" />
</set>

exit_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:propertyName="x"
        android:valueFrom="0"
        android:valueTo="-2000"
        android:valueType="floatType" />
</set>

I hope that would help someone.

How to use npm with ASP.NET Core

By publishing your whole node_modules folder you are deploying far more files than you will actually need in production.

Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.

You can then also completely remove the FileServer configuration and rely on UseStaticFiles instead.

Currently, gulp is the VS task runner of choice. Add a gulpfile.js to the root of your project, and configure it to process your static files on publish.

For example, you can add the following scripts section to your project.json:

 "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  },

Which would work with the following gulpfile (the default when scaffolding with yo):

/// <binding Clean='clean'/>
"use strict";

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify");

var webroot = "./wwwroot/";

var paths = {
    js: webroot + "js/**/*.js",
    minJs: webroot + "js/**/*.min.js",
    css: webroot + "css/**/*.css",
    minCss: webroot + "css/**/*.min.css",
    concatJsDest: webroot + "js/site.min.js",
    concatCssDest: webroot + "css/site.min.css"
};

gulp.task("clean:js", function (cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("min:js", function () {
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.concatJsDest))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function () {
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.concatCssDest))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("min", ["min:js", "min:css"]);

Android SQLite Example

The following Links my help you

1. Android Sqlite Database

2. Tutorial 1

Database Helper Class:

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.

This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.

You need more refer this link Sqlite Helper

Algorithm to compare two images

These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!

Before you begin

Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.

Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.

Matlab is an excellent tool for testing and evaluating images.

Testing the algorithms

You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.

The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.

It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!

You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.

Colour Buckets

With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':

white
red
blue
green
black

(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.

Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.

Edge detection

How about using Edge Detection. alt text
(source: wikimedia.org)

With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.

Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied Gabor Filter (a type of edge detection) in various rotations.

alt text

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.

Regions of Interest

Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:

alt text
(source: meetthegimp.org)

The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.

If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:

alt text
(source: per2000.eu)

We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.

Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.

It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably designed to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.

Morphing

Morphing two images is the process of turning one image into the other through a set of steps:

alt text

Note, this is different to fading one image into another!

There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.

Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.

In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.

This technique could work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.

Zipping

Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.

One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.

Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about how compression works will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.

Transparency

Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.

Inverting Signals

An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.

alt text
(source: themotorreport.com.au)

Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.

However, consider two images that are equal, except one of them has a brighten effect applied to it:

alt text
(source: mcburrz.com)

Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.

I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.

Tree Data structures

At first these don't seem to fit for the problem, but I think they could work.

You could think about extracting certain properties of an image (for example colour bins) and generate a huffman tree or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.

This probably wouldn't work, but it's an idea. The trie datastructure is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:

FFFFFF|000000|FDFD44|FFFFFF

We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.

Comparing trie trees should be reasonably easy, and could possible provide effective results.

More ideas

I stumbled accross an interesting paper breif about classification of satellite imagery, it outlines:

Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.

It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.

Other things to consider

There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.

Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.

Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.

If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.

Be careful to not fall into attempting to complete the never ending project, good luck!

Simple (non-secure) hash function for JavaScript?

I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.

With this prototype you can simply call .hashCode() on any string, e.g. "some string".hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function() {
    var hash = 0;
    if (this.length == 0) {
        return hash;
    }
    for (var i = 0; i < this.length; i++) {
        var char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

Using Java to pull data from a webpage?

Since Java 11 the most convenient way it to use java.net.http.HttpClient from the standard library.

Example:

HttpRequest request = HttpRequest.newBuilder(new URI(
    "https://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"))
  .timeout(Duration.of(10, SECONDS))
  .GET()
  .build();

HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, BodyHandlers.ofString());

if (response.statusCode() != 200) {
  throw new RuntimeException(
    "Invalid response: " + response.statusCode() + ", request: " + response);
}

System.out.println(response.body());

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.

How to force a web browser NOT to cache images

I checked all the answers around the web and the best one seemed to be: (actually it isn't)

<img src="image.png?cache=none">

at first.

However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.

Solution to this problem was:

<img src="image.png?nocache=<?php echo time(); ?>">

where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.

However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.

To solve this problem, I needed to hash $_GET but since it is array here is the solution:

$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";

Edit:

Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:

echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";

filemtime() gets file modification time.

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

Select the first row by group

A base R option is the split()-lapply()-do.call() idiom:

> do.call(rbind, lapply(split(test, test$id), head, 1))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

A more direct option is to lapply() the [ function:

> do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

The comma-space 1, ) at the end of the lapply() call is essential as this is equivalent of calling [1, ] to select first row and all columns.

Link to the issue number on GitHub within a commit message

Just include #xxx in your commit message to reference an issue without closing it.

With new GitHub issues 2.0 you can use these synonyms to reference an issue and close it (in your commit message):

  • fix #xxx
  • fixes #xxx
  • fixed #xxx
  • close #xxx
  • closes #xxx
  • closed #xxx
  • resolve #xxx
  • resolves #xxx
  • resolved #xxx

You can also substitute #xxx with gh-xxx.

Referencing and closing issues across repos also works:

fixes user/repo#xxx

Check out the documentation available in their Help section.

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I also faced the same problem. I updated my .edmx from the database after that the exception has vanished.

How to correctly save instance state of Fragments in back stack?

final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.hide(currentFragment);
ft.add(R.id.content_frame, newFragment.newInstance(context), "Profile");
ft.addToBackStack(null);
ft.commit();

How to get indices of a sorted array in Python

Updated answer with enumerate and itemgetter:

sorted(enumerate(a), key=lambda x: x[1])
# [(0, 1), (1, 2), (2, 3), (4, 5), (3, 100)]

Zip the lists together: The first element in the tuple will the index, the second is the value (then sort it using the second value of the tuple x[1], x is the tuple)

Or using itemgetter from the operatormodule`:

from operator import itemgetter
sorted(enumerate(a), key=itemgetter(1))

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

Maven in Eclipse: step by step installation

I have just include Maven integration plug-in at Eclipse:

Just follow the bellow steps:

  • In eclipse, from upper menu item select- "Help" ->click on "Install New Software.."-> then click on "Add" button.

  • set the "MavenAPI" at name text box and "http://download.eclipse.org/technology/m2e/releases" at location text box.

  • press Ok and select the Maven project and install by clicking next next.

Python variables as keys to dict

Here it is in one line, without having to retype any of the variables or their values:

fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})

Why is "throws Exception" necessary when calling a function?

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

Getting error "The package appears to be corrupt" while installing apk file

In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.

How to get multiple counts with one SQL query?

You can use a CASE statement with an aggregate function. This is basically the same thing as a PIVOT function in some RDBMS:

SELECT distributor_id,
    count(*) AS total,
    sum(case when level = 'exec' then 1 else 0 end) AS ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) AS PersonalCount
FROM yourtable
GROUP BY distributor_id

Close Bootstrap modal on form submit

You can use one of this two options:

1) Add data-dismiss to the submit button i.e.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

2) Do it in JS like

$('#frmStudent').submit(function() {
    $('#StudentModal').modal('hide');
});

Open source PDF library for C/C++ application?

It depends a bit on your needs. Some toolkits are better at drawing, others are better for writing text. Cairo has a pretty good for drawing (it support a wide range of screen and file types, including pdf), but it may not be ideal for good typography.

Targeting only Firefox with CSS

OK, I've found it. This is probably the cleanest and easiest solution out there and does not rely on JavaScript being turned on.

_x000D_
_x000D_
@-moz-document url-prefix() {
  h1 {
    color: red;
  }
}
_x000D_
<h1>This should be red in FF</h1>
_x000D_
_x000D_
_x000D_

It's based on yet another Mozilla specific CSS extension. There's a whole list for these CSS extensions right here: Mozilla CSS Extensions.

How to set up googleTest as a shared library on Linux

Just in case somebody else gets in the same situation like me yesterday (2016-06-22) and also does not succeed with the already posted approaches - on Lubuntu 14.04 it worked for me using the following chain of commands:

git clone https://github.com/google/googletest
cd googletest
cmake -DBUILD_SHARED_LIBS=ON .
make
cd googlemock
sudo cp ./libgmock_main.so ./gtest/libgtest.so gtest/libgtest_main.so ./libgmock.so /usr/lib/
sudo ldconfig

Java Replace Character At Specific Position Of String?

Use StringBuilder:

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();