Programs & Examples On #Dll injection

DLL injection is a technique used to run code within the address space of another process by forcing it to load a dynamic-link library(DLL).

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How using try catch for exception handling is best practice

I know this is an old question, but nobody here mentioned the MSDN article, and it was the document that actually cleared it up for me, MSDN has a very good document on this, you should catch exceptions when the following conditions are true:

  • You have a good understanding of why the exception might be thrown, and you can implement a specific recovery, such as prompting the user to enter a new file name when you catch a FileNotFoundException object.

  • You can create and throw a new, more specific exception.

int GetInt(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch(System.IndexOutOfRangeException e)
    {
        throw new System.ArgumentOutOfRangeException(
            "Parameter index is out of range.");
    }
}
  • You want to partially handle an exception before passing it on for additional handling. In the following example, a catch block is used to add an entry to an error log before re-throwing the exception.
    try
{
    // Try to access a resource.
}
catch (System.UnauthorizedAccessException e)
{
    // Call a custom error logging procedure.
    LogError(e);
    // Re-throw the error.
    throw;     
}

I'd suggest reading the entire "Exceptions and Exception Handling" section and also Best Practices for Exceptions.

How to move a marker in Google Maps API

You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.

How to pass multiple values through command argument in Asp.net?

You can try this:

CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'

Adding Table rows Dynamically in Android

Create an init() function and point the table layout. Then create the needed rows and columns.

   public void init() {
            TableLayout stk = (TableLayout) findViewById(R.id.table_main);
            TableRow tbrow0 = new TableRow(this);
            TextView tv0 = new TextView(this);
            tv0.setText(" Sl.No ");
            tv0.setTextColor(Color.WHITE);
            tbrow0.addView(tv0);
            TextView tv1 = new TextView(this);
            tv1.setText(" Product ");
            tv1.setTextColor(Color.WHITE);
            tbrow0.addView(tv1);
            TextView tv2 = new TextView(this);
            tv2.setText(" Unit Price ");
            tv2.setTextColor(Color.WHITE);
            tbrow0.addView(tv2);
            TextView tv3 = new TextView(this);
            tv3.setText(" Stock Remaining ");
            tv3.setTextColor(Color.WHITE);
            tbrow0.addView(tv3);
            stk.addView(tbrow0);
            for (int i = 0; i < 25; i++) {
                TableRow tbrow = new TableRow(this);
                TextView t1v = new TextView(this);
                t1v.setText("" + i);
                t1v.setTextColor(Color.WHITE);
                t1v.setGravity(Gravity.CENTER);
                tbrow.addView(t1v);
                TextView t2v = new TextView(this);
                t2v.setText("Product " + i);
                t2v.setTextColor(Color.WHITE);
                t2v.setGravity(Gravity.CENTER);
                tbrow.addView(t2v);
                TextView t3v = new TextView(this);
                t3v.setText("Rs." + i);
                t3v.setTextColor(Color.WHITE);
                t3v.setGravity(Gravity.CENTER);
                tbrow.addView(t3v);
                TextView t4v = new TextView(this);
                t4v.setText("" + i * 15 / 32 * 10);
                t4v.setTextColor(Color.WHITE);
                t4v.setGravity(Gravity.CENTER);
                tbrow.addView(t4v);
                stk.addView(tbrow);
            }

        }

Call init function in your onCreate method:

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

        init();
    }

Layout file like:

 <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#3d455b"
        android:layout_alignParentLeft="true" >

        <HorizontalScrollView
            android:id="@+id/hscrll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:id="@+id/RelativeLayout1"
                android:layout_width="fill_parent"
                android:layout_gravity="center"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TableLayout
                    android:id="@+id/table_main"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true" >
                </TableLayout>
            </RelativeLayout>
        </HorizontalScrollView>
    </ScrollView>

Will look like:

enter image description here

iPad WebApp Full Screen in Safari

  1. First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.

  2. After locating the webpage, tap on the arrow icon at the top of your screen.

  3. In the drop-down menu, tap on the Add to Home Screen option.

  4. The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.

  5. A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.

Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:

<meta name="apple-mobile-web-app-capable" content="yes">

You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.

Can't update: no tracked branch

Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".

In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".

Swift: Reload a View Controller

Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

In addition to what Kiran's answer suggests, make sure this is set correctly:

There is an option to in SSIS to save passwords(to access DB or anyother stuff), the default setting is "EncryptSensitiveWithUserKey"... You need to change this.

Package Proprties Window > ProtectionLevel -- Change that to EncryptSensitiveWithPassword PackagePassword -- enter password-> somepassword

How do I collapse a table row in Bootstrap?

Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.

In 2.3.2 the collapse class wasn't getting replaced by the in class. The in class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse class correctly is removed, and the <tr> collapses.

Use @Chad's solution for the html, and try using these links for referencing Bootstrap:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>

How to use export with Python on Linux

Not that simple:

python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty

But:

python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123

Pass arguments to Constructor in VBA

Why not this way:

  1. In a class module »myClass« use Public Sub Init(myArguments) instead of Private Sub Class_Initialize()
  2. Instancing: Dim myInstance As New myClass: myInstance.Init myArguments

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

How do I "decompile" Java class files?

I use JAD Decompiler.

There is an Eclipse plugin for it, jadeclipse. It is pretty nice.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I too faced the same issue. I had installed Oracle Express edition 10g in Windows XP OS using VMware and it was working fine. Since it was very awkward typing SQL queries in the SQL utility provided by 10g and since I was used to working with SQL developer, I installed 32 bit SQL developer in XP and tried connecting to my DB SID "XE". But the connection failed with error-ORA-12505 TNS listener doesn't currently know of SID given in connect descriptor. I was at sea as to how this problem occurred since it was working fine with the SQL utility and I had also created few Informatica mappings using the same. I did browse a lot on this stuff hither thither and applied the suggestions offered to me after pinging the status of "lsnrctl" on public forums but to no avail. However, this morning I tried creating a new connection again, and Voila, it worked with no issues. I am guessing after reading in few posts that sometimes listener listens before the DB connects or something(pardon me for my crude reference as I am a newbie here) but I suggest to just restart the machine and check again.

Why would an Enum implement an Interface?

Enums are like Java Classes, they can have Constructors, Methods, etc. The only thing that you can't do with them is new EnumName(). The instances are predefined in your enum declaration.

SSH configuration: override the default username

If you only want to ssh a few times, such as on a borrowed or shared computer, try:

ssh buck@hostname

or

ssh -l buck hostname

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

JavaScript: how to change form action attribute value based on selection?

$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Can not change UILabel text color

Try this one, where alpha is opacity and others is Red,Green,Blue chanels-

self.statusTextLabel.textColor = [UIColor colorWithRed:(233/255.f) green:(138/255.f) blue:(36/255.f) alpha:1];

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

Convert Iterator to ArrayList

Try StickyList from Cactoos:

List<String> list = new StickyList<>(iterable);

Disclaimer: I'm one of the developers.

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

Get the cartesian product of a series of lists?

For Python 2.5 and older:

>>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]]
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
 (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
 (3, 'b', 4), (3, 'b', 5)]

Here's a recursive version of product() (just an illustration):

def product(*args):
    if not args:
        return iter(((),)) # yield tuple()
    return (items + (item,) 
            for items in product(*args[:-1]) for item in args[-1])

Example:

>>> list(product([1,2,3], ['a','b'], [4,5])) 
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
 (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
 (3, 'b', 4), (3, 'b', 5)]
>>> list(product([1,2,3]))
[(1,), (2,), (3,)]
>>> list(product([]))
[]
>>> list(product())
[()]

How to sort strings in JavaScript

var str = ['v','a','da','c','k','l']
var b = str.join('').split('').sort().reverse().join('')
console.log(b)

Apache Proxy: No protocol handler was valid

This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:

... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.

The configuration related to this was:

  ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
  ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/

"No protocol handler was valid for the URL /~socket.io/" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/"

