Programs & Examples On #Feature driven

Feature-driven development (FDD) is an iterative and incremental software development process. It is one of a number of Agile methods for developing software and forms part of the Agile Alliance. FDD blends a number of industry-recognized best practices into a cohesive whole. These practices are all driven from a client-valued functionality (feature) perspective. Its main purpose is to deliver tangible, working software repeatedly in a timely manner.

How to abort makefile if variable not set?

Use the shell function test:

foo:
    test $(something)

Usage:

$ make foo
test 
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x

Child with max-height: 100% overflows parent

I found a solution here: http://www.sitepoint.com/maintain-image-aspect-ratios-responsive-web-design/

The trick is possible because it exists a relation between WIDTH and PADDING-BOTTOM of an element. So:

parent:

container {
  height: 0;
  padding-bottom: 66%; /* for a 4:3 container size */
  }

child (remove all css related to width, i.e. width:100%):

img {
  max-height: 100%;
  max-width: 100%;
  position: absolute;     
  display:block;
  margin:0 auto; /* center */
  left:0;        /* center */
  right:0;       /* center */
  }

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

pytest cannot import module while python can

I had placed all my tests in a tests folder and was getting the same error. I solved this by adding an init.py in that folder like so:

.
|-- Pipfile
|-- Pipfile.lock
|-- README.md
|-- api
|-- app.py
|-- config.py
|-- migrations
|-- pull_request_template.md
|-- settings.py
`-- tests
    |-- __init__.py <------
    |-- conftest.py
    `-- test_sample.py

Add row to query result using select

In SQL Server, you would say:

Select name from users
UNION [ALL]
SELECT 'JASON'

In Oracle, you would say

Select name from user
UNION [ALL]
Select 'JASON' from DUAL

How to do join on multiple criteria, returning all combinations of both criteria

create table a1
(weddingTable INT(3),
 tableSeat INT(3),
 tableSeatID INT(6),
 Name varchar(10));

insert into a1
 (weddingTable, tableSeat, tableSeatID, Name)
 values (001,001,001001,'Bob'),
 (001,002,001002,'Joe'),
 (001,003,001003,'Dan'),
 (002,001,002001,'Mark');

create table a2
 (weddingTable int(3),
 tableSeat int(3),
 Meal varchar(10));

insert into a2
(weddingTable, tableSeat, Meal)
values 
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');

select x.*, y.Meal

from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);

How can I add a vertical scrollbar to my div automatically?

You need to assign some height to make the overflow: auto; property work.
For testing purpose, add height: 100px; and check.
and also it will be better if you give overflow-y:auto; instead of overflow: auto;, because this makes the element to scroll only vertical but not horizontal.

float:left;
width:1000px;
overflow-y: auto;
height: 100px;

If you don't know the height of the container and you want to show vertical scrollbar when the container reaches a fixed height say 100px, use max-height instead of height property.

For more information, read this MDN article.

Can local storage ever be considered secure?

As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).

It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)

As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.

In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.

Adding and removing style attribute from div with jquery

To completely remove the style attribute of the voltaic_holder span, do this:

$("#voltaic_holder").removeAttr("style");

To add an attribute, do this:

$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");

To remove only the top style, do this:

$("#voltaic_holder").css("top", "");

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Multiple Java versions running concurrently under Windows

I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.

Article by: Ted Neward: Multiple Java Homes: Giving Java Apps Their Own JRE

With the exponential growth of Java as a server-side development language has come an equivablent exponential growth in Java development tools, environments, frameworks, and extensions. Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above, some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0 days, others require the "javax.swing" package names.

Worse yet, this problem can be found even within the corporate enterprise, as systems developed using Java from just six months ago may suddenly "not work" due to the installation of some Java Extension required by a new (seemingly unrelated) application release. This can complicate deployment of Java applications across the corporation, and lead customers to wonder precisely why, five years after the start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes, we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the infamous "DLL-Hell" problem just described.)

This paper describes how to configure a Java installation such that a given application receives its own, private, JRE, allowing multiple Java environments to coexist without driving customers (or system administrators) insane...

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

How do I work with a git repository within another repository?

The key is git submodules.

Start reading the Submodules chapter of the Git Community Book or of the Users Manual

Say you have repository PROJECT1, PROJECT2, and MEDIA...

cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"

Repeat on the other repo...

Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:

cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"

This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.

It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.

With great power comes the great chance to get bitten in the rump.

How to add number of days to today's date?

If the times in the Date are not needed, then you can simply use the date object's methods to extract the Month,Year and Day and add "n" number of days to the Day part.

var n=5; //number of days to add. 
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)

Ref:Mozilla Javascript GetDate

Edit: Ref: Mozilla JavaScript Date

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

Tools: replace not replacing in Android manifest

The missing piece for me was this:

xmlns:tools="http://schemas.android.com/tools"

for example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
    package="com.your.appid">

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

Compare two MySQL databases

For the first part of the question, I just do a dump of both and diff them. Not sure about mysql, but postgres pg_dump has a command to just dump the schema without the table contents, so you can see if you've changed the schema any.

How to send a JSON object over Request with Android?

Sending a json object from Android is easy if you use Apache HTTP Client. Here's a code sample on how to do it. You should create a new thread for network activities so as not to lock up the UI thread.

    protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

You could also use Google Gson to send and retrieve JSON.

Email and phone Number Validation in android

try this:

extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));

private boolean validateMobile()    {   

    String mobile =extMobileNo.getText().toString().trim();
    if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )

    {
            inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
        requestFocus(extMobileNo);
        return false;
    }

    else {
        inputLayoutMobile.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidMobile(String mobile)
{
    return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}

copy-item With Alternate Credentials

that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...

It looks like they do here, copy-item certainly includes a -Credential parameter.

PS C:\> gcm -syn copy-item
Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-I
nclude <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [...]

How do I use the CONCAT function in SQL Server 2008 R2?

NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function

SQL Server 2012:

SELECT CONCAT(data1, data2)

PRE SQL 2012 (Two Solutions):

SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}

SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')

These two solutions collate several excellent answers and caveats raised by other posters including @Martin Smith, @Svish and @vasin1987.

These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.

Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.

Note also the potential issue identified by @Swifty regarding the default varchar size here remedied by varchar(MAX).

Calculating bits required to store decimal number

Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.

For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits

org.hibernate.PersistentObjectException: detached entity passed to persist

You didn't provide many relevant details so I will guess that you called getInvoice and then you used result object to set some values and call save with assumption that your object changes will be saved.

However, persist operation is intended for brand new transient objects and it fails if id is already assigned. In your case you probably want to call saveOrUpdate instead of persist.

You can find some discussion and references here "detached entity passed to persist error" with JPA/EJB code

How to remove special characters from a string?

You can remove single char as follows:

String str="+919595354336";

 String result = str.replaceAll("\\\\+","");

 System.out.println(result);

OUTPUT:

919595354336

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

How do I change the database name using MySQL?

Another way to rename the database or taking an image of the database is by using the reverse engineering option in the database tab. It will create an ER diagram for the database. Rename the schema there.

After that, go to the File menu and go to export and forward engineer the database.

Then you can import the database.

How do I read an attribute on a class at runtime?

A simplified version of Darin Dimitrov's first solution:

public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttribute<DomainNameAttribute>(true);
    if (dnAttribute != null)
    {
        return dnAttribute.Name;
    }
    return null;
}

How to write a basic swap function in Java

What about the mighty IntHolder? I just love any package with omg in the name!

import org.omg.CORBA.IntHolder;

IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);

swap(a, b);

p = a.value;
q = b.value;

void swap(IntHolder a, IntHolder b) {
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

Can I set a TTL for @Cacheable

If you are working with redis and Java 8, you can take a look at JetCache:

@Cached(expire = 10, timeUnit = TimeUnit.MINUTES) User getUserById(long userId);

Cutting the videos based on start and end time using ffmpeg

Use -to instead of -t: -to specifies the end time, -t specifies the duration

How can I create an editable combo box in HTML/Javascript?

Was looking for an Answer as well, but all I could find was outdated.

This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>

If I had not found that, I would have gone with this approach:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

File upload from <input type="file">

I think that it's not supported. If you have a look at this DefaultValueAccessor directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value.

This doesn't apply in the case of inputs with type file since the file object can be reached $event.srcElement.files instead.

For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
  }
}

firefox proxy settings via command line

Thank very much, I find the answers in this website.

Here I refer to the production of a cmd file

by minimo

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "192.168.1.235 ");>>"%ffile%\prefs.js"
echo user_pref("network.proxy.http_port", 80);>>"%ffile%\prefs.js"
echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js"
set ffile=
cd %windir%

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

I put together a quick demo: http://jsbin.com/agugo3/edit

My results on Internet Explorer 8 are 156, 782, and 750, which would indicate slice is much faster in this case.

Open file dialog box in JavaScript

Actually, you don't need all that stuff with opacity, visibility, <input> styling, etc. Just take a look:

