Programs & Examples On #Stateful

A stateful app is one that stores information about what has happened or changed since it started running

Stateless vs Stateful

I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.

Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.

Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.

How to use a table type in a SELECT FROM statement?

In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;

In package body:

initialize the table in declarations:

exch_rt exch_tbl := exch_tbl();

in order to add record to the local collection, in begin - end block you can do:

exch_rt.extend;
                                one_row.exch_rt_usd := 2;
                                one_row.exch_rt_eur := 1;
                                one_row.currency_cd := 'dollar';
                                exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop 

in order to get data from this table , inside package body you can use:

select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)

enjoy!

P.S. sorry for a late answer :D

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

What I would do is use this tool and step through where you are getting the exception

http://www.reflector.net/

Read this it will tell you how to create PDB's so you do not have to have all your references setup.

http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/

It is a trial and I am not related to redgate at all I just use there software.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

You have to sign your application and then run it!

If you are preparing a new update for your application, it is not a problem to continue working. In the end, before releasing the prepared version, when you sign the application, the problem will be solved and users will have no problem installing your application.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had this issue after migrating from spring-boot-starter-data-jpa ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration class I injected entityManagerFactory and transactionManager.

//I've got my data source defined in application.yml config file, 
//so there is no need to configure it from java.
@Autowired
DataSource dataSource;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    //JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    //Add package to scan for entities.
    factory.setPackagesToScan("com.company.domain");
    factory.setDataSource(dataSource);
    return factory;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory);
    return txManager;
}

Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.0.12.Final</version>
</dependency>

Set value for particular cell in pandas DataFrame using index

If one wants to change the cell in the position (0,0) of the df to a string such as '"236"76"', the following options will do the work:

df[0][0] = '"236"76"'
# %timeit df[0][0] = '"236"76"'
# 938 µs ± 83.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Or using pandas.DataFrame.at

df.at[0, 0] = '"236"76"'
#  %timeit df.at[0, 0] = '"236"76"' 
#15 µs ± 2.09 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Or using pandas.DataFrame.iat

df.iat[0, 0] = '"236"76"'
#  %timeit df.iat[0, 0] = '"236"76"'
# 41.1 µs ± 3.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Or using pandas.DataFrame.loc

df.loc[0, 0] = '"236"76"'
#  %timeit df.loc[0, 0] = '"236"76"'
# 5.21 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Or using pandas.DataFrame.iloc

df.iloc[0, 0] = '"236"76"'
#  %timeit df.iloc[0, 0] = '"236"76"'
# 5.12 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

If time is of relevance, using pandas.DataFrame.at is the fastest approach.

Div width 100% minus fixed amount of pixels

We can achieve this using flex-box very easily.

If we have three elements like Header, MiddleContainer and Footer. And we want to give some fixed height to Header and Footer. then we can write like this:

For React/RN(defaults are 'display' as flex and 'flexDirection' as column), in web css we'll have to specify the body container or container containing these as display: 'flex', flex-direction: 'column' like below:

    container-containing-these-elements: {
     display: flex,
     flex-direction: column
    }
    header: {
     height: 40,
    },
    middle-container: {
     flex: 1, // this will take the rest of the space available.
    },
    footer: {
     height: 100,
    }

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

How to update Xcode from command line

Hello I solved it like this:

Install Application> Xcode.app> Contents> Resources> Packages> XcodeSystemResources.pkg.

Ordering issue with date values when creating pivot tables

The problem I had was that although the source data was correctly formatted as 'date' dd/mm/yyyy, the pivot table placed (for example) 22/05/2019 between 16/05/2019 and 17/05/2019. This data was visible in the pivot table, but in the wrong place. In addition, the Pivot chart refused to show that data for that date even though the 'Date' filter allowed it to be selected.

In my case, I had to:

  1. From the Pivot Chart,open the 'Date' Filter menu.

  2. select the 'Sort Oldest to Newest' option.

  3. Bingo! The Pivot chart now shows the missing date data.

How to change the text of a button in jQuery?

it's work for me html:

<button type="button" class="btn btn-primary" id="btnSaveSchedule">abc</button>

js

$("#btnSaveSchedule").text("new value");

How to switch activity without animation in Android?

If your context is an activity you can call overridePendingTransition:

Call immediately after one of the flavors of startActivity(Intent) or finish to specify an explicit transition animation to perform next.

So, programmatically:

this.startActivity(new Intent(v.getContext(), newactivity.class));
this.overridePendingTransition(0, 0);

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

What worked for me was to rename the project by removing the special characters.

Example: "project_marketplace" to "projectmarketplace"

In this case, I redid the project with react-native init and copied the src and package.json folder.

C# Get/Set Syntax Usage

By the way, in C# 3.5 you can instantiate your object's properties like so:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public.

Does List<T> guarantee insertion order?

This is the code I have for moving an item down one place in a list:

if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index + 1, imageName);
    this.folderImages.SelectedIndex = index + 1;
 }

and this for moving it one place up:

if (this.folderImages.SelectedIndex > 0)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index - 1, imageName);
    this.folderImages.SelectedIndex = index - 1;
}

folderImages is a ListBox of course so the list is a ListBox.ObjectCollection, not a List<T>, but it does inherit from IList so it should behave the same. Does this help?

Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.

Uploading multiple files using formData()

Adding [] when appending to fd works, but if you prefer to have your data grouped by file then I'd suggest doing it this way:

var files= document.getElementById('inpFile').files
var fd = new FormData()

for (let i = 0; i < files.length; i++) {
  fd.append(i, files[i])
}

Now your data will be sent grouped by file instead of grouped by attribute.

align text center with android

use this way in xml

   <TextView
        android:id="@+id/myText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Time is precious, so love now."
        android:gravity="center"
        android:textSize="30dp"
        android:textColor="#fff"
        />

Hide particular div onload and then show div after click

You are missing # hash character before id selectors, this should work:

$(document).ready(function() {
    $("#div2").hide();

    $("#preview").click(function() {
      $("#div1").hide();
      $("#div2").show();
    });

});

Learn More about jQuery ID Selectors

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Can you just just some &nbsp; ?

<div style="text-align: center"> 
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
    &nbsp;&nbsp;
    <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>

Output of git branch in tree like fashion

The following example shows commit parents as well:

git log --graph --all \
--format='%C(cyan dim) %p %Cred %h %C(white dim) %s %Cgreen(%cr)%C(cyan dim) <%an>%C(bold yellow)%d%Creset'

How can I declare enums using java

Quite simply as follows:

/**
 * @author The Elite Gentleman
 *
 */
public enum MyEnum {
    ONE("one"), TWO("two")
    ;
    private final String value;

    private MyEnum(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return getValue();
    }
}

For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.


Update, since you've updated your post, I've changed my value from an int to a String.
Related: Java String enum.

Using jQuery To Get Size of Viewport

function showViewPortSize(display) {
    if (display) {
        var height = window.innerHeight;
        var width = window.innerWidth;
        jQuery('body')
            .prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
        jQuery(window)
            .resize(function() {
                height = window.innerHeight;
                width = window.innerWidth;
                jQuery('#viewportsize')
                    .html('Height: ' + height + '<br>Width: ' + width);
            });
    }
}
$(document)
    .ready(function() {
        showViewPortSize(true);
    });

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

Postgresql GROUP_CONCAT equivalent?

My sugestion in postgresql

SELECT cpf || ';' || nome || ';' || telefone  
FROM (
      SELECT cpf
            ,nome
            ,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone 
      FROM (
            SELECT DISTINCT * 
            FROM temp_bd 
            ORDER BY cpf DESC ) AS y
      GROUP BY 1,2 ) AS x   

How to get "GET" request parameters in JavaScript?

If you already use jquery there is a jquery plugin that handles this:

http://plugins.jquery.com/project/query-object

How to resolve 'unrecognized selector sent to instance'?

How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."

Copying, or creating the .h solved it for me.

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

On Windows, I have found that the important thing is to start Eclipse from the command line rather than from the Start Menu or a shortcut, provided that the native DLL is in a directory in your PATH. Apparently, this ensures that the proper directory is on the path.

Assigning out/ref parameters in Moq

This is documentation from Moq site:

// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);

Why doesn't Mockito mock static methods?

Mockito [3.4.0] can mock static methods!

  1. Replace mockito-core dependency with mockito-inline:3.4.0.

  2. Class with static method:

    class Buddy {
      static String name() {
        return "John";
      }
    }
    
  3. Use new method Mockito.mockStatic():

    @Test
    void lookMomICanMockStaticMethods() {
      assertThat(Buddy.name()).isEqualTo("John");
    
      try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
        theMock.when(Buddy::name).thenReturn("Rafael");
        assertThat(Buddy.name()).isEqualTo("Rafael");
      }
    
      assertThat(Buddy.name()).isEqualTo("John");
    }
    

    Mockito replaces the static method within the try block only.

How to do an Integer.parseInt() for a decimal number?

use this one

int number = (int) Double.parseDouble(s);

How to color System.out.println output?

Note

You may not be able to color Window's cmd prompt, but it should work in many unix (or unix-like) terminals.

Also, note that some terminals simply won't support some (if any) ANSI escape sequences and, especially, 24-bit colors.

Usage

Please refer to the section Curses at the bottom for the best solution. For a personal or easy solution (although not as cross-platform solution), refer to the ANSI Escape Sequences section.


