Programs & Examples On #Label control

0

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

Disable developer mode extensions pop up in Chrome

1) Wait for the popup balloon to appear.

2) Open a new tab.

3) Close the a new tab. The popup will be gone from the original tab.

A small Chrome extension can automate these steps:

manifest.json

{
  "name": "Open and close tab",
  "description": "After Chrome starts, open and close a new tab.",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["tabs"],
  "background": {
    "scripts": ["background.js"], 
    "persistent": false
  }
}

background.js

// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {

  // Execute the inner function after a few seconds
  setTimeout(function() {

    // Open new tab
    chrome.tabs.create({url: "about:blank"});

    // Get tab ID of newly opened tab, then close the tab
    chrome.tabs.query({'currentWindow': true}, function(tabs) {
      var newTabId = tabs[1].id;
      chrome.tabs.remove(newTabId);
    });

  }, 5000);

});

With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

boolean in an if statement

Revisa https://www.w3schools.com/js/js_comparisons.asp

example:

var p=5;

p==5 ? true
p=="5" ?  true
p==="5" ? false

=== means same type also same value == just same value

enter image description here

LINQ Aggregate algorithm explained

It partly depends on which overload you're talking about, but the basic idea is:

  • Start with a seed as the "current value"
  • Iterate over the sequence. For each value in the sequence:
    • Apply a user-specified function to transform (currentValue, sequenceValue) into (nextValue)
    • Set currentValue = nextValue
  • Return the final currentValue

You may find the Aggregate post in my Edulinq series useful - it includes a more detailed description (including the various overloads) and implementations.

One simple example is using Aggregate as an alternative to Count:

// 0 is the seed, and for each item, we effectively increment the current value.
// In this case we can ignore "item" itself.
int count = sequence.Aggregate(0, (current, item) => current + 1);

Or perhaps summing all the lengths of strings in a sequence of strings:

int total = sequence.Aggregate(0, (current, item) => current + item.Length);

Personally I rarely find Aggregate useful - the "tailored" aggregation methods are usually good enough for me.

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

How to Replace Multiple Characters in SQL?

I don't know why Charles Bretana deleted his answer, so I'm adding it back in as a CW answer, but a persisted computed column is a REALLY good way to handle these cases where you need cleansed or transformed data almost all the time, but need to preserve the original garbage. His suggestion is relevant and appropriate REGARDLESS of how you decide to cleanse your data.

Specifically, in my current project, I have a persisted computed column which trims all the leading zeros (luckily this is realtively easily handled in straight T-SQL) from some particular numeric identifiers stored inconsistently with leading zeros. This is stored in persisted computed columns in the tables which need it and indexed because that conformed identifier is often used in joins.

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

jQuery on window resize

Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

css

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
        bottom: 3px;
        left: 0px;
        /* more styles */
    }
}

javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

$(window).on('resize', function(){
    var win = $(this); //this = window
    if (win.height() >= 820) { /* ... */ }
    if (win.width() >= 1280) { /* ... */ }
});

How do I stop my resize code from executing so often!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

How can I reference a dll in the GAC from Visual Studio?

Registering assmblies into the GAC does not then place a reference to the assembly in the add references dialog. You still need to reference the assembly by path for your project, the main difference being you do not need to use the copy local option, your app will find it at runtime.

In this particular case, you just need to reference your assembly by path (browse) or if you really want to have it in the add reference dialog there is a registry setting where you can add additional paths.

Note, if you ship your app to someone who does not have this assembly installed you will need to ship it, and in this case you really need to use the SharedManagementObjects.msi redistributable.

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">
</target>

<target name="prepare-copy-true" description="copy file based on condition"
    if="copy-condition">
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />
</target>

<target name="prepare-copy-false" description="copy file based on false condition" 
    unless="copy-condition">
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />
</target>

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

SQL Server : error converting data type varchar to numeric

SQL Server 2012 and Later

Just use Try_Convert instead:

TRY_CONVERT takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CONVERT returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.

Read more about Try_Convert.

SQL Server 2008 and Earlier

The traditional way of handling this is by guarding every expression with a case statement so that no matter when it is evaluated, it will not create an error, even if it logically seems that the CASE statement should not be needed. Something like this:

SELECT
   Account_Code =
      Convert(
         bigint, -- only gives up to 18 digits, so use decimal(20, 0) if you must
         CASE
         WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
         ELSE X.Account_Code
         END
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      CASE
      WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
      ELSE X.Account_Code
      END
   ) BETWEEN 503100 AND 503205

However, I like using strategies such as this with SQL Server 2005 and up:

SELECT
   Account_Code = Convert(bigint, X.Account_Code),
   A.Descr
FROM
   dbo.Account A
   OUTER APPLY (
      SELECT A.Account_Code WHERE A.Account_Code NOT LIKE '%[^0-9]%'
   ) X
WHERE
   Convert(bigint, X.Account_Code) BETWEEN 503100 AND 503205

What this does is strategically switch the Account_Code values to NULL inside of the X table when they are not numeric. I initially used CROSS APPLY but as Mikael Eriksson so aptly pointed out, this resulted in the same error because the query parser ran into the exact same problem of optimizing away my attempt to force the expression order (predicate pushdown defeated it). By switching to OUTER APPLY it changed the actual meaning of the operation so that X.Account_Code could contain NULL values within the outer query, thus requiring proper evaluation order.

You may be interested to read Erland Sommarskog's Microsoft Connect request about this evaluation order issue. He in fact calls it a bug.

There are additional issues here but I can't address them now.

P.S. I had a brainstorm today. An alternate to the "traditional way" that I suggested is a SELECT expression with an outer reference, which also works in SQL Server 2000. (I've noticed that since learning CROSS/OUTER APPLY I've improved my query capability with older SQL Server versions, too--as I am getting more versatile with the "outer reference" capabilities of SELECT, ON, and WHERE clauses!)

SELECT
   Account_Code =
      Convert(
         bigint,
         (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
   ) BETWEEN 503100 AND 503205

It's a lot shorter than the CASE statement.

How to stop app that node.js express 'npm start'

For production environments you should use Forever.js

It's so util for start and stop node process, you can list apps running too.

https://github.com/foreverjs/forever

Random alpha-numeric string in JavaScript?

UPDATED: One-liner solution, for random 20 characters (alphanumeric lowercase):

Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');

Or shorter with lodash:

_.times(20, () => _.random(35).toString(36)).join('');

jQuery hide and show toggle div with plus and minus icon

Toggle the text Show and Hide and move your backgroundPosition Y axis

LIVE DEMO

$(function(){ // DOM READY shorthand

    $(".slidingDiv").hide();

    $('.show_hide').click(function( e ){
        // e.preventDefault(); // If you use anchors
        var SH = this.SH^=1; // "Simple toggler"
        $(this).text(SH?'Hide':'Show')
               .css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
               .next(".slidingDiv").slideToggle();
    });

});

CSS:

.show_hide{
  background:url(plusminus.png) no-repeat;
  padding-left:20px;  
}

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

AppStore - App status is ready for sale, but not in app store

I published an update to my app yesterday noon(I have selected Manual release instead of Automatic) and Today early morning App store review was completed and after I release the build manually, the App shows Ready for sale in iTunesConect immediately. After 45mins I got the update on the App store.

Laravel - Forbidden You don't have permission to access / on this server

I had the same problem and builded a .htaccess file to fix this issue with a few more improvements. You can use it as it is, just download it from Github Gist and change the filename "public/index.php" to "public/app.php" and see how it works! :)

Regular Expression for password validation

Try this ( also corrected check for upper case and lower case, it had a bug since you grouped them as [a-zA-Z] it only looks for atleast one lower or upper. So separated them out ):

(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)^(.{8,15})$

Update: I found that the regex doesn't really work as expected and this is not how it is supposed to be written too!

Try something like this:

(?=^.{8,15}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?!.*\s).*$

(Between 8 and 15 inclusive, contains atleast one digit, atleast one upper case and atleast one lower case and no whitespace.)

And I think this is easier to understand as well.

Auto generate function documentation in Visual Studio

///

is the shortcut for getting the Method Description comment block. But make sure you have written the function name and signature before adding it. First write the Function name and signature.

Then above the function name just type ///

and you will get it automatically

enter image description here

Reading a resource file from within jar

I have found a fix

BufferedReader br = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream(path)));

Replace "Main" with the java class you coded it in. replace "path" with the path within the jar file.

for example, if you put State1.txt in the package com.issac.state, then type the path as "/com/issac/state/State1" if you run Linux or Mac. If you run Windows then type the path as "\com\issac\state\State1". Don't add the .txt extension to the file unless the File not found exception occurs.

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

How do I run two commands in one line in Windows CMD?

You can use call to overcome the problem of environment variables being evaluated too soon - e.g.