I had proxy_http loaded, but also needed proxy_wstunnel. Once that was enabled all was good.

@Autowired and static method

What you can do is @Autowired a setter method and have it set a new static field.

public class Boo {
    @Autowired
    Foo foo;

    static Foo staticFoo;   

    @Autowired
    public void setStaticFoo(Foo foo) {
        Boo.staticFoo = foo;
    }

    public static void randomMethod() {
         staticFoo.doStuff();
    }
}

When the bean gets processed, Spring will inject a Foo implementation instance into the instance field foo. It will then also inject the same Foo instance into the setStaticFoo() argument list, which will be used to set the static field.

This is a terrible workaround and will fail if you try to use randomMethod() before Spring has processed an instance of Boo.

write a shell script to ssh to a remote machine and execute commands

There is are multiple ways to execute the commands or script in the multiple remote Linux machines. One simple & easiest way is via pssh (parallel ssh program)

pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.

Example & Usage:

Connect to host1 and host2, and print "hello, world" from each:

 pssh -i -H "host1 host2" echo "hello, world"

Run commands via a script on multiple servers:

pssh -h hosts.txt -P -I<./commands.sh

Usage & run a command without checking or saving host keys:

pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i  'uptime; hostname -f'

If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:

pssh -i -h hosts.txt -p 100 -t 0 sleep 10000

Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host's file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections

When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no

Source: man pssh

Resolving instances with ASP.NET Core DI from within ConfigureServices

The IServiceCollection interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider instance which you can use to resolve services. You can inject an IServiceProvider into any class. The IApplicationBuilder and HttpContext classes can provide the service provider as well, via their ApplicationServices or RequestServices properties respectively.

IServiceProvider defines a GetService(Type type) method to resolve a service:

var service = (IFooService)serviceProvider.GetService(typeof(IFooService));

There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>() (add a using for Microsoft.Extensions.DependencyInjection).

Resolving services inside the startup class

Injecting dependencies

The runtime's hosting service provider can inject certain services into the constructor of the Startup class, such as IConfiguration, IWebHostEnvironment (IHostingEnvironment in pre-3.0 versions), ILoggerFactory and IServiceProvider. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.

The ConfigureServices() method does not allow injecting services, it only accepts an IServiceCollection argument. This makes sense because ConfigureServices() is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Use Configuration here
}

Any services registered in ConfigureServices() can then be injected into the Configure() method; you can add an arbitrary number of services after the IApplicationBuilder parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IFooService>();
}

public void Configure(IApplicationBuilder app, IFooService fooService)
{
    fooService.Bar();
}

Manually resolving dependencies

If you need to manually resolve services, you should preferably use the ApplicationServices provided by IApplicationBuilder in the Configure() method:

public void Configure(IApplicationBuilder app)
{
    var serviceProvider = app.ApplicationServices;
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}

It is possible to pass and directly use an IServiceProvider in the constructor of your Startup class, but as above this will contain a limited subset of services, and thus has limited utility:

public Startup(IServiceProvider serviceProvider)
{
    var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}

If you must resolve services in the ConfigureServices() method, a different approach is required. You can build an intermediate IServiceProvider from the IServiceCollection instance which contains the services which have been registered up to that point:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFooService, FooService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();

    // This will succeed.
    var fooService = sp.GetService<IFooService>();
    // This will fail (return null), as IBarService hasn't been registered yet.
    var barService = sp.GetService<IBarService>();
}

Please note: Generally you should avoid resolving services inside the ConfigureServices() method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions> instance. You can accomplish this by binding the values from the IConfiguration instance to an instance of MyOptions (which is essentially what the options framework does):

public void ConfigureServices(IServiceCollection services)
{
    var myOptions = new MyOptions();
    Configuration.GetSection("SomeSection").Bind(myOptions);
}

Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.

Connect multiple devices to one device via Bluetooth

That is partly possible (for max 2 devices), because device can be connected only to one other device same time. Better solution in your case will be create an TCP server which sends informations to other devices - but that, of course, requires internet connection. Read also about Samsung Chord API - it provides functions which you need, but then every devices have to be connected to one and the same Wi-Fi network

How to verify element present or visible in selenium 2 (Selenium WebDriver)

webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();

Twitter Bootstrap: div in container with 100% height

Set the class .fill to height: 100%

.fill { 
    min-height: 100%;
    height: 100%;
}

JSFiddle

(I put a red background for #map so you can see it takes up 100% height)

Disable cross domain web security in Firefox

Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases

You can even configure it by Referrers (Website).

MVC4 input field placeholder

This works:

@Html.TextBox("name", null,  new { placeholder = "Text" })

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

How to tell if node.js is installed or not

(This is for windows OS but concept can be applied to other OS)

Running command node -v will be able to confirm if it is installed, however it will not be able to confirm if it is NOT installed. (Executable may not be on your PATH)

Two ways you can check if it is actually installed:

  1. Check default install location C:\Program Files\nodejs\

or

  1. Go to System Settings -> Add or Remove Programs and filter by node, it should show you if you have it installed. For me, it shows as title:"Node.js" and description "Node.js Foundation", with no version specified. Install size is 52.6MB

If you don't have it installed, get it from here https://nodejs.org/en/download/

Code formatting shortcuts in Android Studio for Operation Systems

There are some shortcut keys for rearrange or reformat code in Android studio.

Linux: Ctrl + Shift + Alt + L

mac OS: Option + Command + L

Windows: Ctrl + Alt + L

How to plot all the columns of a data frame in R

Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt from reshape2, gather from tidyr, and pivot_longer from tidyr: Reshaping data.frame from wide to long format

Here's a simple example using pivot_longer:

> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
  time a b
1    1 1 3
2    2 2 4
3    3 3 5
4    4 4 6
5    5 5 7

> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
    time colname   val
   <int> <chr>   <int>
 1     1 a           1
 2     1 b           3
 3     2 a           2
 4     2 b           4
 5     3 a           3
 6     3 b           5
 7     4 a           4
 8     4 b           6
 9     5 a           5
10     5 b           7

As you can see, pivot_longer puts the selected column names in whatever is specified by names_to (default "name"), and puts the long values into whatever is specified by values_to (default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b")).

Now you can plot as normal, ex.

ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()

enter image description here

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

change your return type to ResponseEntity<>, then you can use below for 400

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

and for correct request

return new ResponseEntity<>(json,HttpStatus.OK);

UPDATE 1

after spring 4.1 there are helper methods in ResponseEntity could be used as

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);

and

return ResponseEntity.ok(json);

How to export table data in MySql Workbench to csv?

You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:

MySQL Workbench Export Resultset Button

Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:

MySQL Workbench Preferences Dialog

Hope this helps.

Check if instance is of a type

bool isValid = c.GetType() == typeof(TForm) ? true : false;

or simpler

bool isValid = c.GetType() == typeof(TForm);

How to convert number to words in java

import java.util.*;

public class NumberToWord {
    public void numberToword(int n, String ch) {
        String one[] = {" ", " one", " two", " three", " four", " five", " six", " seven", " eight", " Nine", " ten", " eleven", " twelve", " thirteen", " fourteen", "fifteen", " sixteen", " seventeen", " eighteen", " nineteen"
        };
        String ten[] = {" ", " ", " twenty", " thirty", " forty", " fifty", " sixty", "seventy", " eighty", " ninety"};
        if (n > 19) {
            System.out.print(ten[n / 10] + " " + one[n % 10]);
        } else {
            System.out.print(one[n]);
        }
        if (n > 0) {
            System.out.print(ch);
        }
    }
    public static void main(String[] args) {
        int n = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter an integer number: ");
        n = s.nextInt();
        if (n <= 0) {
            System.out.print("Enter numbers greater than 0");
        } else {
            NumberToWord a = new NumberToWord();
            System.out.print("After conversion number in words is :");
            a.numberToword((n / 1000000000), " Hundred");
            a.numberToword((n / 10000000) % 100, " crore");
            a.numberToword(((n / 100000) % 100), " lakh");
            a.numberToword(((n / 1000) % 100), " thousand");
            a.numberToword(((n / 100) % 10), " hundred");
            a.numberToword((n % 100), " ");
        }
    }
}

Get the Query Executed in Laravel 3/4

in Laravel 4 you can actually use an Event Listener for database queries.

Event::listen('illuminate.query', function($sql, $bindings)
{
    foreach ($bindings as $val) {
        $sql = preg_replace('/\?/', "'{$val}'", $sql, 1);
    }

    Log::info($sql);
});

Place this snippet anywhere, e.g. in start/global.php. It'll write the queries to the info log (storage/log/laravel.log).

Dropdownlist width in IE

You can add a style directly to the select element:

<select name="foo" style="width: 200px">

So this select item will be 200 pixels wide.

Alternatively you can apply a class or id to the element and reference it in a stylesheet

Encoding as Base64 in Java

If you are stuck to an earlier version of Java than 8 but already using AWS SDK for Java, you can use com.amazonaws.util.Base64.

Check/Uncheck all the checkboxes in a table

This will select and deselect all checkboxes:

function checkAll()
{
     var checkboxes = document.getElementsByTagName('input'), val = null;    
     for (var i = 0; i < checkboxes.length; i++)
     {
         if (checkboxes[i].type == 'checkbox')
         {
             if (val === null) val = checkboxes[i].checked;
             checkboxes[i].checked = val;
         }
     }
 }

Demo

Update:

You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:

 function checkAll()
 {
     var table = document.getElementById ('dataTable');
     var checkboxes = table.querySelectorAll ('input[type=checkbox]');
     var val = checkboxes[0].checked;
     for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
 }

Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:

function checkAll (tableID)
{
    var table = document.getElementById (tableID);
    var val = table.rows[0].cells[0].children[0].checked;
    for (var i = 1; i < table.rows.length; i++)
    {
        table.rows[i].cells[0].children[0].checked = val;
    }
}

Demo

How to place two divs next to each other?

Float one or both inner divs.

Floating one div:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* will contain if #first is longer than #second */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    overflow: hidden; /* if you don't want #second to wrap below #first */
}

