Programs & Examples On #Pgu

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Temporary table in SQL server causing ' There is already an object named' error

I usually put these lines at the beginning of my stored procedure, and then at the end.

It is an "exists" check for #temp tables.

IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
        drop table #MyCoolTempTable
end

Full Example:

CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
    SET NOCOUNT ON;


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    CREATE TABLE #MyCoolTempTable (
        MyCoolTempTableKey INT IDENTITY(1,1),
        MyValue VARCHAR(128)
    )  

    INSERT INTO #MyCoolTempTable (MyValue)
        SELECT LEFT(@@VERSION, 128)
        UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects

    SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable


    IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
    BEGIN
            DROP TABLE #MyCoolTempTable
    END


    SET NOCOUNT OFF;
END
GO

Delete all nodes and relationships in neo4j 1.8

As of 2.3.0 and up to 3.3.0

MATCH (n)
DETACH DELETE n

Docs

Pre 2.3.0

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

Docs

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

When to use references vs. pointers

Disclaimer: other than the fact that references cannot be NULL nor "rebound" (meaning thay can't change the object they're the alias of), it really comes down to a matter of taste, so I'm not going to say "this is better".

That said, I disagree with your last statement in the post, in that I don't think the code loses clarity with references. In your example,

add_one(&a);

might be clearer than

add_one(a);

since you know that most likely the value of a is going to change. On the other hand though, the signature of the function

void add_one(int* const n);

is somewhat not clear either: is n going to be a single integer or an array? Sometimes you only have access to (poorly documentated) headers, and signatures like

foo(int* const a, int b);

are not easy to interpret at first sight.

Imho, references are as good as pointers when no (re)allocation nor rebinding (in the sense explained before) is needed. Moreover, if a developer only uses pointers for arrays, functions signatures are somewhat less ambiguous. Not to mention the fact that operators syntax is way more readable with references.

How to Disable GUI Button in Java

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

C++ code file extension? .cc vs .cpp

I personally use .cc extension for implementation files, .hh for headers, and .inl for inline/templates.

As said before, it is mainly a matter of taste.

From what I've seen, .cc seems to be more "open source projects oriented", as it is advised in some great open source software coding styles, whereas .cpp seems to be more Windowish.

--- EDIT

As mentioned, this is "from what i've seen", it may be wrong. It's just that all Windows projects I've worked on used .cpp, and a lot of open source projects (which are mainly on unix-likes) use .cc.

Examples coding styles using .cc:

How does the stack work in assembly language?

The stack is "implemented" by means of the stack pointer, which (assuming x86 architecture here) points into the stack segment. Every time something is pushed on the stack (by means of pushl, call, or a similar stack opcode), it is written to the address the stack pointer points to, and the stack pointer decremented (stack is growing downwards, i.e. smaller addresses). When you pop something off the stack (popl, ret), the stack pointer is incremented and the value read off the stack.

In a user-space application, the stack is already set up for you when your application starts. In a kernel-space environment, you have to set up the stack segment and the stack pointer first...

WAMP 403 Forbidden message on Windows 7

This configuration in httpd.conf work fine for me.

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1 ::1
</Directory>

Field 'id' doesn't have a default value?

For me the issue got fixed when I changed

<id name="personID" column="person_id">
    <generator class="native"/>
</id>

to

<id name="personID" column="person_id">
    <generator class="increment"/>
</id>

in my Person.hbm.xml.

after that I re-encountered that same error for an another field(mobno). I tried restarting my IDE, recreating the database with previous back issue got eventually fixed when I re-create my tables using (without ENGINE=InnoDB DEFAULT CHARSET=latin1; and removing underscores in the field name)

CREATE TABLE `tbl_customers` (
  `pid` bigint(20) NOT NULL,
  `title` varchar(4) NOT NULL,
  `dob` varchar(10) NOT NULL,
  `address` varchar(100) NOT NULL,
  `country` varchar(4) DEFAULT NULL,
  `hometp` int(12) NOT NULL,
  `worktp` int(12) NOT NULL,
  `mobno` varchar(12) NOT NULL,
  `btcfrom` varchar(8) NOT NULL,
  `btcto` varchar(8) NOT NULL,
  `mmname` varchar(20) NOT NULL
)

instead of

CREATE TABLE `tbl_person` (
  `person_id` bigint(20) NOT NULL,
  `person_nic` int(10) NOT NULL,
  `first_name` varchar(20) NOT NULL,
  `sur_name` varchar(20) NOT NULL,
  `person_email` varchar(20) NOT NULL,
  `person_password` varchar(512) NOT NULL,
  `mobno` varchar(10) NOT NULL DEFAULT '1',
  `role` varchar(10) NOT NULL,
  `verified` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I probably think this due to using ENGINE=InnoDB DEFAULT CHARSET=latin1; , because I once got the error org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'mob_no' in 'field list' even though it was my previous column name, which even do not exist in my current table. Even after backing up the database(with modified column name, using InnoDB engine) I still got that same error with old field name. This probably due to caching in that Engine.

How to change the JDK for a Jenkins job?

Here is where you should configure in your job:

In JDK there is the combobox with the different JDK configured in your Jenkins. Job

Here is where you should configure in the config of your Jenkins:

Jenkins general config

call javascript function on hyperlink click

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

How to properly seed random number generator

just to toss it out for posterity: it can sometimes be preferable to generate a random string using an initial character set string. This is useful if the string is supposed to be entered manually by a human; excluding 0, O, 1, and l can help reduce user error.

var alpha = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"

// generates a random string of fixed size
func srand(size int) string {
    buf := make([]byte, size)
    for i := 0; i < size; i++ {
        buf[i] = alpha[rand.Intn(len(alpha))]
    }
    return string(buf)
}

and I typically set the seed inside of an init() block. They're documented here: http://golang.org/doc/effective_go.html#init

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r http://stackoverflow.com/

What is the default value for Guid?

You can use Guid.Empty. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000

you can also use these instead

var g = new Guid();
var g = default(Guid);

beware not to use Guid.NewGuid() because it will generate a new Guid.

use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty is the best one since new Guid() might make us think it is generating a new guid and some may not know what is the value of default(Guid).

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

Remove all line breaks from a long string of text

updated based on Xbello comment:

string = my_string.rstrip('\r\n')

read more here

Difference between dict.clear() and assigning {} in Python

One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:

def conf_decorator(dec):
    """Enables behavior like this:
        @threaded
        def f(): ...

        or

        @threaded(thread=KThread)
        def f(): ...

        (assuming threaded is wrapped with this function.)
        Sends any accumulated kwargs to threaded.
        """
    c_kwargs = {}
    @wraps(dec)
    def wrapped(f=None, **kwargs):
        if f:
            r = dec(f, **c_kwargs)
            c_kwargs = {}
            return r
        else:
            c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
            return wrapped
    return wrapped

The solution is to replace c_kwargs = {} with c_kwargs.clear()

If someone thinks up a more practical example, feel free to edit this post.

PostgreSQL error 'Could not connect to server: No such file or directory'

For me, this works

rm /usr/local/var/postgres/postmaster.pid

How to start color picker on Mac OS?

You can turn the color picker into an application by following the guide here:

http://hints.macworld.com/article.php?story=20060408050920158

From the guide:

Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:

choose color

Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

When to use RSpec let()?

I always prefer let to an instance variable for a couple of reasons:

  • Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to nil, which can lead to subtle bugs and false positives. Since let creates a method, you'll get a NameError when you misspell it, which I find preferable. It makes it easier to refactor specs, too.
  • A before(:each) hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let, the initialization code only runs if the example calls it.
  • You can refactor from a local variable in an example directly into a let without changing the referencing syntax in the example. If you refactor to an instance variable, you have to change how you reference the object in the example (e.g. add an @).
  • This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with let and keeping my it block nice and short.

A related link can be found here: http://www.betterspecs.org/#let

How to insert close button in popover for Bootstrap

    $('.tree span').each(function () {
        var $popOverThis = $(this);
        $popOverThis.popover({
            trigger: 'click',
            container: 'body',
            placement: 'right',
            title: $popOverThis.html() + '<button type="button" id="close" class="close" ">&times;</button>',
            html: true,
            content: $popOverThis.parent().children("div.chmurka").eq(0).html()
        }).on('shown.bs.popover', function (e) {
            var $element = $(this);
            $("#close").click(function () {
                $element.trigger("click");
            });
        });
    });

When you click element and show your popup, next you can raise event shown.bs.popover where in this you get element in which trigger click to close your popover.

ASP.NET strange compilation error

I resolved this by deleting the contents of the bin and obj folders for the project, and the contents of the bin folder on the remote server, then redeploying.

How do I include a pipe | in my linux find -exec command?

the solution is easy: execute via sh

... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;

Add multiple items to already initialized arraylist in java

Collections.addAll is a varargs method which allows us to add any number of items to a collection in a single statement:

List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);

