Programs & Examples On #Actionmailer

Action Mailer is a framework for designing email service layers. Original ActionMailer is written in Ruby, but there is also implementation for ASP.NET MVC.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Remove your Gemfile.lock.

Move to bash if you are using zsh.

sudo bash
gem update --system 

Now run command bundle to create a new Gemfile.lock file. Move back to your zsh sudo exec zsh now run your rake commands.

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Adding the default_url in routes not the right solution although, it works for some cases.

You've to set the default_url in each environment(development, test, production).

You need make these changes.

    config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

 config/environments/test.rb
      config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

  config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

incompatible character encodings: ASCII-8BIT and UTF-8

I had a similar issue on a custom CoffeeScript file. I solved it by changing the endline encoding from "Unix/Linux" to "Mac OS Classic"

Convert from MySQL datetime to another format with PHP

Using PHP version 4.4.9 & MySQL 5.0, this worked for me:

$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate

PubDate is the column in MySQL.

setContentView(R.layout.main); error

Using NetBeans 7.0:

If you fix imports before R.java has been generated for your project (before building it the first time) it will add the line:

import android.R;

which will override the local R.java that you are trying to reference.

Deleting that line resolved the errors for me.

SQL Query to concatenate column values from multiple rows in Oracle

As most of the answers suggest, LISTAGG is the obvious option. However, one annoying aspect with LISTAGG is that if the total length of concatenated string exceeds 4000 characters( limit for VARCHAR2 in SQL ), the below error is thrown, which is difficult to manage in Oracle versions upto 12.1

ORA-01489: result of string concatenation is too long

A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

SELECT pid, LISTAGG(Desc, ' ' on overflow truncate) WITHIN GROUP (ORDER BY seq) AS desc
FROM B GROUP BY pid;

The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

These are some of the additional options of ON OVERFLOW clause:

  • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
  • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
  • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
  • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

What is the best way to remove a table row with jQuery?

$('tr').click(function()
 {
  $(this).remove();
 });

i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.

Is it possible to apply CSS to half of a character?

Here an ugly implementation in canvas. I tried this solution, but the results are worse than I expected, so here it is anyway.

Canvas example