or if you float both, you'll need to encourage the wrapper div to contain both the floated children, or it will think it's empty and not put the border around them

Floating both divs:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* add this to contain floated children */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    float: left; /* add this */
}

How to merge a list of lists with same type of items to a single list of items?

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

How to fit a smooth curve to my data in R?

The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess and approx, which may give better fits or faster performance.

The advantages are more easily demonstrated with an alternate dataset:

sigmoid <- function(x)
{
  y<-1/(1+exp(-.15*(x-100)))
  return(y)
}

dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))

Here is the data overlaid with the sigmoid curve that generated it:

Data

This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).

A large number of points are used to better demonstrate the performance differences of these functions.

Smooth, spline, and smooth.spline all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.

The loess, lowess, and approx functions all produce usable results, although just barely for approx. This is the code for each using lightly optimized parameters:

loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]

approxFit <- approx(dat,n = 15)

lowessFit <-data.frame(lowess(dat,f = .6,iter=1))

And the results:

plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
       legend=c("Sigmoid","Loess","Lowess",'Approx'),
       lty=c(1,1),
       lwd=c(2.5,2.5),col=c("blue","green","red","purple"))

Fits

As you can see, lowess produces a near perfect fit to the original generating curve. Loess is close, but experiences a strange deviation at both tails.

Although your dataset will be very different, I have found that other datasets perform similarly, with both loess and lowess capable of producing good results. The differences become more significant when you look at benchmarks:

> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
                           expr        min         lq       mean     median        uq        max neval cld
  loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746    20   c
            approx(dat, n = 20)   1.297685   1.346773   1.689133   1.441823   1.86018   4.281735    20 a  
 lowess(dat, f = 0.6, iter = 1)   9.637583  10.085613  11.270911  11.350722  12.33046  12.495343    20  b 

Loess is extremely slow, taking 100x as long as approx. Lowess produces better results than approx, while still running fairly quickly (15x faster than loess).

Loess also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.

EDIT: Additional research shows that loess gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.

Find duplicate records in MySQL

Powerlord answer is indeed the best and I would recommend one more change: use LIMIT to make sure db would not get overloaded:

SELECT firstname, lastname, list.address FROM list
INNER JOIN (SELECT address FROM list
GROUP BY address HAVING count(id) > 1) dup ON list.address = dup.address
LIMIT 10

It is a good habit to use LIMIT if there is no WHERE and when making joins. Start with small value, check how heavy the query is and then increase the limit.

How to change Label Value using javascript

hope this help someone else : use innerHTML for using label object.

  document.getElementById('lableObject').innerHTML = res.FullName;

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

Open a facebook link by native Facebook app on iOS

Here are some schemes the Facebook app uses, there are a ton more on the source link:

Example

NSURL *url = [NSURL URLWithString:@"fb://profile/<id>"];
[[UIApplication sharedApplication] openURL:url];

Schemes

fb://profile – Open Facebook app to the user’s profile

fb://friends – Open Facebook app to the friends list

fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)

fb://feed – Open Facebook app to the News Feed

fb://events – Open Facebook app to the Events page

fb://requests – Open Facebook app to the Requests list

fb://notes – Open Facebook app to the Notes page

fb://albums – Open Facebook app to Photo Albums list

If before opening this url you want to check wether the user fas the facebook app you can do the following (as explained in another answer below):

if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
    [[UIApplication sharedApplication] openURL:nsurl];
}
else {
    //Open the url as usual
}

Source

http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Set column as unique in SQL Server from the GUI:

They really make you run around the barn to do it with the GUI:

Make sure your column does not violate the unique constraint before you begin.

  1. Open SQL Server Management Studio.
  2. Right click your Table, click "Design".
  3. Right click the column you want to edit, a popup menu appears, click Indexes/Keys.
  4. Click the "Add" Button.
  5. Expand the "General" tab.
  6. Make sure you have the column you want to make unique selected in the "columns" box.
  7. Change the "Type" box to "Unique Key".
  8. Click "Close".
  9. You see a little asterisk in the file window, this means changes are not yet saved.
  10. Press Save or hit Ctrl+s. It should save, and your column should be unique.

Or set column as unique from the SQL Query window:

alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);

Changes take effect immediately:

Command(s) completed successfully.

UITableView - change section header color

Here's how to add an image in header view:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
    UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];

    headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);

    [headerView addSubview:headerImage];

    return headerView;
}

Change onClick attribute with javascript

Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.

document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};

This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.

include external .js file in node.js app

To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.

If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

// Declare application
var app = require('express').createServer();

// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

require('./models/car.js').make(Schema, mongoose);

in car.js

function make(Schema, mongoose) {
    // Define Car model
    CarSchema = new Schema({
      brand        : String,
      type : String
    });
    mongoose.model('Car', CarSchema);
}

module.exports.make = make;

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Update Eclipse with Android development tools v. 23

NOTE: Use this approach with caution because this might break your Eclipse installation (see comments).

This might help you if you installed the ADT plugin manually. But if you are using the version of Eclipse from the Eclipse ADT Bundle the below steps could break your Eclipse installation, and you may not be able to use Eclipse again!

Go to

Menu Help ? About Eclipse SDK ? Installation Details.

Now you will see all 22.0 versions and then click Uninstall button at bottom.

After uninstallation goto:

Menu Help ? Install New Software ? enter http://dl-ssl.google.com/android/eclipse/

Then install all the things, and now it is ready.

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Check file extension in upload form in PHP

How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.

<?php
if(isset($_POST['save'])) {

//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed =  array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}

}

// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?

Your html will look something like this;

<html>
<head>
</head>

<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>

<!-- Form -->
<form method="post" action="">

<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />

<p><input type="submit" name="save" value="SAVE" /></p>
</form>