It can also be used to add array elements to a collection:

Integer[] arr = ...;
Collections.addAll(list, arr);

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)

window.open('your current page URL', '_self', '');
window.close();

How to print a debug log?

If you are on Linux:

file_put_contents('your_log_file', 'your_content');

or

error_log ('your_content', 3, 'your_log_file');

and then in console

tail -f your_log_file

This will show continuously the last line put in the file.

How can I control the width of a label tag?

label {
  width:200px;
  display: inline-block;
}

OR 

label {
  width:200px;
  display: inline-flex;
}

OR 

label {
  width:200px;
  display: inline-table;
}

Java: JSON -> Protobuf & back conversion

Adding to Ophirs answer, JsonFormat is available even before protobuf 3.0. However, the way to do it differs a little bit.

In Protobuf 3.0+, the JsonFormat class is a singleton and therefore do something like the below

String jsonString = "";
JsonFormat.parser().ignoringUnknownFields().merge(jsonString,yourObjectBuilder);

In Protobuf 2.5+, the below should work

String jsonString = "";
JsonFormat jsonFormat = new JsonFormat();
jsonString = jsonFormat.printToString(yourProtobufMessage);

Here is a link to a tutorial I wrote that uses the JsonFormat class in a TypeAdapter that can be registered to a GsonBuilder object. You can then use Gson's toJson and fromJson methods to convert the proto data to Java and back.

Replying to jean . If we have the protobuf data in a file and want to parse it into a protobuf message object, use the merge method TextFormat class. See the below snippet:

// Let your proto text data be in a file MessageDataAsProto.prototxt
// Read it into string  
String protoDataAsString = FileUtils.readFileToString(new File("MessageDataAsProto.prototxt"));

// Create an object of the message builder
MyMessage.Builder myMsgBuilder = MyMessage.newBuilder();

// Use text format to parse the data into the message builder
TextFormat.merge(protoDataAsString, ExtensionRegistry.getEmptyRegistry(), myMsgBuilder);

// Build the message and return
return myMsgBuilder.build();

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Difference between onCreate() and onStart()?

Take a look on life cycle of Activity enter image description here

Where

***onCreate()***

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

***onStart()***

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

And you can write your simple class to take a look when these methods call

public class TestActivity extends Activity {
    /** Called when the activity is first created. */

    private final static String TAG = "TestActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i(TAG, "On Create .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onDestroy()
    */
    @Override
    protected void onDestroy() { 
        super.onDestroy();
        Log.i(TAG, "On Destroy .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onPause()
    */
    @Override
    protected void onPause() { 
        super.onPause();
        Log.i(TAG, "On Pause .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onRestart()
    */
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "On Restart .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onResume()
    */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "On Resume .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onStart()
    */
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "On Start .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onStop()
    */
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "On Stop .....");
    }
}

Hope this will clear your confusion.

And take a look here for details.

Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Just Add a primary key to the table. That's it. Problem solved.

ALTER TABLE <TABLE_NAME>
ADD CONSTRAINT <CONSTRAINT_NAME> PRIMARY KEY(<COLUMN_NAME>)

Automatically accept all SDK licences

WINDOWS SOLUTION

  • Open Terminal o Windows Power Shell

  • Go to Android SDK folder

Generally this folder can be find in C:\Users(your-windows-user)\AppData\Local\Android\Sdk\tools\bin

  • Begin in "....\Sdk" folder enter to \tools\bin

Finally path C:\Users(your-windows-user)\AppData\Local\Android\Sdk\tools\bin

  • Verify that sdkmanager.bat is in location using ls command

  • Excute the next command .\sdkmanager.bat --licenses

  • Then the terminal will show 7 documents, you need put yes In each one

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

How to create a readonly textbox in ASP.NET MVC3 Razor

 @Html.TextBox("Receivers", Model, new { @class = "form-control", style = "width: 300px", @readonly = "readonly" })

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

How to write a multidimensional array to a text file?

ndarray.tofile() should also work

e.g. if your array is called a:

a.tofile('yourfile.txt',sep=" ",format="%s")

Not sure how to get newline formatting though.

Edit (credit Kevin J. Black's comment here):

Since version 1.5.0, np.tofile() takes an optional parameter newline='\n' to allow multi-line output. https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html

How to search for file names in Visual Studio?

With Visual Studio 2017 Community edition on mac, the shortcut is:

  • Cmd+Shift+D: Find by file name
  • Cmd+Shift+T: Find by type name

To see these commands, navigate to the top menu: Search > Go To

How to ping a server only once from within a batch file?

Enter in a command prompt window ping /? and read the short help output after pressing RETURN. Or take a look on

  • Ping - Windows XP documentation
  • Ping - Microsoft TechNet article

Explanation for option -t given by Microsoft:

Pings the specified host until stopped. To see statistics and continue type Control-Break. To stop type Control-C.

You may want to use:

@%SystemRoot%\system32\ping.exe -n 1 www.google.de

Or to check first if a server is available:

@echo off
set MyServer=Server.MyDomain.de
%SystemRoot%\system32\ping.exe -n 1 %MyServer% >nul
if errorlevel 1 goto NoServer

echo %MyServer% is availabe.
rem Insert commands here, for example 1 or more net use to connect network drives.
goto :EOF

:NoServer
echo %MyServer% is not availabe yet.
pause
goto :EOF

How to draw in JPanel? (Swing/graphics Java)

Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to re-render flatlist?

Oh that's easy, just use extraData

You see the way extra data works behind the scenes is the FlatList or the VirtualisedList just checks wether that object has changed via a normal onComponentWillReceiveProps method.

So all you have to do is make sure you give something that changes to the extraData.

Here's what I do:

I'm using immutable.js so all I do is I pass a Map (immutable object) that contains whatever I want to watch.

<FlatList
    data={this.state.calendarMonths}
    extraData={Map({
        foo: this.props.foo,
        bar: this.props.bar
    })}
    renderItem={({ item })=>((
        <CustomComponentRow
            item={item}
            foo={this.props.foo}
            bar={this.props.bar}
        />
    ))}
/>

In that way, when this.props.foo or this.props.bar change, our CustomComponentRow will update, because the immutable object will be a different one than the previous.

Factorial using Recursion in Java

public class Factorial {

    public static void main(String[] args) {
        System.out.println(factorial(4));
    }

    private static long factorial(int i) {

        if(i<0)  throw new IllegalArgumentException("x must be >= 0"); 
        return i==0||i==1? 1:i*factorial(i-1);
    }
}

SQL query return data from multiple tables

Part 3 - Tricks and Efficient Code

MySQL in() efficiency

I thought I would add some extra bits, for tips and tricks that have come up.

One question I see come up a fair bit, is How do I get non-matching rows from two tables and I see the answer most commonly accepted as something like the following (based on our cars and brands table - which has Holden listed as a brand, but does not appear in the cars table):

select
    a.ID,
    a.brand
from
    brands a
where
    a.ID not in(select brand from cars)

And yes it will work.

+----+--------+
| ID | brand  |
+----+--------+
|  6 | Holden |
+----+--------+
1 row in set (0.00 sec)

However it is not efficient in some database. Here is a link to a Stack Overflow question asking about it, and here is an excellent in depth article if you want to get into the nitty gritty.

The short answer is, if the optimiser doesn't handle it efficiently, it may be much better to use a query like the following to get non matched rows:

select
    a.brand
from
    brands a
        left join cars b
            on a.id=b.brand
where
    b.brand is null

+--------+
| brand  |
+--------+
| Holden |
+--------+
1 row in set (0.00 sec)

Update Table with same table in subquery

Ahhh, another oldie but goodie - the old You can't specify target table 'brands' for update in FROM clause.

MySQL will not allow you to run an update... query with a subselect on the same table. Now, you might be thinking, why not just slap it into the where clause right? But what if you want to update only the row with the max() date amoung a bunch of other rows? You can't exactly do that in a where clause.

update 
    brands 
set 
    brand='Holden' 
where 
    id=
        (select 
            id 
        from 
            brands 
        where 
            id=6);
ERROR 1093 (HY000): You can't specify target table 'brands' 
for update in FROM clause

So, we can't do that eh? Well, not exactly. There is a sneaky workaround that a surprisingly large number of users don't know about - though it does include some hackery that you will need to pay attention to.

You can stick the subquery within another subquery, which puts enough of a gap between the two queries so that it will work. However, note that it might be safest to stick the query within a transaction - this will prevent any other changes being made to the tables while the query is running.

update 
    brands 
set 
    brand='Holden' 
where id=
    (select 
        id 
    from 
        (select 
            id 
        from 
            brands 
        where 
            id=6
        ) 
    as updateTable);

Query OK, 0 rows affected (0.02 sec)
Rows matched: 1  Changed: 0  Warnings: 0

How to set column header text for specific column in Datagridview C#

Dg_View.Columns.Add("userid","User Id");
Dg_View.Columns[0].Width = 100;

Dg_View.Columns.Add("username", "User name");
Dg_View.Columns[0].Width = 100;

How to build minified and uncompressed bundle with webpack?

You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

Commenting multiple lines in DOS batch file

break||(
 code that cannot contain non paired closing bracket
)

While the goto solution is a good option it will not work within brackets (including FOR and IF commands).But this will. Though you should be careful about closing brackets and invalid syntax for FOR and IF commands because they will be parsed.

Update

The update in the dbenham's answer gave me some ideas. First - there are two different cases where we can need multi line comments - in a bracket's context where GOTO cannot be used and outside it. Inside brackets context we can use another brackets if there's a condition which prevents the code to be executed.Though the code thede will still be parsed and some syntax errors will be detected (FOR,IF ,improperly closed brackets, wrong parameter expansion ..).So if it is possible it's better to use GOTO.

Though it is not possible to create a macro/variable used as a label - but is possible to use macros for bracket's comments.Still two tricks can be used make the GOTO comments more symetrical and more pleasing (at least for me). For this I'll use two tricks - 1) you can put a single symbol in front of a label and goto will still able to find it (I have no idea why is this.My guues it is searching for a drive). 2) you can put a single : at the end of a variable name and a replacement/subtring feature will be not triggered (even under enabled extensions). Wich combined with the macros for brackets comments can make the both cases to look almost the same.

So here are the examples (in the order I like them most):

With rectangular brackets:

@echo off

::GOTO comment macro
set "[:=goto :]%%"
::brackets comment macros
set "[=rem/||(" & set "]=)"

::testing
echo not commented 1

%[:%
  multi 
  line
  comment outside of brackets
%:]%

echo not commented 2

%[:%
  second multi 
  line
  comment outside of brackets
%:]%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %[%
        multi line
        comment
    %]%
    echo second not commented line of the %%a execution
)