TL;DR

  • java: System.out.println((char)27 + "[31m" + "ERROR MESSAGE IN RED");

  • python: print(chr(27) + "[31m" + "ERROR MESSAGE IN RED")

  • bash or zsh: printf '\x1b[31mERROR MESSAGE IN RED'
    • this may also work for Os X: printf '\e[31mERROR MESSAGE IN RED'
  • sh: printf 'CTRL+V,CTRL+[[31mERROR MESSAGE IN RED'
    • ie, press CTRL+V and then CTRL+[ in order to get a "raw" ESC character when escape interpretation is not available
    • If done correctly, you should see a ^[. Although it looks like two characters, it is really just one, the ESC character.
    • You can also press CTRL+V,CTRL+[ in vim in any of the programming or sripting langauges because that uses a literal ESC character
    • Also, you can replace Ctrl+[ with ESC … eg, you can use CTRL+V,ESC, but I find the former easier, since I am already pressing CTRL and since [ is less out of the way.

ANSI Escape Sequences

Background on Escape Sequences

While it is not the best way to do it, the easiest way to do this in a programming or scripting language is to use escape sequences. From that link:

An escape sequence is a series of characters used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control.

Backgound on ANSI Escape Sequences

However, it gets even easier than that in video text terminals, as these terminals use ANSI escape sequences. From that link:

ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals. Certain sequences of bytes, most starting with Esc and '[', are embedded into the text, which the terminal looks for and interprets as commands, not as character codes.

How to Use ANSI Escape Sequences

Generally

  • Escape sequences begin with an escape character; for ANSI escape sequences, the sequence always begins with ESC (ASCII: 27 / hex: 0x1B).
  • For a list of what you can do, refer to the ANSI Escape Sequence List on Wikipedia

In Programming Languages

Some programming langauges (like Java) will not interpret \e or \x1b as the ESC character. However, we know that the ASCII character 27 is the ESC character, so we can simply typecast 27 to a char and use that to begin the escape sequence.

Here are some ways to do it in common programming languages:

  • Java

    • System.out.println((char)27 + "[33mYELLOW");
  • Python 3

    • print(chr(27) + "[34mBLUE");
    • print("\x1b[35mMAGENTA");
      • Note that \x1b is interpretted correctly in python
  • Node JS

    • The following will NOT color output in JavaScript in the Web Console
    • console.log(String.fromCharCode(27) + "[36mCYAN");
    • console.log("\x1b[30;47mBLACK_ON_WHITE");
      • Note that \x1b also works in node

In Shell Prompt OR Scripts

If you are working with bash or zsh, it is quite easy to color the output (in most terminals). In Linux, Os X, and in some Window's terminals, you can check to see if your terminal supports color by doing both of the following:

  • printf '\e[31mRED'
  • printf '\x1b[31mRED'

If you see color for both, then that's great! If you see color for only one, then use that sequence. If you do not see color for either of them, then double check to make sure you typed everything correctly and that you are in bash or zsh; if you still do not see any color, then your terminal probably does not support ANSI escape sequences.

If I recall correctly, linux terminals tend to support both \e and \x1b escape sequences, while os x terminals only tend to support \e, but I may be wrong. Nonetheless, if you see something like the following image, then you're all set! (Note that I am using the shell, zsh, and it is coloring my prompt string; also, I am using urxvt as my terminal in linux.)

ANSI Escape Sequences Coloring Text Red

"How does this work?" you might ask. Bascially, printf is interpretting the sequence of characters that follows (everything inside of the single-quotes). When printf encounters \e or \x1b, it will convert these characters to the ESC character (ASCII: 27). That's just what we want. Now, printf sends ESC31m, and since there is an ESC followed by a valid ANSI escape sequence, we should get colored output (so long as it is supported by the terminal).

You can also use echo -e '\e[32mGREEN' (for example), to color output. Note that the -e flag for echo "[enables] interpretation of backslash escapes" and must be used if you want echo to appropriately interpret the escape sequence.


More on ANSI Escape Sequences

ANSI escape sequences can do more than just color output, but let's start with that, and see exactly how color works; then, we will see how to manipulate the cursor; finally, we'll take a look and see how to use 8-bit color and also 24-bit color (although it only has tenuous support).

On Wikipedia, they refer to ESC[ as CSI, so I will do the same.

Color

To color output using ANSI escapes, use the following:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 30-37, 39: foreground
      • 40-47, 49: background
    • m: a literal ASCII m—terminates the escape sequence

I will use bash or zsh to demonstrate all of the possible color combinations. Plop the following in bash or zsh to see for yourself (You may need to replace \e with \x1b):

  • for fg in {30..37} 39; do for bg in {40..47} 49; do printf "\e[${fg};${bg}m~TEST~"; done; printf "\n"; done;

Result:

various foreground/background colors using ANSI escapes

Quick Reference (Color)

+~~~~~~+~~~~~~+~~~~~~~~~~~+
|  fg  |  bg  |  color    |
+~~~~~~+~~~~~~+~~~~~~~~~~~+
|  30  |  40  |  black    |
|  31  |  41  |  red      |
|  32  |  42  |  green    |
|  33  |  43  |  yellow   |
|  34  |  44  |  blue     |
|  35  |  45  |  magenta  |
|  36  |  46  |  cyan     |
|  37  |  47  |  white    |
|  39  |  49  |  default  |
+~~~~~~+~~~~~~+~~~~~~~~~~~+

Select Graphic Rendition (SGR)

SGR just allows you to change the text. Many of these do not work in certain terminals, so use these sparingly in production-level projects. However, they can be useful for making program output more readable or helping you distinguish between different types of output.

Color actually falls under SGR, so the syntax is the same:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 0: reset
      • 1-9: turns on various text effects
      • 21-29: turns off various text effects (less supported than 1-9)
      • 30-37, 39: foreground color
      • 40-47, 49: background color
      • 38: 8- or 24-bit foreground color (see 8/24-bit Color below)
      • 48: 8- or 24-bit background color (see 8/24-bit Color below)
    • m: a literal ASCII m—terminates the escape sequence

Although there is only tenuous support for faint (2), italic (3), underline (4), blinking (5,6), reverse video (7), conceal (8), and crossed out (9), some (but rarely all) tend to work on linux and os x terminals.

It's also worthwhile to note that you can separate any of the above attributes with a semi-colon. For example printf '\e[34;47;1;3mCRAZY TEXT\n' will show CRAZY TEXT with a blue foreground on a white background, and it will be bold and italic.

Eg:

string attributes together example screenshot

Plop the following in your bash or zsh shell to see all of the text effects you can do. (You may need to replace \e with \x1b.)

  • for i in {1..9}; do printf "\e[${i}m~TEST~\e[0m "; done

Result:

SGR state 1 SGR state 2

You can see that my terminal supports all of the text effects except for faint (2), conceal (8) and cross out (9).

Quick Reference (SGR Attributes 0-9)

+~~~~~+~~~~~~~~~~~~~~~~~~+
|  n  |  effect          |
+~~~~~+~~~~~~~~~~~~~~~~~~+
|  0  |  reset           |
|  1  |  bold            |
|  2  |  faint*          |
|  3  |  italic**        |
|  4  |  underline       |
|  5  |  slow blink      |
|  6  |  rapid blink*    |
|  7  |  inverse         |
|  8  |  conceal*        |
|  9  |  strikethrough*  |
+~~~~~+~~~~~~~~~~~~~~~~~~+

* not widely supported
** not widely supported and sometimes treated as inverse

8-bit Color

While most terminals support this, it is less supported than 0-7,9 colors.

Syntax:

  • CSI 38;5; n m
    • CSI: escape character—^[[ or ESC[
    • 38;5;: literal string that denotes use of 8-bit colors for foreground
    • n: a number—one of the following:
      • 0-255

If you want to preview all of the colors in your terminal in a nice way, I have a nice script on gist.github.com.

It looks like this:

8-bit color example screenshot

If you want to change the background using 8-bit colors, just replace the 38 with a 48:

  • CSI 48;5; n m
    • CSI: escape character—^[[ or ESC[
    • 48;5;: literal string that denotes use of 8-bit colors for background
    • n: a number—one of the following:
      • 0-255

24-bit Color

Also known as true color, 24-bit color provides some really cool functionality. Support for this is definitely growing (as far as I know it works in most modern terminals except urxvt, my terminal [insert angry emoji]).

24-bit color is actually supported in vim (see the vim wiki to see how to enable 24-bit colors). It's really neat because it pulls from the colorscheme defined for gvim; eg, it uses the fg/bg from highlight guibg=#______ guifg=#______ for the 24-bit colors! Neato, huh?

Here is how 24-bit color works:

  • CSI 38;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 38;2;: literal string that denotes use of 24-bit colors for foreground
    • r,g,b: numbers—each should be 0-255

To test just a few of the many colors you can have ((2^8)^3 or 2^24 or 16777216 possibilites, I think), you can use this in bash or zsh:

  • for r in 0 127 255; do for g in 0 127 255; do for b in 0 127 255; do printf "\e[38;2;${r};${g};${b}m($r,$g,$b)\e[0m "; done; printf "\n"; done; done;

Result (this is in gnome-terminal since urxvt DOES NOT SUPPORT 24-bit color ... get it together, urxvt maintainer ... for real):

24-bit color example screenshot

If you want 24-bit colors for the background ... you guessed it! You just replace 38 with 48:

  • CSI 48;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 48;2;: literal string that denotes use of 24-bit colors for background
    • r,g,b: numbers—each should be 0-255

Inserting Raw Escape Sequences

Sometimes \e and \x1b will not work. For example, in the sh shell, sometimes neither works (although it does on my system now, I don't think it used to).

To circumvent this, you can use CTRL+V,CTRL+[ or CTRLV,ESC

This will insert a "raw" ESC character (ASCII: 27). It will look like this ^[, but do not fret; it is only one character—not two.

Eg:

sh raw escape char example screenshot


Curses

Refer to the Curses (Programming Library) page for a full reference on curses. It should be noted that curses only works on unix and unix-like operating systems.

Up and Running with Curses

I won't go into too much detail, for search engines can reveal links to websites that can explain this much better than I can, but I'll discuss it briefly here and give an example.

Why Use Curses Over ANSI Escapes?

If you read the above text, you might recall that \e or \x1b will sometimes work with printf. Well, sometimes \e and \x1b will not work at all (this is not standard and I have never worked with a terminal like this, but it is possible). More importantly, more complex escape sequences (think Home and other multi-character keys) are difficult to support for every terminal (unless you are willing to spend a lot of time and effort parsing terminfo and termcap and and figuring out how to handle every terminal).

Curses solves this problem. Basically, it is able to understand what capabilities a terminal has, using these methods (as described by the wikipedia article linked above):

Most implementations of curses use a database that can describe the capabilities of thousands of different terminals. There are a few implementations, such as PDCurses, which use specialized device drivers rather than a terminal database. Most implementations use terminfo; some use termcap. Curses has the advantage of back-portability to character-cell terminals and simplicity. For an application that does not require bit-mapped graphics or multiple fonts, an interface implementation using curses will usually be much simpler and faster than one using an X toolkit.

Most of the time, curses will poll terminfo and will then be able to understand how to manipulate the cursor and text attributes. Then, you, the programmer, use the API provided by curses to manipulate the cursor or change the text color or other attributes if the functionality you seek is desired.

Example with Python

I find python is really easy to use, but if you want to use curses in a different programming language, then simply search it on duckduckgo or any other search engine. :) Here is a quick example in python 3:

import curses

def main(stdscr):
    # allow curses to use default foreground/background (39/49)
    curses.use_default_colors()

    # Clear screen
    stdscr.clear()

    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_GREEN, -1)
    stdscr.addstr("ERROR: I like tacos, but I don't have any.\n", curses.color_pair(1))
    stdscr.addstr("SUCCESS: I found some tacos.\n", curses.color_pair(2))

    stdscr.refresh() # make sure screen is refreshed
    stdscr.getkey()  # wait for user to press key

if __name__ == '__main__':
    curses.wrapper(main)

result:

enter image description here

You might think to yourself that this is a much more round-about way of doing things, but it really is much more cross-platform (really cross-terminal … at least in the unix- and unix-like-platform world). For colors, it is not quite as important, but when it comes to supporting other multi-sequence escape sequences (such as Home, End, Page Up, Page Down, etc), then curses becomes all the more important.

Example with Tput

  • tput is a command line utility for manipulating cursor and text
  • tput comes with the curses package. If you want to use cross-terminal (ish) applications in the terminal, you should use tput, as it parses terminfo or whatever it needs to and uses a set of standardized commands (like curses) and returns the correct escape sequence.
  • example:
echo "$(tput setaf 1)$(tput bold)ERROR:$(tput sgr0)$(tput setaf 1) My tacos have gone missing"
echo "$(tput setaf 2)$(tput bold)SUCCESS:$(tput sgr0)$(tput setaf 2) Oh good\! I found my tacos\!"

Result:

example with tput

More Info on Tput

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Dynamically change color to lighter or darker by percentage CSS (Javascript)

One outdated simple answer (in 2013) was to use a 50% transparent white PNG over the color:

div {
    background-color:red;
}

div:hover {
    background-image:url('lighten.png');
}

Where lighten.png is a PNG of a white fill with 50% transparency.

There's much better ways to do this today. I hope people stop commenting now.

Regex to remove all special characters from string?

If you don't want to use Regex then another option is to use

char.IsLetterOrDigit

You can use this to loop through each char of the string and only return if true.

Eclipse C++ : "Program "g++" not found in PATH"

Had this problem on windows 10, eclipse Neon Release (4.6.0) and MSYS2 installed. Eclipse kept complaining that "Program 'g++' not found in PATH” and "Program 'gcc' not found in PATH”, yet it was compiling and running my C++ code. From the command prompt, I could run g++.

Solution was to define the C++ Environmental variable for eclipse called 'PATH' to point to windows variable called 'path' also $(Path). Menus: Preferences>>C/C++>>Build>>Environment

Looks like eclipse is case sensitive with the name of this environmental, while windows doesn't care about the case.

How to use index in select statement?

Good question,

Usually the DB engine should automatically select the index to use based on query execution plans it builds. However, there are some pretty rare cases when you want to force the DB to use a specific index.

To be able to answer your specific question you have to specify the DB you are using.

For MySQL, you want to read the Index Hint Syntax documentation on how to do this

Yahoo Finance All Currencies quote API Documentation

I have used this URL to obtain multiple currency market quotes.

http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X

"USD",1.0000
"CAD",1.2458
"EUR",0.8396

They can be parsed in PHP like this:

$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');

$quote = array_map( 'str_getcsv', file($url) );

foreach ($quote as $key => $symb) {
    $symbol = $quote[$key][0];
    $value = $quote[$key][1];
}

How can I use a batch file to write to a text file?

You can use echo, and redirect the output to a text file (see notes below):

rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt

Output:

D:\Temp>WriteText

D:\Temp>type test.txt
This is a test
123
245.67

D:\Temp>

Notes:

  • @echo off turns off printing of each command to the console
  • Unless you give it a specific path name, redirection with > or >> will write to the current directory (the directory the code is being run in).
  • The echo This is a test > test.txt uses one > to overwrite any file that already exists with new content.
  • The remaining echo statements use two >> characters to append to the text file (add to), instead of overwriting it.
  • The type test.txt simply types the file output to the command window.

Iterating through a list to render multiple widgets in Flutter?

All you need to do is put it in a list and then add it as the children of the widget.

you can do something like this:

Widget listOfWidgets(List<String> item) {
  List<Widget> list = List<Widget>();
  for (var i = 0; i < item.length; i++) {
    list.add(Container(
        child: FittedBox(
          fit: BoxFit.fitWidth,
          child: Text(
            item[i],
          ),
        )));
  }
  return Wrap(
      spacing: 5.0, // gap between adjacent chips
      runSpacing: 2.0, // gap between lines
      children: list);
}

After that call like this

child: Row(children: <Widget>[
   listOfWidgets(itemList),
])

enter image description here

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I was facing same problem.

When I rightclick-> run on server then select my server manually it worked.

Do

Alt+Shift+X

then mannually select your server. It might help.

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

FWIW the removal of Apache library was foreshadowed a while ago. Our good friend Jesse Wilson gave us a clue back in 2011: http://android-developers.blogspot.com/2011/09/androids-http-clients.html

Google stopped working on ApacheHTTPClient a while ago, so any library that is still relying upon that should be put onto the list of deprecated libraries unless the maintainers update their code.

<rant> I can't tell you how many technical arguments I've had with people who insisted on sticking with Apache HTTP client. There are some major apps that are going to break because management at my not-to-be-named previous employers didn't listen to their top engineers or knew what they were talking about when they ignored the warning ... but, water under the bridge.

I win.

</rant>

indexOf method in an object array?

You can create your own prototype to do this:

something like:

Array.prototype.indexOfObject = function (object) {
    for (var i = 0; i < this.length; i++) {
        if (JSON.stringify(this[i]) === JSON.stringify(object))
            return i;
    }
}

Copy or rsync command

Rsync is better since it will only copy only the updated parts of the updated file, instead of the whole file. It also uses compression and encryption if you want. Check out this tutorial.

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>

Only resolves the @Autowired and @Qualifer annotations, that's all, it about the Dependency Injection, There are other annotations that do the same job, I think how @Inject, but all about to resolve DI through annotations.

Be aware, even when you have declared the <context:annotation-config> element, you must declare your class how a Bean anyway, remember we have three available options

  • XML: <bean>
  • @Annotations: @Component, @Service, @Repository, @Controller
  • JavaConfig: @Configuration, @Bean

Now with

<context:component-scan>

It does two things:

  • It scans all the classes annotated with @Component, @Service, @Repository, @Controller and @Configuration and create a Bean
  • It does the same job how <context:annotation-config> does.

Therefore if you declare <context:component-scan>, is not necessary anymore declare <context:annotation-config> too.

Thats all

A common scenario was for example declare only a bean through XML and resolve the DI through annotations, for example

<bean id="serviceBeanA" class="com.something.CarServiceImpl" />
<bean id="serviceBeanB" class="com.something.PersonServiceImpl" />
<bean id="repositoryBeanA" class="com.something.CarRepository" />
<bean id="repositoryBeanB" class="com.something.PersonRepository" />

We have only declared the beans, nothing about <constructor-arg> and <property>, the DI is configured in their own classes through @Autowired. It means the Services use @Autowired for their Repositories components and the Repositories use @Autowired for the JdbcTemplate, DataSource etc..components

Binding Listbox to List<object> in WinForms

There are two main routes here:

1: listBox1.DataSource = yourList;

Do any manipulation (Add/Delete) to yourList and Rebind.
Set DisplayMember and ValueMember to control what is shown.

2: listBox1.Items.AddRange(yourList.ToArray());

(or use a for-loop to do Items.Add(...))

You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.

How do you round a number to two decimal places in C#?

This is for rounding to 2 decimal places in C#:

label8.Text = valor_cuota .ToString("N2") ;

In VB.NET:

 Imports System.Math
 round(label8.text,2)

Insert image after each list item

My solution to do this:

li span.show::after{
  content: url("/sites/default/files/new5.gif");
  padding-left: 5px;
}

how to call an ASP.NET c# method using javascript

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

in markup:

 var $Username = $("#txtUsername").val();
            var $Password = $("#txtPassword").val();

            //Call the approve method on the code behind
            $.ajax({
                type: "POST",
                url: "Pages/Mobile/Login.aspx/LoginUser",
                data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
                success: function (msg) {
                    if (msg.d == true) {
                        window.location.href = "Pages/Mobile/Basic/Index.aspx";
                    }
                    else {
                        //show error
                        alert('login failed');
                    }
                }
            });

In Code Behind:

/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
    try
    {
        StaticStore.CurrentUser = new User( Username, Password );

        //check the login details were correct
        if ( StaticStore.CurrentUser.IsAuthentiacted )
        {
            //change the status to logged in
            StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;

            //Store the user ID in the list of active users
            ( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;

            return true;
        }
        else
        {
            return false;
        }
    }
    catch ( Exception ex )
    {
        return false;
    }
}

Undefined reference to `pow' and `floor'

For the benefit of anyone reading this later, you need to link against it as Fred said:

gcc fib.c -lm -o fibo

One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow and man floor will both tell you:

Link with -lm.

An explanation for linking math library in C programming - Linking in C

AndroidStudio gradle proxy

in gradle.properties file (project root directory)

You must set proxy for http and https

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=user
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=domain

systemProp.https.proxyHost=www.somehost.org
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=user
systemProp.https.proxyPassword=password
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=domain

if you set proxy from File -> Settings ->HTTP Proxy(Under IDE Settings) it only define http proxy and does not set https proxy

Calculating the distance between 2 points

measure the square distance from one point to the other:

((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d

where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.

or if you prefer:

(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);

Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call Math.Sqrt, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.

Of course you are talking in meters and I supposed point coordinates are expressed in meters too.

What is the Java equivalent for LINQ?

As on 2014, I can finally say that LINQ is finally there in java 8.So no need to find an alternative of LINQ anymore.

How to sum data.frame column values?

to order after the colsum :

order(colSums(people),decreasing=TRUE)

if more than 20+ columns

order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.

How do I get the HTML code of a web page in PHP?

you can use the DomDocument method to get an individual HTML tag level variable too

$homepage = file_get_contents('https://www.example.com/');
$doc = new DOMDocument;
$doc->loadHTML($homepage);
$titles = $doc->getElementsByTagName('h3');
echo $titles->item(0)->nodeValue;

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

Re-assign host access permission to MySQL user

The accepted answer only renamed the user but the privileges were left behind.

I'd recommend using:

RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';

According to MySQL documentation:

RENAME USER causes the privileges held by the old user to be those held by the new user.

How to increment a variable on a for loop in jinja template?

if anyone want to add a value inside loop then you can use this its working 100%

{% set ftotal= {'total': 0} %} 
{%- for pe in payment_entry -%}
    {% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %} 
{%- endfor -%}

{{ftotal.total}}

output = 5

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

These steps solved my problem:

  1. Go into organizer
  2. Devices
  3. select your device
  4. Delete the particular profile.
  5. Run again

Tada...

How to pass arguments within docker-compose?

This feature was added in Compose 1.6.

Reference: https://docs.docker.com/compose/compose-file/#args

services:
  web:
    build:
      context: .
      args:
        FOO: foo

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

What is stability in sorting algorithms and why is it important?

Stable sort will always return same solution (permutation) on same input.

For instance [2,1,2] will be sorted using stable sort as permutation [2,1,3] (first is index 2, then index 1 then index 3 in sorted output) That mean that output is always shuffled same way. Other non stable, but still correct permutation is [2,3,1].

Quick sort is not stable sort and permutation differences among same elements depends on algorithm for picking pivot. Some implementations pick up at random and that can make quick sort yielding different permutations on same input using same algorithm.

Stable sort algorithm is necessary deterministic.

Android EditText Max Length

Possible duplicate of Limit text length of EditText in Android

Use android:maxLength="140"

That should work. :)

Hope that helps

Wait till a Function with animations is finished until running another Function

You can do it via callback function.

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});

function function1(param, callback) { ...do stuff callback(); }

How to handle errors with boto3?

If you are calling the sign_up API (AWS Cognito) using Python3, you can use the following code.

def registerUser(userObj):
    ''' Registers the user to AWS Cognito.
    '''

    # Mobile number is not a mandatory field. 
    if(len(userObj['user_mob_no']) == 0):
        mobilenumber = ''
    else:
        mobilenumber = userObj['user_country_code']+userObj['user_mob_no']

    secretKey = bytes(settings.SOCIAL_AUTH_COGNITO_SECRET, 'latin-1')
    clientId = settings.SOCIAL_AUTH_COGNITO_KEY 

    digest = hmac.new(secretKey,
                msg=(userObj['user_name'] + clientId).encode('utf-8'),
                digestmod=hashlib.sha256
                ).digest()
    signature = base64.b64encode(digest).decode()

    client = boto3.client('cognito-idp', region_name='eu-west-1' ) 

    try:
        response = client.sign_up(
                    ClientId=clientId,
                    Username=userObj['user_name'],
                    Password=userObj['password1'],
                    SecretHash=signature,
                    UserAttributes=[
                        {
                            'Name': 'given_name',
                            'Value': userObj['given_name']
                        },
                        {
                            'Name': 'family_name',
                            'Value': userObj['family_name']
                        },
                        {
                            'Name': 'email',
                            'Value': userObj['user_email']
                        },
                        {
                            'Name': 'phone_number',
                            'Value': mobilenumber
                        }
                    ],
                    ValidationData=[
                        {
                            'Name': 'email',
                            'Value': userObj['user_email']
                        },
                    ]
                    ,
                    AnalyticsMetadata={
                        'AnalyticsEndpointId': 'string'
                    },
                    UserContextData={
                        'EncodedData': 'string'
                    }
                )
    except ClientError as error:
        return {"errorcode": error.response['Error']['Code'],
            "errormessage" : error.response['Error']['Message'] }
    except Exception as e:
        return {"errorcode": "Something went wrong. Try later or contact the admin" }
    return {"success": "User registered successfully. "}

error.response['Error']['Code'] will be InvalidPasswordException, UsernameExistsException etc. So in the main function or where you are calling the function, you can write the logic to provide a meaningful message to the user.

An example for the response (error.response):

{
  "Error": {
    "Message": "Password did not conform with policy: Password must have symbol characters",
    "Code": "InvalidPasswordException"
  },
  "ResponseMetadata": {
    "RequestId": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
    "HTTPStatusCode": 400,
    "HTTPHeaders": {
      "date": "Wed, 17 Jul 2019 09:38:32 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "124",
      "connection": "keep-alive",
      "x-amzn-requestid": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
      "x-amzn-errortype": "InvalidPasswordException:",
      "x-amzn-errormessage": "Password did not conform with policy: Password must have symbol characters"
    },
    "RetryAttempts": 0
  }
}

For further reference : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.sign_up

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

Iterate over a Javascript associative array in sorted order

I really like @luke-schafer's prototype idea, but also hear what he is saying about the issues with prototypes. What about using a simple function?

_x000D_
_x000D_
function sortKeysAndDo( obj, worker ) {_x000D_
  var keys = Object.keys(obj);_x000D_
  keys.sort();_x000D_
  for (var i = 0; i < keys.length; i++) {_x000D_
     worker(keys[i], obj[keys[i]]);_x000D_
  }_x000D_
}_x000D_
_x000D_
function show( key, value ) {_x000D_
  document.write( key + ' : ' + value +'<br>' );_x000D_
}_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
sortKeysAndDo( a, show);_x000D_
_x000D_
var my_object = { 'c': 3, 'a': 1, 'b': 2 };_x000D_
_x000D_
sortKeysAndDo( my_object, show);
_x000D_
_x000D_
_x000D_

This seems to eliminate the issues with prototypes and still provide a sorted iterator for objects. I am not really a JavaScript guru, though, so I'd love to know if this solution has hidden flaws I missed.

Git Push error: refusing to update checked out branch

Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

I have had similar problem and I found a solution to that

if you are echo or print something from controller while return to view this problem will pop up.

so make sure that you are not using echo or print when your controller returns

unsigned APK can not be installed

You cannot install an unsigned application on a phone. You can only use it to test with an emulator. If you still want to go ahead, you can try self-signing the application.

Also, since you are installing the application from an SD card, I hope you have the necessary permissions set. Do go through stackoverflow.com and look at questions regarding installation of applications from an SD card - there have been many and they have been asked before.

Hope that helps.

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

Eclipse: Java was started but returned error code=13

My solution: Because all others did not work for me. I deleted the symlinks at C:\ProgramData\Oracle\Java\javapath. this makes eclipse to run with the jre declared in the PATH. This is better for me because I want to develop Java with the JRE I chose, not the system JRE. Often you want to develop with older versions and such

Angular - Use pipes in services and components

As of Angular 6 you can import formatDate from @angular/common utility to use inside the components.

It was intruduced at https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae

I can be used as:

import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');

Although the locale has to be supplied

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

How do you implement a Stack and a Queue in JavaScript?

Seems to me that the built in array is fine for a stack. If you want a Queue in TypeScript here is an implementation

/**
 * A Typescript implementation of a queue.
 */
export default class Queue {

  private queue = [];
  private offset = 0;

  constructor(array = []) {
    // Init the queue using the contents of the array
    for (const item of array) {
      this.enqueue(item);
    }
  }

  /**
   * @returns {number} the length of the queue.
   */
  public getLength(): number {
    return (this.queue.length - this.offset);
  }

  /**
   * @returns {boolean} true if the queue is empty, and false otherwise.
   */
  public isEmpty(): boolean {
    return (this.queue.length === 0);
  }

  /**
   * Enqueues the specified item.
   *
   * @param item - the item to enqueue
   */
  public enqueue(item) {
    this.queue.push(item);
  }

  /**
   *  Dequeues an item and returns it. If the queue is empty, the value
   * {@code null} is returned.
   *
   * @returns {any}
   */
  public dequeue(): any {
    // if the queue is empty, return immediately
    if (this.queue.length === 0) {
      return null;
    }

    // store the item at the front of the queue
    const item = this.queue[this.offset];

    // increment the offset and remove the free space if necessary
    if (++this.offset * 2 >= this.queue.length) {
      this.queue = this.queue.slice(this.offset);
      this.offset = 0;
    }

    // return the dequeued item
    return item;
  };

  /**
   * Returns the item at the front of the queue (without dequeuing it).
   * If the queue is empty then {@code null} is returned.
   *
   * @returns {any}
   */
  public peek(): any {
    return (this.queue.length > 0 ? this.queue[this.offset] : null);
  }

}

And here is a Jest test for it

it('Queue', () => {
  const queue = new Queue();
  expect(queue.getLength()).toBe(0);
  expect(queue.peek()).toBeNull();
  expect(queue.dequeue()).toBeNull();

  queue.enqueue(1);
  expect(queue.getLength()).toBe(1);
  queue.enqueue(2);
  expect(queue.getLength()).toBe(2);
  queue.enqueue(3);
  expect(queue.getLength()).toBe(3);

  expect(queue.peek()).toBe(1);
  expect(queue.getLength()).toBe(3);
  expect(queue.dequeue()).toBe(1);
  expect(queue.getLength()).toBe(2);

  expect(queue.peek()).toBe(2);
  expect(queue.getLength()).toBe(2);
  expect(queue.dequeue()).toBe(2);
  expect(queue.getLength()).toBe(1);

  expect(queue.peek()).toBe(3);
  expect(queue.getLength()).toBe(1);
  expect(queue.dequeue()).toBe(3);
  expect(queue.getLength()).toBe(0);

  expect(queue.peek()).toBeNull();
  expect(queue.dequeue()).toBeNull();
});

Hope someone finds this useful,

Cheers,

Stu

Failed to resolve: com.android.support:appcompat-v7:28.0

Add the following code on build.gragle (project) for adding Google maven repository

allprojects {
    repositories {
    ...
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    ...
    }
}

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your HTML you have set a "base" tag:

<base href="http://www.cyclistinsuranceaustralia.com.au/">
  1. Delete that line from your HTML if you don't need it. This should make the fonts work when viewed from http://cyclistinsuranceaustralia.com.au.
  2. You'll probably need to redirect http://www.cyclistinsuranceaustralia.com.au to http://cyclistinsuranceaustralia.com.au

Check if file is already open

org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.

I used IOException and it works just fine:

try 
{
  String filePath = "C:\sheet.xlsx";
  FileWriter fw = new FileWriter(filePath );                
}
catch (IOException e)
{
    System.out.println("File is open");
}

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

Error: Cannot find module 'ejs'

Ensure all dependencies are installed. npm install

I was making a quick app for myself and I had forgotten to add express. Threw the above error.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

get an element's id

In events handler you can get id as follows

_x000D_
_x000D_
function show(btn) {_x000D_
  console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
_x000D_
_x000D_

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Unexpected character encountered while parsing value

In my scenario I had a slightly different message, where the line and position were not zero.

E. Path 'job[0].name', line 1, position 12.

This was the top Google answer for the message I quoted.

This came about because I had called a program from the Windows command line, passing JSON as a parameter.

When I reviewed the args in my program, all the double quotes got stripped. You have to reconstitute them.

I posted a solution here. Though it could probably be enhanced with a Regex.

DataGridView - how to set column width?

I know this is an old question but no one ever answered the first part, to set width in percent. That can easily be done with FillWeight (MSDN). In case anyone else searching comes across this answer.

You can set DataGridAutoSizeColumnMode to Fill in the designer. By default that gives each column FillWeight of 100. Then in code behind, on FormLoad event or after binding data to grid, you can simply:

gridName.Columns[0].FillWeight = 200;
gridName.Columns[1].FillWeight = 50;

And so on, for whatever proportional weight you want. If you want to do every single column with numbers that add up to 100, for a literal percent width, you can do that too.

It gives a nice full DataGrid where the headers use the whole space, even if the user resizes the window. Looks good on widescreen, 4:3, whatever.

Filter Pyspark dataframe column with None value

To obtain entries whose values in the dt_mvmt column are not null we have

df.filter("dt_mvmt is not NULL")

and for entries which are null we have

df.filter("dt_mvmt is NULL")

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

Print empty line?

You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).

Trust in the error message -- if it says something specific, assume it to be true and figure out why.

How to get selected path and name of the file opened with file dialog?

Try this

Sub Demo()
    Dim lngCount As Long
    Dim cl As Range

    Set cl = ActiveCell
    ' Open the file dialog
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Show
        ' Display paths of each file selected
        For lngCount = 1 To .SelectedItems.Count
            ' Add Hyperlinks
            cl.Worksheet.Hyperlinks.Add _
                Anchor:=cl, Address:=.SelectedItems(lngCount), _
                TextToDisplay:=.SelectedItems(lngCount)
            ' Add file name
            'cl.Offset(0, 1) = _
            '    Mid(.SelectedItems(lngCount), InStrRev(.SelectedItems(lngCount), "\") + 1)
            ' Add file as formula
            cl.Offset(0, 1).FormulaR1C1 = _
                 "=TRIM(RIGHT(SUBSTITUTE(RC[-1],""\"",REPT("" "",99)),99))"


            Set cl = cl.Offset(1, 0)
        Next lngCount
    End With
End Sub

Git commit date

The show command may be what you want. Try

git show -s --format=%ci <commit>

Other formats for the date string are available as well. Check the manual page for details.

Replace missing values with column mean

With the data.table package you could use the set() function and loop over the columns and replace the NAs or whatever you like with an aggregate or value of your choice (here: mean):

require(data.table)

# data
dt = copy(iris[ ,-5])
setDT(dt)
dt[1:4, Sepal.Length := NA] # introduce NAs

# replace NAs with mean (or whatever function you like)
for (j in seq_along(names(dt))) {
  set(dt,
      i = which(is.na(dt[[j]])),
      j = j, 
      value = mean(dt[[j]], na.rm = TRUE))
}

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Fill formula down till last row in column

Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.

I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.

--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.

 ' **row** **Column1**        **Column2**
 '    1     Title1         Data 1 for title 1
 '    2                    Data 2 for title 1
 '    3                    Data 3 for title 1
 '    4     Title2         Data 1 for title 2
 '    5                    Data 2 for title 2
 '    6                    Data 3 for title 2
 '    7   Title 3          Data 1 for title 3

----- CopyDown code ----------

Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.   
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Set strtCell = ActiveCell
    FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
    Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
'   MsgBox Lastrow
    Range(Lastrow).Formula = strtCell.Formula

    Range(Lastrow).End(xlDown).Select
 End Sub

How can I reset or revert a file to a specific revision?

This is a very simple step. Checkout file to the commit id we want, here one commit id before, and then just git commit amend and we are done.

# git checkout <previous commit_id> <file_name>
# git commit --amend

This is very handy. If we want to bring any file to any prior commit id at the top of commit, we can easily do.

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

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

The definitive solution is to allow the InfoTech protocol to work in the intranet zone.

Add the following value to the registry and the problem should be solved:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001

More info here: http://support.microsoft.com/kb/896054

Connecting to Postgresql in a docker container from outside

For some reason 5432 port seems protected. I changed my port config from 5432:5432to 5416:5432 and the following command worked to connect to your postgres database from outside its docker container:

psql -h localhost -p 5416 -U <my-user> -d <my-database>

How do I save a String to a text file using Java?

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data) 

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

You might also want to consider specifying the encoding for the file as well.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Use the following Statement:

IF EXISTS(SELECT * FROM prueba )
then
  UPDATE prueba
  SET nombre = '1', apellido = '1' 
  WHERE cedula = 'ct'
ELSE 
  INSERT INTO prueba (cedula, nombre, apellido)
  VALUES ('ct', 'ct', 'ct');

Remove Safari/Chrome textinput/textarea glow

I found it helpful to remove the outline on a "sliding door" type of input button, because the outline doesn't cover the right "cap" of the sliding door image making the focus state look a little wonky.

input.slidingdoorbutton:focus { outline: none;}

how to add css class to html generic control div?

Alternative approach if you want to add a class to an existing list of classes of an element:

element.Attributes["class"] += " myCssClass";

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.

How to remove td border with html?

_x000D_
_x000D_
  <table border="1">
  <tr>
    <td>one</td>
    <td style="border-bottom-style: hidden;">two</td>
  </tr>
  <tr>
    <td>one</td>
    <td style="border-top-style: hidden;">two</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

Mongoose limit/offset and count query

db.collection_name.aggregate([
    { '$match'    : { } },
    { '$sort'     : { '_id' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" } ],
        data: [ { $skip: 1 }, { $limit: 10 },{ '$project' : {"_id":0} } ] // add projection here wish you re-shape the docs
    } }
] )

Instead of using two queries to find the total count and skip the matched record.
$facet is the best and optimized way.

  1. Match the record
  2. Find total_count
  3. skip the record
  4. And also can reshape data according to our needs in the query.

How to retrieve element value of XML using Java?

Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.

See the XML how-to

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

Keyboard shortcut to comment lines in Sublime Text 3

On OSX Yosemite, I fixed this by going System Preferences, Keyboard, then Shortcuts. Under App Shortcuts, disable Show Help menu which was bound to CMD+SHIFT+7.

keyboard settings

My keyboard layout is Norwegian, with English as the OS language.

Secure random token in Node.js

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {
    crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}

Why does my sorting loop seem to append an element where it shouldn't?

To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.

This is my full example approach of how you can do it effecively

After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.

static<T>void sort(T[]array,Comparator<?super T>comp)

take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.

The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:

return strB.compareToIgnoreCase(strA);

import java.util.Comparator;

    public class IgnoreCaseComp implements Comparator<String> {

        @Override
        public int compare(String strA, String strB) {
            return strA.compareToIgnoreCase(strB);
        }

    }

  import java.util.Arrays;

    public class IgnoreCaseSort {

        public static void main(String[] args) {
            String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
            System.out.print("Initial order: ");

            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            IgnoreCaseComp icc = new IgnoreCaseComp();

            Arrays.sort(strs, icc);

            System.out.print("Case-insesitive sorted order:  ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            Arrays.sort(strs);

            System.out.print("Default, case-sensitive sorted order: ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");
        }

    }

 run:
    Initial order:  Hello   This  is  Sorting  Example 

    Case-insesitive sorted order:   Hello   This  Example is  Sorting  

    Default, case-sensitive sorted order:  Hello   This  Example Sorting  is  

    BUILD SUCCESSFUL (total time: 0 seconds)

Alternative Choice

The method compareToIgnoreCase(), although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare() from java.text.Collator.

You can find a collator for your location by calling the method getInstance(). After that you should set this Collator's strength property. This can be done with the setStrength() method together with Collator.PRIMARY as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location

import java.text.Collator;
import java.util.Comparator;

//this comparator uses one Collator to determine 
//the right sort usage with no sensitive type 
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {

    Collator col;

    IgnoreCaseComp() {
        //default locale
        col = Collator.getInstance();

        //this will consider only PRIMARY difference ("a" vs "b")
        col.setStrength(Collator.PRIMARY);
    }

    @Override
    public int compare(String strA, String strB) {
        return col.compare(strA, strB);
    }

}

How to get the list of all installed color schemes in Vim?

Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.

Add the below function to your vimrc, then open your source file and call the function from command.

function! DisplayColorSchemes()
   let currDir = getcwd()
   exec "cd $VIMRUNTIME/colors"
   for myCol in split(glob("*"), '\n')
      if myCol =~ '\.vim'
         let mycol = substitute(myCol, '\.vim', '', '')
         exec "colorscheme " . mycol
         exec "redraw!"
         echo "colorscheme = ". myCol
         sleep 2
      endif
   endfor
   exec "cd " . currDir
endfunction

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

Read/write to file using jQuery

Use javascript's execCommand('SaveAs', false, filename); functionality

Edit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.

Now this code is an rare antique zero day collectible.

// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename);
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function like this:

msg =  "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");

How to push to History in React Router v4?

Create a custom Router with its own browserHistory:

import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

const ExtBrowserRouter = ({children}) => (
  <Router history={history} >
  { children }
  </Router>
);

export default ExtBrowserRouter

Next, on your Root where you define your Router, use the following:

import React from 'react';       
import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';

//Use 'ExtBrowserRouter' instead of 'BrowserRouter'
import ExtBrowserRouter from './ExtBrowserRouter'; 
...

export default class Root extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ExtBrowserRouter>
          <Switch>
            ...
            <Route path="/login" component={Login}  />
            ...
          </Switch>
        </ExtBrowserRouter>
      </Provider>
    )
  }
}

Finally, import history where you need it and use it:

import { history } from '../routers/ExtBrowserRouter';
...

export function logout(){
  clearTokens();      
  history.push('/login'); //WORKS AS EXPECTED!
  return Promise.reject('Refresh token has expired');
}

Java: Static Class?

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

Convert PDF to clean SVG?

Bash script to convert each page of a PDF into its own SVG file.

#!/bin/bash
#
#  Make one PDF per page using PDF toolkit.
#  Convert this PDF to SVG using inkscape
#

inputPdf=$1

pageCnt=$(pdftk $inputPdf dump_data | grep NumberOfPages | cut -d " " -f 2)

for i in $(seq 1 $pageCnt); do
    echo "converting page $i..."
    pdftk ${inputPdf} cat $i output ${inputPdf%%.*}_${i}.pdf
    inkscape --without-gui "--file=${inputPdf%%.*}_${i}.pdf" "--export-plain-svg=${inputPdf%%.*}_${i}.svg"
done

To generate in png, use --export-png, etc...

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

java.lang.NoClassDefFoundError: org/json/JSONObject

Add json jar to your classpath

or use java -classpath json.jar ClassName

refer this

How do I determine the size of an object in Python?

If you don't need the exact size of the object but roughly to know how big it is, one quick (and dirty) way is to let the program run, sleep for an extended period of time, and check the memory usage (ex: Mac's activity monitor) by this particular python process. This would be effective when you are trying to find the size of one single large object in a python process. For example, I recently wanted to check the memory usage of a new data structure and compare it with that of Python's set data structure. First I wrote the elements (words from a large public domain book) to a set, then checked the size of the process, and then did the same thing with the other data structure. I found out the Python process with a set is taking twice as much memory as the new data structure. Again, you wouldn't be able to exactly say the memory used by the process is equal to the size of the object. As the size of the object gets large, this becomes close as the memory consumed by the rest of the process becomes negligible compared to the size of the object you are trying to monitor.

How do I delete multiple rows with different IDs?

If you have to select the id:

 DELETE FROM table WHERE id IN (SELECT id FROM somewhere_else)

If you already know them (and they are not in the thousands):

 DELETE FROM table WHERE id IN (?,?,?,?,?,?,?,?)

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Try to download HERE and use this latest chrome driver version.

https://sites.google.com/a/chromium.org/chromedriver/downloads

EDIT:

Try this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
d = webdriver.Chrome('/home/PycharmProjects/chromedriver',chrome_options=chrome_options)
d.get('https://www.google.nl/')

How to compare a local git branch with its remote branch?

Setup

git config alias.udiff 'diff @{u}'

Diffing HEAD with HEAD@{upstream}

git fetch  # Do this if you want to compare with the network state of upstream; if the current local state is enough, you can skip this
git udiff

Diffing with an Arbitrary Remote Branch

This answers the question in your heading ("its remote"); if you want to diff against "a remote" (that isn't configured as the upstream for the branch), you need to target it directly. You can see all remote branches with the following:

git branch -r

You can see all configured remotes with the following:

git remote show

You can see the branch/tracking configuration for a single remote (e.g. origin) as follows:

git remote show origin

Once you determine the appropriate origin branch, just do a normal diff :)

git diff [MY_LOCAL] MY_REMOTE_BRANCH

Associating enums with strings in C#

Based in other opinions, this is what I come up with. This approach avoids having to type .Value where you want to get the constant value.

I have a base class for all string enums like this:

using System;
using Newtonsoft.Json;

[JsonConverter(typeof(ConstantConverter))]
public class StringEnum: IConvertible
{
    public string Value { get; set; }

    protected StringEnum(string value)
    {
        Value = value;
    }

    public static implicit operator string(StringEnum c)
    {
        return c.Value;
    }
    public string ToString(IFormatProvider provider)
    {
        return Value;
    }

    public TypeCode GetTypeCode()
    {
        throw new NotImplementedException();
    }

    public bool ToBoolean(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }
    //The same for all the rest of IConvertible methods
}

The JsonConverter is like this:

using System;
using Newtonsoft.Json;

class ConstantConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null)
        {
            serializer.Serialize(writer, null);
        }
        else
        {
            serializer.Serialize(writer, value.ToString());
        }
    }
}

And an actual string enum will be something like this:

public sealed class Colors : StringEnum
{
    public static Colors Red { get { return new Catalog("Red"); } }
    public static Colors Yellow { get { return new Catalog("Yellow"); } }
    public static Colors White { get { return new Catalog("White"); } }

    private Colors(string value) : base(value) { }
}

And with this, you can just use Color.Red to even serialize to json without using the Value property

m2e error in MavenArchiver.getManifest()

Upgrade your m2e extensions instead downgrade.

From Help > Install New Software.., add a new repository (via the Add.. option)

Specify name for your plugin and add path http://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/

once you are done with installation, please restart eclipse and update your project.

check if file exists on remote host with ssh

Here is a simple approach:

#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'

FILE_NAME=/home/user/file.txt

SSH_PASS='sshpass -p password-for-remote-machine'

if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
            then
                    echo "File exists"
            else
                    echo "File does not exist"

fi

You need to install sshpass on your machine to work it.

Detach (move) subdirectory into separate Git repository

Here is a small modification to CoolAJ86's "The Easy Way™" answer in order to split multiple sub folders (let's say sub1and sub2) into a new git repository.

The Easy Way™ (multiple sub folders)

  1. Prepare the old repo

    pushd <big-repo>
    git filter-branch --tree-filter "mkdir <name-of-folder>; mv <sub1> <sub2> <name-of-folder>/" HEAD
    git subtree split -P <name-of-folder> -b <name-of-new-branch>
    popd
    

    Note: <name-of-folder> must NOT contain leading or trailing characters. For instance, the folder named subproject MUST be passed as subproject, NOT ./subproject/

    Note for windows users: when your folder depth is > 1, <name-of-folder> must have *nix style folder separator (/). For instance, the folder named path1\path2\subproject MUST be passed as path1/path2/subproject. Moreover don't use mvcommand but move.

    Final note: the unique and big difference with the base answer is the second line of the script "git filter-branch..."

  2. Create the new repo

    mkdir <new-repo>
    pushd <new-repo>
    
    git init
    git pull </path/to/big-repo> <name-of-new-branch>
    
  3. Link the new repo to Github or wherever

    git remote add origin <[email protected]:my-user/new-repo.git>
    git push origin -u master
    
  4. Cleanup, if desired

    popd # get out of <new-repo>
    pushd <big-repo>
    
    git rm -rf <name-of-folder>
    

    Note: This leaves all the historical references in the repository.See the Appendix in the original answer if you're actually concerned about having committed a password or you need to decreasing the file size of your .git folder.

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

when I change the code like this, it got worked

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

Server Error in '/' Application. ASP.NET

Removing the web.config-file from the IIS Directory Folder solves the problem.

What is the difference between canonical name, simple name and class name in Java Class?

If you're unsure about something, try writing a test first.

I did this:

class ClassNameTest {
    public static void main(final String... arguments) {
        printNamesForClass(
            int.class,
            "int.class (primitive)");
        printNamesForClass(
            String.class,
            "String.class (ordinary class)");
        printNamesForClass(
            java.util.HashMap.SimpleEntry.class,
            "java.util.HashMap.SimpleEntry.class (nested class)");
        printNamesForClass(
            new java.io.Serializable(){}.getClass(),
            "new java.io.Serializable(){}.getClass() (anonymous inner class)");
    }

    private static void printNamesForClass(final Class<?> clazz, final String label) {
        System.out.println(label + ":");
        System.out.println("    getName():          " + clazz.getName());
        System.out.println("    getCanonicalName(): " + clazz.getCanonicalName());
        System.out.println("    getSimpleName():    " + clazz.getSimpleName());
        System.out.println("    getTypeName():      " + clazz.getTypeName()); // added in Java 8
        System.out.println();
    }
}

Prints:

int.class (primitive):
    getName():          int
    getCanonicalName(): int
    getSimpleName():    int
    getTypeName():      int

String.class (ordinary class):
    getName():          java.lang.String
    getCanonicalName(): java.lang.String
    getSimpleName():    String
    getTypeName():      java.lang.String

java.util.HashMap.SimpleEntry.class (nested class):
    getName():          java.util.AbstractMap$SimpleEntry
    getCanonicalName(): java.util.AbstractMap.SimpleEntry
    getSimpleName():    SimpleEntry
    getTypeName():      java.util.AbstractMap$SimpleEntry

new java.io.Serializable(){}.getClass() (anonymous inner class):
    getName():          ClassNameTest$1
    getCanonicalName(): null
    getSimpleName():    
    getTypeName():      ClassNameTest$1

There's an empty entry in the last block where getSimpleName returns an empty string.

The upshot looking at this is:

  • the name is the name that you'd use to dynamically load the class with, for example, a call to Class.forName with the default ClassLoader. Within the scope of a certain ClassLoader, all classes have unique names.
  • the canonical name is the name that would be used in an import statement. It might be useful during toString or logging operations. When the javac compiler has complete view of a classpath, it enforces uniqueness of canonical names within it by clashing fully qualified class and package names at compile time. However JVMs must accept such name clashes, and thus canonical names do not uniquely identify classes within a ClassLoader. (In hindsight, a better name for this getter would have been getJavaName; but this method dates from a time when the JVM was used solely to run Java programs.)
  • the simple name loosely identifies the class, again might be useful during toString or logging operations but is not guaranteed to be unique.
  • the type name returns "an informative string for the name of this type", "It's like toString: it's purely informative and has no contract value". (as written by sir4ur0n)

How to set a timer in android

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

How to obtain image size using standard Python class (without using external library)?

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info

Output:

foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

xcode-select active developer directory error

I was having the same problem in high sierra. running the following command solved it

npm explore npm -g -- npm install node-gyp@latest

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

Open multiple Projects/Folders in Visual Studio Code

If you are using unix like OS, you can create a soft link to your target folder.

E.g. I want to see golang source while I am using VSCode. So, I create a soft link to go/src under my project folder.

ln -s /usr/local/go/src gosrc

Hope this helps!


Update: 11/28, 2017

Multi Root Workspaces[0] landed in the stable build, finally. https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces

[0] https://github.com/Microsoft/vscode/issues/396

How to create an infinite loop in Windows batch file?

Here is an example of using the loop:

echo off
cls

:begin

set /P M=Input text to encode md5, press ENTER to exit: 
if %M%==%M1% goto end

echo.|set /p ="%M%" | openssl md5

set M1=%M%
Goto begin

This is the simple batch i use when i need to encrypt any message into md5 hash on Windows(openssl required), and the program would loyally repeat itself except given Ctrl+C or empty input.

String Padding in C

#include<stdio.h>
#include <string.h>


void padLeft(int length, char pad, char* inStr,char* outStr) {
    int minLength = length * sizeof(char);
    if (minLength < sizeof(outStr)) {
        return;
    }

    int padLen = length - strlen(inStr);
    padLen = padLen < 0 ? 0 : padLen;

    memset(outStr, 0, sizeof(outStr));
    memset(outStr, pad,padLen);
    memcpy(outStr+padLen, inStr, minLength - padLen);
}

Convert Long into Integer

Integer i = theLong != null ? theLong.intValue() : null;

or if you don't need to worry about null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

Java 8 has a helper method that checks for overflow (you get an exception in that case):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

Formatting html email for Outlook

You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.

Stop absolutely positioned div from overlapping text

Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.

This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.

New structure is as follows:

_x000D_
_x000D_
<div id="outer" style="position: relative; width:450px; background-color:yellow;">
        <p>Content of unknown length</p>
        <div>Content of unknown height </div>
        <div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
        <div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
    </div>
_x000D_
_x000D_
_x000D_

This seems to solve the issue.

Change fill color on vector asset in Android Studio

To change vector image color you can directly use android:tint="@color/colorAccent"

<ImageView
        android:id="@+id/ivVectorImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:tint="@color/colorAccent" />

To change color programatically

ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));