</body>
</html>

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

Regex for string contains?

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]

Difference between "this" and"super" keywords in Java

this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.

super allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

Javascript geocoding from address to latitude and longitude numbers not working

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example

How to make ConstraintLayout work with percentage values?

For someone that might find useful, you can use layout_constraintDimensionRatio im any child view inside a ConstraintLayout and we can define the Height or Width a ratio of the other dimension( at least one must be 0dp either width or heigh) example

 <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:src="@drawable/top_image"
        app:layout_constraintDimensionRatio="16:9"        
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

in this case the aspect ratio it's 16:9 app:layout_constraintDimensionRatio="16:9" you can find more info HERE

how to call url of any other website in php

Depending on what you mean, either redirect or use curl.

How to color the Git console?

As noted by @VonC, color.ui defaults to auto since Git 1.8.4


From the Unix & Linux Stackexchange question How to colorize output of git? and the answer by @Evgeny:

git config --global color.ui auto

The color.ui is a meta configuration that includes all the various color.* configurations available with git commands. This is explained in-depth in git help config.

So basically it's easier and more future proof than setting the different color.* settings separately.

In-depth explanation from the git config documentation:

color.ui: This variable determines the default value for variables such as color.diff and color.grep that control the use of color per command family. Its scope will expand as more commands learn configuration to set a default for the --color option. Set it to always if you want all output not intended for machine consumption to use color, to true or auto if you want such output to use color when written to the terminal, or to false or never if you prefer git commands not to use color unless enabled explicitly with some other configuration or the --color option.

How to get an input text value in JavaScript

<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value) 
window.alert(subadd)  
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>

How to see full absolute path of a symlink

unix flavors -> ll symLinkName

OSX -> readlink symLinkName

Difference is 1st way would display the sym link path in a blinking way and 2nd way would just echo it out on the console.

Javascript - removing undefined fields from an object

Another Javascript Solution

for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){ 
  if(typeof obj[keys[i]] === 'undefined'){
    delete obj[keys[i]];
  }
}

No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.

DEMO

Android and Facebook share intent

Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers:

Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT.)

Here's the best solution I've found that does not involve using any Facebook SDKs.

This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!)

String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);

// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
        intent.setPackage(info.activityInfo.packageName);
        facebookAppFound = true;
        break;
    }
}

// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
    String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}

startActivity(intent);

(Regarding the com.facebook.katana package name, see MatheusJardimB's comment.)

The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed:

enter image description here

wget can't download - 404 error

Actually I don't know what is the reason exactly, I have faced this like of problem. if you have the domain's IP address (ex 208.113.139.4), please use the IP address instead of domain (in this case www.icerts.com)

wget 192.243.111.11/images/logo.jpg

Go to find the IP from URL https://ipinfo.info/html/ip_checker.php

Padding is invalid and cannot be removed?

A serval times of fighting, I finally solved the problem.
(Note: I use standard AES as symmetric algorithm. This answer may not suitable for everyone.)

  1. Change the algorithm class. Replace the RijndaelManaged class to AESManaged one.
  2. Do not explicit set the KeySize of algorithm class, left them default.
    (This is the very important step. I think there is a bug in KeySize property.)

Here is a list you want to check which argument you might have missed:

  • Key
    (byte array, length must be exactly one of 16, 24, 32 byte for different key size.)
  • IV
    (byte array, 16 bytes)
  • CipherMode
    (One of CBC, CFB, CTS, ECB, OFB)
  • PaddingMode
    (One of ANSIX923, ISO10126, None, PKCS7, Zeros)

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

How to set character limit on the_content() and the_excerpt() in wordpress

Or even easier and without the need to create a filter: use PHP's mb_strimwidth to truncate a string to a certain width (length). Just make sure you use one of the get_ syntaxes. For example with the content:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>

This will cut the string at 400 characters and close it with .... Just add a "read more"-link to the end by pointing to the permalink with get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>

Of course you could also build the read more in the first line. Than just replace '...' with '<a href="' . get_permalink() . '">[Read more]</a>'

The multi-part identifier could not be bound

if you have given alies name change that to actual name

for example

SELECT  
    A.name,A.date
  FROM [LoginInfo].[dbo].[TableA] as A
   join 
  [LoginInfo].[dbo].[TableA] as B 
  on  [LoginInfo].[dbo].[TableA].name=[LoginInfo].[dbo].[TableB].name;

change that to

SELECT  
    A.name,A.date
  FROM [LoginInfo].[dbo].[TableA] as A
   join 
  [LoginInfo].[dbo].[TableA] as B 
  on  A.name=B.name;

How to change angular port from 4200 to any other

The location for port settings has changed a couple of times.

If using Angular CLI 1

Change angular-cli.json

{
  "defaults": {
    "serve": {
      "host": "0.0.0.0",
      "port": 5000 
    }
  }
}

If using the latest Angular CLI

Change angular.json

"projects": {
    "project-name": {
        ...
        "architect": {
            "serve": {
                "options": {
                  "host": "0.0.0.0",
                  "port": 5000
                }
            }
        }
        ...
    }
}

Without changing any file

Run the command

ng serve --host 0.0.0.0 --port 5000

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

Detect click inside/outside of element with single event handler

Instead of using the body you could create a curtain with z-index of 100 (to pick a number) and give the inside element a higher z-index while all other elements have a lower z-index than the curtain.

See working example here: http://jsfiddle.net/Flandre/6JvFk/

jQuery:

$('#curtain').on("click", function(e) {

    $(this).hide();
    alert("clicked ouside of elements that stand out");

});

CSS:

.aboveCurtain
{
    z-index: 200; /* has to have a higher index than the curtain */
    position: relative;
    background-color: pink;
}

#curtain
{
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background-color: black;
    width: 100%;
    z-index:100;   
    opacity:0.5 /* change opacity to 0 to make it a true glass effect */
}

Python "extend" for a dictionary

a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

Making a triangle shape using xml definitions?

You can add following triangle in background using following xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#848af8"
            android:pathData="M 0,20 L 0,0 L 100,0 L 100,20 L 54,55  l -1,0.6  l -1,0.4  l -1,0.2  l -1,0   l -1,-0  l -1,-0.2  l -1,-0.4  l -1,-0.6    L 46,55   L 0,20 -100,-100 Z" />
    </group>
</vector>

The whole logic to customize xml design is in pathData. Consider top-left as (0,0) and design the layout as per your requirement. Check this answer.

Difference between Constructor and ngOnInit

The above answers don't really answer this aspect of the original question: What is a lifecycle hook? It took me a while to understand what that means until I thought of it this way.

1) Say your component is a human. Humans have lives that include many stages of living, and then we expire.

2) Our human component could have the following lifecycle script: Born, Baby, Grade School, Young Adult, Mid-age Adult, Senior Adult, Dead, Disposed of.

3) Say you want to have a function to create children. To keep this from getting complicated, and rather humorous, you want your function to only be called during the Young Adult stage of the human component life. So you develop a component that is only active when the parent component is in the Young Adult stage. Hooks help you do that by signaling that stage of life and letting your component act on it.

Fun stuff. If you let your imagination go to actually coding something like this it gets complicated, and funny.

How to check in Javascript if one element is contained within another

I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.

Below is the function:

function isChildOf(childObject, containerObject) {
  var returnValue = false;
  var currentObject;

  if (typeof containerObject === 'string') {
    containerObject = document.getElementById(containerObject);
  }
  if (typeof childObject === 'string') {
    childObject = document.getElementById(childObject);
  }

  currentObject = childObject.parentNode;

  while (currentObject !== undefined) {
    if (currentObject === document.body) {
      break;
    }

    if (currentObject.id == containerObject.id) {
      returnValue = true;
      break;
    }

    // Move up the hierarchy
    currentObject = currentObject.parentNode;
  }

  return returnValue;
}

unable to install pg gem

You just go to here to see if your pg version support Win32 platform, then use this command to install:

gem install pg -v 0.14.1 --platform=x86-mingw32

Create an array with random values

If you need it with random unique values from 0...length range:

const randomRange = length => {
  const results = []
  const possibleValues = Array.from({ length }, (value, i) => i)

  for (let i = 0; i < length; i += 1) {
    const possibleValuesRange = length - (length - possibleValues.length)
    const randomNumber = Math.floor(Math.random() * possibleValuesRange)
    const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange

    const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)

    results.push(nextNumber)
  }

  return results
}

randomRange(5) // [3, 0, 1, 4, 2]

How can I detect window size with jQuery?

Do you want to detect when the window has been resized?

You can use JQuery's resize to attach a handler.

What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

How to get a subset of a javascript object's properties

I've got the same problem and solved it easily by using the following libs:

object.pick

https://www.npmjs.com/package/object.pick

pick({a: 'a', b: 'b', c: 'c'}, ['a', 'b'])
//=> {a: 'a', b: 'b'}

object.omit

https://www.npmjs.com/package/object.omit

omit({a: 'a', b: 'b', c: 'c'}, ['a', 'c'])
//=> { b: 'b' }

Safely limiting Ansible playbooks to a single machine?

AWS users using the EC2 External Inventory Script can simply filter by instance id:

ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts

This works because the inventory script creates default groups.

From Arraylist to Array

This is the recommended usage for newer Java ( >Java 6)

String[] myArray = myArrayList.toArray(new String[0]);

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

Gradle DSL method not found: 'runProguard'

enter image description hereIf you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.

runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

How to replace local branch with remote branch entirely in Git?

Replace everything with the remote branch; but, only from the same commit your local branch is on:

git reset --hard origin/some-branch

OR, get the latest from the remote branch and replace everything:

git fetch origin some-branch
git reset --hard FETCH_HEAD

As an aside, if needed, you can wipe out untracked files & directories that you haven't committed yet:

git clean -fd

Append data to a POST NSURLRequest

The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest rather than NSURLRequest. In its current form, I couldn't get it to respond to the setHTTPMethod call. Changing the type fixed things right up.

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

iTerm2 keyboard shortcut - split pane navigation

From the documentation:

Cmd] and Cmd[ navigates among split panes in order of use.

"End of script output before headers" error in Apache

If this is a CGI script for the web, then you must output your header:

#!"C:\xampp\perl\bin\perl.exe"

print "Content-Type: text/html\n\n";
print "Hello World";

The following error message tells you this End of script output before headers: sample.pl

Or even better, use the CGI module to output the header:

#!"C:\xampp\perl\bin\perl.exe"

use strict;
use warnings;

use CGI;

print CGI::header();
print "Hello World";

Clear icon inside input text

You can do with this commands (without Bootstrap).

_x000D_
_x000D_
Array.from(document.querySelectorAll('.search-field')).forEach(field => {_x000D_
  field.querySelector('span').addEventListener('click', e => {_x000D_
    field.querySelector('input').value = '';_x000D_
  });_x000D_
});
_x000D_
:root {_x000D_
  --theme-color: teal;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input {_x000D_
  background:none;_x000D_
  outline:none;_x000D_
  display: inline-block;_x000D_
  width: 100%;_x000D_
  margin: 8px 0;_x000D_
  padding: 13px 15px;_x000D_
  padding-right: 42.5px;_x000D_
  border: 1px solid var(--theme-color);_x000D_
  border-radius: 5px;_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
span {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  margin: 8px 0;_x000D_
  padding: 13px 15px;_x000D_
  color: var(--theme-color);_x000D_
  font-weight: bold;_x000D_
  cursor: pointer;_x000D_
}_x000D_
span:after {_x000D_
  content: '\2716';_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="search-field">_x000D_
    <input placeholder="Search..." />_x000D_
    <span></span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

When to use AtomicReference in Java?

I won't talk much. Already my respected fellow friends have given their valuable input. The full fledged running code at the last of this blog should remove any confusion. It's about a movie seat booking small program in multi-threaded scenario.

Some important elementary facts are as follows. 1> Different threads can only contend for instance and static member variables in the heap space. 2> Volatile read or write are completely atomic and serialized/happens before and only done from memory. By saying this I mean that any read will follow the previous write in memory. And any write will follow the previous read from memory. So any thread working with a volatile will always see the most up-to-date value. AtomicReference uses this property of volatile.

Following are some of the source code of AtomicReference. AtomicReference refers to an object reference. This reference is a volatile member variable in the AtomicReference instance as below.

private volatile V value;

get() simply returns the latest value of the variable (as volatiles do in a "happens before" manner).

public final V get()

Following is the most important method of AtomicReference.

public final boolean  compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}

The compareAndSet(expect,update) method calls the compareAndSwapObject() method of the unsafe class of Java. This method call of unsafe invokes the native call, which invokes a single instruction to the processor. "expect" and "update" each reference an object.

If and only if the AtomicReference instance member variable "value" refers to the same object is referred to by "expect", "update" is assigned to this instance variable now, and "true" is returned. Or else, false is returned. The whole thing is done atomically. No other thread can intercept in between. As this is a single processor operation (magic of modern computer architecture), it's often faster than using a synchronized block. But remember that when multiple variables need to be updated atomically, AtomicReference won't help.

I would like to add a full fledged running code, which can be run in eclipse. It would clear many confusion. Here 22 users (MyTh threads) are trying to book 20 seats. Following is the code snippet followed by the full code.

Code snippet where 22 users are trying to book 20 seats.

for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }

Following is the full running code.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class Solution {

    static List<AtomicReference<Integer>> seats;// Movie seats numbered as per
                                                // list index

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        seats = new ArrayList<>();
        for (int i = 0; i < 20; i++) {// 20 seats
            seats.add(new AtomicReference<Integer>());
        }
        Thread[] ths = new Thread[22];// 22 users
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new MyTh(seats, i);
            ths[i].start();
        }
        for (Thread t : ths) {
            t.join();
        }
        for (AtomicReference<Integer> seat : seats) {
            System.out.print(" " + seat.get());
        }
    }

    /**
     * id is the id of the user
     * 
     * @author sankbane
     *
     */
    static class MyTh extends Thread {// each thread is a user
        static AtomicInteger full = new AtomicInteger(0);
        List<AtomicReference<Integer>> l;//seats
        int id;//id of the users
        int seats;

        public MyTh(List<AtomicReference<Integer>> list, int userId) {
            l = list;
            this.id = userId;
            seats = list.size();
        }

        @Override
        public void run() {
            boolean reserved = false;
            try {
                while (!reserved && full.get() < seats) {
                    Thread.sleep(50);
                    int r = ThreadLocalRandom.current().nextInt(0, seats);// excludes
                                                                            // seats
                                                                            //
                    AtomicReference<Integer> el = l.get(r);
                    reserved = el.compareAndSet(null, id);// null means no user
                                                            // has reserved this
                                                            // seat
                    if (reserved)
                        full.getAndIncrement();
                }
                if (!reserved && full.get() == seats)
                    System.out.println("user " + id + " did not get a seat");
            } catch (InterruptedException ie) {
                // log it
            }
        }
    }

}    

Is it possible to change the package name of an Android app on Google Play?

Complete guide : https://developer.android.com/studio/build/application-id.html

As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html

We can say that:

  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.

  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.

As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en

Update your apps

Prepare your APK

When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.

Use the following checklist to make sure your new APK is ready to update your existing users:

  • The package name of the updated APK needs to be the same as the current version.
  • The version code needs to be greater than that current version. Learn more about versioning your applications.
  • The updated APK needs to be signed with the same signature as the current version.

To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:

$ jarsigner -verify -verbose -certs my_application.apk

If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.

Learn more about signing your applications

Upload your APK Once your APK is ready, you can create a new release.

VARCHAR to DECIMAL

You are missing the fact that 6.999,50 is not a valid decimal. You can't have a comma and a decimal point in a decimal value surely? What number is it supposed to be?

