Programs & Examples On #Review board

Review Board is an open-source web-based code review tool written in Python.

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

How to make an autocomplete address field with google maps api?

Below I split all the details of formatted address like City, State, Country and Zip code. 
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically. 
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
    var places = new google.maps.places.Autocomplete(document
            .getElementById('txtPlaces'));
    google.maps.event.addListener(places, 'place_changed', function() {
        var place = places.getPlace();
        var address = place.formatted_address;
        var  value = address.split(",");
        count=value.length;
        country=value[count-1];
        state=value[count-2];
        city=value[count-3];
        var z=state.split(" ");
        document.getElementById("selCountry").text = country;
        var i =z.length;
        document.getElementById("pstate").value = z[1];
        if(i>2)
        document.getElementById("pzcode").value = z[2];
        document.getElementById("pCity").value = city;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();
        var mesg = address;
        document.getElementById("txtPlaces").value = mesg;
        var lati = latitude;
        document.getElementById("plati").value = lati;
        var longi = longitude;
        document.getElementById("plongi").value = longi;            
    });
});

How do I use the lines of a file as arguments of a command?

If you want to do this in a robust way that works for every possible command line argument (values with spaces, values with newlines, values with literal quote characters, non-printable values, values with glob characters, etc), it gets a bit more interesting.


To write to a file, given an array of arguments:

printf '%s\0' "${arguments[@]}" >file

...replace with "argument one", "argument two", etc. as appropriate.


To read from that file and use its contents (in bash, ksh93, or another recent shell with arrays):

declare -a args=()
while IFS='' read -r -d '' item; do
  args+=( "$item" )
done <file
run_your_command "${args[@]}"

To read from that file and use its contents (in a shell without arrays; note that this will overwrite your local command-line argument list, and is thus best done inside of a function, such that you're overwriting the function's arguments and not the global list):

set --
while IFS='' read -r -d '' item; do
  set -- "$@" "$item"
done <file
run_your_command "$@"

Note that -d (allowing a different end-of-line delimiter to be used) is a non-POSIX extension, and a shell without arrays may also not support it. Should that be the case, you may need to use a non-shell language to transform the NUL-delimited content into an eval-safe form:

quoted_list() {
  ## Works with either Python 2.x or 3.x
  python -c '
import sys, pipes, shlex
quote = pipes.quote if hasattr(pipes, "quote") else shlex.quote
print(" ".join([quote(s) for s in sys.stdin.read().split("\0")][:-1]))
  '
}

eval "set -- $(quoted_list <file)"
run_your_command "$@"

What does it mean to bind a multicast (UDP) socket?

To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.

Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving

[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

Differences in boolean operators: & vs && and | vs ||

Those are the bitwise AND and bitwise OR operators.

int a = 6; // 110
int b = 4; // 100

// Bitwise AND    

int c = a & b;
//   110
// & 100
// -----
//   100

// Bitwise OR

int d = a | b;
//   110
// | 100
// -----
//   110

System.out.println(c); // 4
System.out.println(d); // 6

Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.

Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&) and Conditional-Or (||) operators except for the fact that they don't short-circuit so while the following is safe:

if((a != null) && (a.something == 3)){
}

This is not:

if((a != null) & (a.something == 3)){
}

"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, && will examine the second condition only when a is not null (otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something will not raise an exception, or is considered "safe."

The & operator always examines every condition in the clause, so in the examples above, a.something may be evaluated when a is in fact a null value, raising an exception.

c# regex matches example

It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.

You can use regex groups as field name in class, after which could be written for example like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.

If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)

This will results in following output:

456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

How to remove decimal part from a number in C#

Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)

Extracting specific columns in numpy array

One thing I would like to point out is, if the number of columns you want to extract is 1 the resulting matrix would not be a Mx1 Matrix as you might expect but instead an array containing the elements of the column you extracted.

To convert it to Matrix the reshape(M,1) method should be used on the resulting array.

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

How can I test a PDF document if it is PDF/A compliant?

If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.

OpenOffice supports PDF/A. For some reason "PDF/A-1" is called

"SelectPdfVersion"
internally in OpenOffice. Just add 1 to that value and your output should be PDF/A.

The different values can be

0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B

You set

FilterData
to be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001

Add 'x' number of hours to date

   $now = date("Y-m-d H:i:s");
   date("Y-m-d H:i:s", strtotime("+1 hours $now"));

Create thumbnail image

The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height)
{
    Bitmap srcBmp = new Bitmap(path);
    float ratio = srcBmp.Width / srcBmp.Height;
    SizeF newSize = new SizeF(width, height * ratio);
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "image/jpeg";
    using (Graphics graphics = Graphics.FromImage(target))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
        using (MemoryStream memoryStream = new MemoryStream()) 
        {
            target.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.WriteTo(HttpContext.Response.OutputStream);
        }
    }
    Response.End();
}

checking if number entered is a digit in jquery

I would suggest using regexes:

var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
   alert('I am a number');
   ...
}

Or with a single regex as per @Platinum Azure's suggestion:

var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
   alert('I am a number');
   ...
}    

git: Your branch is ahead by X commits

Then when I do a git status it tells me that my branch is ahead by X commits (presumably the same number of commits that I have made).

My experience is in a team environment with many branches. We work in our own feature branches (in local clones) and it was one of those that git status showed I was 11 commits ahead. My working assumption, like the question's author, was that +11 was from commits of my own.

It turned out that I had pulled in changes from the common develop branch into my feature branch many weeks earlier -- but forgot! When I revisited my local feature branch today and did a git pull origin develop the number jumped to +41 commits ahead. Much work had been done in develop and so my local feature branch was even further ahead of the feature branch on the origin repository.

So, if you get this message, think back to any pulls/merges you might have done from other branches (of your own, or others) you have access to. The message just signals you need to git push those pulled changes back to the origin repo ('tracking branch') from your local repo to get things sync'd up.

Can I get "&&" or "-and" to work in PowerShell?

A verbose equivalent is to combine $LASTEXITCODE and -eq 0:

msbuild.exe args; if ($LASTEXITCODE -eq 0) { echo 'it built'; } else { echo 'it failed'; }

I'm not sure why if ($?) didn't work for me, but this one did.

Visual Studio 2015 is very slow

After upgrading from VS2013, I found that when debugging in Visual Studio 2015, it would freeze, I unchecked "Tools>Options>Debugging>General>Enable Diagnostics Tools while debugging" It brought debugging sessions back to normal. While Diagnostics are useful, I don't need them all the time so if at any point I need them I can turn it back on.

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Quoting from w3schools:

The "use strict" Directive

The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

The purpose of "use strict" is to indicate that the code should be executed in "strict mode".

With strict mode, you can not, for example, use undeclared variables.

Why Strict Mode?

Strict mode makes it easier to write "secure" JavaScript.

Strict mode changes previously accepted "bad syntax" into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Please refer to http://www.w3schools.com/js/js_strict.asp to know more

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

connecting to mysql server on another PC in LAN

actually you shouldn't specify port in the host name. Mysql has special option for port (if port differs from default)

kind of

mysql --host=192.168.1.2 --port=3306

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

<uses-permission android:name="android.permission.INTERNET" />

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

Facebook key hash does not match any stored key hashes

I have had this Problem for two months now. My key hashes have been pyling up to 9. Today i finally found the simple solution:

STEP 1:

Install the facebook sdk you downloaded from the facebook developer page on your phone. Don´t install the normal facebook app. Make sure you can log into facebook. Then log out.

STEP 2:

Export your app with your final release key as an apk, like you would when uploading it to the playstore.

STEP 3:

Put the Apk file on your phone via usb cable or usb stick.

STEP 4:

Install your app, using a file manager: For example https://play.google.com/store/apps/details?id=com.rhmsoft.fm

STEP 5:

Launch your app and try to log in with facebook. A dialog will open and tell you: "the key has not been found in the facebook developer console

STEP 6:

Write down the key.

STEP 7:

Put it into your facebook developer console and save. Now you are done. Anyone that downloads your app, published with earlier used keystore can log into facebook.

Enjoy

Closing a file after File.Create

File.Create returns a FileStream object that you can call Close() on.

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

What does "wrong number of arguments (1 for 0)" mean in Ruby?

When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.

Example: Takes no arguments:

def dog
end

Takes arguments:

def cat(name)
end

When you call these, you need to call them with the arguments you defined.

dog                  #works fine
cat("Fluffy")        #works fine


dog("Fido")          #Returns ArgumentError (1 for 0)
cat                  #Returns ArgumentError (0 for 1)

Check out the Ruby Koans to learn all this.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

For me, the problem that caused this error arose when I was saving a new row to the database, but a field was null. In the database table design, that field is NOT NULL. So when I tried to save a new row with a null value for not-null field, Visual Studio threw this error. Thus, I made sure that the field was assigned a value, and the problem was fixed.

How do you switch pages in Xamarin.Forms?

If you do not want to go the previous page i.e. do not let the user go back to the login screen once authorization is done, then you can use;

 App.Current.MainPage = new HomePage();

If you want to enable back functionality, just use

Navigation.PushModalAsync(new HomePage())

ImageView in circular through xml

you don't need any third-party library.

you can use the ShapeableImageView in the material.

implementation 'com.google.android.material:material:1.2.0'

style.xml

<style name="ShapeAppearanceOverlay.App.CornerSize">
     <item name="cornerSize">50%</item>
</style>

in layout

<com.google.android.material.imageview.ShapeableImageView
     android:layout_width="100dp"
     android:layout_height="100dp"
     app:srcCompat="@drawable/ic_profile"
     app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.CornerSize"
/>

you can see this