Java ArrayList for integers

Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

For Ex:

list.add(new Integer[3]);

In this way first entry of ArrayList is an integer array which can hold at max 3 values.

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

How do I search an SQL Server database for a string?

For getting a table by name in SQL Server:

SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'

For finding a stored procedure by name:

SELECT name
FROM sys.objects
WHERE name = 'spName'

To get all stored procedures related to a table:

----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

Copying files from one directory to another in Java

Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils

File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

use jQuery's find() on JSON object

Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'") the way you wanted.

There are jQuery plugins to that effect, like json2xml.

Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.

Share data between AngularJS controllers

Simplest Solution:

I have used an AngularJS service.

Step1: I have created an AngularJS service named SharedDataService.

myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

Step2: Create two controllers and use the above created service.

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

Step3: Simply use the created controllers in the view.

<body ng-app="myApp">

<div ng-controller="FirstCtrl">
<input type="text" ng-model="Person.name">
<br>Input is : <strong>{{Person.name}}</strong>
</div>

<hr>

<div ng-controller="SecondCtrl">
Input should also be here: {{Person.name}}
</div>

</body>

To see working solution to this problem please press the link below

https://codepen.io/wins/pen/bmoYLr

.html file:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="Person.name">
    <br>Input is : <strong>{{Person.name}}</strong>
   </div>