_x000D_
_x000D_
$("div").each(function() {_x000D_
  var CHARS = $(this).text().split('');_x000D_
  $(this).html("");_x000D_
  $.each(CHARS, function(index, char) {_x000D_
    var canvas = $("<canvas />")_x000D_
      .css("width", "40px")_x000D_
      .css("height", "40px")_x000D_
      .get(0);_x000D_
    $("div").append(canvas);_x000D_
    var ctx = canvas.getContext("2d");_x000D_
    var gradient = ctx.createLinearGradient(0, 0, 130, 0);_x000D_
    gradient.addColorStop("0", "blue");_x000D_
    gradient.addColorStop("0.5", "blue");_x000D_
    gradient.addColorStop("0.51", "red");_x000D_
    gradient.addColorStop("1.0", "red");_x000D_
    ctx.font = '130pt Calibri';_x000D_
    ctx.fillStyle = gradient;_x000D_
    ctx.fillText(char, 10, 130);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>Example Text</div>
_x000D_
_x000D_
_x000D_

Offset a background image from the right using CSS

!! Outdated answer, since CSS3 brought this feature

Is there a way to position a background image a certain number of pixels from the right of its element?

Nope.

Popular workarounds include

  • setting a margin-right on the element instead
  • adding transparent pixels to the image itself and positioning it top right
  • or calculating the position using jQuery after the element's width is known.

CURRENT_TIMESTAMP in milliseconds

For mysql:

SELECT (UNIX_TIMESTAMP() * 1000) AS unix_now_in_microseconds; --- 1600698677000

Pycharm and sys.argv arguments

The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:

from sys import argv

script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second

And here is how you pass the input parameters : 'Path to your script','First Parameter','Second Parameter'

Lets say that the Path to your script is /home/my_folder/test.py , the output will be like :

Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter

Hope this helps as it took me sometime to figure out input parameters are comma separated.

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I recently had this problem and it ended up being a port issue. My production SQL Server was set up at to be port 1427 instead 1433.

Just change the connection string to be

...data source=MySQLServerName,1427;initial catalog=MyDBName...

Hope this helps anyone who might be seeing this same issue.

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

In my case this error was provoked by a size of a string column. What was weird was when I executed the exact same query in different tool, repeated values nor null values weren't there.

Then I discovered that the size of a string column size was 50 so when I called the fill method the value was chopped, throwing this exception.
I click on the column and set in the properties the size to 200 and the error was gone.

Hope this help

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

Java: convert seconds to minutes, hours and days

my quick answer with basic java arithmetic calculation is this:

First consider the following values:

1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
  1. First divide the input by 86400, if you you can get a number greater than 0 , this is the number of days. 2.Again divide the remained number you get from the first calculation by 3600, this will give you the number of hours
  2. Then divide the remainder of your second calculation by 60 which is the number of Minutes
  3. Finally the remained number from your third calculation is the number of seconds

the code snippet is as follows:

int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;

numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60 
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60  ;

I hope to be helpful to you.

Can I get the name of the currently running function in JavaScript?

This has to go in the category of "world's ugliest hacks", but here you go.

First up, printing the name of the current function (as in the other answers) seems to have limited use to me, since you kind of already know what the function is!

However, finding out the name of the calling function could be pretty useful for a trace function. This is with a regexp, but using indexOf would be about 3x faster:

function getFunctionName() {
    var re = /function (.*?)\(/
    var s = getFunctionName.caller.toString();
    var m = re.exec( s )
    return m[1];
}

function me() {
    console.log( getFunctionName() );
}

me();

How to check if a value exists in an array in Ruby

If you're trying to do this in a MiniTest unit test, you can use assert_includes. Example:

pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog')      # -> passes
assert_includes(pets, 'Zebra')    # -> fails 

displayname attribute vs display attribute

They both give you the same results but the key difference I see is that you cannot specify a ResourceType in DisplayName attribute. For an example in MVC 2, you had to subclass the DisplayName attribute to provide resource via localization. Display attribute (new in MVC3 and .NET4) supports ResourceType overload as an "out of the box" property.

How to use Google Translate API in my Java application?

You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java in line no 124 you are trying to access a null object which results in null pointer exception.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

How to get data from Magento System Configuration

Magento 1.x

(magento 2 example provided below)

sectionName, groupName and fieldName are present in etc/system.xml file of the module.

PHP Syntax:

Mage::getStoreConfig('sectionName/groupName/fieldName');

From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.

{{config path="sectionName/groupName/fieldName"}}

For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:

<?php
    $example = Mage::getModel('identifier/name')->load(1);
    $filter  = Mage::getModel('cms/template_filter');
    echo $filter->filter($example->getData('field'));
?>

Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.

Magento 2.x

From any Block class that extends \Magento\Framework\View\Element\AbstractBlock

$this->_scopeConfig->getValue('sectionName/groupName/fieldName');

Any other PHP class:

If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface via the constructor, you'll have to add it to your class.

// ... Remaining class definition above...

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
protected $_scopeConfig;

/**
 * Constructor
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    // ...any other injected classes the class depends on...
) {
  $this->_scopeConfig = $scopeConfig;
  // Remaining constructor logic...
}

// ...remaining class definition below...

Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.

Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation & var/di

Check if instance is of a type

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

PHP How to fix Notice: Undefined variable:

I would guess your query isn't running as expected and you are getting to the return line with undefined variables.

Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.

Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:

Function ShowDataPatient($idURL){
       $query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
                 AND cmu_patient.patient_hn like '%$idURL%'
                 AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";

   $result = pg_query($query) or die('Query failed: ' . pg_last_error());

   $return = array();
   while ($row = pg_fetch_array($result)){
       $return[] = $row;
   }          

   return $return;
}

You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Can I extend a class using more than 1 class in PHP?

Use traits as base classes. Then use them in a parent class. Extend it .

trait business{
  function sell(){

  }

  function buy(){

  }

  function collectMoney(){
  }

}

trait human{

   function think(){

   }

   function speak(){

   }

}

class BusinessPerson{
  use business;
  use human;
  // If you have more traits bring more
}


class BusinessWoman extends BusinessPerson{

   function getPregnant(){

   }

}


$bw = new BusinessWoman();
$bw ->speak();
$bw->getPregnant();

See now business woman logically inherited business and human both;

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

Get Category name from Post ID

doesn't

<?php get_the_category( $id ) ?>

do just that, inside the loop?

For outside:

<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>

Add Bean Programmatically to Spring Web App Context

Why do you need it to be of type GenericWebApplicationContext?
I think you can probably work with any ApplicationContext type.

Usually you would use an init method (in addition to your setter method):

@PostConstruct
public void init(){
    AutowireCapableBeanFactory bf = this.applicationContext
        .getAutowireCapableBeanFactory();
    // wire stuff here
}

And you would wire beans by using either

AutowireCapableBeanFactory.autowire(Class, int mode, boolean dependencyInject)

or

AutowireCapableBeanFactory.initializeBean(Object existingbean, String beanName)

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

Python method for reading keypress?

It's really late now but I made a quick script which works for Windows, Mac and Linux, simply by using each command line:

import os, platform

def close():
    if platform.system() == "Windows":
        print("Press any key to exit . . .")
        os.system("pause>nul")
        exit()
    
    elif platform.system() == "Linux":
        os.system("read -n1 -r -p \"Press any key to exit . . .\" key")
        exit()
    
    elif platform.system() == "Darwin":
        print("Press any key to exit . . .")
        os.system("read -n 1 -s -p \"\"")
        exit()
    
    else:
        exit()

It uses only inbuilt functions, and should work for all three (although I've only tested Windows and Linux...).

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
    
  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.

Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.

File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run

fciv -sha1 DXSDK_Jun10.exe

and verify you get

8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe

How do I escape double and single quotes in sed?

You need to use \" for escaping " character (\ escape the following character

sed -i 's/\"http://www.fubar.com\"/URL_FUBAR/g'

AWS EFS vs EBS vs S3 (differences & when to use?)

In simple words

Amazon EBS provides block level storage .

Amazon EFS provides network-attached shared file storage.

Amazon S3 provides object storage .

SELECT * WHERE NOT EXISTS

SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)

Never returns any records unless eotm_dyn is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn like

SELECT * from employees
WHERE NOT EXISTS (
    SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)

assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.

Changing one character in a string

I would like to add another way of changing a character in a string.

>>> text = '~~~~~~~~~~~'
>>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
'~+~~~~~~~~~'

How faster it is when compared to turning the string into list and replacing the ith value then joining again?.

List approach

>>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
0.8268570480013295

My solution

>>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
0.588400217000526

pytest cannot import module while python can

Kept everything same and just added a blank test file at the root folder .. Solved it

Here are the findings, this problem really bugged me for a while. My folder structure was

mathapp/
    - server.py  
    - configuration.py 
    - __init__.py 
    - static/ 
       - home.html  
tests/            
    - functional 
       - test_errors.py 
    - unit  
       - test_add.py

and pytest would complain with the ModuleNotFoundError and gives the HINT - make sure your test modules/packages have valid Python names.

I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

Result without the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================

Results with the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================

Split string using a newline delimiter with Python

If you want to split only by newlines, you can use str.splitlines():

Example:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

With str.split() your case also works:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

However if you have spaces (or tabs) it will fail:

>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']

iOS detect if user is on an iPad

UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal. If its an iPhone app running on an iPad then it won't. So you should instead check the model.

Can I recover a branch after its deletion in Git?

IF you are using VSCode... and you synced your branch with the server at some point before deleting it...

Note that git branch delete only deletes the local copy, not the copy on the server. First, in the Git panel (git icon on left toolbar), look through the branches and see if your branch is still there under "origin/your_branch_name". If so, just select that and you should get your code back (suggest that you immediately copy/paste/save it locally somewhere else).

If you didn't see an "origin/your_branch_name", Install the GitLens extension. This allows you to visually poke around in the server repositories and locate the copy you synced to the server. If you have multiple repositories, note that it might be necessary to have at least one file opened from the desired repository in order to make the repository appear in GitLens. Then:

  1. Open the GitLens panel

  2. Expand the repository

  3. You should see a list of categories: Branches / Contributors / Remotes / Stashes / etc

You should find YourLostTreasure under "Branches" or possibly under "Remotes -> Origins". Hopefully, you will see a branch with the desired name - if you expand it, you should see the files you changed in that branch. Double-click the file names to open them, and immediately back up that code.

If you don't immediately see your lost branch, poke around and if you find something promising, immediately open it and grab the code. I had to poke around quite a bit until I found TheGoldenBranch, and even then the code was missing the last one or two saves (possibly because I failed to sync to server before attempting-a-Branch-Merge-but-accidentally-clicking-Branch-Delete). My search was unnecessarily lengthened because when I first found the branch I wasn't completely sure the name was correct so kept looking, and it took some time to re-find that first branch. (Thus, Carpe Carpum and then keep looking.)

java Arrays.sort 2d array

import java.util.*;

public class Arrays2
{
    public static void main(String[] args)
    {
        int small, row = 0, col = 0, z;
        int[][] array = new int[5][5];

        Random rand = new Random();
        for(int i = 0; i < array.length; i++)
        {
            for(int j = 0; j < array[i].length; j++)
            {
                array[i][j] = rand.nextInt(100);
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }

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


        for(int k = 0; k < array.length; k++)
        {
            for(int p = 0; p < array[k].length; p++)
            {
                small = array[k][p];
                for(int i = k; i < array.length; i++)
                {
                    if(i == k)
                        z = p + 1;
                    else
                        z = 0;
                    for(;z < array[i].length; z++)
                    {
                        if(array[i][z] <= small)
                        {
                            small = array[i][z];
                            row = i;
                            col = z;
                        }
                    }
                }
            array[row][col] = array[k][p];
            array[k][p] = small;
            System.out.print(array[k][p] + " ");
            }
            System.out.println();
        }
    }
}

Good Luck

How can you profile a Python script?

cProfile is great for quick profiling but most of the time it was ending for me with the errors. Function runctx solves this problem by initializing correctly the environment and variables, hope it can be useful for someone:

import cProfile
cProfile.runctx('foo()', None, locals())

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.

In the meantime, this link should get you started:

Using reflection to load unreferenced assemblies at runtime

What is the strict aliasing rule?

Strict aliasing doesn't refer only to pointers, it affects references as well, I wrote a paper about it for the boost developer wiki and it was so well received that I turned it into a page on my consulting web site. It explains completely what it is, why it confuses people so much and what to do about it. Strict Aliasing White Paper. In particular it explains why unions are risky behavior for C++, and why using memcpy is the only fix portable across both C and C++. Hope this is helpful.

Rollback a Git merge

If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.

The easiest way I felt was to:

  1. Take out a new branch from develop/master (where you merged)
  2. Revert the "revert" using git revert -m 1 xxxxxx (if the revert was merged using a branch) or using git revert xxxxxx if it was a simple revert
  3. The new branch should now have the changes you want to merge again.
  4. Make changes or merge this branch to develop/master

How to style a clicked button in CSS

There are three states of button

  • Normal : You can select like this button
  • Hover : You can select like this button:hover
  • Pressed/Clicked : You can select like this button:active

Normal:

.button
 {
     //your css
 }

Active

 .button:active
{
        //your css
}

Hover

 .button:hover
{
        //your css
}

SNIPPET:

Use :active to style the active state of button.

_x000D_
_x000D_
button:active{_x000D_
   background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
_x000D_
_x000D_

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Matrix Transpose in Python

def matrixTranspose(anArray):
  transposed = [None]*len(anArray[0])

  for i in range(len(transposed)):
    transposed[i] = [None]*len(transposed)

  for t in range(len(anArray)):
    for tt in range(len(anArray[t])):            
        transposed[t][tt] = anArray[tt][t]
  return transposed

theArray = [['a','b','c'],['d','e','f'],['g','h','i']]

print matrixTranspose(theArray)

ValueError: not enough values to unpack (expected 11, got 1)

The error message is fairly self-explanatory

(a,b,c,d,e) = line.split()

expects line.split() to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.

To see what line is causing the issue, you could add some debug statements like this:

if len(line.split()) != 11:
    print line

As Martin suggests, you might also be splitting on the wrong delimiter.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

Regex to match string containing two names in any order

The expression in this answer does that for one jack and one james in any order.

Here, we'd explore other scenarios.

METHOD 1: One jack and One james

Just in case, two jack or two james would not be allowed, only one jack and one james would be valid, we can likely design an expression similar to:

^(?!.*\bjack\b.*\bjack\b)(?!.*\bjames\b.*\bjames\b)(?=.*\bjames\b)(?=.*\bjack\b).*$

Here, we would exclude those instances using these statements:

(?!.*\bjack\b.*\bjack\b)

and,

(?!.*\bjames\b.*\bjames\b)

RegEx Demo 1

We can also simplify that to:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$

RegEx Demo 2


If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$/gm;
const str = `hi jack here is james
hi james here is jack
hi james jack here is jack james
hi jack james here is james jack
hi jack jack here is jack james
hi james james here is james jack
hi jack jack jack here is james
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
_x000D_
_x000D_
_x000D_


METHOD 2: One jack and One james in a specific order

The expression can be also designed for first a james then a jack, similar to the following one:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b.*\bjack\b).*$

RegEx Demo 3

and vice versa:

^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjack\b.*\bjames\b).*$

RegEx Demo 4

What's the difference between an Angular component and module

enter image description here

Simplest Explanation:

Module is like a big container containing one or many small containers called Component, Service, Pipe

A Component contains :

  • HTML template or HTML code

  • Code(TypeScript)

  • Service: It is a reusable code that is shared by the Components so that rewriting of code is not required

  • Pipe: It takes in data as input and transforms it to the desired output

Reference: https://scrimba.com/

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

PHP: How to remove specific element from an array?

Just u can do single line .it will be remove element from array


$array=array_diff($array,['strawberry']);


When to use the different log levels

It's an old topic, but still relevant. This week, I wrote a small article about it, for my colleagues. For that purpose, I also created this cheat sheet, because I couldn't find any online.

cheat sheet: which log level should I use

How should I throw a divide by zero exception in Java without actually dividing by zero?

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");
}

Using two CSS classes on one element

If you want to apply styles only to an element which is its parents' first child, is it better to use :first-child pseudo-class

.social:first-child{
    border-bottom: dotted 1px #6d6d6d;
    padding-top: 0;
}
.social{
    border: 0;
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
}

Then, the rule .social has both common styles and the last element's styles.

And .social:first-child overrides them with first element's styles.

You could also use :last-child selector, but :first-childis more supported by old browsers: see https://developer.mozilla.org/en-US/docs/CSS/:first-child#Browser_compatibility and https://developer.mozilla.org/es/docs/CSS/:last-child#Browser_compatibility.

Create hyperlink to another sheet

The "!" sign is the key element. If you have a cell object (like "mycell" in following code sample) and link a cell to this object you must pay attention to ! element.

You must do something like this:

.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
     SubAddress:= "'" & ws.Name & "'" & _
     "!" & mycell.Address

Show and hide a View with a slide up/down animation

With Kotlin extensions you can use this:

enum class SlideDirection{
    UP,
    DOWN,
    LEFT,
    RIGHT
}

enum class SlideType{
    SHOW,
    HIDE
}

fun View.slideAnimation(direction: SlideDirection, type: SlideType, duration: Long = 250){
    val fromX: Float
    val toX: Float
    val fromY: Float
    val toY: Float
    val array = IntArray(2)
    getLocationInWindow(array)
    if((type == SlideType.HIDE && (direction == SlideDirection.RIGHT || direction == SlideDirection.DOWN)) ||
        (type == SlideType.SHOW && (direction == SlideDirection.LEFT || direction == SlideDirection.UP))   ){
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val deviceWidth = displayMetrics.widthPixels
        val deviceHeight = displayMetrics.heightPixels
        array[0] = deviceWidth
        array[1] = deviceHeight
    }
    when (direction) {
        SlideDirection.UP -> {
            fromX = 0f
            toX = 0f
            fromY = if(type == SlideType.HIDE) 0f else (array[1] + height).toFloat()
            toY = if(type == SlideType.HIDE) -1f * (array[1] + height)  else 0f
        }
        SlideDirection.DOWN -> {
            fromX = 0f
            toX = 0f
            fromY = if(type == SlideType.HIDE) 0f else -1f * (array[1] + height)
            toY = if(type == SlideType.HIDE) 1f * (array[1] + height)  else 0f
        }
        SlideDirection.LEFT -> {
            fromX = if(type == SlideType.HIDE) 0f else 1f * (array[0] + width)
            toX = if(type == SlideType.HIDE) -1f * (array[0] + width) else 0f
            fromY = 0f
            toY = 0f
        }
        SlideDirection.RIGHT -> {
            fromX = if(type == SlideType.HIDE) 0f else -1f * (array[0] + width)
            toX = if(type == SlideType.HIDE) 1f * (array[0] + width) else 0f
            fromY = 0f
            toY = 0f
        }
    }
    val animate = TranslateAnimation(
        fromX,
        toX,
        fromY,
        toY
    )
    animate.duration = duration
    animate.setAnimationListener(object: Animation.AnimationListener{
        override fun onAnimationRepeat(animation: Animation?) {

        }

        override fun onAnimationEnd(animation: Animation?) {
            if(type == SlideType.HIDE){
                visibility = View.INVISIBLE
            }
        }

        override fun onAnimationStart(animation: Animation?) {
            visibility = View.VISIBLE
        }

    })
    startAnimation(animate)
}

Example for the extension:

view.slideAnimation(SlideDirection.UP, SlideType.HIDE)//to make it disappear through top of the screen
view.slideAnimation(SlideDirection.DOWN, SlideType.SHOW)//to make it reappear from top of the screen

view.slideAnimation(SlideDirection.DOWN, SlideType.HIDE)//to make it disappear through bottom of the screen
view.slideAnimation(SlideDirection.UP, SlideType.SHOW)//to make it reappear from bottom of the screen

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

Change

die (mysqli_error()); 

to

die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

How can I require at least one checkbox be checked before a form can be submitted?

The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

How to format a DateTime in PowerShell

A very convenient -- but probably not all too efficient -- solution is to use the member function GetDateTimeFormats(),

$d = Get-Date
$d.GetDateTimeFormats()

This outputs a large string-array of formatting styles for the date-value. You can then pick one of the elements of the array via the []-operator, e.g.,

PS C:\> $d.GetDateTimeFormats()[12]
Dienstag, 29. November 2016 19.14

jQuery map vs. each

Jquery.map makes more sense when you are doing work on arrays as it performs very well with arrays.

Jquery.each is best used when iterating through selector items. Which is evidenced in that the map function does not use a selector.

$(selector).each(...)

$.map(arr....)

as you can see, map is not intended to be used with selectors.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

Count unique values in a column in Excel

To count the number of different values in A2:A100 (not counting blanks):

=SUMPRODUCT((A2:A100<>"")/COUNTIF(A2:A100,A2:A100&""))


Copied from an answer by @Ulli Schmid to What is this COUNTIF() formula doing?:

=SUMPRODUCT((A1:A100<>"")/COUNTIF(A1:A100,A1:A100&""))

Counts unique cells within A1:A100, excluding blank cells and ones with an empty string ("").

How does it do that? Example:

A1:A100 = [1, 1, 2, "apple", "peach", "apple", "", "", -, -, -, ...]
then:
A1:A100&"" = ["1", "1", "2", "apple", "peach", "apple", "", "", "", "", "", ...]

so this &"" is needed to turn blank cells (-) into empty strings (""). If you were to count directly using blank cells, COUNTIF() returns 0. Using the trick, both "" and - are counted as the same:

COUNTIF(A1:A100,A1:A100) = [2, 2, 1, 2, 1, 2, 94, 94, 0, 0, 0, ...]
but:
COUNTIF(A1:A100,A1:A100&"") = [2, 2, 1, 2, 1, 2, 94, 94, 94, 94, 94, ...]

If we now want to get the count of all unique cells, excluding blanks and "", we can divide

(A1:A100<>""), which is [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, ...]

by our intermediate result, COUNTIF(A1:A100,A1:A100&""), and sum up over the values.

SUMPRODUCT((A1:A100<>"")/COUNTIF(A1:A100,A1:A100&""))  
= (1/2 + 1/2 + 1/1 + 1/2 + 1/1 + 1/2 + 0/94 + 0/94 + 0/94 + 0/94 + 0/94 + ...)
= 4

Had we used COUNTIF(A1:A100,A1:A100) instead of COUNTIF(A1:A100,A1:A100&""), then some of those 0/94 would have been 0/0. As division by zero is not allowed, we would have thrown an error.

How to check whether mod_rewrite is enable on server?

console:

<VirtualHost *:80>
        ...
    <Directory ...>
        AllowOverride All
    </Directory>
</VirtualHost>

sudo a2enmod rewrite
sudo service apache2 restart

Django: OperationalError No Such Table

For django 1.10 you may have to do python manage.py makemigrations appname.

How to install SignTool.exe for Windows 10

to install just the signingtools from the winsdksetup.exe (available at the same url as the windows sdk iso mentioned above) this is an option to, straight from the Dockerfile i'm working in: RUN powershell Start-Process winsdksetup.exe -ArgumentList '/features OptionId.SigningTools', '/q', '/ceip off', '/norestart', -NoNewWindow -Wait

so if you're in windows then that'd be: winsdksetup.exe /features OptionId.SigningTools

winsdksetup /h gives you the options, so i won't summarise them here. I include the dockerfile snippet, as that is what i started my day looking for the solution for.

How to delete or change directory of a cloned git repository on a local computer

Just move it :)

command line :

move "C:\Documents and Setings\$USER\project" C:\project

or just drag the folder in explorer.

Git won't care where it is - all the metadata for the repository is inside a folder called .git inside your project folder.

How to insert a text at the beginning of a file?

Use subshell:

echo "$(echo -n 'hello'; cat filename)" > filename

Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:

echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename

Neither grouping nor command substitution is needed.

What does "select 1 from" do?

It does what you ask, SELECT 1 FROM table will SELECT (return) a 1 for every row in that table, if there were 3 rows in the table you would get

1
1
1

Take a look at Count(*) vs Count(1) which may be the issue you were described.

How to get value from form field in django framework?

Using a form in a view pretty much explains it.

The standard pattern for processing a form in a view looks like this:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            print form.cleaned_data['my_form_field_name']

            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

HTML5 Pre-resize images before uploading

You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.

It has builtin resize functions, but you can provide your own if you want.

How do I get a string format of the current date time, in python?

#python3

import datetime
print(
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
    )

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Description:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

Easily measure elapsed time

#include<time.h> // for clock
#include<math.h> // for fmod
#include<cstdlib> //for system
#include <stdio.h> //for delay

using namespace std;

int main()
{


   clock_t t1,t2;

   t1=clock(); // first time capture

   // Now your time spanning loop or code goes here
   // i am first trying to display time elapsed every time loop runs

   int ddays=0; // d prefix is just to say that this variable will be used for display
   int dhh=0;
   int dmm=0;
   int dss=0;

   int loopcount = 1000 ; // just for demo your loop will be different of course

   for(float count=1;count<loopcount;count++)
   {

     t2=clock(); // we get the time now

     float difference= (((float)t2)-((float)t1)); // gives the time elapsed since t1 in milliseconds

    // now get the time elapsed in seconds

    float seconds = difference/1000; // float value of seconds
    if (seconds<(60*60*24)) // a day is not over
    {
        dss = fmod(seconds,60); // the remainder is seconds to be displayed
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the remainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= hours;  // the hours to be displayed
        ddays=0;
    }
    else // we have reached the counting of days
    {
        float days = seconds/(24*60*60);
        ddays = (int)(days);
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the rmainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= fmod (hours,24);  // the hours to be displayed

    }

    cout<<"Count Is : "<<count<<"Time Elapsed : "<<ddays<<" Days "<<dhh<<" hrs "<<dmm<<" mins "<<dss<<" secs";


    // the actual working code here,I have just put a delay function
    delay(1000);
    system("cls");

 } // end for loop

}// end of main 

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

Floating point exception

It's caused by n % x, when x is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

General notes:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.

How to remove special characters from a string?

Try replaceAll() method of the String class.

BTW here is the method, return type and parameters.

public String replaceAll(String regex,
                         String replacement)

Example:

String str = "Hello +-^ my + - friends ^ ^^-- ^^^ +!";
str = str.replaceAll("[-+^]*", "");

It should remove all the {'^', '+', '-'} chars that you wanted to remove!

What function is to replace a substring from a string in C?

The repl_str() function on creativeandcritical.net is fast and reliable. Also included on that page is a wide string variant, repl_wcs(), which can be used with Unicode strings including those encoded in UTF-8, through helper functions - demo code is linked from the page. Belated full disclosure: I am the author of that page and the functions on it.

Trying to add adb to PATH variable OSX

I use zsh and Android Studio. I use a variable for my Android SDK path and configure in the file ~/.zshrc:

export ANDROID_HOME=/Applications/Android\ Studio.app/sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"

Note: Make sure not to include single or double quotes around the specified path. If you do, it won't work.

How to read GET data from a URL using JavaScript?

It’s 2019 and there is no need for any hand-written solution or third-party library. If you want to parse the URL of current page in browser:

# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

If you want to parse a random URL, either in browser or in Node.js:

let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

It’s making use of the URLSearchParams interface that comes with modern browsers.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

CSS3 selector to find the 2nd div of the same class

.parent_class div:first-child + div

I just used the above to find the second div by chaining first-child with the + selector.

how to open a page in new tab on button click in asp.net?

add target='_blank' after check validation :

_x000D_
_x000D_
    <asp:button id="_ButPrint"  ValidationGroup="print" OnClientClick="if (Page_ClientValidate()){$('form').attr('target','_blank');}"  runat="server" onclick="ButPrint_Click" Text="print" />
                                                                 
_x000D_
_x000D_
_x000D_

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

Function in JavaScript that can be called only once

Talking about static variables, this is a little bit like closure variant:

var once = function() {
    if(once.done) return;
    console.log('Doing this once!');
    once.done = true;
};

once(); once(); 

You could then reset a function if you wish:

once.done = false;

Best way to define error codes/strings in Java?

At my last job I went a little deeper in the enum version:

public enum Messages {
    @Error
    @Text("You can''t put a {0} in a {1}")
    XYZ00001_CONTAINMENT_NOT_ALLOWED,
    ...
}

@Error, @Info, @Warning are retained in the class file and are available at runtime. (We had a couple of other annotations to help describe message delivery as well)

@Text is a compile-time annotation.

I wrote an annotation processor for this that did the following:

  • Verify that there are no duplicate message numbers (the part before the first underscore)
  • Syntax-check the message text
  • Generate a messages.properties file that contains the text, keyed by the enum value.

I wrote a few utility routines that helped log errors, wrap them as exceptions (if desired) and so forth.

I'm trying to get them to let me open-source it... -- Scott

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

Django 1.7 - makemigrations not detecting changes

Maybe this will help someone.

I've deleted my models.py and expected makemigrations to create DeleteModel statements.

Remember to delete *.pyc files!

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

Convert java.util.Date to java.time.LocalDate

LocalDate ld = new java.sql.Date( new java.util.Date().getTime() ).toLocalDate();

How to sort by two fields in Java?

I would be careful when using Guava's ComparisonChain because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N comparison chains just to compare if you are sorting, or N instances if you are iterating and checking for equality.

I would instead create a static Comparator using the newest Java 8 API if possible or Guava's Ordering API which allows you to do that, here is an example with Java 8:

import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;

private static final Comparator<Person> COMPARATOR = Comparator
  .comparing(Person::getName, nullsLast(naturalOrder()))
  .thenComparingInt(Person::getAge);

@Override
public int compareTo(@NotNull Person other) {
  return COMPARATOR.compare(this, other);
}

Here is how to use the Guava's Ordering API: https://github.com/google/guava/wiki/OrderingExplained

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

C# Error "The type initializer for ... threw an exception

I got this error when I modified an Nlog configuration file and didn't format the XML correctly.

Set a variable if undefined in JavaScript

Works even if the default value is a boolean value:

var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );

Apache won't start in wamp

Sometimes it is Skype or another application "Holding" on to port 80. Jusct close Skype

How can I create download link in HTML?

A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:

<a href="path to resource.name of file">Link</a>

<a href="files/installer.exe">Link to installer</a>

Use custom build output folder when using create-react-app

Based on the answers by Ben Carp and Wallace Sidhrée:

This is what I use to copy my entire build folder to my wamp public folder.

package.json

{
  "name": "[your project name]",
  "homepage": "http://localhost/[your project name]/",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
    [...]
  },
}

post_build.ps1

Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force

The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).

Conditional replacement of values in a data.frame

Since you are conditionally indexing df$est, you also need to conditionally index the replacement vector df$a:

index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533 

Of course, the variable index is just temporary, and I use it to make the code a bit more readible. You can write it in one step:

df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533 

For even better readibility, you can use within:

df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)

The results, regardless of which method you choose:

df
          a b      est
1  11.77000 2 0.000000
2  10.90000 3 0.000000
3  10.32000 2 0.000000
4  10.96000 0 2.352941
5   9.90600 0 1.936834
6  10.70000 0 2.250296
7  11.43000 1 0.000000
8  11.41000 2 0.000000
9  10.48512 4 0.000000
10 11.19000 0 2.443743

As others have pointed out, an alternative solution in your example is to use ifelse.

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

How do I wait until Task is finished in C#?

It waits for client.GetAsync("aaaaa");, but doesn't wait for result = Print(x)

Try responseTask.ContinueWith(x => result = Print(x)).Wait()

--EDIT--

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
responseTask.Wait();
Console.WriteLine("End");

Above code doesn't guarantee the output:

In task
In ContinueWith
End

But this does (see the newTask)

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
newTask.Wait();
Console.WriteLine("End");

Refreshing page on click of a button

This question actually is not JSP related, it is HTTP related. you can just do:

window.location = window.location;

Android Studio - local path doesn't exist

For those who still can't solve this issue after following all the answers on here. Look in the Gradle console. I had build errors that for some reason were only showing on the Gradle console. Once I fixed them, I could run the app.

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

Disable / Check for Mock Location (prevent gps spoofing)

This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }

How to download a file via FTP with Python ftplib

Please note if you are downloading from the FTP to your local, you will need to use the following:

with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

Otherwise, the script will at your local file storage rather than the FTP.

I spent a few hours making the mistake myself.

Script below:

import ftplib

# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')


filenames = ftp.nlst()

for filename in filenames:

    with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

        file.close()

ftp.quit()

Eclipse HotKey: how to switch between tabs?

  • Right side move : Ctrl + page Down
  • Left side move : CTRL + page Up

Additional

  • get list of open tabs : Ctrl + F6

Eclipse others Short Cuts

How to add buttons dynamically to my form?

First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:

  for (int i = 0; i < 10; ++i)
  {
      var button = new Button();
      button.Location = new Point(button.Width * i + 4, 0);
      Controls.Add(button);
  }

jquery AJAX and json format

I never had any luck with that approach. I always do this (hope this helps):

var obj = {};

obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();

Then in your ajax:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How to pass extra variables in URL with WordPress

To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:

  • add_query_arg() - to create the URL with your new query variable ('c' in your example)
  • the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
  • get_query_var() - to retrieve the value of your custom query variable passed in your URL.

Note: there's no need to even touch the superglobals ($_GET) if you do it this way.

Example

On the page where you need to create the link / set the query variable:

if it's a link back to this page, just adding the query variable

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">

if it's a link to some other page

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">

In your functions.php, or some plugin file or custom class (front-end only):

function add_custom_query_var( $vars ){
  $vars[] = "c";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

On the page / function where you wish to retrieve and work with the query var set in your URL:

$my_c = get_query_var( 'c' );

On the Back End (wp-admin)

On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.

In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:

$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );

though in a pinch you could do the tried and true

$my_c = isset( $_GET['c'] ? $_GET['c'] : "";

or some variant thereof.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Differences:

1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load. Now, you wouldn't want to write the same code again and again. Hence, implicit wait. However, if you want to wait for only one element, use explicit.

2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

In my case a has to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());

PostgreSQL delete with inner join

If you have more than one join you could use comma separated USING statements:

DELETE 
FROM 
      AAA AS a 
USING 
      BBB AS b,
      CCC AS c
WHERE 
      a.id = b.id 
  AND a.id = c.id
  AND a.uid = 12345 
  AND c.gid = 's434sd4'

Reference

Turning multiple lines into one comma separated line

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

Rails create or update magic?

The magic you have been looking for has been added in Rails 6 Now you can upsert (update or insert). For single record use:

Model.upsert(column_name: value)

For multiple records use upsert_all :

Model.upsert_all(column_name: value, unique_by: :column_name)

Note:

  • Both methods do not trigger Active Record callbacks or validations
  • unique_by => PostgreSQL and SQLite only

Changing the color of a clicked table row using jQuery

I'm not an expert in JQuery but I have the same scenario and I able to accomplis like this:

$("#data tr").click(function(){
   $(this).addClass("selected").siblings().removeClass("selected"); 
});

Style:

<style type="text/css">

.selected {
    background: red;
}

</style> 

Android check internet connection

Use this method:

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

This is the permission needed:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

Remove "Using default security password" on Spring Boot

To remove default user you need to configure authentication menager with no users for example:

@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps

How to succinctly write a formula with many variables from a data frame?

There is a special identifier that one can use in a formula to mean all the variables, it is the . identifier.

y <- c(1,4,6)
d <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
mod <- lm(y ~ ., data = d)

You can also do things like this, to use all variables but one (in this case x3 is excluded):

mod <- lm(y ~ . - x3, data = d)

Technically, . means all variables not already mentioned in the formula. For example

lm(y ~ x1 * x2 + ., data = d)

where . would only reference x3 as x1 and x2 are already in the formula.

How to search and replace text in a file?

My variant, one word at a time on the entire file.

I read it into memory.

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)

Is it possible to style a select box?

You should try using some jQuery plugin like ikSelect.

I tried to make it very customizable but easy to use.

http://github.com/Igor10k/ikSelect

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

Changing all files' extensions in a folder with one command on Windows

Rename multiple file extensions:

You want to change ringtone1.mp3, ringtone2.mp3 to ringtone1.wav, ringtone2.wav

Here is how to do that: I am in d drive on command prompt (CMD) so I use:

d:\>ren *.* *.wav 

This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

How to get the full url in Express?

I use the node package 'url' (npm install url)

What it does is when you call

url.parse(req.url, true, true)

it will give you the possibility to retrieve all or parts of the url. More info here: https://github.com/defunctzombie/node-url

I used it in the following way to get whatever comes after the / in http://www.example.com/ to use as a variable and pull up a particular profile (kind of like facebook: http://www.facebook.com/username)

    var url = require('url');
    var urlParts = url.parse(req.url, true, true);
    var pathname = urlParts.pathname;
    var username = pathname.slice(1);

Though for this to work, you have to create your route this way in your server.js file:

self.routes['/:username'] = require('./routes/users');

And set your route file this way:

router.get('/:username', function(req, res) {
 //here comes the url parsing code
}

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

Split string into array

Do you care for non-English names? If so, all of the presented solutions (.split(''), [...str], Array.from(str), etc.) may give bad results, depending on language:

"????? ???????".split("") // the current president of India, Pranab Mukherjee
// returns ["?", "?", "?", "?", "?", " ", "?", "?", "?", "?", "?", "?", "?"]
// but should return ["??", "?", "?", "?", " ", "??", "?", "??", "??"]

Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

How to check if a word is an English word with Python?

For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.

As another idea, you could query Wiktionary's API.

How to print the current time in a Batch-File?

we can easily print the current time and date using echo and system variables as below.

echo %DATE% %TIME%

output example: 13-Sep-19 15:53:05.62

How to Add Stacktrace or debug Option when Building Android Studio Project

For Android Studio 3.1.3 it was under

File -> Settings -> Build, Execution, Deployment -> Compiler

"UnboundLocalError: local variable referenced before assignment" after an if statement

To Solve this Error just initialize that variable above that loop or statement. For Example var a =""

How to declare a variable in SQL Server and use it in the same Stored Procedure

In sql 2012 (and maybe as far back as 2005), you should do this:

EXEC AddBrand @BrandName = 'Gucci', @CategoryId = 23

What is javax.inject.Named annotation supposed to be used for?

The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.

How to dynamically add a class to manual class names?

className={css(styles.mainDiv, 'subContainer')}

This solution is tried and tested in React SPFx.

Also add import statement :

import { css } from 'office-ui-fabric-react/lib/Utilities';

Inline SVG in CSS

A little late, but if any of you have been going crazy trying to use inline SVG as a background, the escaping suggestions above do not quite work. For one, it does not work in IE, and depending on the content of your SVG the technique will cause trouble in other browsers, like FF.

If you base64 encode the svg (not the entire url, just the svg tag and its contents! ) it works in all browsers. Here is the same jsfiddle example in base64: http://jsfiddle.net/vPA9z/3/

The CSS now looks like this:

body { background-image: 
    url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPScxMCcgaGVpZ2h0PScxMCc+PGxpbmVhckdyYWRpZW50IGlkPSdncmFkaWVudCc+PHN0b3Agb2Zmc2V0PScxMCUnIHN0b3AtY29sb3I9JyNGMDAnLz48c3RvcCBvZmZzZXQ9JzkwJScgc3RvcC1jb2xvcj0nI2ZjYycvPiA8L2xpbmVhckdyYWRpZW50PjxyZWN0IGZpbGw9J3VybCgjZ3JhZGllbnQpJyB4PScwJyB5PScwJyB3aWR0aD0nMTAwJScgaGVpZ2h0PScxMDAlJy8+PC9zdmc+");

Remember to remove any URL escaping before converting to base64. In other words, the above example showed color='#fcc' converted to color='%23fcc', you should go back to #.

The reason why base64 works better is that it eliminates all the issues with single and double quotes and url escaping

If you are using JS, you can use window.btoa() to produce your base64 svg; and if it doesn't work (it might complain about invalid characters in the string), you can simply use https://www.base64encode.org/.

Example to set a div background:

_x000D_
_x000D_
var mySVG = "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='#F00'/><stop offset='90%' stop-color='#fcc'/> </linearGradient><rect fill='url(#gradient)' x='0' y='0' width='100%' height='100%'/></svg>";_x000D_
var mySVG64 = window.btoa(mySVG);_x000D_
document.getElementById('myDiv').style.backgroundImage = "url('data:image/svg+xml;base64," + mySVG64 + "')";
_x000D_
html, body, #myDiv {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}
_x000D_
<div id="myDiv"></div>
_x000D_
_x000D_
_x000D_

With JS you can generate SVGs on the fly, even changing its parameters.

One of the better articles on using SVG is here : http://dbushell.com/2013/02/04/a-primer-to-front-end-svg-hacking/

Hope this helps

Mike

How can I change default dialog button text color in android 5

There are two ways to change the dialog button color.

Basic Way

If you just want to change in an activity, write the below two lines after alertDialog.show();

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

Recommended

I'll recommend adding a theme for AlertDialog in styles.xml so you don't have to write the same code again and again in each activity/dialog call. You can just create a style and apply that theme on the dialog box. So whenever you want to change the color of AlertDialog box, just change color in styles.xml and all the dialog boxes will be updated in the whole application.

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorPrimary</item>
</style>

And apply the theme in AlertDialog.Builder

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);

Best programming based games

Omega is one of them, I played it on C64 :)

C# "must declare a body because it is not marked abstract, extern, or partial"

You can just use the keywork value to accomplish this.

public int Hour {
    get{
        // Do some logic if you want
        //return some custom stuff based on logic

        // or just return the value
        return value;
    }; set { 
        // Do some logic stuff 
        if(value < MINVALUE){
            this.Hour = 0;
        } else {
            // Or just set the value
            this.Hour = value;
        }
    }
}

How do I make a relative reference to another workbook in Excel?

easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")

however indirect() has performance drawbacks if lot of links in workbook

I miss construct like: ['../Data.ods']#Sheet1.A1 in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.

Select rows where column is null

I'm not sure if this answers your question, but using the IS NULL construct, you can test whether any given scalar expression is NULL:

SELECT * FROM customers WHERE first_name IS NULL

On MS SQL Server, the ISNULL() function returns the first argument if it's not NULL, otherwise it returns the second. You can effectively use this to make sure a query always yields a value instead of NULL, e.g.:

SELECT ISNULL(column1, 'No value found') FROM mytable WHERE column2 = 23

Other DBMSes have similar functionality available.

If you want to know whether a column can be null (i.e., is defined to be nullable), without querying for actual data, you should look into information_schema.

In MVC, how do I return a string result?

You can just use the ContentResult to return a plain string:

public ActionResult Temp() {
    return Content("Hi there!");
}

ContentResult by default returns a text/plain as its contentType. This is overloadable so you can also do:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

How can I convert NSDictionary to NSData and vice versa?

In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

How to check heap usage of a running JVM from the command line?

If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.

Please note that jmap should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.

Stuck at ".android/repositories.cfg could not be loaded."

I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

Django MEDIA_URL and MEDIA_ROOT

Please read the official Django DOC carefully and you will find the most fit answer.

The best and easist way to solve this is like below.

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Error in spring application context schema

I also faced this problem and fixed it by removing version part from the XSD name.

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd to http://www.springframework.org/schema/beans/spring-beans.xsd

Versions less XSD's are mapped to the current version of the framework used in the application.

How to remove single character from a String

For example if you want to calculate how many a's are there in the String, you can do it like this:

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

How can I get (query string) parameters from the URL in Next.js?

If you need to retrieve a URL query from outside a component:

import router from 'next/router'

console.log(router.query)

Strip / trim all strings of a dataframe

You can use the apply function of the Series object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df[0][0]
'  a  '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'

Note the usage of strip and not the regex which is much faster

Another option - use the apply function of the DataFrame object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)

   0   1
0  a  10
1  c   5

Cutting the videos based on start and end time using ffmpeg

Try using this. It is the fastest and best ffmpeg-way I have figure it out:

 ffmpeg -ss 00:01:00 -i input.mp4 -to 00:02:00 -c copy output.mp4

This command trims your video in seconds!

Explanation of the command:

-i: This specifies the input file. In that case, it is (input.mp4).
-ss: Used with -i, this seeks in the input file (input.mp4) to position.
00:01:00: This is the time your trimmed video will start with.
-to: This specifies duration from start (00:01:40) to end (00:02:12).
00:02:00: This is the time your trimmed video will end with.
-c copy: This is an option to trim via stream copy. (NB: Very fast)

The timing format is: hh:mm:ss

Please note that the current highly upvoted answer is outdated and the trim would be extremely slow. For more information, look at this official ffmpeg article.

What is 'Currying'?

Here is the example of generic and the shortest version for function currying with n no. of params.

const add = a => b => b ? add(a + b) : a; 

_x000D_
_x000D_
const add = a => b => b ? add(a + b) : a; _x000D_
console.log(add(1)(2)(3)(4)());
_x000D_
_x000D_
_x000D_

SQL time difference between two dates result in hh:mm:ss

declare @StartDate datetime, @EndDate datetime

select @StartDate = '10/01/2012 08:40:18.000',@EndDate='10/04/2012 09:52:48.000'

select convert(varchar(5),DateDiff(s, @startDate, @EndDate)/3600)+':'+convert(varchar(5),DateDiff(s, @startDate, @EndDate)%3600/60)+':'+convert(varchar(5),(DateDiff(s, @startDate, @EndDate)%60)) as [hh:mm:ss]

This query will helpful to you.

How can I check file size in Python?

The other answers work for real files, but if you need something that works for "file-like objects", try this:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().

Edit

Another difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.

Edit 2

At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

phpMyAdmin allow remote users

The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.

To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #ADD following line:
       Require all granted
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     #CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

What static analysis tools are available for C#?

  • Gendarme is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
  • Clone Detective is a nice plug-in for Visual Studio that finds duplicate code.
  • Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).

Multiple variables in a 'with' statement?

I think you want to do this instead:

from __future__ import with_statement

with open("out.txt","wt") as file_out:
    with open("in.txt") as file_in:
        for line in file_in:
            file_out.write(line)

How can I do an UPDATE statement with JOIN in SQL Server?

Simplified update query using JOIN-ing multiple tables.

   UPDATE
        first_table ft
        JOIN second_table st ON st.some_id = ft.some_id
        JOIN third_table tt  ON tt.some_id = st.some_id
        .....
    SET
        ft.some_column = some_value
    WHERE ft.some_column = 123456 AND st.some_column = 123456

Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.

how to stop Javascript forEach?

Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)

Instead you should use a normal for loop:

function recurs(comment) {
    for (var i = 0; i < comment.comments.length; ++i) {
        var subComment = comment.comments[i];
        recurs(subComment);
        if (...) {
            break;
        }
    }
}

(or, if you want to be a little more clever about it and comment.comments[i] is always an object:)

function recurs(comment) {
    for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
        recurs(subComment);
        if (...) {
            break;
        }
    }
}

jQuery: Wait/Delay 1 second without executing code

delay() doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout which others have mentioned.

The purpose of jQuery's delay() is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250); will make the element fade in after 3 seconds.

Rounding up to next power of 2

unsigned long upper_power_of_two(unsigned long v)
{
    v--;
    v |= v >> 1;
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;
    v++;
    return v;

}

End of File (EOF) in C

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

The value of EOF is -1 because it has to be different from any return value from getchar that is an actual character. So getchar returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar() will return EOF, and hence getchar() != EOF will be false, and the loop will terminate.

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

CSS change button style after click

What is the code of your button? If it's an a tag, then you could do this:

_x000D_
_x000D_
a {_x000D_
  padding: 5px;_x000D_
  background: green;_x000D_
}_x000D_
a:visited {_x000D_
  background: red;_x000D_
}
_x000D_
<a href="#">A button</a>
_x000D_
_x000D_
_x000D_

Or you could use jQuery to add a class on click, as below:

_x000D_
_x000D_
$("#button").click(function() {_x000D_
  $("#button").addClass('button-clicked');_x000D_
});
_x000D_
.button-clicked {_x000D_
  background: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="button">Button</button>
_x000D_
_x000D_
_x000D_

phantomjs not waiting for "full" page load

I found this approach useful in some cases:

page.onConsoleMessage(function(msg) {
  // do something e.g. page.render
});

Than if you own the page put some script inside:

<script>
  window.onload = function(){
    console.log('page loaded');
  }
</script>

How to create/read/write JSON files in Qt5

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

Convert audio files to mp3 using ffmpeg

As described here input and output extension will detected by ffmpeg so there is no need to worry about the formats, simply run this command:

ffmpeg -i inputFile.ogg outputFile.mp3

Storing integer values as constants in Enum manner in java

You could store that const value in the enum like so. But why even use the const? Are you persisting the enum's?

public class SO3990319 {
   public static enum PAGE {
      SIGN_CREATE(1);
      private final int constValue;

      private PAGE(int constValue) {
         this.constValue = constValue;
      }

      public int constValue() {
         return constValue;
      }
   }

   public static void main(String[] args) {
      System.out.println("Name:    " + PAGE.SIGN_CREATE.name());
      System.out.println("Ordinal: " + PAGE.SIGN_CREATE.ordinal());
      System.out.println("Const:   " + PAGE.SIGN_CREATE.constValue());

      System.out.println("Enum: " + PAGE.valueOf("SIGN_CREATE"));
   }
}

Edit:

It depends on what you're using the int's for whether to use EnumMap or instance field.

Line Break in XML formatting?

If you are refering to res strings, use CDATA with \n.

<string name="about">
    <![CDATA[
 Author: Sergio Abreu\n
 http://sites.sitesbr.net
  ]]>        
</string>

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Can Mysql Split a column?

Usually substring_index does what you want:

mysql> select substring_index("[email protected]","@",-1);
+-----------------------------------------+
| substring_index("[email protected]","@",-1) |
+-----------------------------------------+
| gmail.com                               |
+-----------------------------------------+
1 row in set (0.00 sec)

How do I clone a subdirectory only of a Git repository?

Just to clarify some of the great answers here, the steps outlined in many of the answers assume that you already have a remote repository somewhere.

Given: an existing git repository, e.g. [email protected]:some-user/full-repo.git, with one or more directories that you wish to pull independently of the rest of the repo, e.g. directories named app1 and app2

Assuming you have a git repository as the above...

Then: you can run steps like the following to pull only specific directories from that larger repo:

mkdir app1
cd app1
git init
git remote add origin [email protected]:some-user/full-repo.git
git config core.sparsecheckout true
echo "app1/" >> .git/info/sparse-checkout
git pull origin master

I had mistakenly thought that the sparse-checkout options had to be set on the original repository, but this is not the case: you define which directories you want locally, prior to pulling from the remote. The remote repo doesn't know or care about your only wanting to track a part of the repo.

Hope this clarification helps someone else.

Get a random boolean in python?

I like

 np.random.rand() > .5

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

Setting Java heap space under Maven 2 on Windows

The environment variable to set is MAVEN_OPTS, for example MAVEN_OPTS=-Xmx1024m. The maxmem configuration in the pom only applies when you set the compiler plugin to fork javac into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS.

To set MAVEN_OPTS under Windows 7:

  1. Right click on My Computer and select Properties (keyboard shortcut press Windows + Pause/Break)
  2. Click the Advanced System Settings link located in the left navigation of System Properties to display the Advanced System Properties
  3. Go to the Advanced tab and click the Environment Variables button located at the bottom of the Advanced System Properties configuration window
  4. Create a New user variable, set the Variable name to MAVEN_OPTS and set the Variable value to -Xmx1024m (or more)

Open a new command window and run mvn.

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

You only need to type the message with "http://" at the start. For example: http://www.google.com shows the thumbnail image, but www.google.com no.

Why should hash functions use a prime number modulus?

It depends on the choice of hash function.

Many hash functions combine the various elements in the data by multiplying them with some factors modulo the power of two corresponding to the word size of the machine (that modulus is free by just letting the calculation overflow).

You don't want any common factor between a multiplier for a data element and the size of the hash table, because then it could happen that varying the data element doesn't spread the data over the whole table. If you choose a prime for the size of the table such a common factor is highly unlikely.

On the other hand, those factors are usually made up from odd primes, so you should also be safe using powers of two for your hash table (e.g. Eclipse uses 31 when it generates the Java hashCode() method).

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

HTTP status code for update and delete?

Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).

Long answer: here's a complete decision diagram (click to magnify).

HTTP 1.1 decision diagram

Source: https://github.com/for-GET/http-decision-diagram

Laravel check if collection is empty

You can always count the collection. For example $mentor->intern->count() will return how many intern does a mentor have.

https://laravel.com/docs/5.2/collections#method-count

In your code you can do something like this

foreach($mentors as $mentor)
    @if($mentor->intern->count() > 0)
    @foreach($mentor->intern as $intern)
        <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}">
            <td>{{ $intern->employee->FirstName }}</td>
            <td>{{  $intern->employee->LastName }}</td>
        </tr>
    @endforeach
    @else
        Mentor don't have any intern
    @endif
@endforeach

Cell Style Alignment on a range

Don't use "Style:

worksheet.Cells[y,x].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

Is it possible to import modules from all files in a directory, using a wildcard?

I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).

Usage (currently you'll need to use babel to use the export file):

$ npm install -g folder-module
$ folder-module my-cool-module/

Generates a file containing:

export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc

Then you can just consume the file:

import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Removing double quotes from variables in batch file creates problems with CMD environment

Spent a lot of time trying to do this in a simple way. After looking at FOR loop carefully, I realized I can do this with just one line of code:

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

Example:

@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

Output:

"Test string"
Test string