<a href="#">Just click me.</a>
<script type="text/javascript">
    $("a").click(function() {
        // creating input on-the-fly
        var input = $(document.createElement("input"));
        input.attr("type", "file");
        // add onchange handler if you wish to get the file :)
        input.trigger("click"); // opening dialog
        return false; // avoiding navigation
    });
</script>

Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.

Cannot open new Jupyter Notebook [Permission Denied]

I had the very same issue running Jupyter. After chasing my tail on permissions, I found that everything cleared up after I changed ownership on the directory where I was trying to run/store my notebooks. Ex.: I was running my files out of my ~/bash dir. That was root:root; when I changed it to jim:jim....no more errors.

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

What is object serialization?

I'll offer an analogy to potentially assist in solidifying the conceptual purpose/practicality of object serialization/deserialization.

I imagine object serialization/deserialization in the context of attempting to move an object through a storm drain. The object is essentially "decomposed" or serialized into more modular versions of itself - in this case, a series of bytes - in order to effectively be granted passage through a medium. In a computational sense, we could view the path traveled by the bytes through the storm drain as being akin to bytes traveling through a network. We're transmuting our object in order to conform to a more desirable mode of transportation, or format. The serialized object will typically be stored in a binary file which may later be read from, written to, or both.

Perhaps once our object is able to slip through the drain as a decomposed series of bytes, we may wish to store that representation of the object as binary data within a database or hard disk drive. The main takeaway though, is that with serialization/deserialization, we have the option to let our object remain in it's binary form after being serialized, or "retrieve" the object's original form by performing deserialization.

Limiting floats to two decimal points

The built-in round() works just fine in Python 2.7 or later.

Example:

>>> round(14.22222223, 2)
14.22

Check out the documentation.

How to dynamically insert a <script> tag via jQuery after page load?

If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.

If the script is static, then Rocket's getScript-suggestion is the way to go.

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

How to use foreach with a hash reference?

So, with Perl 5.20, the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Bin size in Matplotlib (Histogram)

This answer support the @ macrocosme suggestion.

I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.

Describe statistics. enter image description here

# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');

plt.colorbar();

enter image description here

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

Getting indices of True values in a boolean list

TL; DR: use np.where as it is the fastest option. Your options are np.where, itertools.compress, and list comprehension.

See the detailed comparison below, where it can be seen np.where outperforms both itertools.compress and also list comprehension.

>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
  • Method 1: Using list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 2: Using itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 3 (the fastest method): Using numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Display animated GIF in iOS

Another alternative is to use a UIWebView to display the animated GIF. If the GIF is going to be fetched from a server, then this takes care of the fetching. It also works with local GIFs.

How to configure logging to syslog in Python?

I fix it on my notebook. The rsyslog service did not listen on socket service.

I config this line bellow in /etc/rsyslog.conf file and solved the problem:

$SystemLogSocketName /dev/log

Open source PDF library for C/C++ application?

  • LibHaru seems to be used by many.

A non-open source approach is: PDF Creator Pilot which provides more language options including C++, C#, Delphi, ASP, ASP.NET, VB, VB.NET, VBScript, PHP and Python

Where is nodejs log file?

If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name

That will show you STDOUT and STDERR.

Jersey Exception : SEVERE: A message body reader for Java class

In my case, I'm using POJO. And I forgot configure POJOMappingFeature as true. Maycon has pointed it out in an early answer. However some guys might have trouble to configure it in web.xml correctly, here is my example.

<servlet>
    <servlet-name>Jersey Servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

JavaScript validation for empty input field

if(document.getElementById("question").value == "")
{
    alert("empty")
}

Select multiple columns from a table, but group by one

SELECT ProductID, ProductName, OrderQuantity, SUM(OrderQuantity) FROM OrderDetails WHERE(OrderQuantity) IN(SELECT SUM(OrderQuantity) FROM OrderDetails GROUP BY OrderDetails) GROUP BY ProductID, ProductName, OrderQuantity;

I used the above solution to solve a similar problem in Oracle12c.

Apply style to cells of first row

Use tr:first-child to take the first tr:

.category_table tr:first-child td {
    vertical-align: top;
}

If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level tds in the first top-level tr get the styles:

.category_table > tbody > tr:first-child > td {
    vertical-align: top;
}

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I had this problem and took long while to figure it out. Problem came up when I removed projects from solution and replaced those with nuget packages.

Solution seemed to be fine but the .csproj file still contained those projects multiple times as reference.

Seems that VS does not clean that file appropriately. It was still referencing the removed projects under the hood. When manually removed the references from csproj file all works again! wohoo

Could not extract response: no suitable HttpMessageConverter found for response type

As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:

restTemplate.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        });

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

How to add/update an attribute to an HTML element using JavaScript?

Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

Recover unsaved SQL query scripts

You may be able to find them in one of these locations (depending on the version of Windows you are using).

Windows XP

C:\Documents and Settings\YourUsername\My Documents\SQL Server Management Studio\Backup Files\

Windows Vista/7/10

%USERPROFILE%\Documents\SQL Server Management Studio\Backup Files

OR

%USERPROFILE%\AppData\Local\Temp

Googled from this source and this source.

How to use a dot "." to access members of dictionary?

This solution is a refinement upon the one offered by epool to address the requirement of the OP to access nested dicts in a consistent manner. The solution by epool did not allow for accessing nested dicts.

class YAMLobj(dict):
    def __init__(self, args):
        super(YAMLobj, self).__init__(args)
        if isinstance(args, dict):
            for k, v in args.iteritems():
                if not isinstance(v, dict):
                    self[k] = v
                else:
                    self.__setattr__(k, YAMLobj(v))


    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(YAMLobj, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(YAMLobj, self).__delitem__(key)
        del self.__dict__[key]

With this class, one can now do something like: A.B.C.D.

Property 'map' does not exist on type 'Observable<Response>'

In rxjs 6 map operator usage has been changed now you need to Use it like this.

import { map } from 'rxjs/operators';
myObservable
  .pipe(map(data => data * 2))
  .subscribe(...);

For reference https://www.academind.com/learn/javascript/rxjs-6-what-changed/#operators-update-path

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

Reduce left and right margins in matplotlib plot

Sometimes, the plt.tight_layout() doesn't give me the best view or the view I want. Then why don't plot with arbitrary margin first and do fixing the margin after plot? Since we got nice WYSIWYG from there.

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
plt.show()

Change border and spacing GUI here

Then paste settings into margin function to make it permanent:

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
fig.subplots_adjust(
    top=0.981,
    bottom=0.049,
    left=0.042,
    right=0.981,
    hspace=0.2,
    wspace=0.2
)
plt.show()

Authenticating in PHP using LDAP through Active Directory

Importing a whole library seems inefficient when all you need is essentially two lines of code...

$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
  // log them in!
} else {
  // error message
}

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

How to compile a Perl script to a Windows executable with Strawberry Perl?

  :: short answer :
  :: perl -MCPAN -e "install PAR::Packer" 
  pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>> 

  :: long answer - create the following cmd , adjust vars to your taste ...
  :: next_line_is_templatized
  :: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
  :: disable the echo
  @echo off

  :: this is part of the name of the file - not used
  set _Action=run

  :: the name of the Product next_line_is_templatized
  set _ProductName=morphus

  :: the version of the current Product next_line_is_templatized
  set _ProductVersion=1.2.3

  :: could be dev , test , dev , prod next_line_is_templatized
  set _ProductType=dev

  :: who owns this Product / environment next_line_is_templatized
  set _ProductOwner=ysg

  :: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )   
  set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%

  :: go the run dir
  cd %~dp0

  :: do 4 times going up
  for /L %%i in (1,1,5) do pushd ..

  :: The BaseDir is 4 dirs up than the run dir
  set _ProductBaseDir=%CD%
  :: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
  :: remove the trailing \

  IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
  :: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
  :: debug pause


  :: The version directory of the Product 
  set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%

  :: the dir under which all the perl scripts are placed
  set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl

  :: The Perl script performing all the tasks
  set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl

  :: where the log events are stored 
  set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log

  :: define a favorite editor 
  set _MyEditor=textpad

  ECHO Check the variables 
  set _
  :: debug PAUSE
  :: truncate the run log
  echo date is %date% time is %time% > %_RunLog%


  :: uncomment this to debug all the vars 
  :: debug set  >> %_RunLog%

  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1


  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1

  :: now open the run log
  cmd /c start /max %_MyEditor% %_RunLog%


  :: this is the call without debugging
  :: old 
  echo CFPoint1  OK The run cmd script %0 is executed >> %_RunLog%
  echo CFPoint2  OK  compile the exe file  STDOUT and STDERR  to a single _RunLog file >> %_RunLog%
  cd %_ProductVersionPerlDir%

  pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1 

  :: open the run log
  cmd /c start /max %_MyEditor% %_RunLog%

  :: uncomment this line to wait for 5 seconds
  :: ping localhost -n 5

  :: uncomment this line to see what is happening 
  :: PAUSE

  ::
  :::::::
  :: Purpose: 
  :: To compile every *.pl file into *.exe file under a folder 
  :::::::
  :: Requirements : 
  :: perl , pp , win gnu utils tee 
  :: perl -MCPAN -e "install PAR::Packer" 
  :: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
  :::::::
  :: VersionHistory
  :: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
  :::::::
  :: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0