<hr>

  <div ng-controller="SecondCtrl">
    Input should also be here: {{Person.name}}
  </div>

//Script starts from here

<script>

var myApp = angular.module("myApp",[]);
//create SharedDataService
myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
    }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
}]);

</script>


</body>
</html>

commons httpclient - Adding query string parameters to GET/POST request

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

Here is a more flexible solution. Crude but can be refined.

public static void main(String[] args) {

    String host = "localhost";
    String port = "9093";

    String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
    String[] wholeString = param.split("\\?");
    String theQueryString = wholeString.length > 1 ? wholeString[1] : "";

    String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";

    GetMethod method = new GetMethod(SolrUrl );

    if (theQueryString.equalsIgnoreCase("")) {
        method.setQueryString(new NameValuePair[]{
        });
    } else {
        String[] paramKeyValuesArray = theQueryString.split("&");
        List<String> list = Arrays.asList(paramKeyValuesArray);
        List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
        for (String s : list) {
            String[] nvPair = s.split("=");
            String theKey = nvPair[0];
            String theValue = nvPair[1];
            NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
            nvPairList.add(nameValuePair);
        }
        NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
        nvPairList.toArray(nvPairArray);
        method.setQueryString(nvPairArray);       // Encoding is taken care of here by setQueryString

    }
}