https://developer.android.com/reference/com/google/android/material/imageview/ShapeableImageView

or this

https://medium.com/android-beginners/shapeableimageview-material-components-for-android-cac6edac2c0d

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I see that this question is already old but still...

We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.

I hope it helps :)

When to use a linked list over an array/array list?

Arrays, by far, are the most widely used data structures. However, linked lists prove useful in their own unique way where arrays are clumsy - or expensive, to say the least.

Linked lists are useful to implement stacks and queues in situations where their size is subject to vary. Each node in the linked list can be pushed or popped without disturbing the majority of the nodes. Same goes for insertion/deletion of nodes somewhere in the middle. In arrays, however, all the elements have to be shifted, which is an expensive job in terms of execution time.

Binary trees and binary search trees, hash tables, and tries are some of the data structures wherein - at least in C - you need linked lists as a fundamental ingredient for building them up.

However, linked lists should be avoided in situations where it is expected to be able to call any arbitrary element by its index.

Removing page title and date when printing web page (with CSS?)

Try this;

@media print{ @page { margin-top: 30px; margin-bottom: 30px;}}

How to get access to job parameters from ItemReader, in Spring Batch?

If you want to define your ItemReader instance and your Step instance in a single JavaConfig class. You can use the @StepScope and the @Value annotations such as:

@Configuration
public class ContributionCardBatchConfiguration {

   private static final String WILL_BE_INJECTED = null;

   @Bean
   @StepScope
   public FlatFileItemReader<ContributionCard> contributionCardReader(@Value("#{jobParameters['fileName']}")String contributionCardCsvFileName){

     ....
   }

   @Bean
   Step ingestContributionCardStep(ItemReader<ContributionCard> reader){
         return stepBuilderFactory.get("ingestContributionCardStep")
                 .<ContributionCard, ContributionCard>chunk(1)
                 .reader(contributionCardReader(WILL_BE_INJECTED))
                 .writer(contributionCardWriter())
                 .build();
    }
}

The trick is to pass a null value to the itemReader since it will be injected through the @Value("#{jobParameters['fileName']}") annotation.

Thanks to Tobias Flohre for his article : Spring Batch 2.2 – JavaConfig Part 2: JobParameters, ExecutionContext and StepScope

How do you run a command for each line of a file?

Yes.

while read in; do chmod 755 "$in"; done < file.txt

This way you can avoid a cat process.

cat is almost always bad for a purpose such as this. You can read more about Useless Use of Cat.

How to detect idle time in JavaScript elegantly?

Here is the best solution I have found: http://css-tricks.com/snippets/jquery/fire-event-when-user-is-idle/

Here is the JS:

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {

        $('*').bind('mousemove keydown scroll', function () {

            clearTimeout(idleTimer);

            if (idleState == true) { 

                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");            
            }

            idleState = false;

            idleTimer = setTimeout(function () { 

                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

                idleState = true; }, idleWait);
        });

        $("body").trigger("mousemove");

    });
}) (jQuery)

How to get an Instagram Access Token

If you don't want to build your server side, like only developing on a client side (web app or a mobile app) , you could choose an Implicit Authentication .

As the document saying , first make a https request with

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

Fill in your CLIENT-ID and REDIRECT-URL you designated.

Then that's going to the log in page , but the most important thing is how to get the access token after the user correctly logging in.

After the user click the log in button with both correct account and password, the web page will redirect to the url you designated followed by a new access token.

http://your-redirect-uri#access_token=ACCESS-TOKEN

I'm not familiar with javascript , but in Android studio , that's an easy way to add a listener which listen to the event the web page override the url to the new url (redirect event) , then it will pass the redirect url string to you , so you can easily split it to get the access-token like:

String access_token = url.split("=")[1];

Means to break the url into the string array in each "=" character , then the access token obviously exists at [1].

How to validate a date?

It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):

_x000D_
_x000D_
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;_x000D_
function isValidDate(strDate) {_x000D_
  if (!dateValidationRegex.test(strDate)) return false;_x000D_
  const [m, d, y] = strDate.split('/').map(n => parseInt(n));_x000D_
  return m === new Date(y, m - 1, d).getMonth() + 1;_x000D_
}_x000D_
_x000D_
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {_x000D_
  console.log(d, isValidDate(d));_x000D_
});
_x000D_
_x000D_
_x000D_

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

It looks that even if the driver 10.2 is compatible with the JDBC3 it may not work with JRE6 as I've found here:

http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_03

Which JDBC drivers support which versions of Javasoft's JDK?

pre-8i OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.5 OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.6SDK THIN Driver - JDK 1.1.x and JDK 1.2.x (aka Java2)
8.1.6SDK OCI Driver - Only JDK 1.1.x
8.1.6 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
8.1.7 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
9.0.1 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x and JDK 1.3.x
9.2.0 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.1.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.2.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, JDK 1.4.x, and JDK 5.0.x
11.1.0 OCI and THIN Driver - JDK 1.5.x and JDK 1.6.x

Oracle 10.2.0 supports:

Full support for JDBC 3.0
Note that there is no real change in the support for the following in the database. Allthat has changed is that some methods that previously threw SQLException now do something more reasonable instead.
result-set holdability
returning multiple result-sets.

Only get hash value using md5sum (without filename)

You can use cut to split the line on spaces and return only the first such field:

md5=$(md5sum "$my_iso_file" | cut -d ' ' -f 1)

How to pass a URI to an intent?

In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.

Look at this simple approach.

// put uri to intent 
intent.setData(imageUri);

And to get Uri back from intent:

// Get Uri from Intent
Uri imageUri=getIntent().getData();

How to get `DOM Element` in Angular 2?

Update (using renderer):

Note that the original Renderer service has now been deprecated in favor of Renderer2

as on Renderer2 official doc.

Furthermore, as pointed out by @GünterZöchbauer:

Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.


You can achieve this by using elementRef as well as by ViewChild. however it's not recommendable to use elementRef due to:

  • security issue
  • tight coupling

as pointed out by official ng2 documentation.

1. Using elementRef (Direct Access):

export class MyComponent {    
constructor (private _elementRef : ElementRef) {
 this._elementRef.nativeElement.querySelector('textarea').focus();
 }
}

2. Using ViewChild (better approach):

<textarea  #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}" 
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var


export class MyComponent implements AfterViewInit {
  @ViewChild('tasknote') input: ElementRef;

   ngAfterViewInit() {
    this.input.nativeElement.focus();

  }
}

3. Using renderer:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of depreaced invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

How to update specific key's value in an associative array in PHP?

The best approach is using a lambda within "array_walk" native function to make the required changes:

    array_walk($data, function (&$value, $key) {
            if($key == 'transaction_date'){ 
                  $value = date('d/m/Y', $value); 
            }
    });

The value is updated in the array as it's passed with as a reference "&".

What is the difference between g++ and gcc?

gcc and g ++ are both GNU compiler. They both compile c and c++. The difference is for *.c files gcc treats it as a c program, and g++ sees it as a c ++ program. *.cpp files are considered to be c ++ programs. c++ is a super set of c and the syntax is more strict, so be careful about the suffix.

How to do a PUT request with curl?

An example PUT following Martin C. Martin's comment:

curl -T filename.txt http://www.example.com/dir/

With -T (same as --upload-file) curl will use PUT for HTTP.

Open a link in browser with java button?

public static void openWebPage(String url) {
    try {
        Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
        if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
            desktop.browse(new URI(url));
        }
        throw new NullPointerException();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
    }
}

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Nginx:

location ~* \.(eot|ttf|woff)$ {
   add_header Access-Control-Allow-Origin '*';
}

AWS S3:

  1. Select your bucket
  2. Click properties on the right top
  3. Permisions => Edit Cors Configuration => Save
  4. Save

http://schock.net/articles/2013/07/03/hosting-web-fonts-on-a-cdn-youre-going-to-need-some-cors/

jQuery Combobox/select autocomplete?

I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.

I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.

The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.

The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".

So let's say you first set-up your site to deliver the JSON data from a URL like this:

/categories.json

Then your autocomplete source: option would be 'source: /categories.json'.

When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:

/categories.json?term=first-cata

This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.

I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.

Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.

This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.

When a user selects a category, your JavaScript should update a hidden field with the ID.

I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.

These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.

Hope this helped.

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

How do I simulate a hover with a touch in touch enabled browsers?

The mouse hover effect cannot be implemented in touch device . When I'm appeared with same situation in safari ios I used :active in css to make effect.

ie.

p:active {
  color:red;
}

In my case its working .May be this is also the case that can be used with out using javascript. Just give a try.

How to declare a global variable in JavaScript

Declare the variable outside of functions

function dosomething(){
  var i = 0; // Can only be used inside function
}

var i = '';
function dosomething(){
  i = 0; // Can be used inside and outside the function
}

Can I invoke an instance method on a Ruby module without including it?

To invoke a module instance method without including the module (and without creating intermediary objects):

class UsefulWorker
  def do_work
    UsefulThings.instance_method(:format_text).bind(self).call("abc")
    ...
  end
end

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