Get LatLng from Zip Code - Google Maps API

While working on my internship project I found a website for this https://thezipcodes.com/ Create a free account and get the API key from account Section.

https://thezipcodes.com/api/v1/search?zipCode={zipCode}&countryCode={2digitCountryCode}&apiKey={apiKey}

I found majority of data here.

Get the current script file name

Try this

_x000D_
_x000D_
$file = basename($_SERVER['PATH_INFO']);//Filename requested
_x000D_
_x000D_
_x000D_

Code for a simple JavaScript countdown timer?

My solution works with MySQL date time formats and provides a callback function. on complition. Disclaimer: works only with minutes and seconds, as this is what I needed.

jQuery.fn.countDownTimer = function(futureDate, callback){
    if(!futureDate){
        throw 'Invalid date!';
    }

    var currentTs = +new Date();
    var futureDateTs = +new Date(futureDate);

    if(futureDateTs <= currentTs){
        throw 'Invalid date!';
    }


    var diff = Math.round((futureDateTs - currentTs) / 1000);
    var that = this;

    (function countdownLoop(){
        // Get hours/minutes from timestamp
        var m = Math.floor(diff % 3600 / 60);
        var s = Math.floor(diff % 3600 % 60);
        var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);

        $(that).text(text);

        if(diff <= 0){
            typeof callback === 'function' ? callback.call(that) : void(0);
            return;
        }

        diff--;
        setTimeout(countdownLoop, 1000);
    })();

    function zeroPad(num, places) {
      var zero = places - num.toString().length + 1;
      return Array(+(zero > 0 && zero)).join("0") + num;
    }
}

// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})

How to check if click event is already bound - JQuery

Why not use this

unbind() before bind()

$('#myButton').unbind().bind('click',  onButtonClicked);

How to take MySQL database backup using MySQL Workbench?

In workbench 6.0 Connect to any of the database. You will see two tabs.

1.Management 2. Schemas

By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

MIN and MAX in C

The simplest way is to define it as a global function in a .h file, and call it whenever you want, if your program is modular with lots of files. If not, double MIN(a,b){return (a<b?a:b)} is the simplest way.

Maven Install on Mac OS X

When I upgraded recently to OS X Mavericks and my maven builds start failing. So I needed to install maven again as it doesn't come built in. Then I tried with the command:

brew install maven 

it works, but it installs the version 3.1.1 of maven which causes some problems for a few users like (https://cwiki.apache.org/confluence/display/MAVEN/AetherClassNotFound). So if you're running into the same issue you will probably want to install the earlier Maven version, the 3.0.5. To do that with Homebrew, you have to execute the following command:

brew install https://raw.github.com/Homebrew/homebrew-versions/master/maven30.rb

That's it, it will then use a different Homebrew's formulae which will give you the maven 3.0.5 instead.

PHP Fatal error: Cannot access empty property

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

How to get indices of a sorted array in Python

If you do not want to use numpy,

sorted(range(len(seq)), key=seq.__getitem__)

is fastest, as demonstrated here.

Component is part of the declaration of 2 modules

Since the Ionic 3.6.0 release every page generated using Ionic-CLI is now an Angular module. This means you've to add the module to your imports in the file src/app/app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { ErrorHandler, NgModule } from "@angular/core";
import { IonicApp, IonicErrorHandler, IonicModule } from "ionic-angular";
import { SplashScreen } from "@ionic-native/splash-screen";
import { StatusBar } from "@ionic-native/status-bar";;

import { MyApp } from "./app.component";
import { HomePage } from "../pages/home/home"; // import the page
import {HomePageModule} from "../pages/home/home.module"; // import the module

@NgModule({
  declarations: [
    MyApp,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HomePageModule // declare the module
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage, // declare the page
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: ErrorHandler, useClass: IonicErrorHandler },
  ]
})
export class AppModule {}

error: Unable to find vcvarsall.bat

I just had this same problem, so I'll tell my story here hoping it helps someone else with the same issues and save them the couple of hours I just spent:

I have mingw (g++ (GCC) 4.6.1) and python 2.7.3 in a windows 7 box and I'm trying to install PyCrypto.

It all started with this error when running setup.py install:

error: Unable to find vcvarsall.bat

Easily solved after googling the error by specifying mingw as the compiler of choice:

setup.py install build --compiler=mingw32

The problem is that then I got a different error:

configure: error: cannot run C compiled programs.

It turns out that my anti-virus was blocking the execution of a freshly compiled .exe. I just disabled the anti-virus "resident shield" and went to the next error:

cc1.exe: error: unrecognized command line option '-mno-cygwin' 
error: command 'gcc' failed with exit status 1

This solved it: "Either install a slightly older version of MinGW, or edit distutils\cygwinccompiler.py in your Python directory to remove all instances of -mno-cygwin." (from here)

Now, I can finally start working.

How can I round down a number in Javascript?

You need to put -1 to round half down and after that multiply by -1 like the example down bellow.

<script type="text/javascript">

  function roundNumber(number, precision, isDown) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = 0;
    if (isDown) {
      tempNumber = -tempNumber;
      roundedTempNumber = Math.round(tempNumber) * -1;
    } else {
      roundedTempNumber = Math.round(tempNumber);
    }
    return roundedTempNumber / factor;
  }
</script>

<div class="col-sm-12">
  <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
  </p>
  <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>

Scanner vs. BufferedReader

There are different ways of taking input in java like:

1) BufferedReader 2) Scanner 3) Command Line Arguments

BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Where Scanner is a simple text scanner which can parse primitive types and strings using regular expressions.

if you are writing a simple log reader Buffered reader is adequate. if you are writing an XML parser Scanner is the more natural choice.

For more information please refer:

http://java.meritcampus.com/t/240/Bufferedreader?tc=mm69

Can a table have two foreign keys?

The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.

There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

You can call helper class in any controller

//view 
 @Html.ActionLink("Export to Excel", "Excel")

//controller Action
public void Excel()
{
    var model = db.GetModel()

    Export export = new Export();
    export.ToExcel(Response, model);
}

//helper class
public class Export
{        public void ToExcel(HttpResponseBase Response, object clientsList)
    {
        var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = clientsList;
        grid.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

You may need to terminate SQL Server Reporting Services as well.

Visual Studio popup: "the operation could not be completed"

For Visual C++ projects, this can be caused by an improperly formatted vcsproj.filters file.

In my case, someone had performed a manual branch merge and didn't merge the filters file correctly. Visual Studio still loaded and built the file without any warnings, but would give the 'unspecified error' warning whenever trying to add or remove files from the project.

Scan your vcsproj.filters file for any duplicate entries or lines that look like this and remove them. Close and reopen the project.

<ClInclude Include="..\..\path\to\sourcefile.h" />

Visual Studio Enterprise 2017

How to generate sample XML documents from their DTD or XSD?

Microsoft Office has 'InfoPath', which takes an XSD as an import and lets you quickly and easily define a form-based editor for creating XML files. It has two modes - one where you define the form, and another mode where you create the XML file by filling out the form. I believe it first came with Office 2003, and most people never install it. It shocks me at how much I like it.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

How do I rename the extension for a bunch of files?

Here is an example of the rename command:

rename -n ’s/\.htm$/\.html/’ *.htm

The -n means that it's a test run and will not actually change any files. It will show you a list of files that would be renamed if you removed the -n. In the case above, it will convert all files in the current directory from a file extension of .htm to .html.

If the output of the above test run looked ok then you could run the final version:

rename -v ’s/\.htm$/\.html/’ *.htm

The -v is optional, but it's a good idea to include it because it is the only record you will have of changes that were made by the rename command as shown in the sample output below:

$ rename -v 's/\.htm$/\.html/' *.htm
3.htm renamed as 3.html
4.htm renamed as 4.html
5.htm renamed as 5.html

The tricky part in the middle is a Perl substitution with regular expressions, highlighted below:

rename -v ’s/\.htm$/\.html/’ *.htm

How do I get a list of installed CPAN modules?

perldoc perllocal

Edit: There's a (little) more info about it in the CPAN FAQ

How to select all columns, except one column in pandas?

df[df.columns.difference(['b'])]

Out: 
          a         c         d
0  0.427809  0.459807  0.333869
1  0.678031  0.668346  0.645951
2  0.996573  0.673730  0.314911
3  0.786942  0.719665  0.330833

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

Error inflating when extending a class

in my case I added such cyclic resource:

<drawable name="above_shadow">@drawable/above_shadow</drawable>

then changed to

<drawable name="some_name">@drawable/other_name</drawable>

and it worked

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

This query should work:

$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).

This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

How do you get the footer to stay at the bottom of a Web page?

To get a sticky footer:

  1. Have a <div> with class="wrapper" for your content.

  2. Right before the closing </div> of the wrapper place the <div class="push"></div>.