set A=Hello & call echo %A%

Pip error: Microsoft Visual C++ 14.0 is required

I got this error when I tried to install pymssql even though Visual C++ 2015 (14.0) is installed in my system.

I resolved this error by downloading the .whl file of pymssql from here.

Once downloaded, it can be installed by the following command :

pip install python_package.whl

Hope this helps

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to return a value from pthread threads in C?

#include<stdio.h>
#include<pthread.h>
void* myprint(void *x)
{
 int k = *((int *)x);
 printf("\n Thread created.. value of k [%d]\n",k);
 //k =11;
 pthread_exit((void *)k);

}
int main()
{
 pthread_t th1;
 int x =5;
 int *y;
 pthread_create(&th1,NULL,myprint,(void*)&x);
 pthread_join(th1,(void*)&y);
 printf("\n Exit value is [%d]\n",y);
}  

List<T> or IList<T>

You would because defining an IList or an ICollection would open up for other implementations of your interfaces.

You might want to have an IOrderRepository that defines a collection of orders in either a IList or ICollection. You could then have different kinds of implementations to provide a list of orders as long as they conform to "rules" defined by your IList or ICollection.

XAMPP Apache won't start

Look in the control panel: the service has not been installed yet!

Click the (X) button to install apache in windows service and reboot, it should be working now.

Where are Docker images stored on the host machine?

Expanding on Tristan's answer, in Windows with Hyper-V you can move the image with these steps from matthuisman:

In Windows 10,

  1. Stop docker etc
  2. Type "Hyper-V Manager" in task-bar search box and run it.
  3. Select your PC in the left hand pane (Mine is called DESKTOP-CBP**)
  4. Right click on the correct virtual machine (Mine is called MobyLinuxVM)
  5. Select "Turn off" (If it is running)
  6. Right click on it again and select "Move"
  7. Follow the prompts

Express.js: how to get remote client address

According to Express behind proxies, req.ip has taken into account reverse proxy if you have configured trust proxy properly. Therefore it's better than req.connection.remoteAddress which is obtained from network layer and unaware of proxy.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.

The JavaMail FAQ recommends using

Session.getInstance(properties);

instead of

Session.getDefaultInstance(properties);

because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.

See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance

apply drop shadow to border-top only?

In case you want to apply the shadow to the inside of the element (inset) but only want it to appear on one single side you can define a negative value to the "spread" parameter (5th parameter in the second example).

To completely remove it, make it the same size as the shadows blur (4th parameter in the second example) but as a negative value.

Also remember to add the offset to the y-position (3rd parameter in the second example) so that the following:

box-shadow:         inset 0px 4px 3px rgba(50, 50, 50, 0.75);

becomes:

box-shadow:         inset 0px 7px 3px -3px rgba(50, 50, 50, 0.75);

Check this updated fiddle: http://jsfiddle.net/FrEnY/1282/ and more on the box-shadow parameters here: http://www.w3schools.com/cssref/css3_pr_box-shadow.asp

What are the differences between if, else, and else if?

Dead Simple Pseudo-Code Explanation:

/* If Example */
if(condition_is_true){
   do_this
}
now_do_this_regardless_of_whether_condition_was_true_or_false

/*  If-Else Example  */
if(condition_is_true){
    do_this
}else{
    do_this_if_condition_was_false
}
now_do_this_regardless_of_whether_condition_was_true_or_false

/* If-ElseIf-Else Example */
if(condition_is_true){
    do_this
}else if(different_condition_is_true){
    do_this_only_if_first_condition_was_false_and_different_condition_was_true
}else{
    do_this_only_if_neither_condition_was_true
}
now_do_this_regardless_of_whether_condition_was_true_or_false

alert() not working in Chrome

window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win

window is an instance of DOMWindow, and by setting something to window.alert, the correct implementation is being "shadowed", i.e. when accessing alert it is first looking for it on the window object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert property to window it finds it straight away and does not need to go up the prototype chain. Using delete window.alert you can remove the window own property and again expose the prototype implementation of alert. This may help explain:

window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

Try netstat like this: netstat -ntp, without the -l. It will show tcp connection in TIME_WAIT state.

Retrieve the maximum length of a VARCHAR column in SQL Server

For Oracle, it is also LENGTH instead of LEN

SELECT MAX(LENGTH(Desc)) FROM table_name

Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.

If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.

Git - How to fix "corrupted" interactive rebase?

tried everything else but a reboot, what worked for me is rm -fr .git/REBASE_HEAD

How to find the size of a table in SQL?

SQL Server:-

sp_spaceused 'TableName'

Or in management studio: Right Click on table -> Properties -> Storage

MySQL:-

SELECT table_schema, table_name, data_length, index_length FROM information_schema.tables

Sybase:-

sp_spaceused 'TableName'

Oracle:- how-do-i-calculate-tables-size-in-oracle

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

SQL Server ORDER BY date and nulls last

I know this is old but this is what worked for me

Order by Isnull(Date,'12/31/9999')

How to view the Folder and Files in GAC?

Install:

gacutil -i "path_to_the_assembly"

View:

Open in Windows Explorer folder

  • .NET 1.0 - NET 3.5: c:\windows\assembly (%systemroot%\assembly)
  • .NET 4.x: %windir%\Microsoft.NET\assembly

OR gacutil –l

When you are going to install an assembly you have to specify where gacutil can find it, so you have to provide a full path as well. But when an assembly already is in GAC - gacutil know a folder path so it just need an assembly name.

MSDN:

Facebook key hash does not match any stored key hashes

Adding SHA1 keys from Eclipse/keytool helped me only when creating the app on FB, then after rebuilding I would always get the OP error.

What solved my issue was adding the key in the error message to the Facebook dashboard settings.

Select distinct rows from datatable in Linq

Like this: (Assuming a typed dataset)

someTable.Select(r => new { r.attribute1_name, r.attribute2_name }).Distinct();

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

Saving data to a file in C#

Here's an article from MSDN on a guide for how to write text to a file:

http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

I'd start there, then post additional, more specific questions as you continue your development.

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Triangle Draw Method

There is no direct method to draw a triangle. You can use drawPolygon() method for this. It takes three parameters in the following form: drawPolygon(int x[],int y[], int number_of_points); To draw a triangle: (Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.) Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100) Do the following inside public void paint(Graphics g):

int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);

Similarly you can draw any shape using as many points as you want.

How to convert BigDecimal to Double in Java?

You can convert BigDecimal to double using .doubleValue(). But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal objects directly. Precision loss in these calculations are big time problems in currency related calculations.

Display progress bar while doing some work in C#?

For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls

How to create permanent PowerShell Aliases

Open a Windows PowerShell window and type:

notepad $profile

Then create a function, such as:

function goSomewhereThenOpenGoogleThenDeleteSomething {
    cd C:\Users\
    Start-Process -FilePath "http://www.google.com"
    rm fileName.txt
}

Then type this under the function name:

Set-Alias google goSomewhereThenOpenGoogleThenDeleteSomething

Now you can type the word "google" into Windows PowerShell and have it execute the code within your function!

Is it possible to specify condition in Count()?

Do you mean just this:

SELECT Count(*) FROM YourTable WHERE Position = 'Manager'

If so, then yup that works!

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

Reordering Chart Data Series

FYI, if you are using two y-axis, the order numbers will only make a difference within the set of series of that y-axis. I believe secondary -y-axis by default are on top of the primary. If you want the series in the primary axis to be on top, you'll need to make it secondary instead.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

Get the first element of each tuple in a list in Python

You can use list comprehension:

res_list = [i[0] for i in rows]

This should make the trick

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

how can scrapy be used to scrape this dynamic data so that I can use it?

I wonder why no one has posted the solution using Scrapy only.

Check out the blog post from Scrapy team SCRAPING INFINITE SCROLLING PAGES . The example scraps http://spidyquotes.herokuapp.com/scroll website which uses infinite scrolling.

The idea is to use Developer Tools of your browser and notice the AJAX requests, then based on that information create the requests for Scrapy.

import json
import scrapy


class SpidyQuotesSpider(scrapy.Spider):
    name = 'spidyquotes'
    quotes_base_url = 'http://spidyquotes.herokuapp.com/api/quotes?page=%s'
    start_urls = [quotes_base_url % 1]
    download_delay = 1.5

    def parse(self, response):
        data = json.loads(response.body)
        for item in data.get('quotes', []):
            yield {
                'text': item.get('text'),
                'author': item.get('author', {}).get('name'),
                'tags': item.get('tags'),
            }
        if data['has_next']:
            next_page = data['page'] + 1
            yield scrapy.Request(self.quotes_base_url % next_page)

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

I recommend to read this entire article, but here is the most relevant section that addresses your question:

Rollback and Error Handling is Difficult