Are (non-void) self-closing tags valid in HTML5?

  • In HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>&gt;) and <title/hello/ meaning <title>hello</title>). This is an SGML rule that browsers did a very poor job of supporting, and the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>. This is an XML rule that applies to all XML documents. That said, XHTML is often served as text/html which (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelines to follow for XHTML as text/html. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).

  • In HTML5, the meaning of <foo /> depends on the type of element.

    • On HTML elements that are designated as void elements (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

I was debugging the problem for the better part of the day and when I was close to burning the building I discovered the Process Monitor tool from Sysinternals.

Set it to monitor w3wp.exe and check last events before it exits after you fire a request in the browser. Hope that helps further readers.

VMware Workstation and Device/Credential Guard are not compatible

Device/Credential Guard is a Hyper-V based Virtual Machine/Virtual Secure Mode that hosts a secure kernel to make Windows 10 much more secure.

enter image description here

...the VSM instance is segregated from the normal operating system functions and is protected by attempts to read information in that mode. The protections are hardware assisted, since the hypervisor is requesting the hardware treat those memory pages differently. This is the same way to two virtual machines on the same host cannot interact with each other; their memory is independent and hardware regulated to ensure each VM can only access it’s own data.

From here, we now have a protected mode where we can run security sensitive operations. At the time of writing, we support three capabilities that can reside here: the Local Security Authority (LSA), and Code Integrity control functions in the form of Kernel Mode Code Integrity (KMCI) and the hypervisor code integrity control itself, which is called Hypervisor Code Integrity (HVCI).

enter image description here

When these capabilities are handled by Trustlets in VSM, the Host OS simply communicates with them through standard channels and capabilities inside of the OS. While this Trustlet-specific communication is allowed, having malicious code or users in the Host OS attempt to read or manipulate the data in VSM will be significantly harder than on a system without this configured, providing the security benefit.

Running LSA in VSM, causes the LSA process itself (LSASS) to remain in the Host OS, and a special, additional instance of LSA (called LSAIso – which stands for LSA Isolated) is created. This is to allow all of the standard calls to LSA to still succeed, offering excellent legacy and backwards compatibility, even for services or capabilities that require direct communication with LSA. In this respect, you can think of the remaining LSA instance in the Host OS as a ‘proxy’ or ‘stub’ instance that simply communicates with the isolated version in prescribed ways.


And Hyper-V and VMware didn't work the same time until 2020, when VMware used Hyper-V Platform to co-exist with Hyper-V starting with Version 15.5.5.

How does VMware Workstation work before version 15.5.5?

VMware Workstation traditionally has used a Virtual Machine Monitor (VMM) which operates in privileged mode requiring direct access to the CPU as well as access to the CPU’s built in virtualization support (Intel’s VT-x and AMD’s AMD-V). When a Windows host enables Virtualization Based Security (“VBS“) features, Windows adds a hypervisor layer based on Hyper-V between the hardware and Windows. Any attempt to run VMware’s traditional VMM fails because being inside Hyper-V the VMM no longer has access to the hardware’s virtualization support.

Introducing User Level Monitor

To fix this Hyper-V/Host VBS compatibility issue, VMware’s platform team re-architected VMware’s Hypervisor to use Microsoft’s WHP APIs. This means changing our VMM to run at user level instead of in privileged mode, as well modifying it to use the WHP APIs to manage the execution of a guest instead of using the underlying hardware directly.

What does this mean to you?

VMware Workstation/Player can now run when Hyper-V is enabled. You no longer have to choose between running VMware Workstation and Windows features like WSL, Device Guard and Credential Guard. When Hyper-V is enabled, ULM mode will automatically be used so you can run VMware Workstation normally. If you don’t use Hyper-V at all, VMware Workstation is smart enough to detect this and the VMM will be used.

System Requirements

To run Workstation/Player using the Windows Hypervisor APIs, the minimum required Windows 10 version is Windows 10 20H1 build 19041.264. VMware Workstation/Player minimum version is 15.5.5.

To avoid the error, update your Windows 10 to Version 2004/Build 19041 (Mai 2020 Update) and use at least VMware 15.5.5.

Eclipse add Tomcat 7 blank server name

In Eclipse Neon.3 Release (4.6.3) on Ubuntu 17.04 with Tomcat 8.0 the problem persists. What helped me was the combination of deleting the prefs files:

rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jst.server.tomcat.core.prefs    
rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.server.core.prefs

and linking to catalina.policy (somewhat differently than how @michael-brooks suggested for his configuration):

sudo ln -s /var/lib/tomcat8/policy/catalina.policy conf/catalina.policy

Range with step of type float

The problem with floating point is that you may not get the same number of items as you expected, due to inaccuracy. This can be a real problem if you are playing with polynomials where the exact number of items is quite important.

What you really want is an arithmetic progression; the following code will work quite happily for int, float and complex ... and strings, and lists ...

def arithmetic_progression(start, step, length):
    for i in xrange(length):
        yield start + i * step

Note that this code stands a better chance of your last value being within a bull's roar of the expected value than any alternative which maintains a running total.

>>> 10000 * 0.0001, sum(0.0001 for i in xrange(10000))
(1.0, 0.9999999999999062)
>>> 10000 * (1/3.), sum(1/3. for i in xrange(10000))
(3333.333333333333, 3333.3333333337314)

Correction: here's a competetive running-total gadget:

def kahan_range(start, stop, step):
    assert step > 0.0
    total = start
    compo = 0.0
    while total < stop:
        yield total
        y = step - compo
        temp = total + y
        compo = (temp - total) - y
        total = temp

>>> list(kahan_range(0, 1, 0.0001))[-1]
0.9999
>>> list(kahan_range(0, 3333.3334, 1/3.))[-1]
3333.333333333333
>>>

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Rerender view on browser resize with React

@SophieAlpert is right, +1, I just want to provide a modified version of her solution, without jQuery, based on this answer.

var WindowDimensions = React.createClass({
    render: function() {
        return <span>{this.state.width} x {this.state.height}</span>;
    },
    updateDimensions: function() {

    var w = window,
        d = document,
        documentElement = d.documentElement,
        body = d.getElementsByTagName('body')[0],
        width = w.innerWidth || documentElement.clientWidth || body.clientWidth,
        height = w.innerHeight|| documentElement.clientHeight|| body.clientHeight;

        this.setState({width: width, height: height});
        // if you are using ES2015 I'm pretty sure you can do this: this.setState({width, height});
    },
    componentWillMount: function() {
        this.updateDimensions();
    },
    componentDidMount: function() {
        window.addEventListener("resize", this.updateDimensions);
    },
    componentWillUnmount: function() {
        window.removeEventListener("resize", this.updateDimensions);
    }
});

What is the most efficient way to store tags in a database?

I'd suggest using intermediary third table for storing tags<=>items associations, since we have many-to-many relations between tags and items, i.e. one item can be associated with multiple tags and one tag can be associated with multiple items. HTH, Valve.

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Re-doing a reverted merge in Git

I just found this post when facing the same problem. I find above wayyy to scary to do reset hards etc. I'll end up deleting something I don't want to, and won't be able to get it back.

Instead I checked out the commit I wanted the branch to go back to e.g. git checkout 123466t7632723. Then converted to a branch git checkout my-new-branch. I then deleted the branch I didn't want any more. Of course this will only work if you are able to throw away the branch you messed up.

How to export all collections in MongoDB?

If you want to dump all collections in all databases (which is an expansive interpretation of the original questioner's intent) then use

mongodump

All the databases and collections will be created in a directory called 'dump' in the 'current' location

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

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

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.

adding noise to a signal in python

AWGN Similar to Matlab Function

def awgn(sinal):
    regsnr=54
    sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
    sigpower=sigpower/len(sinal)
    noisepower=sigpower/(math.pow(10,regsnr/10))
    noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
    return noise

Adding devices to team provisioning profile

There are two types of provisioning profiles.

  • development and
  • distribution

When app is live on app store then distribution profiles works and do not need any devices to be added.

Only development profiles need to add devices.In order to do so these are the steps-

  1. Login to developer.apple.com member centre.
  2. Go to Certificates, Identifiers & Profiles.
  3. Get UDID of your device and add it in the devices.
  4. Select a developer provisioning profile and edit it.
  5. Click on check box next to the device you just added.
  6. Generate and download the profile.
  7. Double click on it to install it.
  8. Connect your device and retry.

This worked for me hope it works for you.

How to get bitmap from a url in android?

This is a simple one line way to do it:

    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

When you call setAdapter, that does not immediately lay out and position items on the screen (that takes a single layout pass) hence your scrollToPosition() call has no actual elements to scroll to when you call it.

Instead, you should register a ViewTreeObserver.OnGlobalLayoutListener (via addOnGlobalLayoutListner() from a ViewTreeObserver created by conversationView.getViewTreeObserver()) which delays your scrollToPosition() until after the first layout pass:

conversationView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  public void onGlobalLayout() {
    conversationView.scrollToPosition(GENERIC_MESSAGE_LIST.size();
    // Unregister the listener to only call scrollToPosition once
    conversationView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

    // Use vto.removeOnGlobalLayoutListener(this) on API16+ devices as 
    // removeGlobalOnLayoutListener is deprecated.
    // They do the same thing, just a rename so your choice.
  }
});

Connect to sqlplus in a shell script and run SQL scripts

Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:

#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'

runsql () {
  # param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}

echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"

echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh

echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"

echo "TS::$(date): DONE"

runsql allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.

Get Today's date in Java at midnight time

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
Date date = new Date(); System.out.println(dateFormat.format(date));    //2014/08/06 15:59:4

Swift Error: Editor placeholder in source file

Error is straight forward and its because of wrong placeholders you have used in function call. Inside init you are not passing any parameters to your function. It should be this way

destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values

Or you can just initialise with default method

destination = Node()

UPDATE

Add empty initialiser in your Node class

init() {

}

How to use document.getElementByName and getElementByTag?

getElementById returns either a reference to an element with an id matching the argument, or null if no such element exists in the document.

getElementsByName() (note the plural Elements) returns a (possibly empty) HTMLCollection of the elements with a name matching the argument. Note that IE treats the name and id attributes and properties as the same thing, so getElementsByName will return elements with matching id also.

getElementsByTagName is similar but returns a NodeList. It's all there in the relevant specifications.

How to select different app.config for several build configurations

Use SlowCheetah plugin. For more options and details of how to use SlowCheetah keep reading.

As you have already noticed, there is no default and easy way to use different config files for a Library type (.dll) project. The reason is that the current thinking is: "You don't need to"! Framework developers reckon you need configuration for the executable file: be it a console, desktop, web, mobile app or something else. If you start providing configuration for a dll, you may end up with something I can call a config hell. You may no longer understand (easily) why this and that variables have such weird values coming seemingly from nowhere.

"Hold on", - you may say, "but I need this for my integration/unit testing, and it is a library!". And that is true and this is what you can do (pick only one, don't mix):

1. SlowCheetah - transforms current config file

You can install SlowCheetah - a Visual Studio plug-in that does all low level XML poking (or transformation) for you. The way it works, briefly:

  • Install SlowCheetah and restart Visual Studio (Visual Studio > Tools > Extensions and Updates ... > Online > Visual Studio Gallery > search for "Slow Cheetah" )
  • Define your solution configurations (Debug and Release are there by default), you can add more (right click on the solution in Solution Explorer > Configuration Manager... > Active Solution Configuration > New...
  • Add a config file if needed
  • Right click on config file > Add Transform
    • This will create Transformation files - one per your configuration
    • Transform files work as injectors/mutators, they find needed XML code in the original config file and inject new lines or mutate needed value, whatever you tell it to do

2. Fiddle with .proj file - copy-renames a whole new config file

Originally taken from here. It's a custom MSBuild task that you can embed into Visual Studio .proj file. Copy and paste the following code into the project file

<Target Name="AfterBuild">
    <Delete Files="$(TargetDir)$(TargetFileName).config" />
    <Copy SourceFiles="$(ProjectDir)\Config\App.$(Configuration).config"
          DestinationFiles="$(TargetDir)$(TargetFileName).config" />
</Target>

Now create a folder in the project called Config and add new files there: App.Debug.config, App.Release.config and so on. Now, depending on your configuration, Visual Studio will pick the config file from a Config folder, and copy-rename it into the output directory. So if you had PatternPA.Test.Integration project and a Debug config selected, in the output folder after the build you will find a PatternPA.Test.Integration.dll.config file which was copied from Config\App.Debug.config and renamed afterwards.

These are some notes you can leave in the config files

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <!-- This file is copied and renamed by the 'AfterBuild' MSBuild task -->

    <!-- Depending on the configuration the content of projectName.dll.config 
        is fully substituted by the correspondent to build configuration file 
        from the 'Config' directory. -->

</configuration>

In Visual Studio you can have something like this

Project structure

3. Use scripting files outside Visual Studio

Each build tool (like NAnt, MSBuild) will provide capabilities to transform config file depending on the configuration. This is useful if you build your solution on a build machine, where you need to have more control on what and how you prepare the product for release.

For example you can use web publishing dll's task to transform any config file

<UsingTask AssemblyFile="..\tools\build\Microsoft.Web.Publishing.Tasks.dll"
    TaskName="TransformXml"/>

<PropertyGroup>
    <!-- Path to input config file -->  
    <TransformInputFile>path to app.config</TransformInputFile>
    <!-- Path to the transformation file -->    
    <TransformFile>path to app.$(Configuration).config</TransformFile>
    <!-- Path to outptu web config file --> 
    <TransformOutputFile>path to output project.dll.config</TransformOutputFile>
</PropertyGroup>

<Target Name="transform">
    <TransformXml Source="$(TransformInputFile)"
                  Transform="$(TransformFile)"
                  Destination="$(TransformOutputFile)" />
</Target>

What is the perfect counterpart in Python for "while not EOF"

You can use below code snippet to read line by line, till end of file

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

How to re-sign the ipa file?

Check iResign for an easy tool on how to do this!

[edit] after some fudling around, I found a solution to keychain-aware resigning. You can check it out at https://gist.github.com/Weptun/5406993

Java Enum return Int

Do you want to this code?

public static enum FieldIndex {
    HDB_TRX_ID,     //TRX ID
    HDB_SYS_ID      //SYSTEM ID
}

public String print(ArrayList<String> itemName){
    return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}

Python: Adding element to list while iterating

Expanding S.Lott's answer so that new items are processed as well:

todo = myarr
done = []
while todo:
    added = []
    for a in todo:
        if somecond(a):
            added.append(newObj())
    done.extend(todo)
    todo = added

The final list is in done.

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff

    $(anyDomElement).trigger("myCustomEvent");
}


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff
});

How to create a new branch from a tag?

The situation becomes a little bit problematic if we want to create a branch from a tag with the same name.

In this, and in similar scenarios, the important thing is to know: branches and tags are actually single-line text files in .git/refs directory, and we can reference them explicitly using their pathes below .git. Branches are called here "heads", to make our life more simple.

Thus, refs/heads/master is the real, explicit name of the master branch. And refs/tags/cica is the exact name of the tag named cica.

The correct command to create a branch named cica from the tag named cica is:

git branch cica refs/tags/cica

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

Defining array with multiple types in TypeScript

Im using this version:

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

It is a little bit similar to the other suggestions but still easy and quite good to remember.

How to check if input date is equal to today's date?

Date.js is a handy library for manipulating and formatting dates. It can help in this situation.

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

How to find out the location of currently used MySQL configuration file in linux

you can find it by running the following command

mysql --help

it will give you the mysql installed directory and all commands for mysql.

failed to lazily initialize a collection of role

as suggested here solving the famous LazyInitializationException is one of the following methods:

(1) Use Hibernate.initialize

Hibernate.initialize(topics.getComments());

(2) Use JOIN FETCH

You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.

(3) Use OpenSessionInViewFilter

LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

Conversion from 12 hours time to 24 hours time in java

java.time

In Java 8 and later it could be done in one line using class java.time.LocalTime.

In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.

Code example:

String result =                                       // Text representing the value of our date-time object.
    LocalTime.parse(                                  // Class representing a time-of-day value without a date and without a time zone.
        "03:30 PM" ,                                  // Your `String` input text.
        DateTimeFormatter.ofPattern(                  // Define a formatting pattern to match your input text.
            "hh:mm a" ,
            Locale.US                                 // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
        )                                             // Returns a `DateTimeFormatter` object.
    )                                                 // Return a `LocalTime` object.
    .format( DateTimeFormatter.ofPattern("HH:mm") )   // Generate text in a specific format. Returns a `String` object.
;

See this code run live at IdeOne.com.

15:30

See Oracle Tutorial.

Genymotion error at start 'Unable to load virtualbox'

I have spend all day to solve this error since none of the answers worked for me.

I found out that oracle virtual box doesn't install the network adapter correctly in windows 8.1

Solution:

  1. Delete all previous virtual box adapters
  2. Go to device manager and click "Action" > "Add legacy hardware"
  3. Install the oracle virtual box adapters manually (my path was C:\Program Files\Oracle\VirtualBox\drivers\network\netadp\VBoxNetAdp.inf)

Now that virtual box adapters is installed correctly, it needs to be setup correctly. (the following solution is like many other solution in here)

  1. Start Oracle VM VirtualBox and go to "File" > "Preferences" > "Network" > "Host-only Network"
  2. Click edit
  3. Set IPv4 192.168.56.1 mask 255.255.255.0
  4. Click DHCP Server tab and set server adr: 192.168.56.100 server Mask: 255.255.255.0 low address bound: 192.168.56.101 upper adress bound 192.168.56.254
  5. Now click OK and start genymotion

Add space between HTML elements only using CSS

span:not(:last-child) {
    margin-right: 10px;
}

Is a GUID unique 100% of the time?

It should not happen. However, when .NET is under a heavy load, it is possible to get duplicate guids. I have two different web servers using two different sql servers. I went to merge the data and found I had 15 million guids and 7 duplicates.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Inspired by TheIT, I just got this to work by manipulating the manifest file but in a slightly different fashion. Set the icon in the application setting so that the majority of the activities get the icon. On the activity where you want to show the logo, add the android:logo attribute to the activity declaration. In the following example, only LogoActivity should have the logo, while the others will default to icon.

<application
    android:name="com.your.app"
    android:icon="@drawable/your_icon"
    android:label="@string/app_name">

    <activity
        android:name="com.your.app.LogoActivity"
        android:logo="@drawable/your_logo"
        android:label="Logo Activity" >

    <activity
        android:name="com.your.app.IconActivity1"
        android:label="Icon Activity 1" >

    <activity
        android:name="com.your.app.IconActivity2"
        android:label="Icon Activity 2" >

</application>

Hope this helps someone else out!

How to show text in combobox when no item selected?

I can't see any native .NET way to do it but if you want to get your hands dirty with the underlying Win32 controls...

You should be able to send it the CB_GETCOMBOBOXINFO message with a COMBOBOXINFO structure which will contain the internal edit control's handle. You can then send the edit control the EM_SETCUEBANNER message with a pointer to the string. (Note that this requires at least XP and visual styles to be enabled.

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

Microsoft has a special note on this (https://msdn.microsoft.com/en-us/library/bb531344.aspx#BK_CRT):

The printf and scanf family of functions are now defined inline.

The definitions of all of the printf and scanf functions have been moved inline into stdio.h, conio.h, and other CRT headers. This is a breaking change that leads to a linker error (LNK2019, unresolved external symbol) for any programs that declared these functions locally without including the appropriate CRT headers. If possible, you should update the code to include the CRT headers (that is, add #include ) and the inline functions, but if you do not want to modify your code to include these header files, an alternative solution is to add an additional library to your linker input, legacy_stdio_definitions.lib.

To add this library to your linker input in the IDE, open the context menu for the project node, choose Properties, then in the Project Properties dialog box, choose Linker, and edit the Linker Input to add legacy_stdio_definitions.lib to the semi-colon-separated list.

If your project links with static libraries that were compiled with a release of Visual C++ earlier than 2015, the linker might report an unresolved external symbol. These errors might reference internal stdio definitions for _iob, _iob_func, or related imports for certain stdio functions in the form of __imp_*. Microsoft recommends that you recompile all static libraries with the latest version of the Visual C++ compiler and libraries when you upgrade a project. If the library is a third-party library for which source is not available, you should either request an updated binary from the third party or encapsulate your usage of that library into a separate DLL that you compile with the older version of the Visual C++ compiler and libraries.

C++ trying to swap values in a vector

after passing the vector by reference

swap(vector[position],vector[otherPosition]);

will produce the expected result.

How do I write a correct micro-benchmark in Java?

Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.

updating Google play services in Emulator

You need install Google play image, Android SDK -> SDK platforms --> check show Package details --> install Google play. enter image description here

Adding a column to an existing table in a Rails migration

You can also force to table columns in table using force: true, if you table is already exist.

example:

ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

What charset does Microsoft Excel use when saving files?

OOXML files like those that come from Excel 2007 are encoded in UTF-8, according to wikipedia. I don't know about CSV files, but it stands to reason it would use the same format...

top -c command in linux to filter processes listed based on processname

It can be done interactively

After running top -c , hit o and write a filter on a column, e.g. to show rows where COMMAND column contains the string foo, write COMMAND=foo

If you just want some basic output this might be enough:

top -bc |grep name_of_process

how to add jquery in laravel project

you can use online library

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

or else download library and add css in css folder and jquery in js folder.both folder you keep in laravel public folder then you can link like below

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

How to access SOAP services from iPhone

My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.

Time to implement: 15-30 minutes.

Not most elegant, but solid.

Set a request header in JavaScript

W3C Spec on setrequestheader.

The brief points:

If the request header had already been set, then the new value MUST be concatenated to the existing value using a U+002C COMMA followed by a U+0020 SPACE for separation.

UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.

However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing:

// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom Referer type header you could always do:

xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com');

Release generating .pdb files, why?

Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.

Conversion from Long to Double in Java

Simple casting?

double d = (double)15552451L;

flow 2 columns of text automatically with CSS

Here is an example of a simple Two-column class:

.two-col {
       -moz-column-count: 2;
       -moz-column-gap: 20px;
       -webkit-column-count: 2;
       -webkit-column-gap: 20px;
}

Of which you would apply to a block of text like so:

<p class="two-col">Text</p>

Event detect when css property changed using Jquery

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

How to exclude 0 from MIN formula Excel

min() fuction exlude BOOLEAN and STRING values. if you replace your zeroes with "" (empty string) - min() function will do its job as you like!

How to convert string to char array in C++?

Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;

  1. A constant char array is good enough for you so you go with,

    const char *array = tmp.c_str();
    
  2. Or you need to modify the char array so constant is not ok, then just go with this

    char *array = &tmp[0];
    

Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.

Check if string contains \n Java

For portability, you really should do something like this:

public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);

unless you're absolutely certain that "\n" is what you want.

Setting CSS pseudo-class rules from JavaScript

Switching stylesheets in and out is the way to do it. Here is a library to build stylesheets dynamically, so you can set styles on the fly:

http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

What is a word boundary in regex, does \b match hyphen '-'?

when you use \\b(\\w+)+\\b that means exact match with a word containing only word characters ([a-zA-Z0-9])

in your case for example setting \\b at the begining of regex will accept -12(with space) but again it won't accept -12(without space)

for reference to support my words: https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

Removing an activity from the history stack

It is crazy that no one has mentioned this elegant solution. This should be the accepted answer.

SplashActivity -> AuthActivity -> DashActivity

if (!sessionManager.isLoggedIn()) {
    Intent intent = new Intent(context, AuthActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
    finish();
} else {
   Intent intent = new Intent(context, DashActivity.class);
   context.startActivity(intent);
    finish();
}

The key here is to use intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); for the intermediary Activity. Once that middle link is broken, the DashActivity will the first and last in the stack.

android:noHistory="true" is a bad solution, as it causes problems when relying on the Activity as a callback e.g onActivityResult. This is the recommended solution and should be accepted.

Powershell v3 Invoke-WebRequest HTTPS error

This work-around worked for me: http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

Basically, in your PowerShell script:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

Reading entire html file to String?

There's the IOUtils.toString(..) utility from Apache Commons.

If you're using Guava there's also Files.readLines(..) and Files.toString(..).

"Continue" (to next iteration) on VBScript

Your suggestion would work, but using a Do loop might be a little more readable.

This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.

Dim i

For i = 0 To 10
    Do
        If i = 4 Then Exit Do
        WScript.Echo i
    Loop While False
Next

As crush suggests, it looks a little better if you remove the extra indentation level.

Dim i

For i = 0 To 10: Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False: Next

How to select and change value of table cell with jQuery?

i was looking for changing second row html and you can do cascading selector

$('#tbox1 tr:nth-child(2) td').html(11111)

VBA copy cells value and format

Instead of setting the value directly you can try using copy/paste, so instead of:

Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value

Try this:

Worksheets(1).Cells(i, 3).Copy
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteValues

To just set the font to bold you can keep your existing assignment and add this:

If Worksheets(1).Cells(i, 3).Font.Bold = True Then
  Worksheets(2).Cells(a, 15).Font.Bold = True
End If

How to format strings using printf() to get equal length in the output

You can specify a width on string fields, e.g.

printf("%-20s", "initialization...");

And then whatever's printed with that field will be blank-padded to the width you indicate.

The - left-justifies your text in that field.

How to get the Full file path from URI

You can use get File path from diffrent SDk versions

Use RealPathUtils for it

public class RealPathUtils {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            column, sel, new String[]{ id }, null);

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    String result = null;

    CursorLoader cursorLoader = new CursorLoader(
            context,
            contentUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    if(cursor != null){
        int column_index =
                cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
    }
    return result;
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    int column_index
            = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
}

**Now get the file Path from URI **

 String path = null;
                if (Build.VERSION.SDK_INT < 11)
                    path = RealPathUtils.getRealPathFromURI_BelowAPI11(MainActivity.this, uri);

                    // SDK >= 11 && SDK < 19
                else if (Build.VERSION.SDK_INT < 19)
                    path = RealPathUtils.getRealPathFromURI_API11to18(MainActivity.this, uri);

                    // SDK > 19 (Android 4.4)
                else
                    path = RealPathUtils.getRealPathFromURI_API19(MainActivity.this, uri);
                Log.d(TAG, "File Path: " + path);
                // Get the file instance
                 File file = new File(path);

Is it possible to save HTML page as PDF using JavaScript or jquery?

Here is how I would do it, its an idea not bulletproof design, you need to modify it

  • The user clicks the save as PDF button
  • The server is sent a call using ajax
  • The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
  • The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.

How to disable a input in angular2

I presume you meant false instead of 'false'

Also, [disabled] is expecting a Boolean. You should avoid returning a null.

Autowiring two beans implementing same interface - how to set default bean to autowire?

The reason why @Resource(name = "{your child class name}") works but @Autowired sometimes don't work is because of the difference of their Matching sequence

Matching sequence of @Autowire
Type, Qualifier, Name

Matching sequence of @Resource
Name, Type, Qualifier

The more detail explanation can be found here:
Inject and Resource and Autowired annotations

In this case, different child class inherited from the parent class or interface confuses @Autowire, because they are from same type; As @Resource use Name as first matching priority , it works.

Generate random numbers following a normal distribution in C/C++

1) Graphically intuitive way you can generate Gaussian random numbers is by using something similar to the Monte Carlo method. You would generate a random point in a box around the Gaussian curve using your pseudo-random number generator in C. You can calculate if that point is inside or underneath the Gaussian distribution using the equation of the distribution. If that point is inside the Gaussian distribution, then you have got your Gaussian random number as the x value of the point.

This method isn't perfect because technically the Gaussian curve goes on towards infinity, and you couldn't create a box that approaches infinity in the x dimension. But the Guassian curve approaches 0 in the y dimension pretty fast so I wouldn't worry about that. The constraint of the size of your variables in C may be more of a limiting factor to your accuracy.

2) Another way would be to use the Central Limit Theorem which states that when independent random variables are added, they form a normal distribution. Keeping this theorem in mind, you can approximate a Gaussian random number by adding a large amount of independent random variables.