  3. Right after the closing </div> of the wrapper place the <div class="footer"></div>.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

Keylistener in Javascript

A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):

window.onkeyup = function(event) {
    let key = event.key.toUpperCase();
    if ( key == 'W' ) {
        // 'W' key is pressed
    } else if ( key == 'D' ) {
        // 'D' key is pressed
    }
}

Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

Clear the entire history stack and start a new activity on Android

Case 1:Only two activity A and B:

Here Activity flow is A->B .On clicking backbutton from B we need to close the application then while starting Activity B from A just call finish() this will prevent android from storing Activity A in to the Backstack.eg for activity A is Loding/Splash screen of application.

Intent newIntent = new Intent(A.this, B.class);
startActivity(newIntent);
finish();

Case 2:More than two activitiy:

If there is a flow like A->B->C->D->B and on clicking back button in Activity B while coming from Activity D.In that case we should use.

Intent newIntent = new Intent(D.this,B.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);

Here Activity B will be started from the backstack rather than a new instance because of Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK clears the stack and makes it the top one.So when we press back button the whole application will be terminated.

How do I remove blank elements from an array?

Use reject:

>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

Simple logical operators in Bash

very close

if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; 
  then 
    scale=0.05
  fi

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

is a string comparison. otherwise, I am just grouping the comparisons correctly.

Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"

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

This homebrew function have precision down to a 10th of a second or less.

function sleep (a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end

Copy Paste Values only( xlPasteValues )

since you only want values copied, you can pass the values of arr1 directly to arr2 and avoid copy/paste. code inside the loop:

      Sheets("SheetB").Range(arr2(i) & firstrowDB).Resize(lastrow, 1).Value = .Range(.Cells(1, arr1(i)), .Cells(lastrow, arr1(i))).Value

How to adjust an UIButton's imageSize?

Swift 3:

button.setImage(UIImage(named: "checkmark_white"), for: .normal)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)

iPhone UITextField - Change placeholder text color

Since the introduction of attributed strings in UIViews in iOS 6, it's possible to assign a color to the placeholder text like this:

if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
  UIColor *color = [UIColor blackColor];
  textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
  NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
  // TODO: Add fall-back code to set placeholder color.
}

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

How to read and write excel file

Try the Apache POI HSSF. Here's an example on how to read an excel file:

try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;

    int rows; // No of rows
    rows = sheet.getPhysicalNumberOfRows();

    int cols = 0; // No of columns
    int tmp = 0;

    // This trick ensures that we get the data properly even if it doesn't start from first few rows
    for(int i = 0; i < 10 || i < rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            if(tmp > cols) cols = tmp;
        }
    }

    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell((short)c);
                if(cell != null) {
                    // Your code here
                }
            }
        }
    }
} catch(Exception ioe) {
    ioe.printStackTrace();
}

On the documentation page you also have examples of how to write to excel files.

How to make HTML input tag only accept numerical values?

You can use the <input> tag with attribute type='number'.

For example you can use <input type='number' />

This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

Proper way to use **kwargs in Python

While most answers are saying that, e.g.,

def f(**kwargs):
    foo = kwargs.pop('foo')
    bar = kwargs.pop('bar')
    ...etc...

is "the same as"

def f(foo=None, bar=None, **kwargs):
    ...etc...

this is not true. In the latter case, f can be called as f(23, 42), while the former case accepts named arguments only -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- threading.Thread is an example. The first form is how you implement that in Python 2.

The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single * in the def signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:

def f(*, foo=None, bar=None, **kwargs):
    ...etc...

Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value).

However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!

Merge 2 arrays of objects

const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];

 function mergeTwoArray(array1,array2){

    return array1.map((item,i)=>{
        if(array2[i] && item.id===array2[i].id){
          return array2[i];
          }else{
            return item;
          }
    });
  }

const result = mergeTwoArray(array1,array2);
console.log(result);
//here is the result:  Array [Object { id: 1, name: "ganza respice" },
 Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" }, 
Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]

Expected block end YAML error

YAML follows indentation structure very strictly. Even one space/tab can cause above issue. In my case it was just once space at the start.

So make sure no extra spaces/tabs are introduced while updating YAML file

Event system in Python

PyPI packages

As of January 2021, these are the event-related packages available on PyPI, ordered by most recent release date.

There's more

That's a lot of libraries to choose from, using very different terminology (events, signals, handlers, method dispatch, hooks, ...).

I'm trying to keep an overview of the above packages, plus the techniques mentioned in the answers here.

First, some terminology...

Observer pattern

The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern.

Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.

Publish-Subscribe

The disadvantage of Observer event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist.

That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).

Mediator pattern

Might be of interest as well: the Mediator pattern.

Hooks

A 'hook' system is usally used in the context of application plugins. The application contains fixed integration points (hooks), and each plugin may connect to that hook and perform certain actions.

Other 'events'

Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.

Network messaging libraries often use the term 'events' too; sometimes these are similar in concept; sometimes not. They can of course traverse thread-, process- and computer boundaries. See e.g. pyzmq, pymq, Twisted, Tornado, gevent, eventlet.

Weak references

In Python, holding a reference to a method or object ensures that it won't get deleted by the garbage collector. This can be desirable, but it can also lead to memory leaks: the linked handlers are never cleaned up.

Some event systems use weak references instead of regular ones to solve this.

Some words about the various libraries

Observer-style event systems:

  • zope.event shows the bare bones of how this works (see Lennart's answer). Note: this example does not even support handler arguments.
  • LongPoke's 'callable list' implementation shows that such an event system can be implemented very minimalistically by subclassing list.
  • Felk's variation EventHook also ensures the signatures of callees and callers.
  • spassig's EventHook (Michael Foord's Event Pattern) is a straightforward implementation.
  • Josip's Valued Lessons Event class is basically the same, but uses a set instead of a list to store the bag, and implements __call__ which are both reasonable additions.
  • PyNotify is similar in concept and also provides additional concepts of variables and conditions ('variable changed event'). Homepage is not functional.
  • axel is basically a bag-of-handlers with more features related to threading, error handling, ...
  • python-dispatch requires the even source classes to derive from pydispatch.Dispatcher.
  • buslane is class-based, supports single- or multiple handlers and facilitates extensive type hints.
  • Pithikos' Observer/Event is a lightweight design.

Publish-subscribe libraries:

  • blinker has some nifty features such as automatic disconnection and filtering based on sender.
  • PyPubSub is a stable package, and promises "advanced features that facilitate debugging and maintaining topics and messages".
  • pymitter is a Python port of Node.js EventEmitter2 and offers namespaces, wildcards and TTL.
  • PyDispatcher seems to emphasize flexibility with regards to many-to-many publication etc. Supports weak references.
  • louie is a reworked PyDispatcher and should work "in a wide variety of contexts".
  • pypydispatcher is based on (you guessed it...) PyDispatcher and also works in PyPy.
  • django.dispatch is a rewritten PyDispatcher "with a more limited interface, but higher performance".
  • pyeventdispatcher is based on PHP's Symfony framework's event-dispatcher.
  • dispatcher was extracted from django.dispatch but is getting fairly old.
  • Cristian Garcia's EventManger is a really short implementation.

Others:

  • pluggy contains a hook system which is used by pytest plugins.
  • RxPy3 implements the Observable pattern and allows merging events, retry etc.
  • Qt's Signals and Slots are available from PyQt or PySide2. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from QObject.

Is there a destructor for Java?

The finalize() function is the destructor.

However, it should not be normally used because it is invoked after the GC and you can't tell when that will happen (if ever).

Moreover, it takes more than one GC to deallocate objects that have finalize().

You should try to clean up in the logical places in your code using the try{...} finally{...} statements!

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

XPath: difference between dot and text()

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.

In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

Find all files with a filename beginning with a specified string?

Use find with a wildcard:

find . -name 'mystring*'

What are all the uses of an underscore in Scala?

Here are some more examples where _ is used:

val nums = List(1,2,3,4,5,6,7,8,9,10)

nums filter (_ % 2 == 0)

nums reduce (_ + _)

nums.exists(_ > 5)

nums.takeWhile(_ < 8)

In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

I used the following two steps which I found in the comments/posts linked in the other answers:

Step one: Convert the x.509 cert and key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chain option to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a Java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]

Finished

OPTIONAL Step zero: Create self-signed certificate

openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Cheers!

How to make HTML Text unselectable

No one here posted an answer with all of the correct CSS variations, so here it is:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

How to initialize a JavaScript Date to a particular time zone

Building on the answers above, I am using this native one liner to convert the long timezone string to the three letter string:

var longTz = 'America/Los_Angeles';
var shortTz = new Date().
    toLocaleString("en", {timeZoneName: "short", timeZone: longTz}).
    split(' ').
    pop();

This will give PDT or PST depending on the date provided. In my particular use case, developing on Salesforce (Aura/Lightning), we are able to get the user timezone in the long format from the backend.

ADB Shell Input Events

Updating:

Using adb shell input:

Insert text:

adb shell input text "insert%syour%stext%shere"

(obs: %s means SPACE)

..

Event codes:

adb shell input keyevent 82