In my articles on Error and Transaction Handling in SQL Server, I suggest that > you should always have an error handler like

BEGIN CATCH
   IF @@trancount > 0 ROLLBACK TRANSACTION
   EXEC error_handler_sp
   RETURN 55555
END CATCH

The idea is that even if you do not start a transaction in the procedure, you should always include a ROLLBACK, because if you were not able to fulfil your contract, the transaction is not valid.

Unfortunately, this does not work well with INSERT-EXEC. If the called procedure executes a ROLLBACK statement, this happens:

Msg 3915, Level 16, State 0, Procedure SalesByStore, Line 9 Cannot use the ROLLBACK statement within an INSERT-EXEC statement.

The execution of the stored procedure is aborted. If there is no CATCH handler anywhere, the entire batch is aborted, and the transaction is rolled back. If the INSERT-EXEC is inside TRY-CATCH, that CATCH handler will fire, but the transaction is doomed, that is, you must roll it back. The net effect is that the rollback is achieved as requested, but the original error message that triggered the rollback is lost. That may seem like a small thing, but it makes troubleshooting much more difficult, because when you see this error, all you know is that something went wrong, but you don't know what.

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

Blocks and yields in Ruby

Yes, it is a bit puzzling at first.

In Ruby, methods may receive a code block in order to perform arbitrary segments of code.

When a method expects a block, it invokes it by calling the yield function.

This is very handy, for instance, to iterate over a list or to provide a custom algorithm.

Take the following example:

I'm going to define a Person class initialized with a name, and provide a do_with_name method that when invoked, would just pass the name attribute, to the block received.

class Person 
    def initialize( name ) 
         @name = name
    end

    def do_with_name 
        yield( @name ) 
    end
end

This would allow us to call that method and pass an arbitrary code block.

For instance, to print the name we would do:

person = Person.new("Oscar")

#invoking the method passing a block
person.do_with_name do |name|
    puts "Hey, his name is #{name}"
end

Would print:

Hey, his name is Oscar

Notice, the block receives, as a parameter, a variable called name (N.B. you can call this variable anything you like, but it makes sense to call it name). When the code invokes yield it fills this parameter with the value of @name.

yield( @name )

We could provide another block to perform a different action. For example, reverse the name:

#variable to hold the name reversed
reversed_name = ""

#invoke the method passing a different block
person.do_with_name do |name| 
    reversed_name = name.reverse
end

puts reversed_name

=> "racsO"

We used exactly the same method (do_with_name) - it is just a different block.

This example is trivial. More interesting usages are to filter all the elements in an array:

 days = ["monday", "tuesday", "wednesday", "thursday", "friday"]  

 # select those which start with 't' 
 days.select do | item |
     item.match /^t/
 end

=> ["tuesday", "thursday"]

Or, we can also provide a custom sort algorithm, for instance based on the string size:

 days.sort do |x,y|
    x.size <=> y.size
 end

=> ["monday", "friday", "tuesday", "thursday", "wednesday"]

I hope this helps you to understand it better.

BTW, if the block is optional you should call it like:

yield(value) if block_given?

If is not optional, just invoke it.

EDIT

@hmak created a repl.it for these examples: https://repl.it/@makstaks/blocksandyieldsrubyexample

Pretty-Print JSON in Java

Pretty printing with GSON in one line:

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));

Besides inlining, this is equivalent to the accepted answer.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

Turn off enclosing <p> tags in CKEditor 3.0

Edit the source (or turn off rich text) and replace the p tag with a div. Then style the div any which way you want.

ckEditor won't add any wrapper element on the next submit as you've got the div in there.

(This solved my issue, I'm using Drupal and need small snippets of html which the editor always added the extra, but the rest of the time I want the wrapping p tag).

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

I see this is old but... I dont know if you are looking for code to generate the numbers/options every time its loaded or not. But I use an excel or open office calc page and place use the auto numbering all the time. It may look like this...

| <option> | 1 | </option> |

Then I highlight the cells in the row and drag them down until there are 100 or the number that I need. I now have code snippets that I just refer back to.

Specifying row names when reading in a file

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)

What to use now Google News API is deprecated?

I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.

As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Capturing a single image from my webcam in Java or Python

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

Trying to handle "back" navigation button action in iOS

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

Reading a file line by line in Go

In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner. Here is a simple example that reads lines from a file:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

This is the cleanest way to read from a Reader line by line.

There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read().

Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }

How is AngularJS different from jQuery

AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it's not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Read more details here: angularjs-vs-jquery

How to write multiple conditions in Makefile.am with "else if"

ifeq ($(CHIPSET),8960)
   BLD_ENV_BUILD_ID="8960"
else ifeq ($(CHIPSET),8930)
   BLD_ENV_BUILD_ID="8930"
else ifeq ($(CHIPSET),8064)
   BLD_ENV_BUILD_ID="8064"
else ifeq ($(CHIPSET), 9x15)
   BLD_ENV_BUILD_ID="9615"
else
   BLD_ENV_BUILD_ID=
endif

Laravel requires the Mcrypt PHP extension

in ubuntu 14.04 based on your php version : 5.6,7.0,7.1,7.2,7.3

sudo apt-get install php{version}-mcrypt

sudo apt-get install php7.1-mcrypt

sudo phpenmod mcrypt 

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

Angular js init ng-model from default values

As others pointed out, it is not good practice to initialize data on views. Initializing data on Controllers, however, is recommended. (see http://docs.angularjs.org/guide/controller)

So you can write

<input name="card[description]" ng-model="card.description">

and

$scope.card = { description: 'Visa-4242' };

$http.get('/getCardInfo.php', function(data) {
   $scope.card = data;
});

This way the views do not contain data, and the controller initializes the value while the real values are being loaded.

How do you read a file into a list in Python?

hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()

Communicating between a fragment and an activity - best practices

There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

What's the most appropriate HTTP status code for an "item not found" error page

A 404 return code actually means 'resource not found', and applies to any entity for which a request was made but not satisfied. So it works equally-well for pages, subsections of pages, and any item that exists on the page which has a specific request to be rendered.

So 404 is the right code to use in this scenario. Note that it doesn't apply to 'server not found', which is a different situation in which a request was issued but not answered at all, as opposed to answered but without the resource requested.

Convert digits into words with JavaScript

Convert digits to word in French language using JavaScript and html - original French words

_x000D_
_x000D_
        <html>
            <head>
                <title>Number to word</title>
    
                <script>
                    function toWords() {
                        var s = document.getElementById('value').value;
                        var th = ['','mille','million', 'milliard','billion'];
                        var dg = ['zéro','un','deux','trois','quatre', 'cinq','six','sept','huit','neuf'];
                        var tn = 
    
    ['dix','onze','douze','treize', 'quatorze','quinze','seize', 'dix-sept','dix-huit','dix-neuf'];
                    var tw = ['vingt','trente','quarante','cinquante', 'soixante','soixante-dix','quatre-vingt','quatre-vingt-dix'];
                    s = s.toString();
                    s = s.replace(/[\, ]/g,'');
                    if (s != parseFloat(s)) return 'not a number';
                    var x = s.indexOf('.');
                    if (x == -1)
                        x = s.length;
                    if (x > 15)
                        return 'too big';
                    var n = s.split(''); 
                    var str = '';
                    var sk = 0;
                    for (var i=0;   i < x;  i++) {
                        if ((x-i)%3==2) { 
                            if (n[i] == '1') {
    
                                str += tn[Number(n[i+1])] + ' ';
                                i++;
                                sk=1;
                            } else if (n[i]!=0) { 
                                if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                                if(s==20 || s==30 || s==40 || s==50 || s==60 || s==70 || s==80 || s==90){
                                str += tw[n[i]-2] + ' ';} // for not to display hyphens for 20,30...90 
                                else{
                                str += tw[n[i]-2] + '-';}
                                sk=1;
                                }
                            }
                        } else if (n[i]!=0) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
    
                            str += dg[n[i]] +' ';
                            if ((x-i)%3==0) str += 'hundert ';  // for start from 101 - 
    
                            sk=1;
                            }
                        }
                        if ((x-i)%3==1) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                            if (sk)
                                str += th[(x-i-1)/3] + ' ';
                            sk=0;
                            }
                        }
                    }
    
                    if (x != s.length) {
                        var y = s.length;
                        //str += 'point ';
                        //for (var i=x+1; i<y; i++)
                        //  str += dg[n[i]] +' ';
                        str += 'virgule ';
                         var counter=0;
                         for (var i=x+1; i<y; i++){
                            if ((y-i)%3==2) { 
                                                if (n[i] == '1') {
                                                                str += tn[Number(n[i+1])] + ' ';
                                                                i++;
                                                                counter=1;
                                                } else if (n[i]!=0) {
                                                                str += tw[n[i]-2] + '-';
                                                                counter=1;
                                                }
                                            }else if (n[i]!=0) { // 0235
                                                str += dg[n[i]] +' ';
                                            }
                         }
    
                    }
    
                    if (s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                    document.getElementById("demo").innerHTML = str.replace(/\s+/g,' ')
    
                    }
                    else if (s==21){
                    str = 'vingt-et-un'
                    document.getElementById("demo").innerHTML = str;
                    }//alert(str.replace(/\s+/g,' '));
                    else if (s==31){
                    str = 'trente-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==41){
                    str = 'quarante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==51){
                    str = 'cinquante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==61){
                    str = 'soixante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==71){
                    str = 'soixante-et-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==72){
                    str = 'soixante-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==73){
                    str = 'soixante-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==74){
                    str = 'soixante-quatorze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==75){
                    str = 'soixante-quinze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==76){
                    str = 'soixante-seize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==100){
                    str = 'cent'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==91){
                    str = 'quatre-vingt-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==92){
                    str = 'quatre-vingt-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==93){
                    str = 'quatre-vingt-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==94){
                    str = 'quatre-vingt-quatorze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==95){
                    str = 'quatre-vingt-quinze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==96){
                    str = 'quatre-vingt-seize'
                    document.getElementById("demo").innerHTML = str;}               
                }
            </script>
        </head>
        <body>
            <p>Enter only numbers (max 15 digits) : </p>
            <input type="text" name="value" id='value' /><br>
            <input type="button" value="submit" onclick="toWords()" />
            <p id="demo"></p>
            <p id="demo1"></p>
        </body>
    </html> 