Assuming your locale specifies . as grouping and , as decimal separator: To remove the grouping digits:

SELECT CONVERT(decimal(11,2), REPLACE('6.999,50', '.', ''))

will yield 6999,50 as a decimal

Is it possible to add dynamically named properties to JavaScript object?

Yes.

_x000D_
_x000D_
var data = {_x000D_
    'PropertyA': 1,_x000D_
    'PropertyB': 2,_x000D_
    'PropertyC': 3_x000D_
};_x000D_
_x000D_
data["PropertyD"] = 4;_x000D_
_x000D_
// dialog box with 4 in it_x000D_
alert(data.PropertyD);_x000D_
alert(data["PropertyD"]);
_x000D_
_x000D_
_x000D_

Android marshmallow request permission?

This structure I am using to check if my app has permission and than request if it does not have permission. So in my main code from where i want to check write following :

int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
                if (!checkIfAlreadyhavePermission()) {
                    requestForSpecificPermission();
                }
}

Module checkIfAlreadyhavePermission() is implemented as :

private boolean checkIfAlreadyhavePermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

Module requestForSpecificPermission() is implemented as :

private void requestForSpecificPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}

and Override in Activity :

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 101:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //granted
            } else {
                //not granted
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Refer this link for more details : http://revisitingandroid.blogspot.in/2017/01/how-to-check-and-request-for-run-time.html

Keeping session alive with Curl and PHP

You also need to set the option CURLOPT_COOKIEFILE.

The manual describes this as

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

How do I paste multi-line bash codes into terminal and run it all at once?

Another possibility:

bash << EOF
echo "Hello"
echo "World"
EOF

How do I toggle an element's class in pure JavaScript?

don't need regex just use classlist

_x000D_
_x000D_
var id=document.getElementById('myButton');


function toggle(el,classname){
if(el.classList.contains(classname)){
el.classList.remove(classname)
}
else{
el.classList.add(classname)
}
}




id.addEventListener('click',(e)=>{

toggle(e.target,'red')
})
_x000D_
.red{

background:red

}
_x000D_
<button id="myButton">Switch</button>
_x000D_
_x000D_
_x000D_

Simple Usage above Example

_x000D_
_x000D_
var id=document.getElementById('myButton');


function toggle(el,classname){
el.classList.toggle(classname)
}




id.addEventListener('click',(e)=>{

toggle(e.target,'red')
})
_x000D_
.red{

background:red

}
_x000D_
<button id="myButton">Switch</button>
_x000D_
_x000D_
_x000D_

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How do I read a text file of about 2 GB?

Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools

How do I programmatically force an onchange event on an input?

In jQuery I mostly use:

$("#element").trigger("change");

QUERY syntax using cell reference

To make it work with both text and numbers:

Exact match:

=query(D:E,"select * where D like '"&C1&"'", 0)

Convert search string to lowercase:

=query(D:E,"select * where D like lower('"&C1&"')", 0)

Convert to lowercase and contain part of the search string:

=query(D:E,"select * where D like lower('%"&C1&"%')", 0)

enter image description here

A1                = query/formula
yellow / A:B  = result area
green / C1    = search area
blue / D:E     = data area

If you get error when the input is text and not numbers; move the data and delete the (now empty) columns. Then move the data back.

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

How to check for valid email address?

I haven't seen the answer already here among the mess of custom Regex answers, but...

There exists a python library called py3-validate-email validate_email which has 3 levels of email validation, including asking a valid SMTP server if the email address is valid (without sending an email).

To install

python -m pip install py3-validate-email

Basic usage:

from validate_email import validate_email
is_valid = validate_email(email_address='[email protected]', \
    check_regex=True, check_mx=True, \
    from_address='[email protected]', helo_host='my.host.name', \ 
    smtp_timeout=10, dns_timeout=10, use_blacklist=True)

For those interested in the dirty details, validate_email.py (source) aims to be faithful to RFC 2822.

All we are really doing is comparing the input string to one gigantic regular expression. But building that regexp, and ensuring its correctness, is made much easier by assembling it from the "tokens" defined by the RFC. Each of these tokens is tested in the accompanying unit test file.


you may need the pyDNS module for checking SMTP servers

pip install pyDNS

or from Ubuntu

apt-get install python3-dns

how to convert a string to a bool

Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:

bool val = Convert.ToBoolean("true");

or an extension method to do whatever weird mapping you're doing:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

Is there a Python equivalent to Ruby's string interpolation?

Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

Prior to 3.6, the closest you can get to this is

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.

The same code using the .format() method of recent Python versions would look like this:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

There is also the string.Template class:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

Converting user input string to regular expression

In my case the user input somethimes was sorrounded by delimiters and sometimes not. therefore I added another case..

var regParts = inputstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
    // the parsed pattern had delimiters and modifiers. handle them. 
    var regexp = new RegExp(regParts[1], regParts[2]);
} else {
    // we got pattern string without delimiters
    var regexp = new RegExp(inputstring);
}

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Just updating google-service version did not work for me.

  • First make sure all your dependencies compile are replaced with implementation.
  • Update all dependencies in your project. Because if one of your dependency is having compile then your project will show this error. So update all dependencies version.

How do I trim leading/trailing whitespace in a standard way?

I'm not sure what you consider "painless."

C strings are pretty painful. We can find the first non-whitespace character position trivially:

while (isspace(* p)) p++;

We can find the last non-whitespace character position with two similar trivial moves:

while (* q) q++;
do { q--; } while (isspace(* q));

(I have spared you the pain of using the * and ++ operators at the same time.)

The question now is what do you do with this? The datatype at hand isn't really a big robust abstract String that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby's chomp function. What would such a function in C return?

Difference between binary tree and binary search tree

Binary Tree is a specialized form of tree with two child (left child and right Child). It is simply representation of data in Tree structure

Binary Search Tree (BST) is a special type of Binary Tree that follows following condition:

  1. left child node is smaller than its parent Node
  2. right child node is greater than its parent Node

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Replace string within file contents

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

How to navigate a few folders up?

if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder

//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());

string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();

ie,c:\folder1\folder2\folder3

if you want folder2 path then you can get the directory by

string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();

then you will get path as c:\folder1\folder2\

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

How to convert a Datetime string to a current culture datetime string

DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);

How to properly create an SVN tag from trunk?

Try this. It works for me:

mkdir <repos>/tags/Release1.0
svn commit <repos>/tags/Release1.0 
svn copy <repos>/trunk/* <repos>/tag/Release1.0
svn commit <repos/tags/Release1.0 -m "Tagging Release1.0"

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

How to create EditText with cross(x) button at end of it?

Android's support libarary has a SearchView class that does exactly this. (Not derrived from EditText though, so have to use a SearchView.OnQueryTextListener instead of a TextWatcher)

Search view with no text (and hint text "Search")

enter image description here

Use in XML like so:

  <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="@string/SearchHint"
            app:iconifiedByDefault="false"
            app:queryHint="@string/SearchHint" />

Avoiding NullPointerException in Java

This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.

Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.

WRAPPING TO OPTION<T>

Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
      Service s = new  RefrigeratorService();
       //...
      return Optional.ofNullable(s);
   }

As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.

SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?

Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.

Finally, here is our NPE as well as null check-free code:

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

public static void main(String[] args) {
    /* Get Home Services handle */
    Optional<HomeServices> homeServices = HomeServices.get();
    if(homeServices != null) {
        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
        refrigertorControl.ifPresent(HomeServices::switchItOn);
    }
}

public static void switchItOn(Service s){
         //...
    }
}

The complete post is NPE as well as Null check-free code … Really?.

An unhandled exception occurred during the execution of the current web request. ASP.NET

  1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
  2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

Check your problem is solved.

Onclick event to remove default value in a text input field

As stated before I even saw this question placeholder is the answer. HTML5 for the win! But for those poor unfortunate souls that cannot rely on that functionality take a look at the jquery plugin as an augmentation as well. HTML5 Placeholder jQuery Plugin