These methods aren't the most practical, but that is to be expected when you don't want to use a preexisting library. Keep in mind this answer is coming from someone with little or no calculus or statistics experience.

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Multipart File upload Spring Boot

In Controller, your method should be;

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....

Further, you need to update application.yml (or application.properties) to support maximum file size and request size.

spring:
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

What's the difference between using "let" and "var"?

There are some subtle differences — let scoping behaves more like variable scoping does in more or less any other languages.

e.g. It scopes to the enclosing block, They don't exist before they're declared, etc.

However it's worth noting that let is only a part of newer Javascript implementations and has varying degrees of browser support.

How to make an autocomplete TextBox in ASP.NET?

1-Install AjaxControl Toolkit easily by Nugget

PM> Install-Package AjaxControlToolkit

2-then in markup

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
</asp:ToolkitScriptManager>  

<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>  

<asp:AutoCompleteExtender  ID="AutoCompleteExtender1"  TargetControlID="txtMovie"   
    runat="server" />  

3- in code-behind : to get the suggestions

[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]  
    public static string[] GetCompletionList(string prefixText, int count, string contextKey) {  
        // Create array of movies  
        string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};  

        // Return matching movies  
        return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();  
    }

source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx

Case Insensitive String comp in C

There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp in the header strings.h; Microsoft systems have stricmp. To be on the portable side, write your own:

int strcicmp(char const *a, char const *b)
{
    for (;; a++, b++) {
        int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
        if (d != 0 || !*a)
            return d;
    }
}

But note that none of these solutions will work with UTF-8 strings, only ASCII ones.

No process is on the other end of the pipe (SQL Server 2012)

Please check this also enter image description here Also check in configuration TCP/IP,Names PipeLine and shared memory enabled

Django CSRF check failing with an Ajax POST request

The {% csrf_token %} put in html templates inside <form></form>

translates to something like:

<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />

so why not just grep it in your JS like this:

token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()

and then pass it e.g doing some POST, like:

$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
    console.log(data);
});

Correct way to find max in an Array in Swift

With Swift 1.2 (and maybe earlier) you now need to use:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, combine: { max($0, $1) })

For working with Double values I used something like this:

let nums = [1.3, 6.2, 3.6, 9.7, 4.9, 6.3];
let numMax = nums.reduce(-Double.infinity, combine: { max($0, $1) })

Get environment variable value in Dockerfile

You should use the ARG directive in your Dockerfile which is meant for this purpose.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

So your Dockerfile will have this line:

ARG request_domain

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[Warning] One or more build-args [foo] were not consumed.

Convert Float to Int in Swift

Suppose you store float value in "X" and you are storing integer value in "Y".