(82 ---> MENU_BUTTON)

"For more keyevents codes see list below"

..

Tap X,Y position:

adb shell input tap 500 1450

To find the exact X,Y position you want to Tap go to:

Settings > Developer Options > Check the option POINTER SLOCATION

..

Swipe X1 Y1 X2 Y2 [duration(ms)]:

adb shell input swipe 100 500 100 1450 100

in this example X1=100, Y1=500, X2=100, Y2=1450, Duration = 100ms

..

LongPress X Y:

adb shell input swipe 100 500 100 500 250

we utilise the same command for a swipe to emulate a long press

in this example X=100, Y=500, Duration = 250ms

..

Event Codes Updated List:

0 -->  "KEYCODE_0" 
1 -->  "KEYCODE_SOFT_LEFT" 
2 -->  "KEYCODE_SOFT_RIGHT" 
3 -->  "KEYCODE_HOME" 
4 -->  "KEYCODE_BACK" 
5 -->  "KEYCODE_CALL" 
6 -->  "KEYCODE_ENDCALL" 
7 -->  "KEYCODE_0" 
8 -->  "KEYCODE_1" 
9 -->  "KEYCODE_2" 
10 -->  "KEYCODE_3" 
11 -->  "KEYCODE_4" 
12 -->  "KEYCODE_5" 
13 -->  "KEYCODE_6" 
14 -->  "KEYCODE_7" 
15 -->  "KEYCODE_8" 
16 -->  "KEYCODE_9" 
17 -->  "KEYCODE_STAR" 
18 -->  "KEYCODE_POUND" 
19 -->  "KEYCODE_DPAD_UP" 
20 -->  "KEYCODE_DPAD_DOWN" 
21 -->  "KEYCODE_DPAD_LEFT" 
22 -->  "KEYCODE_DPAD_RIGHT" 
23 -->  "KEYCODE_DPAD_CENTER" 
24 -->  "KEYCODE_VOLUME_UP" 
25 -->  "KEYCODE_VOLUME_DOWN" 
26 -->  "KEYCODE_POWER" 
27 -->  "KEYCODE_CAMERA" 
28 -->  "KEYCODE_CLEAR" 
29 -->  "KEYCODE_A" 
30 -->  "KEYCODE_B" 
31 -->  "KEYCODE_C" 
32 -->  "KEYCODE_D" 
33 -->  "KEYCODE_E" 
34 -->  "KEYCODE_F" 
35 -->  "KEYCODE_G" 
36 -->  "KEYCODE_H" 
37 -->  "KEYCODE_I" 
38 -->  "KEYCODE_J" 
39 -->  "KEYCODE_K" 
40 -->  "KEYCODE_L" 
41 -->  "KEYCODE_M" 
42 -->  "KEYCODE_N" 
43 -->  "KEYCODE_O" 
44 -->  "KEYCODE_P" 
45 -->  "KEYCODE_Q" 
46 -->  "KEYCODE_R" 
47 -->  "KEYCODE_S" 
48 -->  "KEYCODE_T" 
49 -->  "KEYCODE_U" 
50 -->  "KEYCODE_V" 
51 -->  "KEYCODE_W" 
52 -->  "KEYCODE_X" 
53 -->  "KEYCODE_Y" 
54 -->  "KEYCODE_Z" 
55 -->  "KEYCODE_COMMA" 
56 -->  "KEYCODE_PERIOD" 
57 -->  "KEYCODE_ALT_LEFT" 
58 -->  "KEYCODE_ALT_RIGHT" 
59 -->  "KEYCODE_SHIFT_LEFT" 
60 -->  "KEYCODE_SHIFT_RIGHT" 
61 -->  "KEYCODE_TAB" 
62 -->  "KEYCODE_SPACE" 
63 -->  "KEYCODE_SYM" 
64 -->  "KEYCODE_EXPLORER" 
65 -->  "KEYCODE_ENVELOPE" 
66 -->  "KEYCODE_ENTER" 
67 -->  "KEYCODE_DEL" 
68 -->  "KEYCODE_GRAVE" 
69 -->  "KEYCODE_MINUS" 
70 -->  "KEYCODE_EQUALS" 
71 -->  "KEYCODE_LEFT_BRACKET" 
72 -->  "KEYCODE_RIGHT_BRACKET" 
73 -->  "KEYCODE_BACKSLASH" 
74 -->  "KEYCODE_SEMICOLON" 
75 -->  "KEYCODE_APOSTROPHE" 
76 -->  "KEYCODE_SLASH" 
77 -->  "KEYCODE_AT" 
78 -->  "KEYCODE_NUM" 
79 -->  "KEYCODE_HEADSETHOOK" 
80 -->  "KEYCODE_FOCUS" 
81 -->  "KEYCODE_PLUS" 
82 -->  "KEYCODE_MENU" 
83 -->  "KEYCODE_NOTIFICATION" 
84 -->  "KEYCODE_SEARCH" 
85 -->  "KEYCODE_MEDIA_PLAY_PAUSE"
86 -->  "KEYCODE_MEDIA_STOP"
87 -->  "KEYCODE_MEDIA_NEXT"
88 -->  "KEYCODE_MEDIA_PREVIOUS"
89 -->  "KEYCODE_MEDIA_REWIND"
90 -->  "KEYCODE_MEDIA_FAST_FORWARD"
91 -->  "KEYCODE_MUTE"
92 -->  "KEYCODE_PAGE_UP"
93 -->  "KEYCODE_PAGE_DOWN"
94 -->  "KEYCODE_PICTSYMBOLS"
...
122 -->  "KEYCODE_MOVE_HOME"
123 -->  "KEYCODE_MOVE_END"

The complete list of commands can be found on: http://developer.android.com/reference/android/view/KeyEvent.html

How to read a local text file?

Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    <html>
    <head>
    <script>
      var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
          node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

HAX kernel module is not installed

After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)

PHP to search within txt file and echo the whole line

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

What does body-parser do with express?

It parses the HTTP request body. This is usually necessary when you need to know more than just the URL you hit, particular in the context of a POST or PUT PATCH HTTP request where the information you want is contains in the body.

Basically its a middleware for parsing JSON, plain text, or just returning a raw Buffer object for you to deal with as you require.

How to convert UTF-8 byte[] to string?

string result = System.Text.Encoding.UTF8.GetString(byteArray);

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

How to encrypt String in Java

Warning

Do not use this as some kind of security measurement.

The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!

Pointed out by Moussa


I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

public class EncryptUtils {
    public static final String DEFAULT_ENCODING = "UTF-8"; 
    static BASE64Encoder enc = new BASE64Encoder();
    static BASE64Decoder dec = new BASE64Decoder();

    public static String base64encode(String text) {
        try {
            return enc.encode(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }//base64encode

    public static String base64decode(String text) {
        try {
            return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
        } catch (IOException e) {
            return null;
        }
    }//base64decode

    public static void main(String[] args) {
        String txt = "some text to be encrypted";
        String key = "key phrase used for XOR-ing";
        System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));

        String encoded = base64encode(txt);       
        System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
        System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
    }

    public static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;

            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();

            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];

            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }//for i

            return new String(newmsg);
        } catch (Exception e) {
            return null;
        }
    }//xorMessage
}//class

How to change default language for SQL Server?

@John Woo's accepted answer has some caveats which you should be aware of:

  1. Default language setting of a session is controlled from default language setting of the user login instead which you have used to create the session. SQL Server instance level setting doesn't affect the default language of the session.
  2. Changing default language setting at SQL Server instance level doesn't affects the default language setting of the existing SQL Server logins. It is meant to be inherited only by the new user logins that you create after changing the instance level setting.

So, there is an intermediate level between your SQL Server instance and the session which you can use to control the default language setting for session - login level.

SQL Server Instance level setting -> User login level setting -> Query Session level setting

This can help you in case you want to set default language of all new sessions belonging to some specific user only.

Simply change the default language setting of the target user login as per this link and you are all set. You can also do it from SQL Server Management Studio (SSMS) UI. Below you can see the default language setting in properties window of sa user in SQL Server:

enter image description here

Note: Also, it is important to know that changing the setting doesn't affect the default language of already active sessions from that user login. It will affect only the new sessions created after changing the setting.

Dump Mongo Collection into JSON format

If you want to dump all collections, run this command:

mongodump -d {DB_NAME}   -o /tmp 

It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

Get latest from Git branch

Although git pull origin yourbranch works, it's not really a good idea

You can alternatively do the following:

git fetch origin
git merge origin/yourbranch

The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.

The second line merges your current branch with that of yourbranch that you fetched from origin (which is one of your remotes).

This is assuming origin points to the repository at address ssh://11.21.3.12:23211/dir1/dir2

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

How to parse freeform street/postal address out of text, and into components

I saw this question a lot when I worked for an address verification company. I'm posting the answer here to make it more accessible to programmers searching around with the same question. The company I was at processed billions of addresses, and we learned a lot in the process.

First, we need to understand a few things about addresses.

Addresses are not regular