With curly brackets:

@echo off

::GOTO comment macro
set "{:=goto :}%%"
::brackets comment macros
set "{=rem/||(" & set "}=)"

::testing
echo not commented 1

%{:%
  multi 
  line
  comment outside of brackets
%:}%

echo not commented 2

%{:%
  second multi 
  line
  comment outside of brackets
%:}%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %{%
        multi line
        comment
    %}%
    echo second not commented line of the %%a execution
)

With parentheses:

@echo off

::GOTO comment macro
set "(:=goto :)%%"
::brackets comment macros
set "(=rem/||(" & set ")=)"

::testing
echo not commented 1

%(:%
  multi 
  line
  comment outside of brackets
%:)%

echo not commented 2

%(:%
  second multi 
  line
  comment outside of brackets
%:)%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %(%
        multi line
        comment
    %)%
    echo second not commented line of the %%a execution
)

Mixture between powershell and C styles (< cannot be used because the redirection is with higher prio.* cannot be used because of the %*) :

@echo off

::GOTO comment macro
set "/#:=goto :#/%%"
::brackets comment macros
set "/#=rem/||(" & set "#/=)"

::testing
echo not commented 1

%/#:%
  multi 
  line
  comment outside of brackets
%:#/%

echo not commented 2

%/#:%
  second multi 
  line
  comment outside of brackets
%:#/%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %/#%
        multi line
        comment
    %#/%
    echo second not commented line of the %%a execution
)

To emphase that's a comment (thought it is not so short):

@echo off

::GOTO comment macro
set "REM{:=goto :}REM%%"
::brackets comment macros
set "REM{=rem/||(" & set "}REM=)"

::testing
echo not commented 1

%REM{:%
  multi 
  line
  comment outside of brackets
%:}REM%

echo not commented 2

%REM{:%
  second multi 
  line
  comment outside of brackets
%:}REM%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %REM{%
        multi line
        comment
    %}REM%
    echo second not commented line of the %%a execution
)

Android Bitmap to Base64 String

Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.

import java.io.ByteArrayOutputStream

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }

SELECTING with multiple WHERE conditions on same column

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

Declare Variable for a Query String

DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'

Then change your query to use this logic:

AND 
(
    tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate) 
    AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)

CSS Child vs Descendant selectors

CSS selection and applying style to a particular element can be done through traversing through the dom element [Example

Example

.a .b .c .d{
    background: #bdbdbd;
}
div>div>div>div:last-child{
    background: red;
}
<div class='a'>The first paragraph.
 <div class='b'>The second paragraph.
  <div class='c'>The third paragraph.
   <div class='d'>The fourth paragraph.</div>
   <div class='e'>The fourth paragraph.</div>
  </div>
 </div>
</div>

Creating a UITableView Programmatically

sample table

 #import "StartreserveViewController.h"
 #import "CollectionViewController.h"
 #import "TableViewCell1.h"
@interface StartreserveViewController ()


{
NSArray *name;
NSArray *images;
NSInteger selectindex;

}

@end

@implementation StartreserveViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor blueColor];
_startReservetable.backgroundColor = [UIColor blueColor];


name = [[NSArray alloc]initWithObjects:@"Mobiles",@"Costumes",@"Shoes", 
nil];
images = [[NSArray 
 alloc]initWithObjects:@"mobilestitle.jpg",@"costumetitle.jpeg", 
 @"shoestitle.png",nil];



  }

 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