<input name="Name" placeholder="Enter Your Name">

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Run below 2 commands in PowerShell window

  1. Set-ExecutionPolicy unrestricted

  2. Unblock-File -Path D:\PowerShell\Script.ps1

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Text-decoration: none not working

Try placing your text-decoration: none; on your a:hover css.

@Directive vs @Component in Angular

If you refer the official angular docs

https://angular.io/guide/attribute-directives

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements. e.g *ngIf
  3. Attribute directives—change the appearance or behavior of an element, component, or another directive. e.g [ngClass].

As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.

JSON Stringify changes time of date because of UTC

In this case I think you need transform the date to UNIX timestamp

timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);

After that you can re use it to create a date object and format it. Example with javascript and toLocaleDateString ( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )

newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
  "fr-FR",
]);

If you use stringify to use AJAX, now it's not useful. You just need to send timestamp and get it in your script:

$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));

Be aware that getTime() will return a time in milliseconds and the PHP function setTimestamp take time in seconds. It's why you need to divide by 1000 and round.

html - table row like a link

When i want simulate a <tr> with a link but respecting the html standards, I do this.

HTML:

<table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>

CSS:

tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE

How to construct a WebSocket URI relative to the page URI?

If your Web server has support for WebSockets (or a WebSocket handler module) then you can use the same host and port and just change the scheme like you are showing. There are many options for running a Web server and Websocket server/module together.

I would suggest that you look at the individual pieces of the window.location global and join them back together instead of doing blind string substitution.

var loc = window.location, new_uri;
if (loc.protocol === "https:") {
    new_uri = "wss:";
} else {
    new_uri = "ws:";
}
new_uri += "//" + loc.host;
new_uri += loc.pathname + "/to/ws";

Note that some web servers (i.e. Jetty based ones) currently use the path (rather than the upgrade header) to determine whether a specific request should be passed on to the WebSocket handler. So you may be limited in whether you can transform the path in the way you want.

What is the shortcut in IntelliJ IDEA to find method / functions?

Android Studio on Mac

Command + Option + O

Opens up the Symbol lookup that you can jump to most of the methods/functions in your currently opened document.

Indentation shortcuts in Visual Studio

If the move-left and move-right shortcuts do not appear on your screen, click at the rightmost position of your toolbar at the top. You should get "Add or Remove Buttons." Add the buttons "decrease line indent" and "increase line indent"

MemoryStream - Cannot access a closed Stream

The problem is this block:

using (var sr = new StreamReader(ms))
{
    Console.WriteLine(sr.ReadToEnd());                        
}

When the StreamReader is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream is closed. When the StreamWriter gets closed, it tries to flush everything to the MemoryStream, but it is closed.

You should consider not putting the StreamReader in a using block.

#1214 - The used table type doesn't support FULLTEXT indexes

*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************

Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.

So i am mentioning here steps in very simple words will resolve your issue.

1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)

2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)

3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM

4.) Now Click on Replace All Button

5.) Click CTRL+S or File>Save

6.) Now Upload This File and I am Sure your issue will be resolved....

Flutter: Run method on Widget build complete

Best ways of doing this,

1. WidgetsBinding

WidgetsBinding.instance.addPostFrameCallback((_) {
      print("WidgetsBinding");
    });

2. SchedulerBinding

SchedulerBinding.instance.addPostFrameCallback((_) {
  print("SchedulerBinding");
});

It can be called inside initState, both will be called only once after Build widgets done with rendering.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("initState");
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("WidgetsBinding");
    });
    SchedulerBinding.instance.addPostFrameCallback((_) {
      print("SchedulerBinding");
    });
  }

both above codes will work the same as both use the similar binding framework. For the difference find the below link.

https://medium.com/flutterworld/flutter-schedulerbinding-vs-widgetsbinding-149c71cb607f

How can I sanitize user input with PHP?

Never trust user data.

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

The trim() function removes whitespace and other predefined characters from both sides of a string.

The stripslashes() function removes backslashes

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

Java 256-bit AES Password-Based Encryption

Use this class for encryption. It works.

public class ObjectCrypter {


    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(mes);

    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException, ClassNotFoundException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(bytes);

    }
}

And these are ivBytes and a random key;

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");

Alternative to a goto statement in Java

The easiest is:

int label = 0;
loop:while(true) {
    switch(state) {
        case 0:
            // Some code
            state = 5;
            break;

        case 2:
            // Some code
            state = 4;
            break;
        ...
        default:
            break loop;
    }
}

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

tSQL - Conversion from varchar to numeric works for all but integer

Try this

declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end

and

declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end

Create line after text with css

Here is another, in my opinion even simpler solution using a flex wrapper:

HTML:

<div class="wrapper">
  <p>Text</p>
  <div class="line"></div>
</div>

CSS:

.wrapper {
  display: flex;
  align-items: center;
}

.line {
  border-top: 1px solid grey;
  flex-grow: 1;
  margin: 0 10px;
}

JSFiddle

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

Remove quotes (') after ALTER USER and keep quote (') after mysql_native_password BY

It is working for me also.

Why does ASP.NET webforms need the Runat="Server" attribute?

I think that Microsoft can fix this ambiguity by making the compiler add runat attribute before the page is ever compiled, something like the type-erasure thing that java has with the generics, instead of erasing, it could be writing runat=server wherever it sees asp: prefix for tags, so the developer would not need to worry about it.

Create a string with n characters

Hmm now that I think about it, maybe Arrays.fill:

char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);

Of course, I assume that the fill method does the same thing as your code, so it will probably perform about the same, but at least this is fewer lines.

How do I remove duplicates from a C# array?

This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:

    public string[] RemoveDuplicates(string[] myList) {
        System.Collections.ArrayList newList = new System.Collections.ArrayList();

        foreach (string str in myList)
            if (!newList.Contains(str))
                newList.Add(str);
        return (string[])newList.ToArray(typeof(string));
    }

DropDownList's SelectedIndexChanged event not firing

Add property ViewStateMode="Enabled" and EnableViewState="true" And AutoPostBack="true" in drop DropDownList

How to Convert an int to a String?

Did you try:

text_Rate.setText(String.valueOf(sdRate));

Refresh Excel VBA Function Results

The Application.Volatile doesn't work for recalculating a formula with my own function inside. I use the following function: Application.CalculateFull

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

Radio Buttons "Checked" Attribute Not Working

also try this way

$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

Python date string to date object

Directly related question:

What if you have

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above.

Answer:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

How can I change all input values to uppercase using Jquery?

$('#id-submit').click(function () {
    $("input").val(function(i,val) {
        return val.toUpperCase();
    });
});

FIDDLE

How to Install gcc 5.3 with yum on CentOS 7.2?

Update:
Often people want the most recent version of gcc, and devtoolset is being kept up-to-date, so maybe you want devtoolset-N where N={4,5,6,7...}, check yum for the latest available on your system). Updated the cmds below for N=7.

There is a package for gcc-7.2.1 for devtoolset-7 as an example. First you need to enable the Software Collections, then it's available in devtoolset-7:

sudo yum install centos-release-scl
sudo yum install devtoolset-7-gcc*
scl enable devtoolset-7 bash
which gcc
gcc --version

How do I check whether input string contains any spaces?

You can use regex “\\s”

Example program to count number of spaces (Java 9 and above)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {

    Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);        
    Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");        

    long matchCount = matcher.results().count();   
 
    if(matchCount > 0) 
      System.out.println("Match found " + matchCount + " times.");           
    else 
      System.out.println("Match not found");        
  }
}

For Java 8 and below you can use matcher.find() in a while loop and increment the count. For example,

int count = 0;
while (matcher.find()) {
  count ++;
}

Find OpenCV Version Installed on Ubuntu

The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.

On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use

 dpkg -l | grep libopencv