This means that regular expressions are out. I've seen it all, from simple regular expressions that match addresses in a very specific format, to this:

/\s+(\d{2,5}\s+)(?![a|p]m\b)(([a-zA-Z|\s+]{1,5}){1,2})?([\s|,|.]+)?(([a-zA-Z|\s+]{1,30}){1,4})(court|ct|street|st|drive|dr|lane|ln|road|rd|blvd)([\s|,|.|;]+)?(([a-zA-Z|\s+]{1,30}){1,2})([\s|,|.]+)?\b(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|GU|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VI|VT|WA|WI|WV|WY)([\s|,|.]+)?(\s+\d{5})?([\s|,|.]+)/i

... to this where a 900+ line-class file generates a supermassive regular expression on the fly to match even more. I don't recommend these (for example, here's a fiddle of the above regex, that makes plenty of mistakes). There isn't an easy magic formula to get this to work. In theory and by theory, it's impossible to match addresses with a regular expression.

USPS Publication 28 documents the many formats of addresses that are possible, with all their keywords and variations. Worst of all, addresses are often ambiguous. Words can mean more than one thing ("St" can be "Saint" or "Street"), and there are words that I'm pretty sure they invented. (Who knew that "Stravenue" was a street suffix?)

You'd need some code that really understands addresses, and if that code does exist, it's a trade secret. But you could probably roll your own if you're really into that.

Addresses come in unexpected shapes and sizes

Here are some contrived (but complete) addresses:

1)  102 main street
    Anytown, state

2)  400n 600e #2, 52173

3)  p.o. #104 60203

Even these are possibly valid:

4)  829 LKSDFJlkjsdflkjsdljf Bkpw 12345

5)  205 1105 14 90210

Obviously, these are not standardized. Punctuation and line break are not guaranteed. Here's what's going on:

  1. Number 1 is complete because it contains a street address and a city and state. With that information, there's enough to identify the address, and it can be considered "deliverable" (with some standardization).

  2. Number 2 is complete because it contains a street address (with secondary/unit number) and a 5-digit ZIP code, which is enough to identify an address.

  3. Number 3 is a complete post office box format, as it contains a ZIP code.

  4. Number 4 is also complete because the ZIP code is unique, meaning that a private entity or corporation has purchased that address space. A unique ZIP code is for high-volume or concentrated delivery spaces. Anything addressed to ZIP code 12345 goes to General Electric in Schenectady, NY. This example won't reach anyone in particular, but the USPS would still deliver it.

  5. Number 5 is also complete, believe it or not. With just those numbers, the full address can be discovered when parsed against a database of all possible addresses. Filling in the missing directionals, secondary designator, and ZIP+4 code is trivial when you see each number as a component. Here's what it looks like, fully expanded and standardized:

205 N 1105 W Apt 14

Beverly Hills CA 90210-5221

Address data is not your own

In most countries that provide official address data to licensed vendors, the address data itself belongs to the governing agency. In the US, the USPS owns the addresses. The same is true for Canada Post, Royal Mail, and others, though each country enforces or defines ownership a little differently. Knowing this is important since it usually forbids reverse-engineering the address database. You have to be careful how to acquire, store, and use the data.

Google Maps is a common go-to for quick address fixes, but the TOS is rather prohibitive; for example, you can't use their data or APIs without showing a Google Map, and for non-commercial purposes only (unless you pay), and you can't store the data (except for temporary caching). Makes sense. Google's data is some of the best in the world. However, Google Maps does not verify the address. If an address does not exist, it will still show you where the address would be if it did exist (try it on your own street; use a house number that you know doesn't exist). This is useful sometimes, but be aware of that.

Nominatim's usage policy is similarly limiting, especially for high volume and commercial use, and the data is mostly drawn from free sources, so it isn't as well maintained (such as the nature of open projects). However, this may still suit your needs. A great community supports it.

The USPS itself has an API, but it goes down a lot and comes with no guarantees nor support. It might also be hard to use. Some people use it sparingly with no problems. But it's easy to miss that the USPS requires that you use their API only for confirming addresses to ship through them.

People expect addresses to be hard

Unfortunately, we've conditioned our society to expect addresses to be complicated. There are dozens of good UX articles all over the Internet about this. Still, the fact is, if you have an address form with individual fields, that's what users expect, even though it makes it harder for edge-case addresses that don't fit the format the form is expecting, or maybe the form requires a field it shouldn't. Or users don't know where to put a certain part of their address.

I could go on and on about the bad UX of checkout forms these days, but instead, I'll say that combining the addresses into a single field will be a welcome change -- people will be able to type their address how they see fit, rather than trying to figure out your lengthy form. However, this change will be unexpected and users may find it a little jarring at first. Just be aware of that.

Part of this pain can be alleviated by putting the country field out front, before the address. When they fill out the country field first, you know how to make your form appear. Maybe you have a good way to deal with single-field US addresses, so if they select the United States, you can reduce your form to a single field, otherwise show the component fields. Just things to think about!

Now we know why it's hard; what can you do about it?

The USPS licenses vendors through a process called CASS™ Certification to provide verified addresses to customers. These vendors have access to the USPS database, updated monthly. Their software must conform to rigorous standards to be certified, and they don't often require agreement to such limiting terms as discussed above.

Many CASS-Certified companies can process lists or have APIs: Melissa Data, Experian QAS, and SmartyStreets, to name a few.

(Due to getting flak for "advertising," I've truncated my answer at this point. It's up to you to find a solution that works for you.)

The Truth: Really, folks, I don't work at any of these companies. It's not an advertisement.

How do I install a plugin for vim?

Update (as 2019):

cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml

Explanation (from :h pack ad :h packages):

  1. All the directories found are added to runtimepath. They must be in ~/.vim/pack/whatever/start [you can only change whatever].
  2. the plugins found in the plugins dir in runtimepath are sourced.

So this load the plugin on start (hence the name start).

You can also get optional plugin (loaded with :packadd) if you put them in ~/.vim/pack/bundle/opt

Android SDK location

The Android SDK path is usually C:\Users\<username>\AppData\Local\Android\sdk.

How to strip HTML tags from a string in SQL Server?

Try this. It's a modified version of the one posted by RedFilter ... this SQL removes all tags except BR, B, and P with any accompanying attributes:

CREATE FUNCTION [dbo].[StripHtml] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
 DECLARE @Start  INT
 DECLARE @End    INT
 DECLARE @Length INT
 DECLARE @TempStr varchar(255)

 SET @Start = CHARINDEX('<',@HTMLText)
 SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
 SET @Length = (@End - @Start) + 1

 WHILE @Start > 0 AND @End > 0 AND @Length > 0
 BEGIN
   IF (UPPER(SUBSTRING(@HTMLText, @Start, 3)) <> '<BR') AND (UPPER(SUBSTRING(@HTMLText, @Start, 2)) <> '<P') AND (UPPER(SUBSTRING(@HTMLText, @Start, 2)) <> '<B') AND (UPPER(SUBSTRING(@HTMLText, @Start, 3)) <> '</B')
   BEGIN
      SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
   END
    
   SET @Start = CHARINDEX('<',@HTMLText, @End)
   SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText, @Start))
   SET @Length = (@End - @Start) - 1
 END

 RETURN RTRIM(LTRIM(@HTMLText))
END

Show DataFrame as table in iPython Notebook

It seems you can just display both dfs using a comma in between in display. I noticed this on some notebooks on github. This code is from Jake VanderPlas's notebook.

class display(object):
    """Display HTML representation of multiple objects"""
    template = """<div style="float: left; padding: 10px;">
    <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
    </div>"""
    def __init__(self, *args):
        self.args = args

    def _repr_html_(self):
        return '\n'.join(self.template.format(a, eval(a)._repr_html_())
                     for a in self.args)

    def __repr__(self):
        return '\n\n'.join(a + '\n' + repr(eval(a))
                       for a in self.args)

display('df', "df2")

default select option as blank

Try this:

<select>
    <option value="">&nbsp;
    <option>Option 1
    <option>Option 2
    <option>Option 3
</select>

Validates in HTML5. Works with required attribute in select element. Can be re-selected. Works in Google Chrome 45, Internet Explorer 11, Edge, Firefox 41.

UICollectionView auto scroll to cell at IndexPath

I totally agree with the above answer. The only thing is that for me the solution was set the code in viewDidAppear

viewDidAppear 
{
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
}

When I used the viewWillAppear the scrolling didn't work.

.htaccess rewrite to redirect root URL to subdirectory

Two ways out of possible solutions to achieve this are: 1. Create a .htaccess file in root folder as under (just replace example.com and my_dir with your corresponding values):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L] 
</IfModule>
  1. Use RedirectMatch to only redirect the root URL “/” to another folder or URL,

    RedirectMatch ^/$ http://www.example.com/my_dir

Run cmd commands through Java

The easiest way would be to use Runtime.getRuntime.exec().

For example, to get a registry value for the default browser on Windows:

String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
    Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
    e.printStackTrace();
}

Then use a Scanner to get the output of the command, if necessary.

Scanner kb = new Scanner(process.getInputStream());

Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).