_x000D_
_x000D_
_x000D_

Android: java.lang.SecurityException: Permission Denial: start Intent

Make sure that the component has the "exported" flag set to true. Also the component defining the permission should be installed before the component that uses it.

How to initialise a string from NSData in Swift

Since the third version of Swift you can do the following:

let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)

simialr to what Sunkas advised.

Creating and playing a sound in swift

Matt Gibson's solution worked for me, here is the swift 3 version.

if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
  var mySound: SystemSoundID = 0
  AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
  AudioServicesPlaySystemSound(mySound);
}

Warning: implode() [function.implode]: Invalid arguments passed

You are getting the error because $ret is not an array.

To get rid of the error, at the start of your function, define it with this line: $ret = array();

It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.

Why is Visual Studio 2013 very slow?

I had the same problem and all the solutions mentioned here didn't work out for me.

After uninstalling the "Productivity Power Tools 2013" extension, the performance was back to normal.

How can I take an UIImage and give it a black border?

With OS > 3.0 you can do this:

//you need this import
#import <QuartzCore/QuartzCore.h>

[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];

Why is datetime.strptime not working in this simple example?

You can also do the following,to import datetime

from datetime import datetime as dt

dt.strptime(date, '%Y-%m-%d')

Deleting specific rows from DataTable

I have a dataset in my app and I went to set changes (deleting a row) to it but ds.tabales["TableName"] is read only. Then I found this solution.

It's a wpf C# app,

try {
    var results = from row in ds.Tables["TableName"].AsEnumerable() where row.Field<string>("Personalid") == "47" select row;                
    foreach (DataRow row in results) {
        ds.Tables["TableName"].Rows.Remove(row);                 
    }           
}

Get loop count inside a Python FOR loop

I know rather old question but....came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

Test or check if sheet exists

Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.

Dim wb as Workbook
Dim ws as Worksheet

Set wb = ActiveWorkbook

For Each ws in wb.Worksheets

    if ws.Name = "Sheet1" then
        'Do something here
    End if

Next

Server is already running in Rails

You can get rid of the process by killing it:

kill -9 $(lsof -i tcp:3000 -t)

I can't access http://localhost/phpmyadmin/

Just change - $cfg['Servers'][$i]['host'] = 'localhost'; in config.inc.ph. i.e. from existing to localhost if you installed it locally

The create-react-app imports restriction outside of src directory

There are a few answers that provide solutions with react-app-rewired, but customize-cra exposes a special removeModuleScopePlugin() API which is a bit more elegant. (It's the same solution, but abstracted away by the customize-cra package.)

npm i --save-dev react-app-rewired customize-cra

package.json

"scripts": {
    - "start": "react-scripts start"
    + "start": "react-app-rewired start",
    ...
},

config-overrides.js

const { removeModuleScopePlugin } = require('customize-cra')

module.exports = removeModuleScopePlugin()

Order columns through Bootstrap4

even this will work:

<div class="container">
            <div class="row">
                <div class="col-4 col-sm-4 col-md-6 order-1">
                    1
                </div>
                <div class="col-4 col-sm-4  col-md-6 order-3">
                    2
                </div>
                <div class="col-4 col-sm-4  col-md-12 order-2">
                    3
                </div>
            </div>
          </div>

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

How do I rename a Git repository?

With Github As Your Remote

Renaming the Remote Repo on Github

Regarding the remote repository, if you are using Github or Github Enterprise as the server location for saving/distributing your repository remotely, you can simply rename the repository directly in the repo settings.

From the main repo page, the settings tab is on the right, and the repo name is the first item on the page:

enter image description here

Github will redirect requests to the new URL

One very nice feature in Github when you rename a repo, is that Github will save the old repo name and all the related URLs and redirect traffic to the new URLs. Since your username/org and repo name are a part of the URL, a rename will change the URL.

Since Github saves the old repo name and redirects requests to the new URLs, if anyone uses links based on the old repo name when trying to access issues, wiki, stars, or followers they will still arrive at the new location on the Github website. Github also redirects lower level Git commands like git clone, git fetch, etc.

More information is in the Github Help for Renaming a Repo

Renaming the Local Repo Name

As others have mentioned, the local "name" of your repo is typically considered to be the root folder/directory name, and you can change that, move, or copy the folder to any location and it will not affect the repo at all.

Git is designed to only worry about files inside the root folder.

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

In a nutshell:

  • CMD sets default command and/or parameters, which can be overwritten from command line when docker container runs.
  • ENTRYPOINT command and parameters will not be overwritten from command line. Instead, all command line arguments will be added after ENTRYPOINT parameters.

If you need more details or would like to see difference on example, there is a blog post that comprehensively compare CMD and ENTRYPOINT with lots of examples - http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/

How to unescape HTML character entities in Java?

Spring Framework HtmlUtils

If you're using Spring framework already, use the following method:

import static org.springframework.web.util.HtmlUtils.htmlUnescape;

...

String result = htmlUnescape(source);

jQuery "blinking highlight" effect on div?

<script>
$(document).ready(function(){
    var count = 0;
    do {
        $('#toFlash').fadeOut(500).fadeIn(500);
        count++;
    } while(count < 10);/*set how many time you want it to flash*/
});
</script

How do you display a Toast from a background thread on Android?

I like to have a method in my activity called showToast which I can call from anywhere...

public void showToast(final String toast)
{
    runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());
}

I then most frequently call it from within MyActivity on any thread like this...

showToast(getString(R.string.MyMessage));

How should I use try-with-resources with JDBC?

There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ; at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:

public List<User> getUser(int userId) {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, userId);
        try (ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

outline on only one border

Outline indeed does apply to the whole element.

Now that I see your image, here's how to achieve it.

_x000D_
_x000D_
.element {_x000D_
  padding: 5px 0;_x000D_
  background: #CCC;_x000D_
}_x000D_
.element:before {_x000D_
  content: "\a0";_x000D_
  display: block;_x000D_
  padding: 2px 0;_x000D_
  line-height: 1px;_x000D_
  border-top: 1px dashed #000; _x000D_
}_x000D_
.element p {_x000D_
  padding: 0 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <p>Some content comes here...</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Or see external demo.)

All sizes and colors are just placeholders, you can change it to match the exact desired result.

Important note: .element must have display:block; (default for a div) for this to work. If it's not the case, please provide your full code, so that i can elaborate a specific answer.

Regular expression to stop at first match

Use of Lazy quantifiers ? with no global flag is the answer.

Eg,

enter image description here

If you had global flag /g then, it would have matched all the lowest length matches as below. enter image description here

pandas three-way joining multiple dataframes on columns

You could try this if you have 3 dataframes

# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32'])

pd.merge(pd.merge(df1,df2,on='name'),df3,on='name')

alternatively, as mentioned by cwharland

df1.merge(df2,on='name').merge(df3,on='name')

How to access environment variable values?

You can also try this

First, install python-decouple

pip install python-decouple

import it in your file

from decouple import config

Then get the env variable

SECRET_KEY=config('SECRET_KEY')

Read more about the python library here

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

I had using solution all this way in this thread, and it's easy working with plugin Android Drawable Importer

If u using Android Studio on MacOS, just try this step to get in:

  • Click bar menu Android Studio then choose Preferences or tap button Command + ,
  • Then choose Plugins
  • Click Browse repositories
  • Write in the search coloumn Android Drawable Importer
  • Click Install button
  • And then dialog Restart is showing, just restart it Android Studio

After ur success installing the plugin, to work it this plugin just click create New menu and then choose Batch Drawable Import. Then click plus button a.k.a Add button, and go choose your file to make drawable. And then just click ok and ok the drawable has make it all of them.

If u confused with my word, just see the image tutorial from learningmechine.

How to add headers to a multicolumn listbox in an Excel userform using VBA

I like to use the following approach for headers on a ComboBox where the CboBx is not loaded from a worksheet (data from sql for example). The reason I specify not from a worksheet is that I think the only way to get RowSource to work is if you load from a worksheet.

This works for me:

  1. Create your ComboBox and create a ListBox with an identical layout but just one row.
  2. Place the ListBox directly on top of the ComboBox.
  3. In your VBA, load ListBox row1 with the desired headers.
  4. In your VBA for the action yourListBoxName_Click, enter the following code:

    yourComboBoxName.Activate`
    yourComboBoxName.DropDown`
    
  5. When you click on the listbox, the combobox will drop down and function normally while the headings (in the listbox) remain above the list.

TypeError: $(...).autocomplete is not a function

Just add these to libraries to your project:

<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

Save and reload. You're good to go.

php delete a single file in directory

// This code was tested by me (Helio Barbosa)

    // this directory (../backup) is for try only.
    // it is necessary create it and put files into him.

    $hDir = '../backup';
    if ($handle = opendir( $hDir )) {
        echo "Manipulador de diretório: $handle\n";
        echo "Arquivos:\n";

        /* Esta é a forma correta de varrer o diretório */
        /* Here is the correct form to do find files into the directory */
        while (false !== ($file = readdir($handle))) {
            // echo($file . "</br>");
            $filepath = $hDir . "/" . $file ;
            // echo( $filepath . "</br>" );
            if(is_file($filepath))
            {
                echo("Deleting:" . $file . "</br>");
                unlink($filepath);
            }           
        }

        closedir($handle);
    }

Histogram using gnuplot?

I have a couple corrections/additions to Born2Smile's very useful answer:

  1. Empty bins caused the box for the adjacent bin to incorrectly extend into its space; avoid this using set boxwidth binwidth
  2. In Born2Smile's version, bins are rendered as centered on their lower bound. Strictly they ought to extend from the lower bound to the upper bound. This can be corrected by modifying the bin function: bin(x,width)=width*floor(x/width) + width/2.0

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

A non-blocking read on a subprocess.PIPE in Python

I add this problem to read some subprocess.Popen stdout. Here is my non blocking read solution:

import fcntl

def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read()
    except:
        return ""

# Use example
from subprocess import *
sb = Popen("echo test && sleep 1000", shell=True, stdout=PIPE)
sb.kill()

# sb.stdout.read() # <-- This will block
non_block_read(sb.stdout)
'test\n'

On linux SUSE or RedHat, how do I load Python 2.7

If you want to install Python 2.7 on Oracle Linux, you can proceed as follows:

Enable the Software Collection in /etc/yum.repos.d/public-yum-ol6.repo.

vim /etc/yum.repos.d/public-yum-ol6.repo

[public_ol6_software_collections] 
name=Software Collection Library release 1.2 packages for Oracle Linux 6 
(x86_64) 
baseurl=[http://yum.oracle.com/repo/OracleLinux/OL6/SoftwareCollections12/x86_64/][1] 
    gpgkey=file:[///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle][2] 
    gpgcheck=1 
    enabled=1 <==============change from 0 to 1

After making this change to the yum repository you can simply run the yum command to install the Python:

yum install gcc libffi libffi-devel python27 python27-python-devel openssl-devel python27-MySQL-python

edit bash_profile with follow variables:

vim ~/.bash_profile
PATH=$PATH:$HOME/bin:/opt/rh/python27/root/usr/bin export PATH
LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64 export LD_LIBRARY_PATH
PKG_CONFIG_PATH=/opt/rh/python27/root/usr/lib64/pkgconfig export PKG_CONFIG_PATH

Now you can use python2.7 and pip for install Python modules:

/opt/rh/python27/root/usr/bin/pip install pynacl
/opt/rh/python27/root/usr/bin/python2.7 --version

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Remove duplicates in the list using linq

var distinctItems = items.Distinct();

To match on only some of the properties, create a custom equality comparer, e.g.:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Then use it like this:

var distinctItems = items.Distinct(new DistinctItemComparer());

Why doesn't CSS ellipsis work in table cell?

Apparently, adding:

td {
  display: block; /* or inline-block */
}

solves the problem as well.


Another possible solution is to set table-layout: fixed; for the table, and also set it's width. For example: http://jsfiddle.net/fd3Zx/5/

Check whether a path is valid

I haven't had any problems with the code below. (Relative paths must start with '/' or '\').

private bool IsValidPath(string path, bool allowRelativePaths = false)
{
    bool isValid = true;

    try
    {
        string fullPath = Path.GetFullPath(path);

        if (allowRelativePaths)
        {
            isValid = Path.IsPathRooted(path);
        }
        else
        {
            string root = Path.GetPathRoot(path);
            isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
        }
    }
    catch(Exception ex)
    {
        isValid = false;
    }

    return isValid;
}

For example these would return false:

IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);

And these would return true:

IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);

What's the "Content-Length" field in HTTP header?

Consider if you have headers such as:

content-encoding: gzip
content-length: 52098
content-type: text/javascript; charset=UTF-8

The content-length is the size of the compressed message body, in "octets" (i.e. in units of 8 bits, which happen to be "bytes" for all modern computers).

The size of the actual message body can be something else, perhaps 150280 bytes.

The number of characters can be different again, perhaps 150231 characters, because some unicode characters use multiple bytes (note UTF-8 is a standard encoding).

So, different numbers depending on whether you care how much data is transmitted, or how much data is held, or how many symbols are seen. Of course, there is no guarantee that these headers will be provided..

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */
 }

 .big {
     height: 60px;
     width: 100px;
 }
 .small {
     height: 40px;
     width: 70px;
 }

and so on.

Change the row color in DataGridView based on the quantity of a cell value

I fixed my error. just removed "Value" from this line:

If drv.Item("Quantity").Value < 5  Then

So it will look like

If drv.Item("Quantity") < 5 Then

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

How to do a redirect to another route with react-router?

How to do a redirect to another route with react-router?

For example, when a user clicks a link <Link to="/" />Click to route</Link> react-router will look for / and you can use Redirect to and send the user somewhere else like the login route.

From the docs for ReactRouterTraining:

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

to: string, The URL to redirect to.

<Redirect to="/somewhere/else"/>

to: object, A location to redirect to.

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>

How can I install a CPAN module into a local directory?

I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.

Remove insignificant trailing zeros from a number?

If you cannot use Floats for any reason (like money-floats involved) and are already starting from a string representing a correct number, you could find this solution handy. It converts a string representing a number to a string representing number w/out trailing zeroes.

function removeTrailingZeroes( strAmount ) {
    // remove all trailing zeroes in the decimal part
    var strDecSepCd = '.'; // decimal separator
    var iDSPosition = strAmount.indexOf( strDecSepCd ); // decimal separator positions
    if ( iDSPosition !== -1 ) {
        var strDecPart = strAmount.substr( iDSPosition ); // including the decimal separator

        var i = strDecPart.length - 1;
        for ( ; i >= 0 ; i-- ) {
            if ( strDecPart.charAt(i) !== '0') {
                break;
            }
        }

        if ( i=== 0 ) {
            return strAmount.substring(0, iDSPosition);
        } else {
            // return INTPART and DS + DECPART including the rightmost significant number
            return strAmount.substring(0, iDSPosition) + strDecPart.substring(0,i + 1);
        }
    }

    return strAmount;
}

Eclipse cannot load SWT libraries

I came across this error when tried to start 32-bit build of Eclipse under 64-bit linux. The problem was solved after installing ia32-libs package.

cmake - find_library - custom library location

Use CMAKE_PREFIX_PATH by adding multiple paths (separated by semicolons and no white spaces). You can set it as an environmental variable to avoid having absolute paths in your cmake configuration files

Notice that cmake will look for config file in any of the following folders where is any of the path in CMAKE_PREFIX_PATH and name is the name of the library you are looking for