How to install sshpass on mac?

Another option in 2020 is this homebrew tap, maintained by esolitos

brew install esolitos/ipa/sshpass

Navigation bar show/hide

This isn't something that can fit into a few lines of code, but this is one approach that might work for you.

To hide the navigation bar:

[[self navigationController] setNavigationBarHidden:YES animated:YES];

To show it:

[[self navigationController] setNavigationBarHidden:NO animated:YES];

Documentation for this method is available here.

To listen for a "double click" or double-tap, subclass UIView and make an instance of that subclass your view controller's view property.

In the view subclass, override its -touchesEnded:withEvent: method and count how many touches you get in a duration of time, by measuring the time between two consecutive taps, perhaps with CACurrentMediaTime(). Or test the result from [touch tapCount].

If you get two taps, your subclassed view issues an NSNotification that your view controller has registered to listen for.

When your view controller hears the notification, it fires a selector that either hides or shows the navigation bar using the aforementioned code, depending on the navigation bar's current visible state, accessed through reading the navigation bar's isHidden property.

EDIT

The part of my answer for handling tap events is probably useful back before iOS 3.1. The UIGestureRecognizer class is probably a better approach for handling double-taps, these days.

EDIT 2

The Swift way to hide the navigation bar is:

navigationController?.setNavigationBarHidden(true, animated: true)