If you have the development packages installed, like libopencv-core-dev, you'll probably have .pc files and can use pkg-config:

 pkg-config --modversion opencv

CSS3 Transform Skew One Side

Try this:

To unskew the image use a nested div for the image and give it the opposite skew value. So if you had 20deg on the parent then you can give the nested (image) div a skew value of -20deg.

_x000D_
_x000D_
.container {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#parallelogram {_x000D_
  width: 150px;_x000D_
  height: 100px;_x000D_
  margin: 0 0 0 -20px;_x000D_
  -webkit-transform: skew(20deg);_x000D_
  -moz-transform: skew(20deg);_x000D_
  -o-transform: skew(20deg);_x000D_
  background: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  background: url(http://placekitten.com/301/301);_x000D_
  position: absolute;_x000D_
  top: -30px;_x000D_
  left: -30px;_x000D_
  right: -30px;_x000D_
  bottom: -30px;_x000D_
  -webkit-transform: skew(-20deg);_x000D_
  -moz-transform: skew(-20deg);_x000D_
  -o-transform: skew(-20deg);_x000D_
}
_x000D_
<div class="container">_x000D_
  <div id="parallelogram">_x000D_
    <div class="image"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The example:

http://jsfiddle.net/diegoh/mXLgF/1154/

Failed to execute 'createObjectURL' on 'URL':

This error is caused because the function createObjectURL is deprecated for Google Chrome

I changed this:

video.src=vendorUrl.createObjectURL(stream);
video.play();

to this:

video.srcObject=stream;
video.play();

This worked for me.

Unit testing with Spring Security

Authentication is a property of a thread in server environment in the same way as it is a property of a process in OS. Having a bean instance for accessing authentication information would be inconvenient configuration and wiring overhead without any benefit.

Regarding test authentication there are several ways how you can make your life easier. My favourite is to make a custom annotation @Authenticated and test execution listener, which manages it. Check DirtiesContextTestExecutionListener for inspiration.

How to add soap header in java

I struggled to get this working. That's why I'll add a complete solution here:

My objective is to add this header to the SOAP envelope:

   <soapenv:Header>
      <urn:OTAuthentication>
         <urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
      </urn:OTAuthentication>
   </soapenv:Header>
  1. First create a SOAPHeaderHandler class.

    import java.util.Set;
    import java.util.TreeSet;
    
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPFactory;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    
    public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
    
        private final String authenticatedToken;
    
        public SOAPHeaderHandler(String authenticatedToken) {
            this.authenticatedToken = authenticatedToken;
        }
    
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outboundProperty =
                    (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outboundProperty.booleanValue()) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPFactory factory = SOAPFactory.newInstance();
                    String prefix = "urn";
                    String uri = "urn:api.ecm.opentext.com";
                    SOAPElement securityElem =
                            factory.createElement("OTAuthentication", prefix, uri);
                    SOAPElement tokenElem =
                            factory.createElement("AuthenticationToken", prefix, uri);
                    tokenElem.addTextNode(authenticatedToken);
                    securityElem.addChildElement(tokenElem);
                    SOAPHeader header = envelope.addHeader();
                    header.addChildElement(securityElem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // inbound
            }
            return true;
        }
    
        public Set<QName> getHeaders() {
            return new TreeSet();
        }
    
        public boolean handleFault(SOAPMessageContext context) {
            return false;
        }
    
        public void close(MessageContext context) {
            //
        }
    }
    
    1. Add the handler to the proxy. Note that according javax.xml.ws.Binding's documentation: "If the returned chain is modified a call to setHandlerChain is required to configure the binding instance with the new chain."

    Authentication_Service authentication_Service = new Authentication_Service();

    Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication(); String authenticatedToken = "TOKEN"; List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain(); handlerChain.add(new SOAPHeaderHandler(authenticatedToken)); ((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Getting the number of filled cells in a column (VBA)

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

What’s the best RESTful method to return total number of items in an object?

While the response to /API/users is paged and returns only 30, records, there's nothing preventing you from including in the response also the total number of records, and other relevant info, like the page size, the page number/offset, etc.

The StackOverflow API is a good example of that same design. Here's the documentation for the Users method - https://api.stackexchange.com/docs/users

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

How to draw a rounded Rectangle on HTML Canvas?

Here's a solution using a lineJoin to round the corners. Works if you just need a solid shape but not so much if you need a thin border that's smaller than the border radius.

    function roundedRect(ctx, options) {

        ctx.strokeStyle = options.color;
        ctx.fillStyle = options.color;
        ctx.lineJoin = "round";
        ctx.lineWidth = options.radius;

        ctx.strokeRect(
            options.x+(options.radius*.5),
            options.y+(options.radius*.5),
            options.width-options.radius,
            options.height-options.radius
        );

        ctx.fillRect(
            options.x+(options.radius*.5),
            options.y+(options.radius*.5),
            options.width-options.radius,
            options.height-options.radius
        );

        ctx.stroke();
        ctx.fill();

    }

    const canvas = document.getElementsByTagName("CANVAS")[0];
    let ctx = canvas.getContext('2d');

    roundedRect(ctx, {
        x: 10,
        y: 10,
        width: 200,
        height: 100,
        radius: 10,
        color: "red"
    });

Getting rid of all the rounded corners in Twitter Bootstrap

You may also want to have a look at FlatStrap. It provides a Metro-Style replacement for the Bootstrap CSS without rounded corners, gradients and drop shadows.

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

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

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

How to play .mp4 video in videoview in android?

Finally it works for me.

private VideoView videoView;

videoView = (VideoView) findViewById(R.id.videoView);

Uri video = Uri.parse("http://www.servername.com/projects/projectname/videos/1361439400.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  @Override       
  public void onPrepared(MediaPlayer mp) {
       mp.setLooping(true);
       videoView.start();
    }
});

Hope this would help others.

How to pass parameters to ThreadStart method in Thread?

here is the perfect way...

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}

Upload folder with subfolders using S3 and the AWS console

You can't upload nested structures like that through the online tool. I'd recommend using something like Bucket Explorer for more complicated uploads.

AngularJS Directive Restrict A vs E

The restrict option is typically set to:

  • 'A' - only matches attribute name
  • 'E' - only matches element name
  • 'C' - only matches class name
  • 'M' - only matches comment

Here is the documentation link.

Case Function Equivalent in Excel

I understand that this is a response to an old post-

I like the If() function combined with Index()/Match():

=IF(B2>0,"x",INDEX($H$2:$I$9,MATCH(A2,$H$2:$H$9,0),2))

The if function compare what is in column b and if it is greater than 0, it returns x, if not it uses the array (table of information) identified by the Index() function and selected by Match() to return the value that a corresponds to.

The Index array has the absolute location set $H$2:$I$9 (the dollar signs) so that the place it points to will not change as the formula is copied. The row with the value that you want returned is identified by the Match() function. Match() has the added value of not needing a sorted list to look through that Vlookup() requires. Match() can find the value with a value: 1 less than, 0 exact, -1 greater than. I put a zero in after the absolute Match() array $H$2:$H$9 to find the exact match. For the column that value of the Index() array that one would like returned is entered. I entered a 2 because in my array the return value was in the second column. Below my index array looked like this:

32   1420

36   1650

40   1790

44   1860

55   2010

The value in your 'a' column to search for in the list is in the first column in my example and the corresponding value that is to be return is to the right. The look up/reference table can be on any tab in the work book - or even in another file. -Book2 is the file name, and Sheet2 is the 'other tab' name.

=IF(B2>0,"x",INDEX([Book2]Sheet2!$A$1:$B$8,MATCH(A2,[Book2]Sheet2!$A$1:$A$8,0),2))

If you do not want x return when the value of b is greater than zero delete the x for a 'blank'/null equivalent or maybe put a 0 - not sure what you would want there.

Below is beginning of the function with the x deleted.

=IF(B2>0,"",INDEX...

HashMap - getting First Key value

You can also try below:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);