<prefix>/                                               (W)
<prefix>/(cmake|CMake)/                                 (W)
<prefix>/<name>*/                                       (W)
<prefix>/<name>*/(cmake|CMake)/                         (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/          (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/                (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/  (U)

In your case you need to add to CMAKE_PREFIX_PATH the following two paths:

D:/develop/cmake/libs/libA;D:/develop/cmake/libB

How do I view the SQLite database on an Android device?

Here are step-by-step instructions (mostly taken from a combination of the other answers). This works even on devices that are not rooted.

  1. Connect your device and launch the application in debug mode.

  2. You may want to use adb -d shell "run-as com.yourpackge.name ls /data/data/com.yourpackge.name/databases/" to see what the database filename is.

Notice: com.yourpackge.name is your application package name. You can get it from the manifest file.

  1. Copy the database file from your application folder to your SD card.

    adb -d shell "run-as com.yourpackge.name cat /data/data/com.yourpackge.name/databases/filename.sqlite > /sdcard/filename.sqlite"

Notice: filename.sqlite is your database name you used when you created the database

  1. Pull the database files to your machine:

    adb pull /sdcard/filename.sqlite

This will copy the database from the SD card to the place where your ADB exist.

  1. Install Firefox SQLite Manager: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

  2. Open Firefox SQLite Manager (Tools->SQLite Manager) and open your database file from step 3 above.

  3. Enjoy!

How can I initialize an array without knowing it size?

Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)

 static int isLeft(ArrayList<String> left, ArrayList<String> right)

    {
        int f = 0;
        for (int i = 0; i < left.size(); i++) {
            for (int j = 0; j < right.size(); j++)

            {
                if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
                    System.out.println("Grammar is left recursive");
                    f = 1;
                }

            }
        }
        return f;

    }

    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<String> left = new ArrayList<String>();
        ArrayList<String> right = new ArrayList<String>();


        Scanner sc = new Scanner(System.in);
        System.out.println("enter no of prod");
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println("enter left prod");
            String leftText = sc.next();
            left.add(leftText);
            System.out.println("enter right prod");
            String rightText = sc.next();
            right.add(rightText);
        }

        System.out.println("the productions are");
        for (int i = 0; i < n; i++) {
            System.out.println(left.get(i) + "->" + right.get(i));
        }
        int flag;
        flag = isLeft(left, right);
        if (flag == 1) {
            System.out.println("Removing left recursion");
        } else {
            System.out.println("No left recursion");
        }

    }

Declare and assign multiple string variables at the same time

string a = "", b = a , c = a, d = a, e = a, f =a;

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

This Activity already has an action bar supplied by the window decor

Just put parent="Theme.AppCompat.NoActionBar" in your style.xml file

Like - <style parent="Theme.AppCompat.NoActionBar" name="AppTheme.NoActionBar">

How to split a comma-separated string?

You could do this:

String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));

Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings.

However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList() utility. Just as an FYI you could also do something like so:

String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));

But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.

jQuery: Clearing Form Inputs

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Original Answer: Resetting a multi-stage form with jQuery


Mike's suggestion (from the comments) to keep checkbox and selects intact!

Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

How do I find the install time and date of Windows?

In Powershell run the command:

systeminfo | Select-String "Install Date:"

Sequelize OR condition object

Use Sequelize.or:

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

Reference (search for Sequelize.or)

Edit: Also, this has been modified and for the latest method see Morio's answer,

How do you modify the web.config appSettings at runtime?

Try This:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Bash: Strip trailing linebreak from output

If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr utility, or to Perl if preferred:

wc -l < log.txt | tr -d '\n'

wc -l < log.txt | perl -pe 'chomp'

You can also use command substitution to remove the trailing newline:

echo -n "$(wc -l < log.txt)"

printf "%s" "$(wc -l < log.txt)"

If your expected output may contain multiple lines, you have another decision to make:

If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:

printf "%s" "$(< log.txt)"

If you want to strictly remove THE LAST newline character from a file, use Perl:

perl -pe 'chomp if eof' log.txt

Note that if you are certain you have a trailing newline character you want to remove, you can use head from GNU coreutils to select everything except the last byte. This should be quite quick:

head -c -1 log.txt

Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat and the 'show-all' flag -A. The dollar sign character will indicate the end of each line:

cat -A log.txt

python numpy ValueError: operands could not be broadcast together with shapes

You are looking for np.matmul(X, y). In Python 3.5+ you can use X @ y.

How do I center list items inside a UL element?

I had a problem slimier to yours I this quick and its the best solution I have found so far.

What the output looks like

Shows what the output of the code looks like The borders are just to show the spacing and are not needed.


Html:

    <div class="center">
      <ul class="dots">
        <span>
          <li></li>
          <li></li>
          <li></li>
        </span>
      </ul>
    </div>

CSS:

    ul {list-style-type: none;}
    ul li{
        display: inline-block;
        padding: 2px;
        border: 2px solid black;
        border-radius: 5px;}
    .center{
        width: 100%;
        border: 3px solid black;}
    .dots{
        padding: 0px;
        border: 5px solid red;
        text-align: center;}
    span{
        width: 100%;
        border: 5px solid blue;}

Not everything here is needed to center the list items.

You can cut the css down to this to get the same effect:

    ul {list-style-type: none;}
    ul li{display: inline-block;}
    .center{width: 100%;}
    .dots{
        text-align: center;
        padding: 0px;}
    span{width: 100%;}

Replace Fragment inside a ViewPager

I found simple solution, which works fine even if you want add new fragments in the middle or replace current fragment. In my solution you should override getItemId() which should return unique id for each fragment. Not position as by default.

There is it:

public class DynamicPagerAdapter extends FragmentPagerAdapter {

private ArrayList<Page> mPages = new ArrayList<Page>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

public DynamicPagerAdapter(FragmentManager fm) {
    super(fm);
}

public void replacePage(int position, Page page) {
    mPages.set(position, page);
    notifyDataSetChanged();
}

public void setPages(ArrayList<Page> pages) {
    mPages = pages;
    notifyDataSetChanged();
}

@Override
public Fragment getItem(int position) {
    if (mPages.get(position).mPageType == PageType.FIRST) {
        return FirstFragment.newInstance(mPages.get(position));
    } else {
        return SecondFragment.newInstance(mPages.get(position));
    }
}

@Override
public int getCount() {
    return mPages.size();
}

@Override
public long getItemId(int position) {
    // return unique id
    return mPages.get(position).getId();
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    while (mFragments.size() <= position) {
        mFragments.add(null);
    }
    mFragments.set(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    super.destroyItem(container, position, object);
    mFragments.set(position, null);
}

@Override
public int getItemPosition(Object object) {
    PagerFragment pagerFragment = (PagerFragment) object;
    Page page = pagerFragment.getPage();
    int position = mFragments.indexOf(pagerFragment);
    if (page.equals(mPages.get(position))) {
        return POSITION_UNCHANGED;
    } else {
        return POSITION_NONE;
    }
}
}

Notice: In this example FirstFragment and SecondFragment extends abstract class PageFragment, which has method getPage().

Oracle SQL Developer - tables cannot be seen

I have the same problem in sqlDeveloper64-3.0.4.34 and sqlDeveloper64-3.1.07.42.

According to https://forums.oracle.com/forums/thread.jspa?threadID=2202388 it appears there is a bug in the JDBC driver having to do with 'Out Of Band Breaks' - basically a low level TCP issue.

The workaround is launch sql developer with JVM property -Doracle.net.disableOob=true I tried this solutions for 3.0 and 3.1 and it works.

So I just quote here the solution from forum:


I believe I have identified what is causing these issues for some users and not others. It appears there is a bug in the JDBC driver having to do with 'Out Of Band Breaks' - basically a low level TCP issue. The bug seems to manifest itself in a number of ways. So far I've identified using shared connections (particularly with Vista or Windows 7) and connecting over VPN (any OS) as common scenarios. In all cases, not having DBA access is also an issue.

First, let me explain why DBA access makes a difference. When we first access any particular data dictionary view, we first try to see if we can get access to the DBA version of the view (or is some cases tab$, etc). These views are much more efficient than the ordinary USER versions, so we want to use them if we can. We only check each DBA view once per session (and only when needed), but we can end up checking for access to a bunch of views.

The OOB bug seems to rear its head when we do this check. We should get a nice, simple response back from the database. However, in the scenarios where the bug is occurring, this low level network bug is instead causing an error to occur that puts the connection into an unusable state. This then results in all the Connection Closed errors. There does appear to be a workaround - the JDBC driver supports disabling OOB. However, doing so will affect the ability to cancel an executing statement, So I wouldn't recommend using the workaround in general, but it should solve the issue for the situations where users are running into this specific problem.

To enable the workaround, a Java system property needs to be set - oracle.net.disableOob=true. You can set this in two ways. The first is to pass it in on the command line as sqldeveloper -J-Doracle.net.disableOob=true. Of course, that only works if you are normally running from the command line. You can also add a line to the sqldeveloper.conf file (located under +sqldeveloper\bin+). There the line would be AddVMOption -Doracle.net.disableOob=true

We are looking into additional resolutions, but for now the workaround should enable you to work with SQL Developer.

- John

SQL Developer Team

How to run mvim (MacVim) from Terminal?

If you already have macVim installed: /Applications/MacVim.app/Contents/MacOS/Vim -g will give you macVim GUI.

just add an alias.

i use gvim because that is what i use on linux for gnome-vim.

alias gvim='/Applications/MacVim.app/Contents/MacOS/Vim -g'

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Solution for me without reinstalling or creating a new project:

Step 1: Change line in build.gradle from:

dependencies {
    classpath 'com.android.tools.build:gradle:0.4'
}

to

dependencies {
    classpath 'com.android.tools.build:gradle:0.5.+'
}

Note: for newer versions of gradle you may need to change it to 0.6.+ instead.

Step 2: In the <YourProject>.iml file, delete the entire<component name="FacetManager">[...]</component> tag.

Step 3 (Maybe not necessary): In the Android SDK manager, install (if not already installed) Android Support Repository under Extras.


Info found here

Converting char* to float or double

You are missing an include : #include <stdlib.h>, so GCC creates an implicit declaration of atof and atod, leading to garbage values.

And the format specifier for double is %f, not %d (that is for integers).

#include <stdlib.h>
#include <stdio.h>

int main()
{
  char *test = "12.11";
  double temp = strtod(test,NULL);
  float ftemp = atof(test);
  printf("price: %f, %f",temp,ftemp);
  return 0;
}
/* Output */
price: 12.110000, 12.110000

Difference between two lists

bit late but here is working solution for me