To show it:

navigationController?.setNavigationBarHidden(false, animated: true)

codeigniter, result() vs. result_array()

Result has an optional $type parameter which decides what type of result is returned. By default ($type = "object"), it returns an object (result_object()). It can be set to "array", then it will return an array of result, that being equivalent of caling result_array(). The third version accepts a custom class to use as a result object.

The code from CodeIgniter:

/**
* Query result. Acts as a wrapper function for the following functions.
*
* @param string $type 'object', 'array' or a custom class name
* @return array
*/
public function result($type = 'object')
{
    if ($type === 'array')
    {
        return $this->result_array();
    }
    elseif ($type === 'object')
    {
        return $this->result_object();
    }
    else
    {
        return $this->custom_result_object($type);
    }
}

Arrays are technically faster, but they are not objects. It depends where do you want to use the result. Most of the time, arrays are sufficient.

How to get the index of an element in an IEnumerable?

Using @Marc Gravell 's answer, I found a way to use the following method:

source.TakeWhile(x => x != value).Count();

in order to get -1 when the item cannot be found:

internal static class Utils
{

    public static int IndexOf<T>(this IEnumerable<T> enumerable, T item) => enumerable.IndexOf(item, EqualityComparer<T>.Default);

    public static int IndexOf<T>(this IEnumerable<T> enumerable, T item, EqualityComparer<T> comparer)
    {
        int index = enumerable.TakeWhile(x => comparer.Equals(x, item)).Count();
        return index == enumerable.Count() ? -1 : index;
    }
}