However, there is no executable called cd, because it can't be implemented in a separate process.

The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.

Easiest way for your command:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

Fundamental difference between Hashing and Encryption algorithms

Cryptography deals with numbers and strings. Basically every digital thing in the entire universe are numbers. When I say numbers, its 0 & 1. You know what they are, binary. The images you see on screen, the music that you listen through your earphone, everything are binaries. But our ears and eyes will not understand binaries right? Only brain could understand that, and even if it could understand binaries, it can’t enjoy binaries. So we convert the binaries to human understandable formats such as mp3,jpg,etc. Let’s term the process as Encoding. It’s two way process and can be easily decoded back to its original form.

Hashing

Hashing is another cryptography technique in which a data once converted to some other form can never be recovered back. In Layman’s term, there is no process called de-hashing. There are many hash functions to do the job such as sha-512, md5 and so on.

If the original value cannot be recovered, then where do we use this? Passwords! When you set up a password for your mobile or PC, a hash of your password is created and stored in a secure place. When you make a login attempt next time, the entered string is again hashed with the same algorithm (hash function) and the output is matched with the stored value. If it’s the same, you get logged in. Otherwise you are thrown out.

Credits: wikimedia By applying hash to the password, we can ensure that an attacker will never get our password even if he steal the stored password file. The attacker will have the hash of the password. He can probably find a list of most commonly used passwords and apply sha-512 to each of it and compare it with the value in his hand. It is called the dictionary attack. But how long would he do this? If your password is random enough, do you think this method of cracking would work? All the passwords in the databases of Facebook, Google and Amazon are hashed, or at least they are supposed to be hashed.

Then there is Encryption

Encryption lies in between hashing and encoding. Encoding is a two way process and should not be used to provide security. Encryption is also a two way process, but original data can be retrieved if and only if the encryption key is known. If you don’t know how encryption works, don’t worry, we will discuss the basics here. That would be enough to understand the basics of SSL. So, there are two types of Encryption namely Symmetric and Asymmetric encryption.

Symmetric Key Encryption

I am trying to keep things as simple as I could. So, let’s understand the symmetric encryption by means of a shift algorithm. This algorithm is used to encrypt alphabets by shifting the letters to either left or right. Let’s take a string CRYPTO and consider a number +3. Then, the encrypted format of CRYPTO will be FUBSWR. That means each letter is shifted to right by 3 places. Here, the word CRYPTO is called Plaintext, the output FUBSWR is called the Ciphertext, the value +3 is called the Encryption key (symmetric key) and the whole process is a cipher. This is one of the oldest and basic symmetric key encryption algorithm and its first usage was reported during the time of Julius Caesar. So, it was named after him and it is the famous Caesar Cipher. Anyone who knows the encryption key and can apply the reverse of Caesar’s algorithm and retrieve the original Plaintext. Hence it is called a Symmetric Encryption.

Asymmetric Key Encryption

We know that, in Symmetric encryption same key is used for both encryption and decryption. Once that key is stolen, all the data is gone. That’s a huge risk and we need more complex technique. In 1976, Whitfield Diffie and Martin Hellman first published the concept of Asymmetric encryption and the algorithm was known as Diffie–Hellman key exchange. Then in 1978, Ron Rivest, Adi Shamir and Leonard Adleman of MIT published the RSA algorithm. These can be considered as the foundation of Asymmetric cryptography.

As compared to Symmetric encryption, in Asymmetric encryption, there will be two keys instead of one. One is called the Public key, and the other one is the Private key. Theoretically, during initiation we can generate the Public-Private key pair to our machine. Private key should be kept in a safe place and it should never be shared with anyone. Public key, as the name indicates, can be shared with anyone who wish to send encrypted text to you. Now, those who have your public key can encrypt the secret data with it. If the key pair were generated using RSA algorithm, then they should use the same algorithm while encrypting the data. Usually the algorithm will be specified in the public key. The encrypted data can only be decrypted with the private key which is owned by you.

Source: SSL/TLS for dummies part 1 : Ciphersuite, Hashing,Encryption | WST (https://www.wst.space/ssl-part1-ciphersuite-hashing-encryption/)

Difference between private, public, and protected inheritance

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

Scroll Automatically to the Bottom of the Page

You can use this to go down the page in an animation format.

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

Try setting "Integrated Security=False" in the connection string.

<add name="YourContext" connectionString="Data Source=<IPAddressOfDBServer>;Initial Catalog=<DBName>;USER ID=<youruserid>;Password=<yourpassword>;Integrated Security=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

Create a circular button in BS3

Boostrap 3 has a component for exactly this. It's:

<span class="badge">100</span>

Select multiple rows with the same value(s)

This may work for you:

select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
    from table2
    group by t2.Chromosome, t2.Locus
    having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

How can I remove Nan from list Python/NumPy

Another way to do it would include using filter like this:

countries = list(filter(lambda x: str(x) != 'nan', countries))

How to obtain a Thread id in Python?

The thread.get_ident() function returns a long integer on Linux. It's not really a thread id.

I use this method to really get the thread id on Linux:

import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')

# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186

def getThreadId():
   """Returns OS thread id - Specific to Linux"""
   return libc.syscall(SYS_gettid)

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

md-table - How to update the column width

Sample Mat-table column and corresponding CSS:

HTML/Template

<ng-container matColumnDef="">
  <mat-header-cell *matHeaderCellDef>
     Wider Column Header
  </mat-header-cell>
  <mat-cell *matCellDef="let displayData">
    {{ displayData.value}}
  </mat-cell>`enter code here`
</ng-container>

CSS

.mat-column-courtFolderId {
    flex: 0 0 35%;
}

Difference between numpy dot() and Python 3.5+ matrix multiplication @

In mathematics, I think the dot in numpy makes more sense

dot(a,b)_{i,j,k,a,b,c} = formula

since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices


As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as

>matmul(a,b)_{i,j,k,c} = formula

So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get

matmul(a,b)_{i,j,k,l} = formula

for example.


From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)

  • To use dot(a,b) you need

    1. t3=s4;
  • To use matmul(a,b) you need

    1. t3=s4
    2. t2=s2, or one of t2 and s2 is 1
    3. t1=s1, or one of t1 and s1 is 1

Use the following piece of code to convince yourself.

Code sample

import numpy as np
for it in xrange(10000):
    a = np.random.rand(5,6,2,4)
    b = np.random.rand(6,4,3)
    c = np.matmul(a,b)
    d = np.dot(a,b)
    #print 'c shape: ', c.shape,'d shape:', d.shape

    for i in range(5):
        for j in range(6):
            for k in range(2):
                for l in range(3):
                    if not c[i,j,k,l] == d[i,j,k,j,l]:
                        print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

Removing multiple files from a Git repo that have already been deleted from disk

something like

git status | sed -s "s/^.*deleted: //" | xargs git rm 

may do it.

How to delete all files and folders in a directory?

System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);

Get class name of object as string in Swift

Swift 5.1 :-

You can also use generic function for get class name of object as string

struct GenericFunctions {
 static func className<T>(_ name: T) -> String {
        return "\(name)"
    }

}

Call this function by using following:-

let name = GenericFunctions.className(ViewController.self)

Happy Coding :)

How to present popover properly in iOS 8

In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,

- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];

viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }

How to include CSS file in Symfony 2 and Twig?

And you can use %stylesheets% (assetic feature) tag:

{% stylesheets
    "@MainBundle/Resources/public/colorbox/colorbox.css"
    "%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}

You can write path to css as parameter (%parameter_name%).

More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank(foo) will perform a null check for you. If you perform foo.isEmpty() and foo is null, you will raise a NullPointerException.

Java Synchronized list

You can have 2 diffent problems with lists :
1) If you do a modification within an iteration even though in a mono thread environment, you will have ConcurrentModificationException like in this following example :

List<String> list = new ArrayList<String>();
for (int i=0;i<5;i++)
   list.add("Hello "+i);

for(String msg:list)
   list.remove(msg);

So, to avoid this problem, you can do :

for(int i=list.size()-1;i>=0;i--)
   list.remove(i);

2)The second problem could be multi threading environment. As mentioned above, you can use synchronized(list) to avoid exceptions.

subquery in codeigniter active record

CodeIgniter Active Records do not currently support sub-queries, However I use the following approach:

#Create where clause
$this->db->select('id_cer');
$this->db->from('revokace');
$where_clause = $this->db->_compile_select();
$this->db->_reset_select();

#Create main query
$this->db->select('*');
$this->db->from('certs');
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);

_compile_select() and _reset_select() are two undocumented (AFAIK) methods which compile the query and return the sql (without running it) and reset the query.

On the main query the FALSE in the where clause tells codeigniter not to escape the query (or add backticks etc) which would mess up the query. (The NULL is simply because the where clause has an optional second parameter we are not using)

However you should be aware as _compile_select() and _reset_select() are not documented methods it is possible that there functionality (or existence) could change in future releases.

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        numbersList.add(number1);
        numberList.add(number2);
        ....
        return numberList;
    }
}

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like