pragma mark - UiTableview Datasource

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;
 }

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
 (NSInteger)section
 {
return 3;
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView 
  cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {


static NSString *cellId = @"tableview";

TableViewCell1  *cell =[tableView dequeueReusableCellWithIdentifier:cellId];


cell.cellTxt .text = [name objectAtIndex:indexPath.row];

cell.cellImg.image = [UIImage imageNamed:[images 
objectAtIndex:indexPath.row]];

return cell;



 }


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
 {
selectindex = indexPath.row;
[self performSegueWithIdentifier:@"second" sender:self];
}



   #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little     
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([segue.identifier isEqualToString:@"second"])

  {
    CollectionViewController *obj = segue.destinationViewController;
           obj.receivename = [name objectAtIndex:selectindex];

  }



// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}

 @end

.h

#import <UIKit/UIKit.h>

@interface StartreserveViewController :      
UIViewController<UITableViewDelegate,UITableViewDataSource>    
@property (strong, nonatomic) IBOutlet UITableView *startReservetable;

 @end

Difference between hamiltonian path and euler path

A Hamiltonian path visits every node (or vertex) exactly once, and a Eulerian path traverses every edge exactly once.

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

Solution for UBUNTU Worked for me:

Installed tesseract in ubuntu by following below link

https://medium.com/quantrium-tech/installing-tesseract-4-on-ubuntu-18-04-b6fcd0cbd78f

Later added traindata language to tessdata by following below link

Tesseract running error

How to link to apps on the app store

I can confirm that if you create an app in iTunes connect you get your app id before you submit it.

Therefore..

itms-apps://itunes.apple.com/app/id123456789

NSURL *appStoreURL = [NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id123456789"];
    if ([[UIApplication sharedApplication]canOpenURL:appStoreURL])
        [[UIApplication sharedApplication]openURL:appStoreURL];

Works a treat

How to determine the content size of a UIWebView?

I'm using a UIWebView that isn't a subview (and thus isn't part of the window hierarchy) to determine the sizes of HTML content for UITableViewCells. I found that the disconnected UIWebView doesn't report its size properly with -[UIWebView sizeThatFits:]. Additionally, as mentioned in https://stackoverflow.com/a/3937599/9636, you must set the UIWebView's frame height to 1 in order to get the proper height at all.

If the UIWebView's height is too big (i.e. you have it set to 1000, but the HTML content size is only 500):

UIWebView.scrollView.contentSize.height
-[UIWebView stringByEvaluatingJavaScriptFromString:@"document.height"]
-[UIWebView sizeThatFits:]

All return a height of 1000.

To solve my problem in this case, I used https://stackoverflow.com/a/11770883/9636, which I dutifully voted up. However, I only use this solution when my UIWebView.frame.width is the same as the -[UIWebView sizeThatFits:] width.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

How to refresh a Page using react-route Link

You can use this

<a onClick={() => {window.location.href="/something"}}>Something</a>

jQuery: get the file name selected from <input type="file" />

I had used following which worked correctly.

$('#fileAttached').attr('value', $('#attachment').val())

Logo image and H1 heading on the same line

Steps:

  1. Surround both the elements with a container div.
  2. Add overflow:auto to container div.
  3. Add float:left to the first element.
  4. Add position:relative; top: 0.2em; left: 24em to the second element (Top and left values can vary according to you).

Does Python's time.time() return the local or UTC timestamp?

There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

@brennanyoung's answer is great, but if you're wondering what to do in the failure case you could use an IP geolocation API such as https://ipinfo.io (which is my service). Here's an example:

function do_something(coords) {
    // Do something with the coords here
    // eg. show the user on a map, or customize
    // the site contents somehow
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

See https://ipinfo.io/developers/replacing-getcurrentposition for more details.

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

"Application tried to present modally an active controller"?

I have the same problem. I try to present view controller just after dismissing.

[self dismissModalViewControllerAnimated:YES];

When I try to do it without animation it works perfectly so the problem is that controller is still alive. I think that the best solution is to use dismissViewControllerAnimated:completion: for iOS5

iPhone 5 CSS media query

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

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

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

(Disclaimer: This is my website)

Is there a java setting for disabling certificate validation?

On my Mac that I'm sure I'm not going to allow java anyplace other than a specific site, I was able to use Preferences->Java to bring up the Java control panel and turned the checking off. If DLink ever fixes their certificate, I'll turn it back on.

Java control panel - Advanced

Refresh a page using JavaScript or HTML

Use:

window.location.reload();

Java abstract interface

It's not necessary, it's optional, just as public on interface methods.

See the JLS on this:

http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html

9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

And

9.4 Abstract Method Declarations

[...]

For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

What is Cache-Control: private?

To answer your question about why caching is working, even though the web-server didn't include the headers:

  • Expires: [a date]
  • Cache-Control: max-age=[seconds]

The server kindly asked any intermediate proxies to not cache the contents (i.e. the item should only be cached in a private cache, i.e. only on your own local machine):

  • Cache-Control: private

But the server forgot to include any sort of caching hints:

  • they forgot to include Expires, so the browser knows to use the cached copy until that date
  • they forgot to include Max-Age, so the browser knows how long the cached item is good for
  • they forgot to include E-Tag, so the browser can do a conditional request

But they did include a Last-Modified date in the response:

Last-Modified: Tue, 16 Oct 2012 03:13:38 GMT

Because the browser knows the date the file was modified, it can perform a conditional request. It will ask the server for the file, but instruct the server to only send the file if it has been modified since 2012/10/16 3:13:38:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

The server receives the request, realizes that the client has the most recent version already. Rather than sending the client 200 OK, followed by the contents of the page, instead it tells you that your cached version is good:

304 Not Modified

Your browser did have to suffer the delay of sending a request to the server, and wait for a response, but it did save having to re-download the static content.

Why Max-Age? Why Expires?

Because Last-Modified sucks.

Not everything on the server has a date associated with it. If I'm building a page on the fly, there is no date associated with it - it's now. But I'm perfectly willing to let the user cache the homepage for 15 seconds:

200 OK
Cache-Control: max-age=15

If the user hammers F5, they'll keep getting the cached version for 15 seconds. If it's a corporate proxy, then all 67198 users hitting the same page in the same 15-second window will all get the same contents - all served from close cache. Performance win for everyone.

The virtue of adding Cache-Control: max-age is that the browser doesn't even have to perform a conditional request.

  • if you specified only Last-Modified, the browser has to perform a request If-Modified-Since, and watch for a 304 Not Modified response
  • if you specified max-age, the browser won't even have to suffer the network round-trip; the content will come right out of the caches

The difference between "Cache-Control: max-age" and "Expires"

Expires is a legacy equivalent of the modern (c. 1998) Cache-Control: max-age header:

  • Expires: you specify a date (yuck)
  • max-age: you specify seconds (goodness)
  • And if both are specified, then the browser uses max-age:

    200 OK
    Cache-Control: max-age=60
    Expires: 20180403T192837 
    

Any web-site written after 1998 should not use Expires anymore, and instead use max-age.

What is ETag?

ETag is similar to Last-Modified, except that it doesn't have to be a date - it just has to be a something.

If I'm pulling a list of products out of a database, the server can send the last rowversion as an ETag, rather than a date:

200 OK
ETag: "247986"

My ETag can be the SHA1 hash of a static resource (e.g. image, js, css, font), or of the cached rendered page (i.e. this is what the Mozilla MDN wiki does; they hash the final markup):

200 OK
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

And exactly like in the case of a conditional request based on Last-Modified:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

304 Not Modified

I can perform a conditional request based on the ETag:

GET / HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

304 Not Modified

An ETag is superior to Last-Modified because it works for things besides files, or things that have a notion of date. It just is

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.


<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.


 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.


 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.


See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

    <element
      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1
      >
    
    </element>
    

Filter values only if not null using lambda in Java8

The proposed answers are great. Just would like to suggest an improvement to handle the case of null list using Optional.ofNullable, new feature in Java 8:

 List<String> carsFiltered = Optional.ofNullable(cars)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

So, the full answer will be:

 List<String> carsFiltered = Optional.ofNullable(cars)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull) //filtering car object that are null
                .map(Car::getName) //now it's a stream of Strings
                .filter(Objects::nonNull) //filtering null in Strings
                .filter(name -> name.startsWith("M"))
                .collect(Collectors.toList()); //back to List of Strings

How can I format bytes a cell in Excel as KB, MB, GB etc?

I use CDH hadoop and when I export excel report, I have two problems;

1) convert Linux date to excel date,
For that, add an empty column next to date column lets say the top row is B4, paste below formula and drag the BLACK "+" all the way to your last day at the end of the column. Then hide the original column

=(((B4/1000/60)/60)/24)+DATE(1970|1|1)+(-5/24)

2) Convert disk size from byte to TB, GB, and MB
the best formula for that is this

[>999999999999]# ##0.000,,,," TB";[>999999999]# ##0.000,,," GB";# ##0.000,," MB"

it will give you values with 3 decimals just format cells --> Custom and paste the above code there

Could not connect to React Native development server on Android

Default metro builder runs on port 8081. But in my PC, this port is already occupied by some other process (McAfee Antivirus) So I changed the default running port of metro builder to port number 8088 using the following command

react-native run-android start --port=8088

This resolved my issue and the app works fine now.

PS: You can check whether a port is occupied or not in windows using "Resource Monitor" app. (Under "Listening Ports" in "Network" tab). Check out this link for detailed explanation: https://www.paddingleft.com/2018/05/03/Find-process-listening-port-on-Windows/

How to add a new line of text to an existing file in Java?

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

Details about these methods can be found in the Oracle's tutorial.

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

Static class initializer in PHP

Note - the RFC proposing this is still in the draft state.


class Singleton
{
    private static function __static()
    {
        //...
    }
    //...
}

proposed for PHP 7.x (see https://wiki.php.net/rfc/static_class_constructor )

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

I resolved it by replacing Tomcat 8.5.* with Tomcat 7.0.* version.

jquery if div id has children

There's actually quite a simple native method for this:

if( $('#myfav')[0].hasChildNodes() ) { ... }

Note that this also includes simple text nodes, so it will be true for a <div>text</div>.

How can I generate a tsconfig.json file?

I recommend to uninstall typescript first with the command:

npm uninstall -g typescript

then use the chocolatey package in order to run:

choco install typescript

in PowerShell.

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

How to get the selected index of a RadioGroup in Android

//use to get the id of selected item

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//get the view of the selected item

View selectedView = (View)findViewById( selectedID);

Create mysql table directly from CSV file using the CSV Storage engine?

I have made a Windows command line tool that do just that.

You can download it here: http://commandline.dk/csv2ddl.htm

Usage:

C:\Temp>csv2ddl.exe mysql test.csv test.sql

Or

C:\Temp>csv2ddl.exe mysql advanced doublequote comma test.csv test.sql

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

Truncate all tables in a MySQL database in one command?

The following MySQL query will itself produce a single query that will truncate all tables in a given database. It bypasses FOREIGN keys:

SELECT CONCAT(
         'SET FOREIGN_KEY_CHECKS=0; ',
         GROUP_CONCAT(dropTableSql SEPARATOR '; '), '; ',
         'SET FOREIGN_KEY_CHECKS=1;'
       ) as dropAllTablesSql
FROM   ( SELECT  Concat('TRUNCATE TABLE ', table_schema, '.', TABLE_NAME) AS dropTableSql
         FROM    INFORMATION_SCHEMA.TABLES
         WHERE   table_schema = 'DATABASE_NAME' ) as queries

Output single character in C

As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.

What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.

Using printf is like using a machine gun to fire one bullet.

Event detect when css property changed using Jquery

For properties for which css transition will affect, can use transitionend event, example for z-index:

_x000D_
_x000D_
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
  console.log("end", e);_x000D_
  alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
  console.log("click");_x000D_
  document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
  transition: z-index 1ms;_x000D_
  -webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
  position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
_x000D_
_x000D_

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

No appenders could be found for logger(log4j)?

Log4J display this warning message when Log4j Java code is searching to create a first log line in your program.

At this moment, Log4j make 2 things

  1. it search to find log4j.properties file
  2. it search to instantiate the appender define in log4j.properties

If log4J doesn't find log4j.properties file or if appender declared in log4j.rootlogger are not defined elsewhere in log4j.properties file the warning message is displayed.

CAUTION: the content of Properties file must be correct.

The following content is NOT correct

log4j.rootLogger=file

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=c:/Trace/MsgStackLogging.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%m%n
log4j.appender.FILE.ImmediateFlush=true
log4j.appender.FILE.Threshold=debug
log4j.appender.FILE.Append=false

because file appender is declared in LOWER-CASE in log4j.rootlogger statement and defined in log4j.appender statement using UPPER-CASE !

A correct file would be

log4j.rootLogger=FILE

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=c:/Trace/MsgStackLogging.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%m%n
log4j.appender.FILE.ImmediateFlush=true
log4j.appender.FILE.Threshold=debug
log4j.appender.FILE.Append=false

If MAVEN is used, you must put log4j.properties files in src/main/resources AND start a MAVEN build.

Log4j.properties file is then copied in target/classes folder.

Log4J use the log4j.properties file that it found in target/classes !

sed: print only matching group

I agree with @kent that this is well suited for grep -o. If you need to extract a group within a pattern, you can do it with a 2nd grep.

# To extract \1 from /xx([0-9]+)yy/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'xx[0-9]+yy' | grep -Eo '[0-9]+'
123
4

# To extract \1 from /a([0-9]+)b/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'a[0-9]+b' | grep -Eo '[0-9]+'
678
9

I generally cringe when I see 2 calls to grep/sed/awk piped together, but it's not always wrong. While we should exercise our skills of doing things efficiently, "A foolish consistency is the hobgoblin of little minds", and "Real artists ship".

How often does python flush to a file?

Here is another approach, up to the OP to choose which one he prefers.

When including the code below in the __init__.py file before any other code, messages printed with print and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:

import sys

path = "/Users/#username#"

errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog

(for Mac, change #username# to the name of your user folder. On Windows the path to your user folder will have a different format)

When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.

Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Is there 'byte' data type in C++?

No, but since C++11 there is [u]int8_t.

Spring Data JPA and Exists query

in my case it didn't work like following

@Query("select count(e)>0 from MyEntity e where ...")

You can return it as boolean value with following

@Query(value = "SELECT CASE  WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")

Assembly Language - How to do Modulo?

An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.

https://godbolt.org/z/64zKGr

Checking for a null int value from a Java ResultSet

You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database

private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
    try {
        Integer value = rset.getInt(columnName);
        return rset.wasNull() ? null : value;
    } catch (Exception e) {
        return null;
    }
}

How to add http:// if it doesn't exist in the URL

Try this. It is not watertight1, but it might be good enough:

function addhttp($url) {
    if (!preg_match("@^[hf]tt?ps?://@", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

1. That is, prefixes like "fttps://" are treated as valid.

What is this CSS selector? [class*="span"]

It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.

I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.

It just helps to apply blanket CSS rules.

Is there a method for String conversion to Title Case?

This should work:

String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
    Character oldchar=str1.charAt(0);
    Character newchar=Character.toUpperCase(str1.charAt(0));
    strNew=strNew+str1.replace(oldchar,newchar)+" ";    
}
System.out.println(strNew);

How to change a TextView's style at runtime

Like Jonathan suggested, using textView.setTextTypeface works, I just used it in an app a few seconds ago.

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

How to remove numbers from string using Regex.Replace?

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Opening port 80 EC2 Amazon web services

For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.

See here on how to completely disable it (for testing purposes only!). And here for specific rules

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

How to read specific lines from a file (by line number)?

with open("test.txt", "r") as fp:
lines = fp.readlines()
print(lines[3])

test.txt is filename prints line number four in test.txt

How to create a directory if it doesn't exist using Node.js?

One Line Solution: Creates directory if NOT exist

// import
const fs = require('fs')  // in javascript
import * as fs from "fs"  // in typescript
import fs from "fs"       // in typescript

// use
!fs.existsSync(`./assets/`) && fs.mkdirSync(`./assets/`, { recursive: true })

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

How to communicate between Docker containers via "hostname"

The new networking feature allows you to connect to containers by their name, so if you create a new network, any container connected to that network can reach other containers by their name. Example:

1) Create new network

$ docker network create <network-name>       

2) Connect containers to network

$ docker run --net=<network-name> ...

or

$ docker network connect <network-name> <container-name>

3) Ping container by name

docker exec -ti <container-name-A> ping <container-name-B> 

64 bytes from c1 (172.18.0.4): icmp_seq=1 ttl=64 time=0.137 ms
64 bytes from c1 (172.18.0.4): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from c1 (172.18.0.4): icmp_seq=3 ttl=64 time=0.074 ms
64 bytes from c1 (172.18.0.4): icmp_seq=4 ttl=64 time=0.074 ms

See this section of the documentation;

Note: Unlike legacy links the new networking will not create environment variables, nor share environment variables with other containers.

This feature currently doesn't support aliases

How to open a folder in Windows Explorer from VBA?

Here's an answer that gives the switch-or-launch behaviour of Start, without the Command Prompt window. It does have the drawback that it can be fooled by an Explorer window that has a folder of the same name elsewhere opened. I might fix that by diving into the child windows and looking for the actual path, I need to figure out how to navigate that.

Usage (requires "Windows Script Host Object Model" in your project's References):

Dim mShell As wshShell

mDocPath = whatever_path & "\" & lastfoldername
mExplorerPath = mShell.ExpandEnvironmentStrings("%SystemRoot%") & "\Explorer.exe"

If Not SwitchToFolder(lastfoldername) Then
    Shell PathName:=mExplorerPath & " """ & mDocPath & """", WindowStyle:=vbNormalFocus
End If

Module:

Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal lngHWnd As Long) As Long

Function SwitchToFolder(pFolder As String) As Boolean

Dim hWnd As Long
Dim mRet As Long
Dim mText As String
Dim mWinClass As String
Dim mWinTitle As String

    SwitchToFolder = False

    hWnd = FindWindowEx(0, 0&, vbNullString, vbNullString)
    While hWnd <> 0 And SwitchToFolder = False
        mText = String(100, Chr(0))
        mRet = GetClassName(hWnd, mText, 100)
        mWinClass = Left(mText, mRet)
        If mWinClass = "CabinetWClass" Then
            mText = String(100, Chr(0))
            mRet = GetWindowText(hWnd, mText, 100)
            If mRet > 0 Then
                mWinTitle = Left(mText, mRet)
                If UCase(mWinTitle) = UCase(pFolder) Or _
                   UCase(Right(mWinTitle, Len(pFolder) + 1)) = "\" & UCase(pFolder) Then
                    BringWindowToTop hWnd
                    SwitchToFolder = True
                End If
            End If
        End If
        hWnd = FindWindowEx(0, hWnd, vbNullString, vbNullString)
    Wend

End Function

Execute jar file with multiple classpath libraries from command prompt

I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin

What is the best way to iterate over a dictionary?

The best answer is of course: Don´t use exact a dictionary if you plan to iterate over it- as Vikas Gupta mentioned already in the discussion under the question. But that discussion as this whole thread still lacks surprisingly good alternatives. One is:

SortedList<string, string> x = new SortedList<string, string>();

x.Add("key1", "value1");
x.Add("key2", "value2");
x["key3"] = "value3";
foreach( KeyValuePair<string, string> kvPair in x )
            Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");

Why a lot of people consider it a code smell of iterating over a dictionary (e.g. by foreach(KeyValuePair<,>): It is quite surprising, but there is a little cited, but basic principle of Clean Coding: "Express intent!" Robert C. Martin writes in "Clean Code": "Choosing names that reveal intent". Obviously this is too weak. "Express (reveal) intent with every coding decision" would be better. My wording. I am lacking a good first source but I am sure there are... A related principle is "Principle of least surprise" (=Principle of Least Astonishment).

Why this is related to iterating over a dictionary? Choosing a dictionary expresses the intent of choosing a data structure which was made for finding data by key. Nowadays there are so much alternatives in .NET, if you want to iterate through key/value pairs that you don´t need this crutch.

Moreover: If you iterate over something, you have to reveal something about how the items are (to be) ordered and expected to be ordered! AFAIK, Dictionary has no specification about ordering (implementation-specific conventions only). What are the alternatives?

TLDR:
SortedList: If your collection is not getting too large, a simple solution would be to use SortedList<,> which gives you also full indexing of key/value pairs.

Microsoft has a long article about mentioning and explaining fitting collections:
Keyed collection

To mention the most important: KeyedCollection<,> and SortedDictionary<,> . SortedDictionary<,> is a bit faster than SortedList for oly inserting if it gets large, but lacks indexing and is needed only if O(log n) for inserting is preferenced over other operations. If you really need O(1) for inserting and accept slower iterating in exchange, you have to stay with simple Dictionary<,>. Obviously there is no data structure which is the fastest for every possible operation..

Additionally there is ImmutableSortedDictionary<,>.

And if one data structure is not exactly what you need, then derivate from Dictionary<,> or even from the new ConcurrentDictionary<,> and add explicit iteration/sorting functions!

Ubuntu: OpenJDK 8 - Unable to locate package

I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:

sudo apt-get install debian-keyring debian-archive-keyring

Make /etc/apt/sources.list.d/debian-jessie-backports.list:

deb http://httpredir.debian.org/debian/ jessie-backports main

Make /etc/apt/preferences.d/debian-jessie-backports:

Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200

Then finally do the install:

sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk

Google Maps JS API v3 - Simple Multiple Marker Example

Asynchronous version :

<script type="text/javascript">
  function initialize() {
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;
  </script>

How to modify the nodejs request default timeout time?

I'm assuming you're using express, given the logs you have in your question. The key is to set the timeout property on server (the following sets the timeout to one second, use whatever value you want):

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:

var http = require('http');
var server = http.createServer(function (req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 200);
}).listen(1337, '127.0.0.1');

server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');

ExecuteNonQuery: Connection property has not been initialized.

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

No provider for HttpClient

I had same issue. After browsing and struggling with issue found the below solution

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

imports: [
  HttpModule,
  HttpClientModule
]

Import HttpModule and HttpClientModule in app.module.ts and add into the imports like mentioned above.

Visualizing decision tree in scikit-learn

If you run into issues with grabbing the source .dot directly you can also use Source.from_file like this:

from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')

Run AVD Emulator without Android Studio

You can make a batch file, that will open your emulator directly without opening Android Studio. If you are using Windows:

  • Open Notepad

  • New file

  • Copy the next lines into your file:

     cd /d C:\Users\%username%\AppData\Local\Android\sdk\tools
     emulator @[YOUR_EMULATOR_DEVICE_NAME]
    

    Notes:

  • Replace [YOUR_EMULATOR_DEVICE_NAME] with the device name you created in emulator

  • To get the device name go to: C:\Users\%username%\AppData\Local\Android\sdk\tools

  • Run cmd and type: emulator -list-avds

  • Copy the device name and paste it in the batch file

  • Save the file as emulator.bat and close

  • Now double click on emulator.bat and you got the emulator running!

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

Function ereg_replace() is deprecated - How to clear this bug?

http://php.net/ereg_replace says:

Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.

Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.

Difference between JSON.stringify and JSON.parse

They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

How do I turn a C# object into a JSON string in .NET?

Use the below code for converting XML to JSON.

var json = new JavaScriptSerializer().Serialize(obj);

The request was aborted: Could not create SSL/TLS secure channel

The root of this exception in my case was that at some point in code the following was being called:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).

In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:

  • This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
  • The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
  • If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)

Trying to include a library, but keep getting 'undefined reference to' messages

Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:

gcc -static -L/usr/lib -I/usr/lib main.c -ltommath

How do you keep parents of floated elements from collapsing?

add this in the parent div at the bottom

 <div style="clear:both"></div>

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

How to convert index of a pandas dataframe into a column?

either:

df['index1'] = df.index

or, .reset_index:

df.reset_index(level=0, inplace=True)

so, if you have a multi-index frame with 3 levels of index, like:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303

How to set environment variables in Jenkins?

Try Environment Script Plugin (GitHub) which is very similar to EnvInject. It allows you to run a script before the build (after SCM checkout) that generates environment variables for it. E.g.

Jenkins Build - Regular job - Build Environment

and in your script, you can print e.g. FOO=bar to the standard output to set that variable.

Example to append to an existing PATH-style variable:

echo PATH+unique_identifier=/usr/local/bin

So you're free to do whatever you need in the script - either cat a file, or run a script in some other language from your project's source tree, etc.

Group by multiple field names in java 8

The groupingBy method has the first parameter is Function<T,K> where:

@param <T> the type of the input elements

@param <K> the type of the keys

If we replace lambda with the anonymous class in your code, we can see some kind of that:

people.stream().collect(Collectors.groupingBy(new Function<Person, int>() {
            @Override
            public int apply(Person person) {
                return person.getAge();
            }
        }));

Just now change output parameter<K>. In this case, for example, I used a pair class from org.apache.commons.lang3.tuple for grouping by name and age, but you may create your own class for filtering groups as you need.

people.stream().collect(Collectors.groupingBy(new Function<Person, Pair<Integer, String>>() {
                @Override
                public YourFilter apply(Person person) {
                    return Pair.of(person.getAge(), person.getName());
                }
            }));

Finally, after replacing with lambda back, code looks like that:

Map<Pair<Integer,String>, List<Person>> peopleByAgeAndName = people.collect(Collectors.groupingBy(p -> Pair.of(person.getAge(), person.getName()), Collectors.mapping((Person p) -> p, toList())));

Secure hash and salt for PHP passwords

Google says SHA256 is available to PHP.

You should definitely use a salt. I'd recommend using random bytes (and not restrict yourself to characters and numbers). As usually, the longer you choose, the safer, slower it gets. 64 bytes ought to be fine, i guess.

How Does Modulus Divison Work

The result of a modulo division is the remainder of an integer division of the given numbers.

That means:

27 / 16 = 1, remainder 11
=> 27 mod 16 = 11

Other examples:

30 / 3 = 10, remainder 0
=> 30 mod 3 = 0

35 / 3 = 11, remainder 2
=> 35 mod 3 = 2

How to scan multiple paths using the @ComponentScan annotation?

There is another type-safe alternative to specifying a base-package location as a String. See the API here, but I've also illustrated below:

@ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})

Using the basePackageClasses specifier with your class references will tell Spring to scan those packages (just like the mentioned alternatives), but this method is both type-safe and adds IDE support for future refactoring -- a huge plus in my book.

Reading from the API, Spring suggests creating a no-op marker class or interface in each package you wish to scan that serves no other purpose than to be used as a reference for/by this attribute.

IMO, I don't like the marker-classes (but then again, they are pretty much just like the package-info classes) but the type safety, IDE support, and drastically reducing the number of base packages needed to include for this scan is, with out a doubt, a far better option.

Convert java.util.date default format to Timestamp in Java

java.time

I am providing the modern answer. The Timestamp class was always poorly designed, a real hack on top of the already poorly designed Date class. Both those classes are now long outdated. Don’t use them.

When the question was asked, you would need a Timestamp for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone (recommended for true timestamps), pass it an OffsetDateTime.

Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013: the time zone abbreviation. IST may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("EEE MMM dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
            .appendPattern(" yyyy")
            .toFormatter(Locale.ROOT);
    String dateString = "Mon May 27 11:46:15 IST 2013";
    OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
            .atOffset(ZoneOffset.UTC);
    System.out.println(dateTime);

This snippet prints:

2013-05-27T06:16:15Z

This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime to your database using one of the PreparedStatement.setObject methods (not setTimestamp).

How can I convert this into timestamp and calculate in seconds the difference between the same and current time?

Calculating the difference in seconds goes very naturally with java.time:

    long differenceInSeconds = ChronoUnit.SECONDS
            .between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
    System.out.println(differenceInSeconds);

When running just now I got:

202213260

Link: Oracle tutorial: Date Time explaining how to use java.time.

Strip HTML from Text JavaScript

I made some modifications to original Jibberboy2000 script Hope it'll be usefull for someone

str = '**ANY HTML CONTENT HERE**';

str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");

Update statement with inner join on Oracle

Just as a matter of completeness, and because we're talking Oracle, this could do it as well:

declare
begin
  for sel in (
    select table2.code, table2.desc
    from table1
    join table2 on table1.value = table2.desc
    where table1.updatetype = 'blah'
  ) loop
    update table1 
    set table1.value = sel.code
    where table1.updatetype = 'blah' and table1.value = sel.desc;    
  end loop;
end;
/

Transparent scrollbar with css

With pure css it is not possible to make it transparent. You have to use transparent background image like this:

::-webkit-scrollbar-track-piece:start {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

::-webkit-scrollbar-track-piece:end {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

RegExp matching string not starting with my

You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:

^(.?$|[^m].+|m[^y].*)

This matches strings that are either zero or one characters long (^.?$) and thus can not be my. Or strings with two or more characters where when the first character is not an m any more characters may follow (^[^m].+); or if the first character is a m it must not be followed by a y (^m[^y]).

What is the '.well' equivalent class in Bootstrap 4

I'm mading my classes well for class alert, for me it looks like it's getting nice, but some tweaks are sometimes needed as to put the width 100%

<div class="alert alert-light" style="width:100%;">
  <strong>Heads up!</strong> This <a href="#" class="alert-link">alert needs your attention</a>, but it's not super important.
</div>

URL Encode a string in jQuery for an AJAX request

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)

Hardcoded URL i.e.>

 var encodedName = encodeURIComponent(name);
 var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;

Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method

 var url = "ControllerName/ActionName/";   
 $.post(url,
        { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
 function (data) {.......});

jQuery hasAttr checking to see if there is an attribute on an element

How about just $(this).is("[name]")?

The [attr] syntax is the CSS selector for an element with an attribute attr, and .is() checks if the element it is called on matches the given CSS selector.

How can I remove a commit on GitHub?

Note: please see an alternative to git rebase -i in the comments below—

git reset --soft HEAD^

First, remove the commit on your local repository. You can do this using git rebase -i. For example, if it's your last commit, you can do git rebase -i HEAD~2 and delete the second line within the editor window that pops up.

Then, force push to GitHub by using git push origin +branchName --force

See Git Magic Chapter 5: Lessons of History - And Then Some for more information (i.e. if you want to remove older commits).

Oh, and if your working tree is dirty, you have to do a git stash first, and then a git stash apply after.

SQL SERVER DATETIME FORMAT

The default date format depends on the language setting for the database server. You can also change it per session, like:

set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM

write newline into a file

Or you could use something like the following. Pay attention to "\n":

/**
 * Created by mona on 3/26/16.
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {


    public static void main (String[] args) throws java.io.IOException {

        File newFile = new File("tweet.txt");
        FileWriter fileWriter = new FileWriter(newFile);
        fileWriter.write("Mona Jalal");
        fileWriter.append("\nMona Mona");
        fileWriter.close();
        FileReader fileReader = new FileReader(newFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        fileReader.close();
        bufferedReader.close();



    }
}

select2 - hiding the search box

@Misha Kobrin's answer work well for me So I have decided to explain it more

You want to hide the search box you can do it by jQuery.

for example you have initialized select2 plugin on a drop down having id audience

element_select = '#audience';// id or class
$(element_select).select2("close").parent().hide();

The example works on all devices on which select2 works.

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In My case, I had a added async at app.js like shown below.

const App = async() => {
return(
<Text>Hello world</Text>
)
}

But it was not necessary, when testing something I had added it and it was no longer required. After removing it, as shown below, things started working.

 const App =() => {
    return(
    <Text>Hello world</Text>
    )
}

Add a common Legend for combined ggplots

@Guiseppe:

I have no idea of Grobs etc whatsoever, but I hacked together a solution for two plots, should be possible to extend to arbitrary number but its not in a sexy function:

plots <- list(p1, p2)
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
tmp <- arrangeGrob(p1 + theme(legend.position = "none"), p2 + theme(legend.position = "none"), layout_matrix = matrix(c(1, 2), nrow = 1))
grid.arrange(tmp, legend, ncol = 1, heights = unit.c(unit(1, "npc") - lheight, lheight))

Windows batch file file download from a URL

CURL

With the build 17063 of windows 10 the CURL utility was added. To download a file you can use:

curl "https://download.sysinternals.com/files/PSTools.zip" --output pstools.zip

BITSADMIN

It can be easier to use bitsadmin with a macro:

set "download=bitsadmin /transfer myDownloadJob /download /priority normal"
%download% "https://download.sysinternals.com/files/PSTools.zip" %cd%\pstools.zip

Winhttp com objects

For backward compatibility you can use winhttpjs.bat (with this you can perform also POST,DELETE and the others http methods):

call winhhtpjs.bat "https://example.com/files/some.zip" -saveTo "c:\somezip.zip" 

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Try pulling out the NVIDIA graphics card and reinserting it.

Graphviz: How to go from .dot to a graph?

there is no requirement of any conversion.

We can simply use xdot command in Linux which is an Interactive viewer for Graphviz dot files.

ex: xdot file.dot

for more infor:https://github.com/rakhimov/cppdep/wiki/How-to-view-or-work-with-Graphviz-Dot-files

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to add 'libs' folder in Android Studio?

You can create lib folder inside app you press right click and select directory you named as libs its will be worked

Git clone particular version of remote repository

Probably git reset solves your problem.

git reset --hard -#commit hash-

Google Maps how to Show city or an Area outline

i was looking for the same and found the answer,

solution is to use the styled map, on below link you can create your custom styles through wizard and test is at the same time google map style wizard

you can check all available options : here

here is my sample code which creates boundary for states and hide all the road and there labels.

    var styles = [
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [
      { "visibility": "on" },
      { "weight": 2.5 },
      { "color": "#24b0e2" }
    ]
  },{
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "administrative.locality",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "road",
    "elementType": "labels",
    "stylers": [
      { "visibility": "off" }
    ]
  }
];

  var  geocoder = new google.maps.Geocoder();
   geocoder.geocode({
       'address': "rajasthan"
   }, (results, status)=> {
     var mapOpts = {
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       scaleControl: true,
       scrollwheel: false,
       styles:styles,
       center: results[0].geometry.location,
       zoom:6
     }
     map = new google.maps.Map(document.getElementById("map"), mapOpts);
   });

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

AttributeError: Module Pip has no attribute 'main'

To verify whether is your pip installation problem, try using easy_install to install an earlier version of pip:

easy_install pip==9.0.1

If this succeed, pip should be working now. Then you can go ahead to install any other version of pip you want with:

pip install pip==10....

Or you can just stay with version 9.0.1, as your project requires version >= 9.0.

Try building your project again.

jQuery: Return data after ajax call success

Idk if you guys solved it but I recommend another way to do it, and it works :)

    ServiceUtil = ig.Class.extend({
        base_url : 'someurl',

        sendRequest: function(request)
        {
            var url = this.base_url + request;
            var requestVar = new XMLHttpRequest();
            dataGet = false;

            $.ajax({
                url: url,
                async: false,
                type: "get",
                success: function(data){
                    ServiceUtil.objDataReturned = data;
                }
            });
            return ServiceUtil.objDataReturned;                
        }
    })

So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

How to filter array in subdocument with MongoDB

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $unwind: '$list'},
    { $match: {'list.a': {$gt: 3}}},
    { $group: {_id: '$_id', list: {$push: '$list.a'}}}
])

outputs:

{
  "result": [
    {
      "_id": ObjectId("512e28984815cbfcb21646a7"),
      "list": [
        4,
        5
      ]
    }
  ],
  "ok": 1
}

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to do this more efficiently by only including the list elements you want during a $project:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}
        }}
    }}
])

What is the difference between --save and --save-dev?

--save-dev saves semver spec into "devDependencies" array in your package descriptor file, --save saves it into "dependencies" instead.

How do I check if a column is empty or null in MySQL?

Get rows with NULL, 0, '', ' ', ' '

    SELECT * FROM table WHERE some_col IS NOT TRUE;

Get rows without NULL, 0, '', ' ', ' '

    SELECT * FROM table WHERE some_col IS TRUE;

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon(); did not work for me either.

The way I had to write it to get it to work was like this. Might work for you too.

HttpContext.Current.Session.Abandon();

Regex pattern including all special characters

Try using this for the same things - StringUtils.isAlphanumeric(value)

ExpressJS How to structure an application?

A simple way to structure ur express app:

  • In main index.js the following order should be maintained.

    all app.set should be first.

    all app.use should be second.

    followed by other apis with their functions or route-continue in other files

    Exapmle

    app.use("/password", passwordApi);

    app.use("/user", userApi);

    app.post("/token", passport.createToken);

    app.post("/logout", passport.logout)

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

C# Threading - How to start and stop a thread

Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.

AutoResetEvent clarification

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

format statement in a string resource file

For me it worked like that in Kotlin:

my string.xml

 <string name="price" formatted="false">Price:U$ %.2f%n</string>

my class.kt

 var formatPrice: CharSequence? = null
 var unitPrice = 9990
 formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 99,90

For an even better result, we can do so

 <string name="price_to_string">Price:U$ %1$s</string>

 var formatPrice: CharSequence? = null
 var unitPrice = 199990
 val numberFormat = (unitPrice/100.0).toString()
 formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))

  fun formatValue(value: String) :String{
    val mDecimalFormat = DecimalFormat("###,###,##0.00")
    val s1 = value.toDouble()
    return mDecimalFormat.format(s1)
 }

 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 1.999,90

JSON post to Spring Controller

see here

The consumable media types of the mapped request, narrowing the primary mapping.

the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

Plot different DataFrames in the same figure

Just to enhance @adivis12 answer, you don't need to do the if statement. Put it like this:

fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
    dict_of_dfs[BAR].plot(ax=ax)

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Bi-directional Map in Java?

Use Google's BiMap

It is more convenient.

Copy Paste Values only( xlPasteValues )

selection=selection.values

this do things at a very fast way.

Is there a limit to the length of a GET request?

setFixedLengthStreamingMode(int) with contentLength parameters could set the fixed length of a HTTP request body.

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

Type List vs type ArrayList in Java

I think the people who use (2) don't know the Liskov substitution principle or the Dependency inversion principle. Or they really have to use ArrayList.

Delete all records in a table of MYSQL in phpMyAdmin

'Truncate tableName' will fail on a table with key constraint defined. It will also not reindex the table AUTO_INCREMENT value. Instead, Delete all table entries and reset indexing back to 1 using this sql syntax:

DELETE FROM tableName;
ALTER TABLE tableName AUTO_INCREMENT = 1

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

How does String substring work in Swift

Heres a more generic implementation:

This technique still uses index to keep with Swift's standards, and imply a full Character.

extension String
{
    func subString <R> (_ range: R) -> String? where R : RangeExpression, String.Index == R.Bound
    {
        return String(self[range])
    }

    func index(at: Int) -> Index
    {
        return self.index(self.startIndex, offsetBy: at)
    }
}

To sub string from the 3rd character:

let item = "Fred looks funny"
item.subString(item.index(at: 2)...) // "ed looks funny"

I've used camel subString to indicate it returns a String and not a Substring.

Why doesn't CSS ellipsis work in table cell?

It's also important to put

table-layout:fixed;

Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.

How to use Typescript with native ES6 Promises

Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

No npm install required as ES6 Promises is native.

Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

What's the best way to select the minimum value from several columns?

The best way to do that is probably not to do it - it's strange that people insist on storing their data in a way that requires SQL "gymnastics" to extract meaningful information, when there are far easier ways to achieve the desired result if you just structure your schema a little better :-)

The right way to do this, in my opinion, is to have the following table:

ID    Col    Val
--    ---    ---
 1      1      3
 1      2     34
 1      3     76

 2      1     32
 2      2    976
 2      3     24

 3      1      7
 3      2    235
 3      3      3

 4      1    245
 4      2      1
 4      3    792

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual 'old columns' separately by using where col = 2 in your other queries. This also allows for easy expansion should the number of 'old columns' grow.

This makes your queries so much easier. The general guideline I tend to use is, if you ever have something that looks like an array in a database row, you're probably doing something wrong and should think about restructuring the data.


However, if for some reason you can't change those columns, I'd suggest using insert and update triggers and add another column which these triggers set to the minimum on Col1/2/3. This will move the 'cost' of the operation away from the select to the update/insert where it belongs - most database tables in my experience are read far more often than written so incurring the cost on write tends to be more efficient over time.

In other words, the minimum for a row only changes when one of the other columns change, so that's when you should be calculating it, not every time you select (which is wasted if the data isn't changing). You would then end up with a table like:

ID   Col1   Col2   Col3   MinVal
--   ----   ----   ----   ------
 1      3     34     76        3
 2     32    976     24       24
 3      7    235      3        3
 4    245      1    792        1

Any other option that has to make decisions at select time is usually a bad idea performance-wise, since the data only changes on insert/update - the addition of another column takes up more space in the DB and will be slightly slower for the inserts and updates but can be much faster for selects - the preferred approach should depend on your priorities there but, as stated, most tables are read far more often than they're written.

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

In PostMan we have ->Pre-request Script. Paste the Below snippet.

const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());

And now we are ready to use.

{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}

If you are using JPA Entity classes then use the below snippet

    @JsonFormat(pattern="MM/dd/yyyy")
    @Column(name = "creation_date")
    private Date creationDate;

enter image description here enter image description here

How to put sshpass command inside a bash script?

I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.


After your provided script commands, execute additional commands like below:

sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command

In your script:

#! /bin/bash

sshpass -p 'password' ssh user@host "ls; whois google.com;"

Differentiate between function overloading and function overriding

You are putting in place an overloading when you change the original types for the arguments in the signature of a method.

You are putting in place an overriding when you change the original Implementation of a method in a derived class.

Java variable number or arguments for a method

Yes Java allows vargs in method parameter .

public class  Varargs
{
   public int add(int... numbers)
   { 
      int result = 1; 
      for(int number: numbers)
      {
         result= result+number;  
      }  return result; 
   }
}

appending list but error 'NoneType' object has no attribute 'append'

When doing pan_list.append(p.last) you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None).

You should do something like this :

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list.append(p.last)  # Here I modify the last_list, no affectation
print last_list

Android TextView Justify Text

Try using < RelativeLayout > (making sure to fill_parent), then just add android:layout_alignParentLeft="true" and

android:layout_alignParentRight="true" to the elements you would like on the outside LEFT & RIGHT.

BLAM, justified!

How to sort multidimensional array by column?

The optional key parameter to sort/sorted is a function. The function is called for each item and the return values determine the ordering of the sort

>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
...     print("The key for {} is {}".format(item, item[1]))
...     return item[1]
... 
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]

taking the print out of the function leaves

>>> def my_key_func(item):
...     return item[1]

This function is simple enough to write "inline" as a lambda function

>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]

Hide div element when screen size is smaller than a specific size

You simply need to use a media query in CSS to accomplish this.

@media (max-width: 1026px) {
    #fadeshow1 { display: none; }
}

Unfortunately some browsers do not support @media (looking at you IE8 and below). In those cases, you have a few options, but the most common is Respond.js which is a lightweight polyfill for min/max-width CSS3 Media Queries.

<!--[if lt IE 9]>
    <script src="respond.min.js"></script>
<![endif]-->

This will allow your responsive design to function in those old versions of IE.
*reference

R define dimensions of empty data frame

A more general method to create an arbitrary size data frame is to create a n-by-1 data-frame from a matrix of the same dimension. Then, you can immediately drop the first row:

> v <- data.frame(matrix(NA, nrow=1, ncol=10))
> v <- v[-1, , drop=FALSE]
> v
 [1] X1  X2  X3  X4  X5  X6  X7  X8  X9  X10
<0 rows> (or 0-length row.names)

Loop through an array of strings in Bash?

Possible first line of every Bash script/session:

say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }

Use e.g.:

$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e

May consider: echo interprets -e as option here

How to output something in PowerShell

Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta

Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.

The + $File.FullName is optional, and shows how to put a variable into the string.

jQuery: outer html()

Just use standard DOM functionality:

$('#xxx')[0].outerHTML

outerHTML is well supported - verify at Mozilla or caniuse.

White space showing up on right side of page when background image should extend full length of page

I added:

html,body
{
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    overflow-x: hidden; 
}

into your CSS at the very top above the other classes and it seemed to fix your issue.

Your updated .css file is available here

How to debug a referenced dll (having pdb)

I had the *.pdb files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

There is a sort that's called bogobogosort. First, it checks the first 2 elements, and bogosorts them. Next it checks the first 3, bogosorts them, and so on.

Should the list be out of order at any time, it restarts by bogosorting the first 2 again. Regular bogosort has a average complexity of O(N!), this algorithm has a average complexity of O(N!1!2!3!...N!)

Edit: To give you an idea of how large this number is, for 20 elements, this algorithm takes an average of 3.930093*10^158 years,well above the proposed heat death of the universe(if it happens) of 10^100 years,

whereas merge sort takes around .0000004 seconds, bubble sort .0000016 seconds, and bogosort takes 308 years, 139 days, 19 hours, 35 minutes, 22.306 seconds, assuming a year is 365.242 days and a computer does 250,000,000 32 bit integer operations per second.

Edit2: This algorithm is not as slow as the "algorithm" miracle sort, which probably, like this sort, will get the computer sucked in the black hole before it successfully sorts 20 elemtnts, but if it did, I would estimate an average complexity of 2^(32(the number of bits in a 32 bit integer)*N)(the number of elements)*(a number <=10^40) years,

since gravity speeds up the chips alpha moving, and there are 2^N states, which is 2^640*10^40, or about 5.783*10^216.762162762 years, though if the list started out sorted, its complexity would only be O(N), faster than merge sort, which is only N log N even at the worst case.

Edit3: This algorithm is actually slower than miracle sort as the size gets very big, say 1000, since my algorithm would have a run time of 2.83*10^1175546 years, while the miracle sort algorithm would have a run time of 1.156*10^9657 years.

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

I just run this command as a root from terminal and problem is solved,

sudo apt-get install -y postgis postgresql-9.3-postgis-2.1
pip install psycopg2

or

sudo apt-get install libpq-dev python-dev
pip install psycopg2