Var Y = Int(x);

or

var myIntValue = Int(myFloatValue)

ITSAppUsesNonExemptEncryption export compliance while internal testing?

There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:

Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15

Consumer applications

  • piracy and theft prevention for software or music;
  • music, movies, tunes/music, digital photos – players, recorders and organizers
  • games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
  • LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
  • printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
  • household utilities and appliances

Business / systems applications: systems operations, integration and control. Some examples

  • business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery

  • transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.

  • industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC

  • medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality

  • applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology

Research /scientific /analytical. Some examples:

  • business process management (BPM) – business process abstraction and modeling

  • scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)

  • data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)

Secure intellectual property delivery and installation. Some examples

  • software download auto-installers and updaters

  • license key product protection and similar purchase validation

  • software and hardware design IP protection

  • computer aided design (CAD) software and other drafting tools

Note: These regulations are also true for testing your app using TestFlight

Unable to find valid certification path to requested target - error even after cert imported

In my case I was facing the problem because in my tomcat process specific keystore was given using

-Djavax.net.ssl.trustStore=/pathtosomeselfsignedstore/truststore.jks

Wheras I was importing the certificate to the cacert of JRE/lib/security and the changes were not reflecting. Then I did below command where /tmp/cert1.test contains the certificate of the target server

keytool -import -trustcacerts -keystore /pathtosomeselfsignedstore/truststore.jks -storepass password123 -noprompt -alias rapidssl-myserver -file /tmp/cert1.test

We can double check if the certificate import is successful

keytool -list -v -keystore /pathtosomeselfsignedstore/truststore.jks

and see if your taget server is found against alias rapidssl-myserver

jQuery "blinking highlight" effect on div?

If you are not already using the Jquery UI library and you want to mimic the effect what you can do is very simple

$('#blinkElement').fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100);

you can also play around with the numbers to get a faster or slower one to fit your design better.

This can also be a global jquery function so you can use the same effect across the site. Also note that if you put this code in a for loop you can have 1 milion pulses so therefore you are not restricted to the default 6 or how much the default is.

EDIT: Adding this as a global jQuery function

$.fn.Blink = function (interval = 100, iterate = 1) {
    for (i = 1; i <= iterate; i++)
        $(this).fadeOut(interval).fadeIn(interval);
}

Blink any element easily from your site using the following

$('#myElement').Blink(); // Will Blink once

$('#myElement').Blink(500); // Will Blink once, but slowly

$('#myElement').Blink(100, 50); // Will Blink 50 times once

How to debug PDO database queries?

Searching internet I found this as an acceptable solution. A different class is used instead of PDO and PDO functions are called through magic function calls. I am not sure this creates serious performance problems. But it can be used until a sensible logging feature is added to PDO.

So as per this thread, you can write a wrapper for your PDO connection which can log and throws an exception when you get a error.

Here is simple example:

class LoggedPDOSTatement extends PDOStatement    {

function execute ($array)    {
    parent::execute ($array);
    $errors = parent::errorInfo();
    if ($errors[0] != '00000'):
        throw new Exception ($errors[2]);
    endif;
  }

}

so you can use that class instead of PDOStatement:

$this->db->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('LoggedPDOStatement', array()));

Here a mentioned PDO decorator implementation:

class LoggedPDOStatement    {

function __construct ($stmt)    {
    $this->stmt = $stmt;
}

function execute ($params = null)    {
    $result = $this->stmt->execute ($params); 
    if ($this->stmt->errorCode() != PDO::ERR_NONE):
        $errors = $this->stmt->errorInfo();
        $this->paint ($errors[2]);
    endif;
    return $result;
}

function bindValue ($key, $value)    {
    $this->values[$key] = $value;    
    return $this->stmt->bindValue ($key, $value);
}

function paint ($message = false)    {
    echo '<pre>';
    echo '<table cellpadding="5px">';
    echo '<tr><td colspan="2">Message: ' . $message . '</td></tr>';
    echo '<tr><td colspan="2">Query: ' . $this->stmt->queryString . '</td></tr>';
    if (count ($this->values) > 0):
    foreach ($this->values as $key => $value):
    echo '<tr><th align="left" style="background-color: #ccc;">' . $key . '</th><td>' . $value . '</td></tr>';
    endforeach;
    endif;
    echo '</table>';
    echo '</pre>';
}

function __call ($method, $params)    {
    return call_user_func_array (array ($this->stmt, $method), $params); 
}

}

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

Deserialize Java 8 LocalDateTime with JacksonMapper

UPDATE:

Change to:

@Column(name = "start_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm", iso = ISO.DATE_TIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime startDate;

JSON request:

{
 "startDate":"2019-04-02 11:45"
}

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Though late in answering, this is a hard one to Google (the single quotes) and it’s not clear what’s happening. I don't have the reputation yet to comment or ask for scope (or post 3 links), so this answer may be a little tedious.

To answer fast, you may have multiple Gradle plugins in your project.

Synchronize Gradle Wrapper and Plugins

My issue seemed to start with a corrupted IML file. Android Studio (between closing and reopening a project) began complaining an IML was gone (it wasn’t) and a module should be deleted, which I declined. It persisted, I upgraded to AS 0.8.7 (canary channel) and got stuck on the OP issue (Task '' not found in root project). This completely blocked builds so I had to dig in to Gradle.

My repair steps on OSX (please adjust for Windows):

  1. Upgrade Android Studio to 0.8.7
    • Preferences | Updates | Switch "Beta Channel" to "Canary Channel", then do a Check Now.
    • You might be able to skip this.
  2. Checked the Gradle wrapper (currently 1.12.2; don’t try to use 2.0 at this time).

    • Assuming you don’t need a particular version, use the latest supported distribution

      $ vi ~/project/gradle-wrapper.properties ... distributionUrl=http\://services.gradle.org/distributions/gradle-1.12-all.zip

    • This can be set in Android Studio at Preferences | Gradle (but 0.8.7 was giving me ‘invalid location’ errors).

    • The 'wrapper' is just a copy of Gradle for each Android Studio project. It allows you to have Gradle 2 in your OS, and different versions in your projects. The Android Developer docs explain that here.
    • Then adjust your build.gradle files for the plugin. The Gradle plugin version must be compatible with the distribution/wrapper version, for the whole project. As the Tools documentation (tools.android.com/tech-docs/new-build-system/user-guide#TOC-Requirements) is slightly out of date, you can set the plugin version too low (like 0.8.0) and Android Studio will throw an error with the acceptable range for the wrapper.

Example, in build.gradle, you have this plugin:

dependencies {
    classpath "com.android.tools.build:gradle:0.12.+"
}

You can try switching it to the exact version, like this:

dependencies {
    classpath "com.android.tools.build:gradle:0.12.2"
}

and (after recording what version you’re changing from in each case) verifying that every build.gradle file in your project pulls in the same plugin version. Keeping the “+” should work (for 0.12.0, 0.12.1, 0.12.2, etc), but my build succeeded when I updated Google’s Volley library (originally gradle:0.8.+) and my main project (originally 0.12.+) to the fixed version: gradle:0.12.2.

Other checks

  1. Ensure you don’t have two Android Application modules in the same Project

    • This may interact with the final solution (different Gradle versions, above), and cause

      UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define (various classes)

    • To check, Build | Make Project should not pop up a window asking what application you want to make.

  2. Invalidate your caches
    • File | Invalidate Caches / Restart (stackoverflow.com/a/19223269/513413)
  3. If step 2 doesn't work, delete ~/.gradle/ (www.wuttech.com/index.php/tag/groovy-lang-closure/)
    • Quit Android Studio
    • $ rm -rf ~/.gradle/
    • Start Android Studio, then sync:
      • Tools | Android | Sync Project with Gradle Files
    • Repeat this entire sequence (quit...sync) a few times before giving up.
  4. Clean the project
    • Build | Clean Project

If You See This...

In my recent builds, I kept seeing horrible fails (pages of exceptions) but within seconds the messages would clear, build succeeded and the app deployed. Since I could never explain it and the app worked, I never noticed that I had two Gradle plugins in my project. So I think the Gradle plugins fought each other; one crashed, the other lost its state and reported the error.

If you have time, the 1-hour video "A Gentle Introduction to Gradle" (www.youtube.com/watch?v=OFUEb7pLLXw) really helped me approach the Gradle build files, tasks, build decisions, etc.

Disclaimer

I'm learning this entire stack, on a foreign OS, after working a different career...all at the same time and under pressure. In the last few months I have hit every wall I think Android has; I've been here quite often and this is my first post. I thought this was a hard fix, so I sincerely apologize if the quality of my answer reflects the difficulty I had in getting to it.

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

Argument list too long error for rm, cp, mv commands

The below option seems simple to this problem. I got this info from some other thread but it helped me.

for file in /usr/op/data/Software/temp/application/openpages-storage/*; do
    cp "$file" /opt/sw/op-storage/
done

Just run the above one command and it will do the task.

Compiling a java program into an executable

I usually use a bat script for that. Here's what I typically use:

@echo off
set d=%~dp0
java -Xmx400m -cp "%d%myapp.jar;%d%libs/mylib.jar" my.main.Class %*

The %~dp0 extract the directory where the .bat is located. This allows the bat to find the locations of the jars without requiring any special environment variables nor the setting of the PATH variable.

EDIT: Added quotes to the classpath. Otherwise, as Joey said, "fun things can happen with spaces"

How to play a local video with Swift?

None of the above worked for me Swift 5 for Local Video Player

after reading apple documentation I was able to create simple example for playing video from Local resources

Here is code snip

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project

Enabling CORS in Cloud Functions for Firebase

For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.

Getting the PublicKeyToken of .Net assemblies

If you have included the assembly in your project, you can do :

            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies();


            foreach (var assem in assemblies)
            {
                    Console.WriteLine(assem.FullName);
            }

How to test abstract class in Java with JUnit?

My way of testing this is quite simple, within each abstractUnitTest.java. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

When to use MongoDB or other document oriented database systems?

I would say use an RDBMS if you need complex transactions. Otherwise I would go with MongoDB - more flexible to work with and you know it can scale when you need to. (I'm biased though - I work on the MongoDB project)

How can I make a horizontal ListView in Android?

I used Pauls (see his answer) Implementation of HorizontalListview and it works, thank you so much for sharing!

I slightly changed his HorizontalListView-Class (btw. Paul there is a typo in your classname, your classname is "HorizontialListView" instead of "HorizontalListView", the "i" is too much) to update child-views when selected.

UPDATE: My code that I posted here was wrong I suppose, as I ran into trouble with selection (i think it has to do with view recycling), I have to go back to the drawing board...

UPDATE 2: Ok Problem solved, I simply commented "removeNonVisibleItems(dx);" in "onLayout(..)", I guess this will hurt performance, but since I am using only very small Lists this is no Problem for me.

I basically used this tutorial here on developerlife and just replaced ListView with Pauls HorizontalListView, and made the changes to allow for "permanent" selection (a child that is clicked on changes its appearance, and when its clicked on again it changes it back).

I am a beginner, so probably many ugly things in the code, let me know if you need more details.

How to mkdir only if a directory does not already exist?

directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi

Change directory command in Docker?

RUN git clone http://username:password@url/example.git
WORKDIR /folder
RUN make

JBoss vs Tomcat again

Strictly speaking; With no Java EE features your app hardly need an appserver at all ;-)

Like others have pointed out JBoss has a (more or less) full Java EE stack while Tomcat is a webcontainer only. JBoss can be configured to only serve as a webcontainer as well, it'd then just be a thin wrapper around the included tomcat webcontainer. That way you could have an almost as lightweight JBoss, which would actually just be a thin "wrapper" around Tomcat. That would be almost as lightweigth.

If you won't need any of the extras JBoss has to offer, go for the one you're most comfortable with. Which is easiest to configure and maintain for you?

Java8: sum values from specific field of the objects in a list

In Java 8 for an Obj entity with field and getField() method you can use:

List<Obj> objs ...

Stream<Obj> notNullObjs =
  objs.stream().filter(obj -> obj.getValue() != null);

Double sum = notNullObjs.mapToDouble(Obj::getField).sum();

Multiline strings in VB.NET

you can use XML for this like

dim vrstr as string = <s>
    some words
    some words
    some
    words
</s>

remove item from array using its name / value

Created a handy function for this..

function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      array.splice(index, 1);
    }    
  });
}

//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

css overflow - only 1 line of text

You can use this css code:

text-overflow: ellipsis; 
overflow: hidden; 
white-space: nowrap;

The text-overflow property in CSS deals with situations where text is clipped when it overflows the element's box. It can be clipped (i.e. cut off, hidden), display an ellipsis ('…', Unicode Range Value U+2026).

Note that text-overflow only occurs when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap;.

Text overflow can only happen on block or inline-block level elements, because the element needs to have a width in order to be overflow-ed. The overflow happens in the direction as determined by the direction property or related attributes.

Multiple types were found that match the controller named 'Home'

If it could help other, I've also face this error. The problem was cause by on incorrect reference in me web site. For unknown reason my web site was referring another web site, in the same solution. And once I remove that bad reference, thing began to work properly.

Eclipse interface icons very small on high resolution screen in Windows 8.1

I found a reference that suggested adding the following to eclipse.ini

-Dswt.enable.autoScale=true
-Dswt.autoScale=200
-Dswt.autoScale.method=nearest

This doubled the size of the icons for me on Windows 10. I am using Eclipse Version: 2020-03 (4.15.0)

Deploying my application at the root in Tomcat

open tomact manager url :- http://localhost:8080/manager/html/
then in applications you see a application having path as "/" is deployed
simply Undeploy this.
enter image description here Rename your application's war file as ROOT.war and just place at path :-
C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps
start your Tomcat No extra configuration needed.
Now we can see our application home page or configured url at http://localhost:8080

How do I search for files in Visual Studio Code?

You can also press F1 to open the Command Palette and then remove the > via Backspace. Now you can search for files, too.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

There was auto generated Copyright message in XML and a blank line before <resources> tag, once I removed it my build was successful.

enter image description here

Notepad++ - How can I replace blank lines

This should get your sorted:

  • Highlight from the end of the first line, to the very beginning of the third line.
  • Use the Ctrl + H to bring up the 'Find and Replace' window.
  • The highlighed region will already be plased in the 'Find' textbox.
  • Replace with: \r\n
  • 'Replace All' will then remove all the additional line spaces not required.

Here's how it should look: enter image description here

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

How to use SharedPreferences in Android to store, fetch and edit values

Simple and hassle-free :: "Android-SharedPreferences-Helper" library

Better late than never: I created the "Android-SharedPreferences-Helper" library to help reduce the complexity and effort of using SharedPreferences. It also provides some extended functionality. Few things that it offers are as follows:

  • One line initialization and setup
  • Easily selecting whether to use default preferences or a custom preference file
  • Predefined (data type defaults) and customizable (what you may choose) default values for each datatype
  • Ability to set different default value for single use with just an additional param
  • You can register and unregister OnSharedPreferenceChangeListener as you do for default class
dependencies {
    ...
    ...
    compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}

Declaration of SharedPreferencesHelper object: (recommended at class level)

SharedPreferencesHelper sph; 

Instantiation of the SharedPreferencesHelper object: (recommended in onCreate() method)

// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode

Putting values into shared preferences

Fairly simple! Unlike the default way (when using the SharedPreferences class) you'll NOT need to call .edit() and .commit() ever time.

sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);

// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);

That's it! Your values are stored in the shared preferences.

Getting values from shared preferences

Again, just one simple method call with the key name.

sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");

// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");

It has a lot of other extended functionality

Check the details of extended functionality, usage and installation instructions etc on the GitHub Repository Page.

ReactJS call parent method

You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

And use it into the Child like this (for any actions or into any child methods):

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});

How to model type-safe enum types?

Starting from Scala 3, there is now enum keyword which can represent a set of constants (and other use cases)

enum Color:
   case Red, Green, Blue

scala> val red = Color.Red
val red: Color = Red
scala> red.ordinal
val res0: Int = 0

Comparing two files in linux terminal

Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.

For example:

mcdiff file1 file2

Enjoy!

Check if a row exists, otherwise insert

Pass updlock, rowlock, holdlock hints when testing for existence of the row.

begin tran /* default read committed isolation level is fine */

if not exists (select * from Table with (updlock, rowlock, holdlock) where ...)
    /* insert */
else
    /* update */

commit /* locks are released here */

The updlock hint forces the query to take an update lock on the row if it already exists, preventing other transactions from modifying it until you commit or roll back.

The holdlock hint forces the query to take a range lock, preventing other transactions from adding a row matching your filter criteria until you commit or roll back.

The rowlock hint forces lock granularity to row level instead of the default page level, so your transaction won't block other transactions trying to update unrelated rows in the same page (but be aware of the trade-off between reduced contention and the increase in locking overhead - you should avoid taking large numbers of row-level locks in a single transaction).

See http://msdn.microsoft.com/en-us/library/ms187373.aspx for more information.

Note that locks are taken as the statements which take them are executed - invoking begin tran doesn't give you immunity against another transaction pinching locks on something before you get to it. You should try and factor your SQL to hold locks for the shortest possible time by committing the transaction as soon as possible (acquire late, release early).

Note that row-level locks may be less effective if your PK is a bigint, as the internal hashing on SQL Server is degenerate for 64-bit values (different key values may hash to the same lock id).

Creating SolidColorBrush from hex color value

using System.Windows.Media;

byte R = Convert.ToByte(color.Substring(1, 2), 16);
byte G = Convert.ToByte(color.Substring(3, 2), 16);
byte B = Convert.ToByte(color.Substring(5, 2), 16);
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
//applying the brush to the background of the existing Button btn:
btn.Background = scb;

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

How do I configure git to ignore some files locally?

If your repo doesn't already have a .gitignore file, then a simple solution is to create a .gitignore file, and in it add .gitignore to the list of files to be ignored.

Git: Installing Git in PATH with GitHub client for Windows

GitHub for Windows does indeed install its own version of Git, but it doesn't add it to the PATH variable, which is easy enough to do. Here's instructions on how to do it:

  1. Get the Git URL

    We need to get the url of the Git \cmd directory your computer. Git is located here:

    C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd\git.exe
    

    So on your computer, replace <user> with your user and find out what the <guid> is for your computer. (The guid may change each time GitHub updates PortableGit, but they're working on a solution to that.)

    Copy it and paste it into a command prompt (right-click > paste to paste in the terminal) to verify that it works. You should see the Git help response that lists common Git commands. If you see The system cannot find the path specified. Then the URL isn’t right. Once you have it right, create the link to the directory using this format:

    ;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd
    

    (Note: \cmd at the end, not \cmd\git.exe anymore!)

    On my system, it’s this, yours will be different:

    ;C:\Users\brenton\AppData\Local\GitHub\PortableGit_7eaa494e16ae7b397b2422033as45d8ff6ac2010\cmd
    
  2. Edit the PATH Variable

    Navigate to the Environmental Variables Editor (instructions) and find the Path variable in the “System Variables” section. Click Edit… and paste the URL of Git to the end of that string. Save! It might be easier to pull this into Notepad to do the edit, just make sure you put one semicolon before you paste in the URL. If it doesn't work it’s probably because this path got messed up either with a space in there somewhere (should be no spaces around the semicolon) or a semicolon at the end (semicolons should only separate URLs, no semicolon at beginning or end of string).

If it worked, you should be able to close & reopen a terminal and type git and it will give you that same git help file. Then installing the Linter should work. (Atom > File > Settings > Packages > Linter)

C++ int float casting

You should be aware that in evaluating an expression containing integers, the temporary results from each stage of evaluation are also rounded to be integers. In your assignment to float m, the value is only converted to the real-number capable float type after the integer arithmetic. This means that, for example, 3 / 4 would already be a "0" value before becoming 0.0. You need to force the conversion to float to happen earlier. You can do this by using the syntax float(value) on any of a.y, b.y, a.x, b.x, a.y - b.y, or a.x - b.x: it doesn't matter when it's done as long as one of the terms is a float before the division happens, e.g.

float m = float(a.y - b.y) / (a.x - b.x); 
float m = (float(a.y) - b.y) / (a.x - b.x); 
...etc...

How to assign string to bytes array

Arrays are values... slices are more like pointers. That is [n]type is not compatible with []type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.

One way to convert a slice of for example []byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:

buf := make([]byte, 10)
var arr [10]byte
copy(arr[:], buf)

Essentially what a lot of other answers get wrong is that []type is NOT an array.

[n]T and []T are completely different things!

When using reflect []T is not of kind Array but of kind Slice and [n]T is of kind Array.

You also can't use map[[]byte]T but you can use map[[n]byte]T.

This can sometimes be cumbersome because a lot of functions operate for example on []byte whereas some functions return [n]byte (most notably the hash functions in crypto/*). A sha256 hash for example is [32]byte and not []byte so when beginners try to write it to a file for example:

sum := sha256.Sum256(data)
w.Write(sum)

they will get an error. The correct way of is to use

w.Write(sum[:])

However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to []byte using:

bytes := []byte(str)

but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.

Unable to run Java GUI programs with Ubuntu

I too had OpenJDK on my Ubuntu machine:

$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)

Replacing OpenJDK with the HotSpot VM works fine:

sudo apt-get autoremove openjdk-7-jre-headless

How to install the JDK on Ubuntu (Linux)

How to change the new TabLayout indicator color and height

With the desing support library v23 you can set programmatically the color and the height.

Just use for the height:

TabLayout.setSelectedTabIndicatorHeight(int height)

Here the official javadoc.

Just use for the color:

TabLayout.setSelectedTabIndicatorColor(int color)

Here the official javadoc.

Here you can find the info in the Google Tracker.

Parsing JSON from URL

A simple alternative solution:

  • Paste the URL into a json to csv converter

  • Open the CSV file in either Excel or Open Office

  • Use the spreadsheet tools to parse the data

jQuery Datepicker onchange event issue

I know this is an old question. But i couldnt get the jquery $(this).change() event to fire correctly onSelect. So i went with the following approach to fire the change event via vanilla js.

$('.date').datepicker({
     showOn: 'focus',
     dateFormat: 'mm-dd-yy',
     changeMonth: true,
     changeYear: true,
     onSelect: function() {
         var event;
         if(typeof window.Event == "function"){
             event = new Event('change');
             this.dispatchEvent(event);
         }   else {
             event = document.createEvent('HTMLEvents');
             event.initEvent('change', false, false);
             this.dispatchEvent(event);
         }
     }
});

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Can you get a Windows (AD) username in PHP?

Use this code:

shell_exec("wmic computersystem get username")

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes and Mesos are a match made in heaven. Kubernetes enables the Pod (group of co-located containers) abstraction, along with Pod labels for service discovery, load-balancing, and replication control. Mesos provides the fine-grained resource allocations for pods across nodes in a cluster, and can make Kubernetes play nicely with other frameworks running on the same cluster resources.

from readme of kubernetes-mesos

How to center the elements in ConstraintLayout

The solution with guideline works only for this particular case with single line EditText. To make it work for multiline EditText you should use "packed" chain.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/authenticate"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toBottomOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>

Here's how it looks:

View on Nexus 5

You can read more about using chains in following posts:

Javascript search inside a JSON object

If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOf or a regular expression to test the strings.

For the loop, you have at least three choices:

  1. A boring old for loop.

  2. On ES5-enabled environments (or with a shim), Array#filter.

  3. Because you're using jQuery, jQuery.map.

Boring old for loop example:

function search(source, name) {
    var results = [];
    var index;
    var entry;

    name = name.toUpperCase();
    for (index = 0; index < source.length; ++index) {
        entry = source[index];
        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
            results.push(entry);
        }
    }

    return results;
}

Where you'd call that with obj.list as source and the desired name fragment as name.

Or if there's any chance there are blank entries or entries without names, change the if to:

        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {

Array#filter example:

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = source.filter(function(entry) {
        return entry.name.toUpperCase().indexOf(name) !== -1;
    });
    return results;
}

And again, if any chance that there are blank entries (e.g., undefined, as opposed to missing; filter will skip missing entries), change the inner return to:

        return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;

jQuery.map example (here I'm assuming jQuery = $ as is usually the case; change $ to jQuery if you're using noConflict):

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = $.map(source, function(entry) {
        var match = entry.name.toUpperCase().indexOf(name) !== -1;
        return match ? entry : null;
    });
    return results;
}

(And again, add entry && entry.name && in there if necessary.)

How to draw a line with matplotlib?

Just want to mention another option here.

You can compute the coefficients using numpy.polyfit(), and feed the coefficients to numpy.poly1d(). This function can construct polynomials using the coefficients, you can find more examples here

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.poly1d.html

Let's say, given two data points (-0.3, -0.5) and (0.8, 0.8)

import numpy as np
import matplotlib.pyplot as plt

# compute coefficients
coefficients = np.polyfit([-0.3, 0.8], [-0.5, 0.8], 1) 

# create a polynomial object with the coefficients
polynomial = np.poly1d(coefficients)

# for the line to extend beyond the two points, 
# create the linespace using the min and max of the x_lim
# I'm using -1 and 1 here
x_axis = np.linspace(-1, 1)

# compute the y for each x using the polynomial
y_axis = polynomial(x_axis)

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.set_xlim(-1, 1)
axes.set_ylim(-1, 1)
axes.plot(x_axis, y_axis)
axes.plot(-0.3, -0.5, 0.8, 0.8, marker='o', color='red')

enter image description here

Hope it helps.

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

How can I simulate a print statement in MySQL?

If you do not want to the text twice as column heading as well as value, use the following stmt!

SELECT 'some text' as '';

Example:

mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)

Floating point inaccuracy examples

Here is my simple understanding.

Problem: The value 0.45 cannot be accurately be represented by a float and is rounded up to 0.450000018. Why is that?

Answer: An int value of 45 is represented by the binary value 101101. In order to make the value 0.45 it would be accurate if it you could take 45 x 10^-2 (= 45 / 10^2.) But that’s impossible because you must use the base 2 instead of 10.

So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 45 (101101) + 3 bits for the value 7 (111). Then the value 45 x 2^-7 = 0.3515625. Now you have a serious inaccuracy problem. 0.3515625 is not nearly close to 0.45.

How do we improve this inaccuracy? Well we could change the value 45 and 7 to something else.

How about 460 x 2^-10 = 0.44921875. You are now using 9 bits for 460 and 4 bits for 10. Then it’s a bit closer but still not that close. However if your initial desired value was 0.44921875 then you would get an exact match with no approximation.

So the formula for your value would be X = A x 2^B. Where A and B are integer values positive or negative. Obviously the higher the numbers can be the higher would your accuracy become however as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

Could not resolve this reference. Could not locate the assembly

This confused me for a while until I worked out that the dependencies of the various projects in the solution had been messed up. Get that straight and naturally your assembly appears in the right place.

jQuery $(this) keyword

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.