numbers.numberList;

if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

Sharing link on WhatsApp from mobile website (not application) for Android

This code worked for me.

After clicking on the link, it will ask you to choose the contact to share a message.

_x000D_
_x000D_
<a href="https://api.whatsapp.com/send?text=enter message here">Click here to share on Whatsapp</a>
_x000D_
_x000D_
_x000D_

You can add target="_blank" attribute to open it in a new window or tab.

I don't think the phone number is needed when someone wants to share a particular message or article.

Print a div using javascript in angularJS single page application

Okay i might have some even different approach.

I am aware that it won't suit everybody but nontheless someone might find it useful.

For those who do not want to pupup a new window, and like me, are concerned about css styles this is what i came up with:

I wrapped view of my app into additional container, which is being hidden when printing and there is additional container for what needs to be printed which is shown when is printing.

Below working example:

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
 app.controller('myCtrl', function($scope) {_x000D_
  _x000D_
    $scope.people = [{_x000D_
      "id" : "000",_x000D_
      "name" : "alfred"_x000D_
    },_x000D_
    {_x000D_
      "id" : "020",_x000D_
      "name" : "robert"_x000D_
    },_x000D_
    {_x000D_
      "id" : "200",_x000D_
      "name" : "me"_x000D_
    }];_x000D_
_x000D_
    $scope.isPrinting = false;_x000D_
  $scope.printElement = {};_x000D_
  _x000D_
  $scope.printDiv = function(e)_x000D_
  {_x000D_
   console.log(e);_x000D_
   $scope.printElement = e;_x000D_
   _x000D_
   $scope.isPrinting = true;_x000D_
      _x000D_
      //does not seem to work without toimeouts_x000D_
   setTimeout(function(){_x000D_
    window.print();_x000D_
   },50);_x000D_
   _x000D_
   setTimeout(function(){_x000D_
    $scope.isPrinting = false;_x000D_
   },50);_x000D_
   _x000D_
   _x000D_
  };_x000D_
    _x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
 <div ng-show="isPrinting">_x000D_
  <p>Print me id: {{printElement.id}}</p>_x000D_
    <p>Print me name: {{printElement.name}}</p>_x000D_
 </div>_x000D_
 _x000D_
 <div ng-hide="isPrinting">_x000D_
    <!-- your actual application code -->_x000D_
    <div ng-repeat="person in people">_x000D_
      <div ng-click="printDiv(person)">Print {{person.name}}</div>_x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
  _x000D_
</div>_x000D_
 
_x000D_
_x000D_
_x000D_

Note that i am aware that this is not an elegant solution, and it has several drawbacks, but it has some ups as well:

  • does not need a popup window
  • keeps the css intact
  • does not store your whole page into a var (for whatever reason you don't want to do it)

Well, whoever you are reading this, have a nice day and keep coding :)

EDIT:

If it suits your situation you can actually use:

@media print  { .noprint  { display: none; } }
@media screen { .noscreen { visibility: hidden; position: absolute; } }

instead of angular booleans to select your printing and non printing content

EDIT:

Changed the screen css because it appears that display:none breaks printiing when printing first time after a page load/refresh.

visibility:hidden approach seem to be working so far.

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

How do I remove accents from characters in a PHP string?

What about the WordPress implementation?

function remove_accents($string) {
    if ( !preg_match('/[\x80-\xff]/', $string) )
        return $string;

    $chars = array(
    // Decompositions for Latin-1 Supplement
    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
    chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
    chr(195).chr(191) => 'y',
    // Decompositions for Latin Extended-A
    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
    chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
    chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
    chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
    chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
    chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
    chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
    chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
    chr(197).chr(190) => 'z', chr(197).chr(191) => 's'
    );

    $string = strtr($string, $chars);

    return $string;
}

To understand what this function does, check the conversion table:

À => A
Á => A
 => A
à => A
Ä => A
Å => A
Ç => C
È => E
É => E
Ê => E
Ë => E
Ì => I
Í => I
Î => I
Ï => I
Ñ => N
Ò => O
Ó => O
Ô => O
Õ => O
Ö => O
Ù => U
Ú => U
Û => U
Ü => U
Ý => Y
ß => s
à => a
á => a
â => a
ã => a
ä => a
å => a
ç => c
è => e
é => e
ê => e
ë => e
ì => i
í => i
î => i
ï => i
ñ => n
ò => o
ó => o
ô => o
õ => o
ö => o
ù => u
ú => u
û => u
ü => u
ý => y
ÿ => y
A => A
a => a
A => A
a => a
A => A
a => a
C => C
c => c
C => C
c => c
C => C
c => c
C => C
c => c
D => D
d => d
Ð => D
d => d
E => E
e => e
E => E
e => e
E => E
e => e
E => E
e => e
E => E
e => e
G => G
g => g
G => G
g => g
G => G
g => g
G => G
g => g
H => H
h => h
H => H
h => h
I => I
i => i
I => I
i => i
I => I
i => i
I => I
i => i
I => I
i => i
? => IJ
? => ij
J => J
j => j
K => K
k => k
? => k
L => L
l => l
L => L
l => l
L => L
l => l
? => L
? => l
L => L
l => l
N => N
n => n
N => N
n => n
N => N
n => n
? => N
? => n
? => N
O => O
o => o
O => O
o => o
O => O
o => o
Π=> OE
œ => oe
R => R
r => r
R => R
r => r
R => R
r => r
S => S
s => s
S => S
s => s
S => S
s => s
Š => S
š => s
T => T
t => t
T => T
t => t
T => T
t => t
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
W => W
w => w
Y => Y
y => y
Ÿ => Y
Z => Z
z => z
Z => Z
z => z
Ž => Z
ž => z
? => s

You can generate the conversion table yourself by simply iterating over the $chars array of the function:

foreach($chars as $k=>$v) {
   printf("%s -> %s", $k, $v);
}

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

Error: the entity type requires a primary key

None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

How can I get the last 7 characters of a PHP string?

for last 7 characters

$newstring = substr($dynamicstring, -7);

$newstring : 5409els

for first 7 characters

$newstring = substr($dynamicstring, 0, 7);

$newstring : 2490slk

Choosing line type and color in Gnuplot 4.0

Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.

You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:


set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"

Fire event on enter key press for a textbox

Try follow: Aspx:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="EnterEvent(event, someMethod)"></asp:TextBox>    
<asp:Button ID="Button1" onclick="someMethod()" runat="server" Text="Button" />

JS:

function EnterEvent(e, callback) {
        if (e.keyCode == 13) {
            callback();
        }
    }

Bootstrap number validation

You should use jquery validation because if you use type="number" then you can also enter "E" character in input type, which is not correct.

Solution:

HTML

<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" > 

JQuery

//integer value validation
$('input.floatNumber').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});

Change size of text in text input tag?

In your CSS stylesheet, try adding:

input[type="text"] {
    font-size:25px;
}

See this jsFiddle example

Input placeholders for Internet Explorer

i use jquery.placeholderlabels. It's based on this and can be demoed here.

works in ie7, ie8, ie9.

behavior mimics current firefox and chrome behavior - where the the "placeholder" text remains visible on focus and only disappears once something is typed in the field.

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

ASP.NET MVC View Engine Comparison

I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.

Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>

How to define a relative path in java

 File f1 = new File("..\\..\\..\\config.properties");  

this path trying to access file is in Project directory then just access file like this.

File f=new File("filename.txt");

if your file is in OtherSources/Resources

this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder

How to get param from url in angular 4?

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}

Getting the absolute path of the executable, using C#?

MSDN has an article that says to use System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; if you need the directory, use System.IO.Path.GetDirectoryName on that result.

Or, there's the shorter Application.ExecutablePath which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.

How to display data from database into textbox, and update it

The answer is .IsPostBack as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

private void PopulateFields()
{
  using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
  {
    DataTable dt = new DataTable();
    con1.Open();
    SqlDataReader myReader = null;  
    SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);

    myReader = myCommand.ExecuteReader();

    while (myReader.Read())
    {
        TextBoxPassword.Text = (myReader["password"].ToString());
        TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
        DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
        DropDownListMonth.Text = (myReader["birth"].ToString());
        DropDownListYear.Text = (myReader["birth"].ToString());
        TextBoxAddress.Text = (myReader["address"].ToString());
        TextBoxCity.Text = (myReader["city"].ToString());
        DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
        TextBoxPostcode.Text = (myReader["postcode"].ToString());
        TextBoxEmail.Text = (myReader["email"].ToString());
        TextBoxCarno.Text = (myReader["carno"].ToString());
    }
    con1.Close();
  }//end using
}

Then call it in your Page_Load

protected void Page_Load(object sender, EventArgs e)
{

    if(!Page.IsPostBack)
    {
       PopulateFields();
    }
}

Embedding JavaScript engine into .NET

You can use Rhino a Mozilla Javascript engine written on Java, and use it with IKVM , here are some instructions

Instructions:https://www.codeproject.com/Articles/41792/Embedding-JavaScript-into-C-with-Rhino-and-IKVM