 var myBaseProperty = (typeof(BaseClass)).GetProperties();//get base code properties
                    var allProperty = entity.GetProperties()[0].DeclaringType.GetProperties();//get derived class property plus base code as it is derived from it
                    var declaredClassProperties = allProperty.Where(x => !myBaseProperty.Any(l => l.Name == x.Name)).ToList();//get the difference

In above mention code I am getting the properties difference between my base class and derived class list

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

tl;dr Set the editor to something nicer, like Sublime or Atom

Here nice is used in the meaning of an editor you like or find more user friendly.

The underlying problem is that Git by default uses an editor that is too unintuitive to use for most people: Vim. Now, don't get me wrong, I love Vim, and while you could set some time aside (like a month) to learn Vim and try to understand why some people think Vim is the greatest editor in existence, there is a quicker way of fixing this problem :-)

The fix is not to memorize cryptic commands, like in the accepted answer, but configuring Git to use an editor that you like and understand! It's really as simple as configuring either of these options

  1. the git config setting core.editor (per project, or globally)
  2. the VISUAL or EDITOR environment variable (this works for other programs as well)

I'll cover the first option for a couple of popular editors, but GitHub has an excellent guide on this for many editors as well.

To use Atom

Straight from its docs, enter this in a terminal: git config --global core.editor "atom --wait"

Git normally wait for the editor command to finish, but since Atom forks to a background process immediately, this won't work, unless you give it the --wait option.

To use Sublime Text

For the same reasons as in the Atom case, you need a special flag to signal to the process that it shouldn't fork to the background:

git config --global core.editor "subl -n -w"

Java method to swap primitives

You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

You can however write a method that swaps two items in an array or list if that's what you want.

¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.

How to simulate a click with JavaScript?

Here's what I cooked up. It's pretty simple, but it works:

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

Usage:

eventFire(document.getElementById('mytest1'), 'click');

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

How to combine multiple inline style objects?

Actually, there is a formal way to combine and it is like below:

<View style={[style01, style02]} />

But, there is a small issue, if one of them is passed by the parent component and it was created by a combined formal way we have a big problem:

// The passing style02 from props: [parentStyle01, parentStyle02]

// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />

And this last line causes to have UI bug, surly, React Native cannot deal with a deep array inside an array. So I create my helper function:

import { StyleSheet } from 'react-native';

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

By using my styleJoiner anywhere you can combine any type of style and combine styles. even undefined or other useless types don't cause to break the styling.

Aligning textviews on the left and right edges in Android layout

There are many other ways to accomplish this, I would do something like this.

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="30dp"
        android:text="YOUR TEXT ON THE RIGHT"
        android:textSize="16sp"
        android:textStyle="italic" />


    <TextView
        android:id="@+id/textLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="30dp"
        android:text="YOUR TEXT ON THE LEFT"
        android:textSize="16sp" />
</RelativeLayout>

How do I initialise all entries of a matrix with a specific value?

Given a predefined m-by-n matrix size and the target value val, in your example:

m = 1;
n = 10;
val = 5;

there are currently 7 different approaches that come to my mind:


1) Using the repmat function (0.094066 seconds)

A = repmat(val,m,n)

2) Indexing on the undefined matrix with assignment (0.091561 seconds)

A(1:m,1:n) = val

3) Indexing on the target value using the ones function (0.151357 seconds)

A = val(ones(m,n))

4) Default initialization with full assignment (0.104292 seconds)

A = zeros(m,n);
A(:) = val

5) Using the ones function with multiplication (0.069601 seconds)

A = ones(m,n) * val

6) Using the zeros function with addition (0.057883 seconds)

A = zeros(m,n) + val

7) Using the repelem function (0.168396 seconds)

A = repelem(val,m,n)

After the description of each approach, between parentheses, its corresponding benchmark performed under Matlab 2017a and with 100000 iterations. The winner is the 6th approach, and this doesn't surprise me.

The explaination is simple: allocation generally produces zero-filled slots of memory... hence no other operations are performed except the addition of val to every member of the matrix, and on the top of that, input arguments sanitization is very short.

The same cannot be said for the 5th approach, which is the second fastest one because, despite the input arguments sanitization process being basically the same, on memory side three operations are being performed instead of two:

  • the initial allocation
  • the transformation of every element into 1
  • the multiplication by val

Best way to split string into lines

    private string[] GetLines(string text)
    {

        List<string> lines = new List<string>();
        using (MemoryStream ms = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(text);
            sw.Flush();

            ms.Position = 0;

            string line;

            using (StreamReader sr = new StreamReader(ms))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }
            sw.Close();
        }



        return lines.ToArray();
    }

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

PDF Blob - Pop up window not showing content

If you set { responseType: 'blob' }, no need to create Blob on your own. You can simply create url based with response content:

$http({
    url: "...",
    method: "POST",
    responseType: "blob"
}).then(function(response) {
    var fileURL = URL.createObjectURL(response.data);
    window.open(fileURL);
});

How can I call a function using a function pointer?

If you need help with complex definitions, like

double (*(*pf)())[3][4];

take a look at my right-left rule here.

How to correctly implement custom iterators and const_iterators?

They often forget that iterator must convert to const_iterator but not the other way around. Here is a way to do that:

template<class T, class Tag = void>
class IntrusiveSlistIterator
   : public std::iterator<std::forward_iterator_tag, T>
{
    typedef SlistNode<Tag> Node;
    Node* node_;

public:
    IntrusiveSlistIterator(Node* node);

    T& operator*() const;
    T* operator->() const;

    IntrusiveSlistIterator& operator++();
    IntrusiveSlistIterator operator++(int);

    friend bool operator==(IntrusiveSlistIterator a, IntrusiveSlistIterator b);
    friend bool operator!=(IntrusiveSlistIterator a, IntrusiveSlistIterator b);

    // one way conversion: iterator -> const_iterator
    operator IntrusiveSlistIterator<T const, Tag>() const;
};

In the above notice how IntrusiveSlistIterator<T> converts to IntrusiveSlistIterator<T const>. If T is already const this conversion never gets used.

How to group an array of objects by key

Agree that unless you use these often there is no need for an external library. Although similar solutions are available, I see that some of them are tricky to follow here is a gist that has a solution with comments if you're trying to understand what is happening.

_x000D_
_x000D_
const cars = [{
  'make': 'audi',
  'model': 'r8',
  'year': '2012'
}, {
  'make': 'audi',
  'model': 'rs5',
  'year': '2013'
}, {
  'make': 'ford',
  'model': 'mustang',
  'year': '2012'
}, {
  'make': 'ford',
  'model': 'fusion',
  'year': '2015'
}, {
  'make': 'kia',
  'model': 'optima',
  'year': '2012'
}, ];

/**
 * Groups an array of objects by a key an returns an object or array grouped by provided key.
 * @param array - array to group objects by key.
 * @param key - key to group array objects by.
 * @param removeKey  - remove the key and it's value from the resulting object.
 * @param outputType - type of structure the output should be contained in.
 */