I guess this way could be both the fastest and the simpler. However, I've not tested performances yet.

Switch focus between editor and integrated terminal in Visual Studio Code

Here is a way to add your own keybinding for switching focus.

  1. Open your VSCode
  2. Press Ctrl+Shift+P and search for keyboard shortcuts and hit this (Preferences: Open Keyboard shortcuts).
  3. Search for 'focus terminal' in the search panel and find this option (Terminal: Focus on Terminal View) and click on the plus icon.

enter image description here

  1. Enter the shortcut as you like which is not used and hit Enter.
  2. Go to Editor mode and try using your shortcut.
  3. Now hit Alt+Shift+T to go to the terminal.
  4. Want to go back to the editor? Just Hit Ctrl+tab

Tested on Windows 10 machine with VSCode(1.52.1)

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

Why is lock(this) {...} bad?

Because any chunk of code that can see the instance of your class can also lock on that reference. You want to hide (encapsulate) your locking object so that only code that needs to reference it can reference it. The keyword this refers to the current class instance, so any number of things could have reference to it and could use it to do thread synchronization.

To be clear, this is bad because some other chunk of code could use the class instance to lock, and might prevent your code from obtaining a timely lock or could create other thread sync problems. Best case: nothing else uses a reference to your class to lock. Middle case: something uses a reference to your class to do locks and it causes performance problems. Worst case: something uses a reference of your class to do locks and it causes really bad, really subtle, really hard-to-debug problems.

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Java: Insert multiple rows into MySQL with PreparedStatement