const groupBy = (
  inputArray,
  key,
  removeKey = false,
  outputType = {},
) => {
  return inputArray.reduce(
    (previous, current) => {
      // Get the current value that matches the input key and remove the key value for it.
      const {
        [key]: keyValue
      } = current;
      // remove the key if option is set
      removeKey && keyValue && delete current[key];
      // If there is already an array for the user provided key use it else default to an empty array.
      const {
        [keyValue]: reducedValue = []
      } = previous;

      // Create a new object and return that merges the previous with the current object
      return Object.assign(previous, {
        [keyValue]: reducedValue.concat(current)
      });
    },
    // Replace the object here to an array to change output object to an array
    outputType,
  );
};

console.log(groupBy(cars, 'make', true))
_x000D_
_x000D_
_x000D_

Python Remove last char from string and return it

I decided to go with a for loop and just avoid the item in question, is it an acceptable alternative?

new = ''
for item in str:
    if item == str[n]:
        continue
    else:
        new += item

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

Deny direct access to all .php files except index.php

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

How to multiply a BigDecimal by an integer in Java

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
           BigDecimal   itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

How to comment out a block of Python code in Vim

CtrlK for comment (Visual Mode):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU for uncomment (Visual Mode):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

OVER clause in Oracle

Another way to use OVER is to have a result column in your select operate on another "partition", so to say.

This:

SELECT 
    name, 
    ssn, 
    case 
      when ( count(*) over (partition by ssn) ) > 1      
      then 1
      else 0
    end AS hasDuplicateSsn
FROM table;

returns 1 in hasDuplicateSsn for each row whose ssn is shared by another row. Great for making "tags" for data for different error reports and such.

How to parseInt in Angular.js

This are to way to bind add too numbers

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
  return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Installing SciPy and NumPy using pip

I was working on a project that depended on numpy and scipy. In a clean installation of Fedora 23, using a python virtual environment for Python 3.4 (also worked for Python 2.7), and with the following in my setup.py (in the setup() method)

setup_requires=[
    'numpy',
],
install_requires=[
    'numpy',
    'scipy',
],

I found I had to run the following to get pip install -e . to work:

pip install --upgrade pip

and

sudo dnf install atlas-devel gcc-{c++,gfortran} subversion redhat-rpm-config

The redhat-rpm-config is for scipy's use of redhat-hardened-cc1 as opposed to the regular cc1

Cannot open local file - Chrome: Not allowed to load local resource

You just need to replace all image network paths to byte strings in stored Encoded HTML string. For this you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

// Decode the encoded string.
StringWriter myWriter = new StringWriter();
HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
string DecodedHtmlString = myWriter.ToString();

//find and replace each img src with byte string
HtmlDocument document = new HtmlDocument();
document.LoadHtml(DecodedHtmlString);
document.DocumentNode.Descendants("img")
    .Where(e =>
    {
        string src = e.GetAttributeValue("src", null) ?? "";
        return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
    })
    .ToList()
    .ForEach(x =>
        {
        string currentSrcValue = x.GetAttributeValue("src", null);                                
        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
        string filename = Path.GetFileName(currentSrcValue);
        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
    });

string result = document.DocumentNode.OuterHtml;
//Encode HTML string
string myEncodedString = HttpUtility.HtmlEncode(result);

Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

Execution failed app:processDebugResources Android Studio

In my case, crashlytics (Fabric.io) was generating files that conflicted at some point and a second file was automatically generated with an invalid name.

Long story short: Check if you don't have any filenames with invalid lengths, you should be warned above the original exception.

jQuery `.is(":visible")` not working in Chrome

A cross browser/version solution to determine whether an element is visible, is to add/remove a css class to the element on show/hide. The default(visible) state of the element could be for example like this:

<span id="span1" class="visible">Span text</span>

Then on hide, remove the class:

$("#span1").removeClass("visible").hide();

On show, add it again:

$("#span1").addClass("visible").show();

Then to determine whether the element is visible, use this:

if ($("#span1").hasClass("visible")) { // do something }

This also solves the performance implications, which may occur on heavy usage of the ":visible" selector, which are pointed in jQuery's documentation:

Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance.

Official jQuery API Documentation for ":visible" selector

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

how to fetch array keys with jQuery?

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

Extracting an attribute value with beautifulsoup

you can also use this :

import requests
from bs4 import BeautifulSoup
import csv

url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text

soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})

for val in get_details:
    get_val = val["value"]
    print(get_val)

GenyMotion Unable to start the Genymotion virtual device

Also make sure to update your Oracle VM Virtual Box. I tried everything but later realized that the issue was due to the use of older version of Virtual Box.

Ansible: deploy on multiple hosts in the same time

As of Ansible 2.0 there seems to be an option called strategy on a playbook. When setting the strategy to free, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.

It looks something like this (taken from the above link):

- hosts: all
  strategy: free
  tasks:
  ...

Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.

EDIT:

It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.

This includes specifying async and poll on a task. The following is taken from the 2nd link I mentioned:

- name: simulate long running op, allow to run for 45 sec, fire and forget
  command: /bin/sleep 15
  async: 45
  poll: 0

I guess you can specify longer async times if your task is lengthy. You can probably define your three concurrent task this way.

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

How to do a regular expression replace in MySQL?

The one below basically finds the first match from the left and then replaces all occurences of it (tested in ).

Usage:

SELECT REGEX_REPLACE('dis ambiguity', 'dis[[:space:]]*ambiguity', 'disambiguity');

Implementation:

DELIMITER $$
CREATE FUNCTION REGEX_REPLACE(
  var_original VARCHAR(1000),
  var_pattern VARCHAR(1000),
  var_replacement VARCHAR(1000)
  ) RETURNS
    VARCHAR(1000)
  COMMENT 'Based on https://techras.wordpress.com/2011/06/02/regex-replace-for-mysql/'
BEGIN
  DECLARE var_replaced VARCHAR(1000) DEFAULT var_original;
  DECLARE var_leftmost_match VARCHAR(1000) DEFAULT
    REGEX_CAPTURE_LEFTMOST(var_original, var_pattern);
    WHILE var_leftmost_match IS NOT NULL DO
      IF var_replacement <> var_leftmost_match THEN
        SET var_replaced = REPLACE(var_replaced, var_leftmost_match, var_replacement);
        SET var_leftmost_match = REGEX_CAPTURE_LEFTMOST(var_replaced, var_pattern);
        ELSE
          SET var_leftmost_match = NULL;
        END IF;
      END WHILE;
  RETURN var_replaced;
END $$
DELIMITER ;

DELIMITER $$
CREATE FUNCTION REGEX_CAPTURE_LEFTMOST(
  var_original VARCHAR(1000),
  var_pattern VARCHAR(1000)
  ) RETURNS
    VARCHAR(1000)
  COMMENT '
  Captures the leftmost substring that matches the [var_pattern]
  IN [var_original], OR NULL if no match.
  '
BEGIN
  DECLARE var_temp_l VARCHAR(1000);
  DECLARE var_temp_r VARCHAR(1000);
  DECLARE var_left_trim_index INT;
  DECLARE var_right_trim_index INT;
  SET var_left_trim_index = 1;
  SET var_right_trim_index = 1;
  SET var_temp_l = '';
  SET var_temp_r = '';
  WHILE (CHAR_LENGTH(var_original) >= var_left_trim_index) DO
    SET var_temp_l = LEFT(var_original, var_left_trim_index);
    IF var_temp_l REGEXP var_pattern THEN
      WHILE (CHAR_LENGTH(var_temp_l) >= var_right_trim_index) DO
        SET var_temp_r = RIGHT(var_temp_l, var_right_trim_index);
        IF var_temp_r REGEXP var_pattern THEN
          RETURN var_temp_r;
          END IF;
        SET var_right_trim_index = var_right_trim_index + 1;
        END WHILE;
      END IF;
    SET var_left_trim_index = var_left_trim_index + 1;
    END WHILE;
  RETURN NULL;
END $$
DELIMITER ;

Get record counts for all tables in MySQL database

If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.

Install following Gems:

$> gem install dbi
$> gem install dbd-mysql

File: count_table_records.rb

require 'rubygems'
require 'dbi'

db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')

# Collect all Tables
sql_1 = db_handler.prepare('SHOW tables;')
sql_1.execute
tables = sql_1.map { |row| row[0]}
sql_1.finish

tables.each do |table_name|
  sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};")
  sql_2.execute
  sql_2.each do |row|
    puts "Table #{table_name} has #{row[0]} rows."
  end
  sql_2.finish
end

db_handler.disconnect

Go back to the command-line:

$> ruby count_table_records.rb

Output:

Table users has 7328974 rows.

Storing Images in DB - Yea or Nay?

The trick here is to not become a zealot.

One thing to note here is that no one in the pro file system camp has listed a particular file system. Does this mean that everything from FAT16 to ZFS handily beats every database?

No.

The truth is that many databases beat many files systems, even when we're only talking about raw speed.

The correct course of action is to make the right decision for your precise scenario, and to do that, you'll need some numbers and some use case estimates.