we can be submit multiple updates together in JDBC to submit batch updates.

we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit

addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate

here addBatch() method adds a set of statements or parameters to the current batch.

How to deploy a React App on Apache web server

Ultimately was able to figure it out , i just hope it will help someone like me.
Following is how the web pack config file should look like check the dist dir and output file specified. I was missing the way to specify the path of dist directory

const webpack = require('webpack');
const path = require('path');
var config = {
    entry: './main.js',

    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index.js',
    },

    devServer: {
        inline: true,
        port: 8080
    },
    resolveLoader: {
        modules: [path.join(__dirname, 'node_modules')]
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
}

module.exports = config;

Then the package json file

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --progress",
    "production": "webpack -p --progress"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack": "^2.2.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.20",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "express": "^4.13.3",
    "webpack": "^1.9.6",
    "webpack-devserver": "0.0.6"
  }
}

Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )

Rest fot the things will depend upon your code and components

Execute following sequence of commands

npm install

this should get you all the dependency (node modules)

then

npm run production

this should get you the final index.js file which will contain all the code bundled

Once done place index.html and index.js files under www/html or the web app root directory and that's all.

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

How can I combine multiple rows into a comma-delimited list in Oracle?

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

jquery function setInterval

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

How to get numeric value from a prompt box?

var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I agree with Beytan Kurt.

I had 503 thrown for both the Central Admin site as well as the SharePoint landing page. In both cases the Passwords were expired.

After resetting the password in the AD, and refreshing the Identity, CA worked but the SharePoint landing page threw a 500 error.

It turned out that the .Net Framework Version was set to V4.0. I changed it to V2.0 and it worked.

Remember after each change you need to recycle the appropriate app pool.

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

Javascript Regexp dynamic generation from variables?

You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

How to add content to html body using JS?

In most browsers, you can use a javascript variable instead of using document.getElementById. Say your html body content is like this:

<section id="mySection"> Hello </section>

Then you can just refer to mySection as a variable in javascript:

mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'

See this snippet:

_x000D_
_x000D_
mySection.innerText += ', world!'
_x000D_
<section id="mySection"> Hello </section>
_x000D_
_x000D_
_x000D_

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Instead of the JSON document, you can update the ObjectMapper object like below :

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Best way to find if an item is in a JavaScript array?

First, implement indexOf in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras (also, the associated blog post). And then you can use indexOf without worrying about browser support. Here's a slightly optimised version of his indexOf implementation:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var i = -1, j = arr.length; ++i < j;)
            if(arr[i] === obj) return true;
        return false;
    };

I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

Installing a local module using npm?

So I had a lot of problems with all of the solutions mentioned so far...

I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.

I also need it to work on Windows AND Unix, so sym-links aren't ideal.

Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.

so.. This is what worked well for me!

Main Project's Package.json File Snippet:

  "name": "main-project-name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    ...
    "preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
  },
  "private": true,
  "dependencies": {
    ...
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
    ...
  }

This achieves 3 things:

  • Avoids the common error (at least with angular npm projects) "index.ts is not part of the compilation." - as it points to the built (dist) folder.
  • Adds a preinstall step to build the referenced npm client package to make sure the dist folder of our dependent package is built.
  • Avoids issues where referencing a tar.gz file locally may be cached by npm and not updated in the main project without lots of cleaning/troubleshooting/re-building/re-installing.

I hope this is clear, and helps someone out.

The tar.gz approach also sort of works..

npm install (file path) also sort of works.

This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)

====== UPDATE: ======

There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.

As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.

First:

For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.

As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:

  "scripts": {
    "build": "ng-packagr -p ng-package.json",
    "package": "npm install && npm run build && cd dist && npm pack"
  },

And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:

  "scripts": {
    "preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
  },

Second

Reference the built tgz npm package from your main project!

  "dependencies": {
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
    ...
  }

Third

Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.

If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348

for now, just update the:

"version": "1.0.0-build5",

In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:

"dependencies": {
       "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
        ...
}

You get used to it. Just update the two package.json files - version then the ref to the new filename.

Hope that helps someone...

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

@Override
protected Result doInBackground(Params... params) {
    createTimeoutListener();
    return doInBackgroundImpl(params);
}

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {
            Looper.prepare();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                        AsyncTaskWithTimer.this.cancel(true);
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
                }
            }, HTTP_REQUEST_TIMEOUT);

            Looper.loop();
        }
    };
    timeout.start();
}

abstract protected Result doInBackgroundImpl(Params... params);
}

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    @Override
    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");
        super.onCancelled(result);
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");
        super.onCancelled();
    }

    @Override
    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;
    };
 }

How to NodeJS require inside TypeScript file?

Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

declare function require(name:string);
var sampleModule = require('modulename');

On my system, this compiles just fine.

NuGet auto package restore does not work with MSBuild

MSBuild 15 has a /t:restore option that does this. it comes with Visual Studio 2017.

If you want to use this, you also have to use the new PackageReference, which means replacing the packages.config file with elements like this (do this in *.csproj):

<ItemGroup>
  <!-- ... -->
  <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0" />
  <!-- ... -->
</ItemGroup>

There is an automated migration to this format if you right click on 'References' (it might not show up if you just opened visual studio, rebuild or open up the 'Manage NuGet packages for solution' window and it will start appearing).

How do I pipe or redirect the output of curl -v?

add the -s (silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body

curl -vs google.com 2>&1 | less

Markdown `native` text alignment

In order to center text in md files you can use the center tag like html tag:

<center>Centered text</center>

How to embed a Facebook page's feed into my website

Correct me if I am wrong, but it seems that Facebook deprecated the Activity Feed plugin. Additionally there does not seem to be any substitute plugin for activity anymore.

Here is the link: https://developers.facebook.com/docs/plugins/activity

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

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

Looking for a one line option:

    <div class="jumbotron bg-dark"> got a team? </div>        

https://getbootstrap.com/docs/4.0/components/jumbotron/