Programs & Examples On #Mount

mount is a command used to attach the file data structure of a device as a branch of the root tree.

Linux: Which process is causing "device busy" when doing umount?

Look at the lsof command (list open files) -- it can tell you which processes are holding what open. Sometimes it's tricky but often something as simple as sudo lsof | grep (your device name here) could do it for you.

How to mount a host directory in a Docker container

Had the same problem. Found this in the docker documentation:

Note: The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.

So, mounting a read/write host directory is only possible with the -v parameter in the docker run command, as the other answers point out correctly.

A terminal command for a rooted Android to remount /System as read/write

This is what works on my first generation Droid X with Android version 2.3.4. I suspect that this will be universal. Steps:

  1. root system and install su.

  2. Install busybox

  3. Install a terminal program.

  4. to mount system rw first su then

    busybox mount -o rw,remount system
    
  5. To remount ro

    busybox mount -o ro,remount system
    

Note that there are no slashes on "system".

Force unmount of NFS-mounted directory

If the NFS server disappeared and you can't get it back online, one trick that I use is to add an alias to the interface with the IP of the NFS server (in this example, 192.0.2.55).

Linux

The command for that is something roughly like:

ifconfig eth0:fakenfs 192.0.2.55 netmask 255.255.255.255

Where 192.0.2.55 is the IP of the NFS server that went away. You should then be able to ping the address, and you should also be able to unmount the filesystem (use unmount -f). You should then destroy the aliased interface so you no longer route traffic to the old NFS server to yourself with:

ifconfig eth0:fakenfs down

FreeBSD and similar operating systems

The command would be something like:

ifconfig em0 alias 192.0.2.55 netmask 255.255.255.255

And then to remove it:

ifconfig em0 delete 192.0.2.55

man ifconfig(8) for more!

Transport endpoint is not connected

Now this answer is for those lost souls that got here with this problem because they force-unmounted the drive but their hard drive is NTFS Formatted. Assuming you have ntfs-3g installed (sudo apt-get install ntfs-3g).

sudo ntfs-3g /dev/hdd /mnt/mount_point -o force

Where hdd is the hard drive in question and the "/mnt/mount_point" directory exists.

NOTES: This fixed the issue on an Ubuntu 18.04 machine using NTFS drives that had their journal files reset through sudo ntfsfix /dev/hdd and unmounted by force using sudo umount -l /mnt/mount_point

Leaving my answer here in case this fix can aid anyone!

How to mount host volumes into docker containers in Dockerfile during build

As many have already answered, mounting host volumes during the build is not possible. I just would like to add docker-compose way, I think it'll be nice to have, mostly for development/testing usage

Dockerfile

FROM node:10
WORKDIR /app
COPY . .
RUN npm ci
CMD sleep 999999999

docker-compose.yml

version: '3'
services:
  test-service:
    image: test/image
    build:
      context: .
      dockerfile: Dockerfile
    container_name: test
    volumes:
      - ./export:/app/export
      - ./build:/app/build

And run your container by docker-compose up -d --build

VMware Workstation and Device/Credential Guard are not compatible

I also struggled a lot with this issue. The answers in this thread were helpful but were not enough to resolve my error. You will need to disable Hyper-V and Device guard like the other answers have suggested. More info on that can be found in here.

I am including the changes needed to be done in addition to the answers provided above. The link that finally helped me was this.

My answer is going to summarize only the difference between the rest of the answers (i.e. Disabling Hyper-V and Device guard) and the following steps :

  1. If you used Group Policy, disable the Group Policy setting that you used to enable Windows Defender Credential Guard (Computer Configuration -> Administrative Templates -> System -> Device Guard -> Turn on Virtualization Based Security).
  2. Delete the following registry settings:

    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LsaCfgFlags HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\EnableVirtualizationBasedSecurity HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\RequirePlatformSecurityFeatures

    Important : If you manually remove these registry settings, make sure to delete them all. If you don't remove them all, the device might go into BitLocker recovery.

  3. Delete the Windows Defender Credential Guard EFI variables by using bcdedit. From an elevated command prompt(start in admin mode), type the following commands:

     mountvol X: /s
    
     copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y
    
     bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"
    
     bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:
    
     mountvol X: /d
    
  4. Restart the PC.

  5. Accept the prompt to disable Windows Defender Credential Guard.

  6. Alternatively, you can disable the virtualization-based security features to turn off Windows Defender Credential Guard.

Permission denied on accessing host directory in Docker

Try docker volume create.

mkdir -p /data1/Downloads
docker volume create --driver local --name hello --opt type=none --opt device=/data1/Downloads --opt o=uid=root,gid=root --opt o=bind
docker run -i -v hello:/Downloads ubuntu bash

Take a look at the document https://docs.docker.com/engine/reference/commandline/volume_create/

How can I remount my Android/system as read-write in a bash script using adb?

Otherwise... if

getenforce

returns

Enforcing

Then maybe you should call

setenforce 0 
mount -o rw,remount /system 
setenforce 1

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

Optimal way to concatenate/aggregate strings

You can use += to concatenate strings, for example:

declare @test nvarchar(max)
set @test = ''
select @test += name from names

if you select @test, it will give you all names concatenated

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

Make the current Git branch a master branch

For me, i wanted my devl to be back to the master after it was ahead.

While on develop:

git checkout master
git pull

git checkout develop
git pull

git reset --hard origin/master
git push -f

Spring Boot Multiple Datasource

Using two datasources you need their own transaction managers.

@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction

@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

Print a file, skipping the first X lines, in Bash

Use the sed delete command with a range address. For example:

sed 1,100d file.txt # Print file.txt omitting lines 1-100.

Alternatively, if you want to only print a known range, use the print command with the -n flag:

sed -n 201,300p file.txt # Print lines 201-300 from file.txt

This solution should work reliably on all Unix systems, regardless of the presence of GNU utilities.

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Is there a function to split a string in PL/SQL?

I like the look of that apex utility. However its also good to know about the standard oracle functions you can use for this: subStr and inStr http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm

Best practice for instantiating a new Android Fragment

use this code 100% fix your problem

enter this code in firstFragment

public static yourNameParentFragment newInstance() {

    Bundle args = new Bundle();
    args.putBoolean("yourKey",yourValue);
    YourFragment fragment = new YourFragment();
    fragment.setArguments(args);
    return fragment;
}

this sample send boolean data

and in SecendFragment

yourNameParentFragment name =yourNameParentFragment.newInstance();
   Bundle bundle;
   bundle=sellDiamondFragments2.getArguments();
  boolean a= bundle.getBoolean("yourKey");

must value in first fragment is static

happy code

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

How do I 'foreach' through a two-dimensional array?

I'm not a big fan of this method because of the memory usage involved, but if you use the arrays it produces, it isn't such a waste.

public static void ForEachRow<T>(this T[,] list, Action<int, T[]> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    T[] e;
    int i, j;

    for (i = 0; i < len; i++)
    {
        e = new T[sub];

        for (j = 0; j < sub; j++)
        {
            e[j] = list[i, j];
        }

        action(i, e);
    }
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    for (var j = 0; j < row.Length; j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, row[j]);
    }
});

The other solution I found is less memory intensive, but will use more CPU, especially when the dimensions of the arrays' entries are larger.

public static void ForEachRow<T>(this T[,] list, Action<int, IEnumerable<T>> action)
{
    var len = list.GetLength(0);
    var sub = list.GetLength(1);

    int i, j;
    IEnumerable<T> e;

    for (i = 0; i < len; i++)
    {
        e = Enumerable.Empty<T>();

        for (j = 0; j < sub; j++)
        {
            e = e.Concat(AsEnumerable(list[i, j]));
        }

        action(i, e);
    }
}

private static IEnumerable<T> AsEnumerable<T>(T add)
{
    yield return add;
}

Implementation:

var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};

list.ForEachRow((i, row) =>
{
    var j = 0;

    forrach (var o in row)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, o);

        ++j;
    }
});

As a whole, I find the first option to be more intuitive, especially if you want to access the produced array by its indexer.

At the end of the day, this is all just eye candy, neither methods should really be used in favour of directly accessing the source array;

for (var i = 0; i < list.GetLength(0); i++)
{
    foreach (var j = 0; j < list.GetLength(1); j++)
    {
        Console.WriteLine("[{0},{1}]: {2}", i, j, list[i, j]);
    }
}

In C#, what's the difference between \n and \r\n?

\n = LF (Line Feed) // Used as a new line character on Unix

\r = CR (Carriage Return) // Used as a new line character on Mac

\r\n = CR + LF // Used as a new line character on Windows

(char)13 = \r = CR

Environment.NewLine = any of the above code based on the operating system

// .NET provides the Environment class which provides many data based on operating systems, so if the application is built on Windows, and you use CR + LF ("\n\r" instead of Environment.NewLine) as the new line character in your strings, and then Microsoft creates a VM for running .NET applications in Unix, then there will be problem. So, you should always use Environment.NewLine when you want a new line character. Now you need not to care about the operating system.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

What is DOM element?

Document Object Model (DOM), a programming interface specification being developed by the World Wide Web Consortium (W3C), lets a programmer create and modify HTML pages and XML documents as full-fledged program objects.

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

Convert a SQL query result table to an HTML table for email

Following piece of code, I have prepared for generating the HTML file for documentation which includes Table Name and Purpose in each table and Table Metadata information. It might be helpful!

use Your_Database_Name;
print '<!DOCTYPE html>'
PRINT '<html><body>'
SET NOCOUNT ON
DECLARE @tableName VARCHAR(30)
DECLARE tableCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT T.name AS TableName 
      FROM sys.objects AS T
     WHERE T.type_desc = 'USER_TABLE'
     ORDER BY T.name
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO @tableName
WHILE @@FETCH_STATUS = 0 BEGIN
    print '<table>'
    print '<tr><td><b>Table Name: <b></td><td>'+@tableName+'</td></tr>'
    print '<tr><td><b>Prupose: <b></td><td>????YOu can Fill later????</td></tr>'
    print '</table>'

    print '<table>'
    print '<tr><th>ColumnName</th><th>DataType</th><th>Size</th><th>PrecScale</th><th>Nullable</th><th>Default</th><th>Identity</th><th>Remarks</th></tr>'
    SELECT  concat('<tr><td>',
            LEFT(C.name, 30) /*AS ColumnName*/,'</td><td>',
           LEFT(ISC.DATA_TYPE, 10) /*AS DataType*/,'</td><td>',
           C.max_length /*AS Size*/,'</td><td>',
           CAST(P.precision AS VARCHAR(4)) + '/' + CAST(P.scale AS VARCHAR(4)) /*AS PrecScale*/,'</td><td>',
           CASE WHEN C.is_nullable = 1 THEN 'Null' ELSE 'No Null' END /*AS [Nullable]*/,'</td><td>',
           LEFT(ISNULL(ISC.COLUMN_DEFAULT, ' '), 5)  /*AS [Default]*/,'</td><td>',
           CASE WHEN C.is_identity = 1 THEN 'Identity' ELSE '' END /*AS [Identity]*/,'</td><td></td></tr>')
    FROM   sys.objects AS T
           JOIN sys.columns AS C ON T.object_id = C.object_id
           JOIN sys.types AS P ON C.system_type_id = P.system_type_id and c.user_type_id = p.user_type_id
           JOIN INFORMATION_SCHEMA.COLUMNS AS ISC ON T.name = ISC.TABLE_NAME AND C.name = ISC.COLUMN_NAME
    WHERE  T.type_desc = 'USER_TABLE'
      AND  T.name = @tableName
    ORDER BY T.name, ISC.ORDINAL_POSITION
    print '</table>'
    print '</br>'
    FETCH NEXT FROM tableCursor INTO @tableName

END

CLOSE tableCursor
DEALLOCATE tableCursor
SET NOCOUNT OFF
PRINT '</body></html>'

Oracle Differences between NVL and Coalesce

NVL and COALESCE are used to achieve the same functionality of providing a default value in case the column returns a NULL.

The differences are:

  1. NVL accepts only 2 arguments whereas COALESCE can take multiple arguments
  2. NVL evaluates both the arguments and COALESCE stops at first occurrence of a non-Null value.
  3. NVL does a implicit datatype conversion based on the first argument given to it. COALESCE expects all arguments to be of same datatype.
  4. COALESCE gives issues in queries which use UNION clauses. Example below
  5. COALESCE is ANSI standard where as NVL is Oracle specific.

Examples for the third case. Other cases are simple.

select nvl('abc',10) from dual; would work as NVL will do an implicit conversion of numeric 10 to string.

select coalesce('abc',10) from dual; will fail with Error - inconsistent datatypes: expected CHAR got NUMBER

Example for UNION use-case

SELECT COALESCE(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      );

fails with ORA-00932: inconsistent datatypes: expected CHAR got DATE

SELECT NVL(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      ) ;

succeeds.

More information : http://www.plsqlinformation.com/2016/04/difference-between-nvl-and-coalesce-in-oracle.html

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

How to validate an e-mail address in swift?

I would suggest using it as an extension of String:

extension String {    
    public var isEmail: Bool {
        let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)

        let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))

        return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
    }

    public var length: Int {
        return self.characters.count
    }
}

And to use it:

if "[email protected]".isEmail { // true
    print("Hold the Door")
}

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

For me, i forget to add AUTO_INCREMENT to my primary field and inserted data without id.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

make a phone call click on a button

None of the above worked so with a bit of tinkering here's code that did for me

        Intent i = new Intent(Intent.ACTION_DIAL);
        String p = "tel:" + getString(R.string.phone_number);
        i.setData(Uri.parse(p));
        startActivity(i);

php: how to get associative array key from numeric index?

If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:

echo array_keys($array)[$i];

Why aren't Xcode breakpoints functioning?

For Xcode 4.x: Goto Product>Debug Workflow and uncheck "Show Disassembly When Debugging".

For Xcode 5.x Goto Debug>Debug Workflow and uncheck "Show Disassembly When Debugging".

How to determine the current language of a wordpress page when using polylang?

This plugin is documented rather good in https://polylang.wordpress.com/documentation.

Switching post language

The developers documentation states the following logic as a means to generate URL's for different translations of the same post

<?php while ( have_posts() ) : the_post(); ?>
<ul class='translations'><?php pll_the_languages(array('post_id' =>; $post->ID)); ?></ul>
<?php the_content(); ?>
<?php endwhile; ?>

If you want more influence on what is rendered, inspet pll_the_languages function and copy it's behaviour to your own output implementation

Switching site language

As you want buttons to switch language, this page: https://polylang.wordpress.com/documentation/frequently-asked-questions/the-language-switcher/ will give you the required info.

An implementation example:

<ul><?php pll_the_languages();?></ul>

Then style with CSS to create buttons, flags or whatever you want. It is also possible to use a widget for this, provided by te plugin

Getting current language

All plugins functions are explained here: https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/

In this case use:

pll_current_language();

Passing a varchar full of comma delimited values to a SQL Server IN function

Of course if you're lazy like me, you could just do this:

Declare @Ids varchar(50) Set @Ids = ',1,2,3,5,4,6,7,98,234,'

Select * from sometable
 where Charindex(','+cast(tableid as varchar(8000))+',', @Ids) > 0

How to get size of mysql database?

Alternatively you can directly jump into data directory and check for combined size of v3.myd, v3. myi and v3. frm files (for myisam) or v3.idb & v3.frm (for innodb).

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Initially, check the type of compression with the below command: file <file_name> If the output is a Posix compressed file, use the below command to uncompress: tar xvf <file_name>

How can I submit a POST form using the <a href="..."> tag?

No JavaScript needed if you use a button instead:

<form action="your_url" method="post">
    <button type="submit" name="your_name" value="your_value" class="btn-link">Go</button>
</form>

You can style a button to look like a link, for example:

.btn-link {
    border: none;
    outline: none;
    background: none;
    cursor: pointer;
    color: #0000EE;
    padding: 0;
    text-decoration: underline;
    font-family: inherit;
    font-size: inherit;
}

How do I set up Vim autoindentation properly for editing Python files?

I use this on my macbook:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(edited to only show stuff related to indent / tabs)

Property getters and setters

Update for Swift 5.1

As of Swift 5.1 you can now get your variable without using get keyword. For example:

var helloWorld: String {
"Hello World"
}

What is the difference between encrypting and signing in asymmetric encryption?

Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.

Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.

How do I calculate power-of in C#?

Math.Pow() returns double so nice would be to write like this:

double d = Math.Pow(100.00, 3.00);

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual Studio.net)

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

How to send FormData objects with Ajax-requests in jQuery?

I believe you could do it like this :

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Notes:

  • Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

  • Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

Time complexity of accessing a Python dict

To answer your specific questions:

Q1:
"Am I correct that python dicts suffer from linear access times with such inputs?"

A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)

Q2:
"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"

A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key).

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

Can't build create-react-app project with custom PUBLIC_URL

People like me who are looking for something like this in in build:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

Then setting https://dsomething.cloudfront.net to homepage in package.json will not work.

1. Quick Solution

Build your project like this:
(windows)

set PUBLIC_URL=https://dsomething.cloudfront.net&&npm run build

(linux/mac)

PUBLIC_URL=https://dsomething.cloudfront.net npm run build

And you will get

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

in your built index.html

2. Permanent & Recommended Solution

Create a file called .env at your project root(same place where package.json is located).
In this file write this(no quotes around the url):

PUBLIC_URL=https://dsomething.cloudfront.net

Build your project as usual (npm run build)
This will also generate index.html with:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

3. Weird Solution (Will do not work in latest react-scripts version)

Add this in your package.json
"homepage": "http://://dsomething.cloudfront.net",

Then index.html will be generated with:

<script type="text/javascript" src="//dsomething.cloudfront.net/static/js/main.ec7f8972.js">

Which is basically the same as:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

in my understanding.

Github Issue Github Comment

Center an item with position: relative

Another option is to create an extra wrapper to center the element vertically.

_x000D_
_x000D_
#container{_x000D_
  border:solid 1px #33aaff;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
}_x000D_
_x000D_
#helper{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:50%;_x000D_
  border:dotted 1px #ff55aa;_x000D_
}_x000D_
_x000D_
#centered{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:-50%;_x000D_
  border:solid 1px #ff55aa;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="helper">_x000D_
    <div id="centered"></div>_x000D_
  </div>_x000D_
<div>
_x000D_
_x000D_
_x000D_

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

What are invalid characters in XML

For XSL (on really lazy days) I use:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

to translate all &-signs that aren't follwed på amp; to proper ones.

We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...

Is Safari on iOS 6 caching $.ajax results?

From my own blog post iOS 6.0 caching Ajax POST requests:

How to fix it: There are various methods to prevent caching of requests. The recommended method is adding a no-cache header. This is how it is done.

jQuery:

Check for iOS 6.0 and set Ajax header like this:

$.ajaxSetup({ cache: false });

ZeptoJS:

Check for iOS 6.0 and set the Ajax header like this:

$.ajax({
    type: 'POST',
    headers : { "cache-control": "no-cache" },
    url : ,
    data:,
    dataType : 'json',
    success : function(responseText) {…}

Server side

Java:

httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

Make sure to add this at the top the page before any data is sent to the client.

.NET

Response.Cache.SetNoStore();

Or

Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

PHP

header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

How to read a text file into a string variable and strip newlines?

To remove line breaks using Python you can use replace function of a string.

This example removes all 3 types of line breaks:

my_string = open('lala.json').read()
print(my_string)

my_string = my_string.replace("\r","").replace("\n","")
print(my_string)

Example file is:

{
  "lala": "lulu",
  "foo": "bar"
}

You can try it using this replay scenario:

https://repl.it/repls/AnnualJointHardware

enter image description here

Is there a way to represent a directory tree in a Github README.md?

Here is a useful git alias that works for me.

git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\//   |/g" -e "s/|\([^ ]\)/|-- \1/"'

Here is the output of git tree

jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
   |-- main
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- AbstractFile.java
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Main.java
   |   |   |   |   |   |   |-- Numeral.java
   |   |   |   |   |   |   |-- RomanNumberInputFile.java
   |   |   |   |   |   |   |-- RomanNumeralToDecimalEvaluator.java
   |-- test
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- InterpretSteps.java
   |   |   |   |   |   |   |-- RunCukesTest.java
   |   |-- resources
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Interpret.feature
   |   |   |-- sample-input.txt

The comparable tree command

jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
+-- pom.xml
+-- src
¦   +-- main
¦   ¦   +-- java
¦   ¦       +-- com
¦   ¦           +-- foxguardsolutions
¦   ¦               +-- jonavon
¦   ¦                   +-- AbstractFile.java
¦   ¦                   +-- roman
¦   ¦                       +-- Main.java
¦   ¦                       +-- Numeral.java
¦   ¦                       +-- RomanNumberInputFile.java
¦   ¦                       +-- RomanNumeralToDecimalEvaluator.java
¦   +-- test
¦       +-- java
¦       ¦   +-- com
¦       ¦       +-- foxguardsolutions
¦       ¦           +-- jonavon
¦       ¦               +-- roman
¦       ¦                   +-- InterpretSteps.java
¦       ¦                   +-- RunCukesTest.java
¦       +-- resources
¦           +-- com
¦           ¦   +-- foxguardsolutions
¦           ¦       +-- jonavon
¦           ¦           +-- roman
¦           ¦               +-- Interpret.feature
¦           +-- sample-input.txt
+-- target
    +-- classes
    ¦   +-- com
    ¦       +-- foxguardsolutions
    ¦           +-- jonavon
    ¦               +-- AbstractFile.class
    ¦               +-- roman
    ¦                   +-- Main.class
    ¦                   +-- Numeral.class
    ¦                   +-- RomanNumberInputFile.class
    ¦                   +-- RomanNumeralToDecimalEvaluator.class
    +-- generated-sources
    ¦   +-- annotations
    +-- maven-status
        +-- maven-compiler-plugin
            +-- compile
                +-- default-compile
                    +-- createdFiles.lst
                    +-- inputFiles.lst

30 directories, 17 files

Clearly tree has better output, but I would like it to use my .gitignore file. So that my compiled content doesn't show

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

Check if number is decimal

Maybe try looking into this as well

!is_int()

Shortcut for changing font size

This worked for me:

Ctrl + - to minimize

Ctrl + + to maximize

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I had the following property working for me in IntelliJ 2017

  <properties>
        <java.version>1.8</java.version>       
  </properties>

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

"Port 4200 is already in use" when running the ng serve command

I had big troubles with this, and I was even trying with many others ports and nothing.

I did npm install [email protected] and it solved the problem. For some reason the typescript version was causing a conflict and using yarn or ng serve were not working.

hope this works for anyone else with the same issue.

Calculating and printing the nth prime number

To calculate the n-th prime, I know two main variants.

The straightforward way

That is to count all the primes starting from 2 as you find them until you have reached the desired nth.

This can be done with different levels of sophistication and efficiency, and there are two conceptually different ways to do it. The first is

Testing the primality of all numbers in sequence

This would be accomplished by a driver function like

public static int nthPrime(int n) {
    int candidate, count;
    for(candidate = 2, count = 0; count < n; ++candidate) {
        if (isPrime(candidate)) {
            ++count;
        }
    }
    // The candidate has been incremented once after the count reached n
    return candidate-1;
}

and the interesting part that determines the efficiency is the isPrime function.

The obvious way for a primality check, given the definition of a prime as a number greater than 1 that is divisible only by 1 and by itself that we learned in school¹, is

Trial division

The direct translation of the definition into code is

private static boolean isPrime(int n) {
    for(int i = 2; i < n; ++i) {
        if (n % i == 0) {
            // We are naive, but not stupid, if
            // the number has a divisor other
            // than 1 or itself, we return immediately.
            return false;
        }
    }
    return true;
}

but, as you will soon discover if you try it, its simplicity is accompanied by slowness. With that primality test, you can find the 1000th prime, 7919, in a few milliseconds (about 20 on my computer), but finding the 10000th prime, 104729, takes seconds (~2.4s), the 100000th prime,1299709, several minutes (about 5), the millionth prime, 15485863, would take about eight and a half hours, the ten-millionth prime, 179424673, weeks, and so on. The runtime complexity is worse than quadratic - T(n² * log n).

So we'd like to speed the primality test up somewhat. A step that many people take is the realisation that a divisor of n (other than n itself) can be at most n/2. If we use that fact and let the trial division loop only run to n/2 instead of n-1, how does the running time of the algorithm change? For composite numbers, the lower loop limit doesn't change anything. For primes, the number of trial divisions is halved, so overall, the running time should be reduced by a factor somewhat smaller than 2. If you try it out, you will find that the running time is almost exactly halved, so almost all the time is spent verifying the primality of primes despite there being many more composites than primes.

Now, that didn't help much if we want to find the one-hundred-millionth prime, so we have to do better. Trying to reduce the loop limit further, let us see for what numbers the upper bound of n/2 is actually needed. If n/2 is a divisor of n, then n/2 is an integer, in other words, n is divisible by 2. But then the loop doesn't go past 2, so it never (except for n = 4) reaches n/2. Jolly good, so what's the next largest possible divisor of n? Why, n/3 of course. But n/3 can only be a divisor of n if it is an integer, in other words, if n is divisible by 3. Then the loop will exit at 3 (or before, at 2) and never reach n/3 (except for n = 9). The next largest possible divisor ...

Hang on a minute! We have 2 <-> n/2 and 3 <-> n/3. The divisors of n come in pairs.

If we consider the pair (d, n/d) of corresponding divisors of n, either d = n/d, i.e. d = vn, or one of them, say d, is smaller than the other. But then d*d < d*(n/d) = n and d < vn. Each pair of corresponding divisors of n contains (at least) one which does not exceed vn.

If n is composite, its smallest nontrivial divisor does not exceed vn.

So we can reduce the loop limit to vn, and that reduces the runtime complexity of the algorithm. It should now be T(n1.5 * v(log n)), but empirically it seems to scale a little bit better - however, there's not enough data to draw reliable conclusions from empirical results.

That finds the millionth prime in about 16 seconds, the ten-millionth in just under nine minutes, and it would find the one-hundred-millionth in about four and a half hours. That's still slow, but a far cry from the ten years or so it would take the naive trial division.

Since there are squares of primes and products of two close primes, like 323 = 17*19, we cannot reduce the limit for the trial division loop below vn. Therefore, while staying with trial division, we must look for other ways to improve the algorithm now.

One easily seen thing is that no prime other than 2 is even, so we need only check odd numbers after we have taken care of 2. That doesn't make much of a difference, though, since the even numbers are the cheapest to find composite - and the bulk of time is still spent verifying the primality of primes. However, if we look at the even numbers as candidate divisors, we see that if n is divisible by an even number, n itself must be even, so (excepting 2) it will have been recognised as composite before division by any even number greater than 2 is attempted. So all divisions by even numbers greater than 2 that occur in the algorithm must necessarily leave a nonzero remainder. We can thus omit these divisions and check for divisibility only by 2 and the odd numbers from 3 to vn. This halves (not quite exactly) the number of divisions required to determine a number as prime or composite and therefore the running time. That's a good start, but can we do better?

Another large family of numbers is the multiples of 3. Every third division we perform is by a multiple of 3, but if n is divisible by one of them, it is also divisible by 3, and hence no division by 9, 15, 21, ... that we perform in our algorithm will ever leave a remainder of 0. So, how can we skip these divisions? Well, the numbers divisible by neither 2 nor 3 are precisely the numbers of the form 6*k ± 1. Starting from 5 (since we're only interested in numbers greater than 1), they are 5, 7, 11, 13, 17, 19, ..., the step from one to the next alternates between 2 and 4, which is easy enough, so we can use

private static boolean isPrime(int n) {
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int step = 4, m = (int)Math.sqrt(n) + 1;
    for(int i = 5; i < m; step = 6-step, i += step) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

This gives us another speedup by a factor of (nearly) 1.5, so we'd need about one and a half hours to the hundred-millionth prime.

If we continue this route, the next step is the elimination of multiples of 5. The numbers coprime to 2, 3 and 5 are the numbers of the form

30*k + 1, 30*k + 7, 30*k + 11, 30*k + 13, 30*k + 17, 30*k + 19, 30*k + 23, 30*k + 29

so we'd need only divide by eight out of every thirty numbers (plus the three smallest primes). The steps from one to the next, starting from 7, cycle through 4, 2, 4, 2, 4, 6, 2, 6. That's still easy enough to implement and yields another speedup by a factor of 1.25 (minus a bit for more complicated code). Going further, the multiples of 7 would be eliminated, leaving 48 out of every 210 numbers to divide by, then 11 (480/2310), 13 (5760/30030) and so on. Each prime p whose multiples are eliminated yields a speedup of (almost) p/(p-1), so the return decreases while the cost (code complexity, space for the lookup table for the steps) increases with each prime.

In general, one would stop soonish, after eliminating the multiples of maybe six or seven primes (or even fewer). Here, however, we can follow through to the very end, when the multiples of all primes have been eliminated and only the primes are left as candidate divisors. Since we are finding all primes in order, each prime is found before it is needed as a candidate divisor and can then be stored for future use. This reduces the algorithmic complexity to - if I haven't miscalculated - O(n1.5 / v(log n)). At the cost of space usage for storing the primes.

With trial division, that is as good as it gets, you have to try and divide by all primes to vn or the first dividing n to determine the primality of n. That finds the hundred-millionth prime in about half an hour here.

So how about

Fast primality tests

Primes have other number-theoretic properties than the absence of nontrivial divisors which composite numbers usually don't have. Such properties, if they are fast to check, can form the basis of probabilistic or deterministic primality tests. The archetypical such property is associated with the name of Pierre de Fermat, who, in the early 17th century, found that

If p is a prime, then p is a divisor of (ap-a) for all a.

This - Fermat's so-called 'little theorem' - is, in the equivalent formulation

Let p be a prime and a not divisible by p. Then p divides ap-1 - 1.

the basis of most of the widespread fast primality tests (for example Miller-Rabin) and variants or analogues of that appear in even more (e.g. Lucas-Selfridge).

So if we want to know if a not too small odd number n is a prime (even and small numbers are efficiently treated by trial division), we can choose any number a (> 1) which is not a multiple of n, for example 2, and check whether n divides an-1 - 1. Since an-1 becomes huge, that is most efficiently done by checking whether a^(n-1) = 1 (mod n), i.e. by modular exponentiation. If that congruence doesn't hold, we know that n is composite. If it holds, however, we cannot conclude that n is prime, for example 2^340 = 1 (mod 341), but 341 = 11 * 31 is composite. Composite numbers n such that a^(n-1) = 1 (mod n) are called Fermat pseudoprimes for the base a.

But such occurrences are rare. Given any base a > 1, although there are an infinite number of Fermat pseudoprimes to base a, they are much rarer than actual primes. For example, there are only 78 base-2 Fermat pseudoprimes and 76 base-3 Fermat pseudoprimes below 100000, but 9592 primes. So if one chooses an arbitrary odd n > 1 and an arbitrary base a > 1 and finds a^(n-1) = 1 (mod n), there's a good chance that n is actually prime.

However, we are in a slightly different situation, we are given n and can only choose a. So, for an odd composite n, for how many a, 1 < a < n-1 can a^(n-1) = 1 (mod n) hold? Unfortunately, there are composite numbers - Carmichael numbers - such that the congruence holds for every a coprime to n. That means that to identify a Carmichael number as composite with the Fermat test, we have to pick a base that is a multiple of one of n's prime divisors - there may not be many such multiples.

But we can strengthen the Fermat test so that composites are more reliably detected. If p is an odd prime, write p-1 = 2*m. Then, if 0 < a < p,

a^(p-1) - 1 = (a^m + 1) * (a^m - 1)

and p divides exactly one of the two factors (the two factors differ by 2, so their greatest common divisor is either 1 or 2). If m is even, we can split a^m - 1 in the same way. Continuing, if p-1 = 2^s * k with k odd, write

a^(p-1) - 1 = (a^(2^(s-1)*k) + 1) * (a^(2^(s-2)*k) + 1) * ... * (a^k + 1) * (a^k - 1)

then p divides exactly one of the factors. This gives rise to the strong Fermat test,

Let n > 2 be an odd number. Write n-1 = 2^s * k with k odd. Given any a with 1 < a < n-1, if

  1. a^k = 1 (mod n) or
  2. a^((2^j)*k) = -1 (mod n) for any j with 0 <= j < s

then n is a strong (Fermat) probable prime for base a. A composite strong base a (Fermat) probable prime is called a strong (Fermat) pseudoprime for the base a. Strong Fermat pseudoprimes are even rarer than ordinary Fermat pseudoprimes, below 1000000, there are 78498 primes, 245 base-2 Fermat pseudoprimes and only 46 base-2 strong Fermat pseudoprimes. More importantly, for any odd composite n, there are at most (n-9)/4 bases 1 < a < n-1 for which n is a strong Fermat pseudoprime.

So if n is an odd composite, the probability that n passes k strong Fermat tests with randomly chosen bases between 1 and n-1 (exclusive bounds) is less than 1/4^k.

A strong Fermat test takes O(log n) steps, each step involves one or two multiplications of numbers with O(log n) bits, so the complexity is O((log n)^3) with naive multiplication [for huge n, more sophisticated multiplication algorithms can be worthwhile].

The Miller-Rabin test is the k-fold strong Fermat test with randomly chosen bases. It is a probabilistic test, but for small enough bounds, short combinations of bases are known which give a deterministic result.

Strong Fermat tests are part of the deterministic APRCL test.

It is advisable to precede such tests with trial division by the first few small primes, since divisions are comparatively cheap and that weeds out most composites.

For the problem of finding the nth prime, in the range where testing all numbers for primality is feasible, there are known combinations of bases that make the multiple strong Fermat test correct, so that would give a faster - O(n*(log n)4) - algorithm.

For n < 2^32, the bases 2, 7, and 61 are sufficient to verify primality. Using that, the hundred-millionth prime is found in about six minutes.

Eliminating composites by prime divisors, the Sieve of Eratosthenes

Instead of investigating the numbers in sequence and checking whether each is prime from scratch, one can also consider the whole set of relevant numbers as one piece and eliminate the multiples of a given prime in one go. This is known as the Sieve of Eratosthenes:

To find the prime numbers not exceeding N

  1. make a list of all numbers from 2 to N
  2. for each k from 2 to N: if k is not yet crossed off, it is prime; cross off all multiples of k as composites

The primes are the numbers in the list which aren't crossed off.

This algorithm is fundamentally different from trial division, although both directly use the divisibility characterisation of primes, in contrast to the Fermat test and similar tests which use other properties of primes.

In trial division, each number n is paired with all primes not exceeding the smaller of vn and the smallest prime divisor of n. Since most composites have a very small prime divisor, detecting composites is cheap here on average. But testing primes is expensive, since there are relatively many primes below vn. Although there are many more composites than primes, the cost of testing primes is so high that it completely dominates the overall running time and renders trial division a relatively slow algorithm. Trial division for all numbers less than N takes O(N1.5 / (log N)²) steps.

In the sieve, each composite n is paired with all of its prime divisors, but only with those. Thus there the primes are the cheap numbers, they are only ever looked at once, while the composites are more expensive, they are crossed off multiple times. One might believe that since a sieve contains many more 'expensive' numbers than 'cheap' ones, it would overall be a bad algorithm. However, a composite number does not have many distinct prime divisors - the number of distinct prime divisors of n is bounded by log n, but usually it is much smaller, the average of the number of distinct prime divisors of the numbers <= n is log log n - so even the 'expensive' numbers in the sieve are on average no more (or hardly more) expensive than the 'cheap' numbers for trial division.

Sieving up to N, for each prime p, there are T(N/p) multiples to cross off, so the total number of crossings-off is T(? (N/p)) = T(N * log (log N)). This yields much faster algorithms for finding the primes up to N than trial division or sequential testing with the faster primality tests.

There is, however, a disadvantage to the sieve, it uses O(N) memory. (But with a segmented sieve, that can be reduced to O(vN) without increasing the time complexity.)

For finding the nth prime, instead of the primes up to N, there is also the problem that it is not known beforehand how far the sieve should reach.

The latter can be solved using the prime number theorem. The PNT says

p(x) ~ x/log x (equivalently: lim p(x)*log x/x = 1),

where p(x) is the number of primes not exceeding x (here and below, log must be the natural logarithm, for the algorithmic complexities it is not important which base is chosen for the logarithms). From that, it follows that p(n) ~ n*log n, where p(n) is the nth prime, and there are good upper bounds for p(n) known from deeper analysis, in particular

n*(log n + log (log n) - 1) < p(n) < n*(log n + log (log n)), for n >= 6.

So one can use that as the sieving limit, it doesn't exceed the target far.

The O(N) space requirement can be overcome by using a segmented sieve. One can then record the primes below vN for O(vN / log N) memory consumption and use segments of increasing length (O(vN) when the sieve is near N).

There are some easy improvements on the algorithm as stated above:

  1. start crossing off multiples of p only at , not at 2*p
  2. eliminate the even numbers from the sieve
  3. eliminate the multiples of further small primes from the sieve

None of these reduce the algorithmic complexity, but they all reduce the constant factors by a significant amount (as with trial division, the elimination of multiples of p yields lesser speedup for larger p while increasing the code complexity more than for smaller p).

Using the first two improvements yields

// Entry k in the array represents the number 2*k+3, so we have to do
// a bit of arithmetic to get the indices right.
public static int nthPrime(int n) {
    if (n < 2) return 2;
    if (n == 2) return 3;
    int limit, root, count = 1;
    limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;
    root = (int)Math.sqrt(limit) + 1;
    limit = (limit-1)/2;
    root = root/2 - 1;
    boolean[] sieve = new boolean[limit];
    for(int i = 0; i < root; ++i) {
        if (!sieve[i]) {
            ++count;
            for(int j = 2*i*(i+3)+3, p = 2*i+3; j < limit; j += p) {
                sieve[j] = true;
            }
        }
    }
    int p;
    for(p = root; count < n; ++p) {
        if (!sieve[p]) {
            ++count;
        }
    }
    return 2*p+1;
}

which finds the hundred-millionth prime, 2038074743, in about 18 seconds. This time can be reduced to about 15 seconds (here, YMMV) by storing the flags packed, one bit per flag, instead of as booleans, since the reduced memory usage gives better cache locality.

Packing the flags, eliminating also multiples of 3 and using bit-twiddling for faster faster counting,

// Count number of set bits in an int
public static int popCount(int n) {
    n -= (n >>> 1) & 0x55555555;
    n = ((n >>> 2) & 0x33333333) + (n & 0x33333333);
    n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F);
    return (n * 0x01010101) >> 24;
}

// Speed up counting by counting the primes per
// array slot and not individually. This yields
// another factor of about 1.24 or so.
public static int nthPrime(int n) {
    if (n < 2) return 2;
    if (n == 2) return 3;
    if (n == 3) return 5;
    int limit, root, count = 2;
    limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;
    root = (int)Math.sqrt(limit);
    switch(limit%6) {
        case 0:
            limit = 2*(limit/6) - 1;
            break;
        case 5:
            limit = 2*(limit/6) + 1;
            break;
        default:
            limit = 2*(limit/6);
    }
    switch(root%6) {
        case 0:
            root = 2*(root/6) - 1;
            break;
        case 5:
            root = 2*(root/6) + 1;
            break;
        default:
            root = 2*(root/6);
    }
    int dim = (limit+31) >> 5;
    int[] sieve = new int[dim];
    for(int i = 0; i < root; ++i) {
        if ((sieve[i >> 5] & (1 << (i&31))) == 0) {
            int start, s1, s2;
            if ((i & 1) == 1) {
                start = i*(3*i+8)+4;
                s1 = 4*i+5;
                s2 = 2*i+3;
            } else {
                start = i*(3*i+10)+7;
                s1 = 2*i+3;
                s2 = 4*i+7;
            }
            for(int j = start; j < limit; j += s2) {
                sieve[j >> 5] |= 1 << (j&31);
                j += s1;
                if (j >= limit) break;
                sieve[j >> 5] |= 1 << (j&31);
            }
        }
    }
    int i;
    for(i = 0; count < n; ++i) {
        count += popCount(~sieve[i]);
    }
    --i;
    int mask = ~sieve[i];
    int p;
    for(p = 31; count >= n; --p) {
        count -= (mask >> p) & 1;
    }
    return 3*(p+(i<<5))+7+(p&1);
}

finds the hundred-millionth prime in about 9 seconds, which is not unbearably long.

There are other types of prime sieves, of particular interest is the Sieve of Atkin, which exploits the fact that certain congruence classes of (rational) primes are composites in the ring of algebraic integers of some quadratic extensions of Q. Here is not the place to expand on the mathematical theory, suffice it to say that the Sieve of Atkin has lower algorithmic complexity than the Sieve of Eratosthenes and hence is preferable for large limits (for small limits, a not overly optimised Atkin sieve has higher overhead and thus can be slower than a comparably optimised Eratosthenes sieve). D. J. Bernstein's primegen library (written in C) is well optimised for numbers below 232 and finds the hundred-millionth prime (here) in about 1.1 seconds.

The fast way

If we only want to find the nth prime, there is no intrinsic value in also finding all the smaller primes. If we can skip most of them, we can save a lot of time and work. Given a good approximation a(n) to the nth prime p(n), if we have a fast way to calculate the number of primes p(a(n)) not exceeding a(n), we can then sieve a small range above or below a(n) to identify the few missing or excess primes between a(n) and p(n).

We have seen an easily computed fairly good approximation to p(n) above, we could take

a(n) = n*(log n + log (log n))

for example.

A good method to compute p(x) is the Meissel-Lehmer method, which computes p(x) in roughly O(x^0.7) time (the exact complexity depends on the implementation, a refinement by Lagarias, Miller, Odlyzko, Deléglise and Rivat lets one compute p(x) in O(x2/3 / log² x) time).

Starting with the simple approximation a(n), we compute e(n) = p(a(n)) - n. By the prime number theorem, the density of primes near a(n) is about 1/log a(n), so we expect p(n) to be near b(n) = a(n) - log a(n)*e(n) and we would sieve a range slightly larger than log a(n)*e(n). For greater confidence that p(n) is in the sieved range, one can increase the range by a factor of 2, say, which almost certainly will be large enough. If the range seems too large, one can iterate with the better approximation b(n) in place of a(n), compute p(b(n)) and f(n) = p((b(n)) - n. Typically, |f(n)| will be much smaller than |e(n)|. If f(n) is approximately -e(n), c(n) = (a(n) + b(n)) / 2 will be a better approximation to p(n). Only in the very unlikely case that f(n) is very close to e(n) (and not very close to 0), finding a sufficiently good approximation to p(n) that the final sieving stage can be done in time comparable to computing p(a(n)) becomes a problem.

In general, after one or two improvements to the initial approximation, the range to be sieved is small enough for the sieving stage to have a complexity of O(n^0.75) or better.

This method finds the hundred-millionth prime in about 40 milliseconds, and the 1012-th prime, 29996224275833, in under eight seconds.


tl;dr: Finding the nth prime can be efficiently done, but the more efficient you want it, the more mathematics is involved.


I have Java code for most of the discussed algorithms prepared here, in case somebody wants to play around with them.


¹ Aside remark for overinterested souls: The definition of primes used in modern mathematics is different, applicable in much more general situations. If we adapt the school definition to include negative numbers - so a number is prime if it's neither 1 nor -1 and divisible only by 1, -1, itself and its negative - that defines (for integers) what is nowadays called an irreducible element of Z, however, for integers, the definitions of prime and irreducible elements coincide.

Using jQuery to test if an input has focus

Simple

 <input type="text" /> 



 <script>
     $("input").focusin(function() {

    alert("I am in Focus");

     });
 </script>

How do I remove lines between ListViews on Android?

For ListFragment use

getListView().setDivider(null)

after the list has been obtained.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

How to pass multiple parameters from ajax to mvc controller?

I think you may need to stringify the data using JSON.stringify.

 var data = JSON.stringify({ 
                 'StrContactDetails': Details,
                 'IsPrimary':true
               });

$.ajax({
        type: "POST",
        url: @url.Action("Dhp","SaveEmergencyContact"),
        data: data,
        success: function(){},
        contentType: 'application/json'
    });

So the controller method would look like,

public ActionResult SaveEmergencyContact(string  StrContactDetails, bool IsPrimary)

How to affect other elements when one element is hovered

Using the sibling selector is the general solution for styling other elements when hovering over a given one, but it works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:

Signal bar rating widget

This can actually be done easily using the CSS flexbox model, by setting flex-direction to reverse, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.

Flexbox is very well supported by 95% of modern browsers.

_x000D_
_x000D_
.rating {_x000D_
  display: flex;_x000D_
  flex-direction: row-reverse;_x000D_
  width: 9rem;_x000D_
}_x000D_
.rating div {_x000D_
  flex: 1;_x000D_
  align-self: flex-end;_x000D_
  background-color: black;_x000D_
  border: 0.1rem solid white;_x000D_
}_x000D_
.rating div:hover {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
.rating div[data-rating="1"] {_x000D_
  height: 5rem;_x000D_
}_x000D_
.rating div[data-rating="2"] {_x000D_
  height: 4rem;_x000D_
}_x000D_
.rating div[data-rating="3"] {_x000D_
  height: 3rem;_x000D_
}_x000D_
.rating div[data-rating="4"] {_x000D_
  height: 2rem;_x000D_
}_x000D_
.rating div[data-rating="5"] {_x000D_
  height: 1rem;_x000D_
}_x000D_
.rating div:hover ~ div {_x000D_
  background-color: lightblue;_x000D_
}
_x000D_
<div class="rating">_x000D_
  <div data-rating="1"></div>_x000D_
  <div data-rating="2"></div>_x000D_
  <div data-rating="3"></div>_x000D_
  <div data-rating="4"></div>_x000D_
  <div data-rating="5"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL query to find third highest salary in company

I found a very good explanation in

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

This query should give nth highest salary

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)

What is the difference between smoke testing and sanity testing?

Try to understand both by this example.


Suppose if you're buying a car from showroom.

The first thing you will check the car contains are for example if it's four tires, a staring, headlight, or all other basic things. This is called smoke testing.

If you're checking how much mileage the car is giving or what is max speed, then this is known as sanity testing.

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
    {
        return IsNetworkAvailable(0);
    }

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
                continue;

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)
                continue;

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
                continue;

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
                continue;

            return true;
        }
        return false;
    }

What does \u003C mean?

It's a unicode character. In this case \u003C and \u003E mean :

U+003C < Less-than sign

U+003E > Greater-than sign

See a list here

What do \t and \b do?

No, that's more or less what they're meant to do.

In C (and many other languages), you can insert hard-to-see/type characters using \ notation:

  • \a is alert/bell
  • \b is backspace/rubout
  • \n is newline
  • \r is carriage return (return to left margin)
  • \t is tab

You can also specify the octal value of any character using \0nnn, or the hexadecimal value of any character with \xnn.

  • EG: the ASCII value of _ is octal 137, hex 5f, so it can also be typed \0137 or \x5f, if your keyboard didn't have a _ key or something. This is more useful for control characters like NUL (\0) and ESC (\033)

As someone posted (then deleted their answer before I could +1 it), there are also some less-frequently-used ones:

  • \f is a form feed/new page (eject page from printer)
  • \v is a vertical tab (move down one line, on the same column)

On screens, \f usually works the same as \v, but on some printers/teletypes, it will go all the way to the next form/sheet of paper.

Run a Command Prompt command from Desktop Shortcut

Yes. One option you have is to create a batch file containing the command

cmd -c {your command}

or

cmd -k {your command}

The shortcut will then be to this batch file.

Bound method error

The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list.

But I suspect this indicates a design problem. What's the point of calls like

test.parser()
test.sort_word_list()
test.num_words()

which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.

E.G.,

def sort_word_list(self):
   if self.sorted_word_list is not None:
      self.sorted_word_list = sorted(self.word_list)
   return self.sorted_word_list

(Alternately, you could use properties.)

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Tree view of a directory/folder in Windows?

In the Windows command prompt you can use "tree /F" to view a tree of the current folder and all descending files & folders.

In File Explorer under Windows 8.1:

  • Select folder
  • Press Shift, right-click mouse, and select "Open command window here"
  • Type tree /f > tree.txt and press Enter
  • Use MS Word to open "tree.txt"
  • The dialog box "File Conversion - tree.txt" will open
  • For "Text encoding" tick the "MS-DOS" option

You now have an editable tree structure file.

This works for versions of Windows from Windows XP to Windows 8.1.

What is thread safe or non-thread safe in PHP?

For me, I always choose non-thread safe version because I always use nginx, or run PHP from the command line.

The non-thread safe version should be used if you install PHP as a CGI binary, command line interface or other environment where only a single thread is used.

A thread-safe version should be used if you install PHP as an Apache module in a worker MPM (multi-processing model) or other environment where multiple PHP threads run concurrently.

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

When can I use a forward declaration?

The main rule is that you can only forward-declare classes whose memory layout (and thus member functions and data members) do not need to be known in the file you forward-declare it.

This would rule out base classes and anything but classes used via references and pointers.

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

Disabling Log4J Output in Java

You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.

You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.

You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.

Passing two command parameters using a WPF binding

About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
        return tuple;
    }      
} 

Then execution logic in Command could be like this

public void OnExecute(object parameter) 
{
    var param = (Tuple<object, object>) parameter;

    // e.g. for two TextBox object
    var txtZip = (System.Windows.Controls.TextBox)param.Item1;
    var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}

and multi-bind with converter to create the parameters (with two TextBox objects)

<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConvert}">
            <Binding ElementName="txtZip"/>
            <Binding ElementName="txtCity"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

How to find the most recent file in a directory using .NET, and without looping?

If you want to search recursively, you can use this beautiful piece of code:

public static FileInfo GetNewestFile(DirectoryInfo directory) {
   return directory.GetFiles()
       .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
       .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
       .FirstOrDefault();                        
}

Just call it the following way:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));

and that's it. Returns a FileInfo instance or null if the directory is empty.

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

How to read a local text file?

How to read a local file?

By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');

Static Block in Java

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

What's the difference between fill_parent and wrap_content?

  • fill_parent will make the width or height of the element to be as large as the parent element, in other words, the container.

  • wrap_content will make the width or height be as large as needed to contain the elements within it.

Click here for ANDROID DOC Reference

Using union and order by clause in mysql

A union query can only have one master ORDER BY clause, IIRC. To get this, in each query making up the greater UNION query, add a field that will be the one field you sort by for the UNION's ORDER BY.

For instance, you might have something like

SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort

That union_sort field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

PHP: How to remove all non printable characters in a string?

To strip all non-ASCII characters from the input string

$result = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);

That code removes any characters in the hex ranges 0-31 and 128-255, leaving only the hex characters 32-127 in the resulting string, which I call $result in this example.

$on and $broadcast in angular

First, a short description of $on(), $broadcast() and $emit():

  • .$on(name, listener) - Listens for a specific event by a given name
  • .$broadcast(name, args) - Broadcast an event down through the $scope of all children
  • .$emit(name, args) - Emit an event up the $scope hierarchy to all parents, including the $rootScope

Based on the following HTML (see full example here):

<div ng-controller="Controller1">
    <button ng-click="broadcast()">Broadcast 1</button>
    <button ng-click="emit()">Emit 1</button>
</div>

<div ng-controller="Controller2">
    <button ng-click="broadcast()">Broadcast 2</button>
    <button ng-click="emit()">Emit 2</button>
    <div ng-controller="Controller3">
        <button ng-click="broadcast()">Broadcast 3</button>
        <button ng-click="emit()">Emit 3</button>
        <br>
        <button ng-click="broadcastRoot()">Broadcast Root</button>
        <button ng-click="emitRoot()">Emit Root</button>
    </div>
</div>

The fired events will traverse the $scopes as follows:

  • Broadcast 1 - Will only be seen by Controller 1 $scope
  • Emit 1 - Will be seen by Controller 1 $scope then $rootScope
  • Broadcast 2 - Will be seen by Controller 2 $scope then Controller 3 $scope
  • Emit 2 - Will be seen by Controller 2 $scope then $rootScope
  • Broadcast 3 - Will only be seen by Controller 3 $scope
  • Emit 3 - Will be seen by Controller 3 $scope, Controller 2 $scope then $rootScope
  • Broadcast Root - Will be seen by $rootScope and $scope of all the Controllers (1, 2 then 3)
  • Emit Root - Will only be seen by $rootScope

JavaScript to trigger events (again, you can see a working example here):

app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
    $scope.broadcastAndEmit = function(){
        // This will be seen by Controller 1 $scope and all children $scopes 
        $scope.$broadcast('eventX', {data: '$scope.broadcast'});

        // Because this event is fired as an emit (goes up) on the $rootScope,
        // only the $rootScope will see it
        $rootScope.$emit('eventX', {data: '$rootScope.emit'});
    };
    $scope.emit = function(){
        // Controller 1 $scope, and all parent $scopes (including $rootScope) 
        // will see this event
        $scope.$emit('eventX', {data: '$scope.emit'});
    };

    $scope.$on('eventX', function(ev, args){
        console.log('eventX found on Controller1 $scope');
    });
    $rootScope.$on('eventX', function(ev, args){
        console.log('eventX found on $rootScope');
    });
}]);

How to check if an object is a list or tuple (but not string)?

The str object doesn't have an __iter__ attribute

>>> hasattr('', '__iter__')
False 

so you can do a check

assert hasattr(x, '__iter__')

and this will also raise a nice AssertionError for any other non-iterable object too.

Edit: As Tim mentions in the comments, this will only work in python 2.x, not 3.x

Check to see if python script is running

Using bash to look for a process with the current script's name. No extra file.

import commands
import os
import time
import sys

def stop_if_already_running():
    script_name = os.path.basename(__file__)
    l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
    if l[1]:
        sys.exit(0);

To test, add

stop_if_already_running()
print "running normally"
while True:
    time.sleep(3)

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

How do I order my SQLITE database in descending order, for an android app?

public List getExpensesList(){
    SQLiteDatabase db = this.getWritableDatabase();

    List<String> expenses_list = new ArrayList<String>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME ;

    Cursor cursor = db.rawQuery(selectQuery, null);
    try{
        if (cursor.moveToLast()) {

            do{
                String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
                expenses_list.add(info);
            }while (cursor.moveToPrevious());
        }
    }finally{
        cursor.close();
    }
    return expenses_list;
}

This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~

How can I strip all punctuation from a string in JavaScript using regex?

If you want to remove specific punctuation from a string, it will probably be best to explicitly remove exactly what you want like

replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"")

Doing the above still doesn't return the string as you have specified it. If you want to remove any extra spaces that were left over from removing crazy punctuation, then you are going to want to do something like

replace(/\s{2,}/g," ");

My full example:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");

Results of running code in firebug console:

alt text

Why is list initialization (using curly braces) better than the alternatives?

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.

Internet Explorer cache location

If you want to find the folder in a platform independent way, you should query the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

How do I use valgrind to find memory leaks?

Try this:

valgrind --leak-check=full -v ./your_program

As long as valgrind is installed it will go through your program and tell you what's wrong. It can give you pointers and approximate places where your leaks may be found. If you're segfault'ing, try running it through gdb.

Why do we have to normalize the input for an artificial neural network?

I believe the answer is dependent on the scenario.

Consider NN (neural network) as an operator F, so that F(input) = output. In the case where this relation is linear so that F(A * input) = A * output, then you might choose to either leave the input/output unnormalised in their raw forms, or normalise both to eliminate A. Obviously this linearity assumption is violated in classification tasks, or nearly any task that outputs a probability, where F(A * input) = 1 * output

In practice, normalisation allows non-fittable networks to be fittable, which is crucial to experimenters/programmers. Nevertheless, the precise impact of normalisation will depend not only on the network architecture/algorithm, but also on the statistical prior for the input and output.

What's more, NN is often implemented to solve very difficult problems in a black-box fashion, which means the underlying problem may have a very poor statistical formulation, making it hard to evaluate the impact of normalisation, causing the technical advantage (becoming fittable) to dominate over its impact on the statistics.

In statistical sense, normalisation removes variation that is believed to be non-causal in predicting the output, so as to prevent NN from learning this variation as a predictor (NN does not see this variation, hence cannot use it).

Create web service proxy in Visual Studio from a WSDL file

There's a Microsoft Doc for creating your WCF proxy from the command line .

You can find your local copy of wsdl.exe in a location similar to this: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools (Learn more here)

In the end your Command should look similar to this:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\wsdl.exe"
 /language:CS /n:"My.Namespace" https://www.example.com/service/wsdl

How to find nth occurrence of character in a string?

//scala

// throw's -1 if the value isn't present for nth time, even if it is present till n-1 th time. // throw's index if the value is present for nth time

def indexOfWithNumber(tempString:String,valueString:String,numberOfOccurance:Int):Int={
var stabilizeIndex=0 
var tempSubString=tempString 
var tempIndex=tempString.indexOf(valueString) 
breakable
{
for ( i <- 1 to numberOfOccurance)
if ((tempSubString.indexOf(valueString) != -1) && (tempIndex != -1))
{
tempIndex=tempSubString.indexOf(valueString)
tempSubString=tempSubString.substring(tempIndex+1,tempSubString.size) // ADJUSTING FOR 0
stabilizeIndex=stabilizeIndex+tempIndex+1 // ADJUSTING FOR 0
}
else
{ 
stabilizeIndex= -1
tempIndex= 0
break
}
}
stabilizeIndex match { case value if value <= -1 => -1 case _ => stabilizeIndex-1 } // reverting for adjusting 0 previously
}


indexOfWithNumber("bbcfgtbgft","b",3) // 6
indexOfWithNumber("bbcfgtbgft","b",2) //1
indexOfWithNumber("bbcfgtbgft","b",4) //-1

indexOfWithNumber("bbcfgtbcgft","bc",1)  //1
indexOfWithNumber("bbcfgtbcgft","bc",4) //-1
indexOfWithNumber("bbcfgtbcgft","bc",2) //6

Converting string to double in C#

Most people already tried to answer your questions.
If you are still debugging, have you thought about using:

Double.TryParse(String, Double);

This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:

Double.TryParse(String, NumberStyles, IFormatProvider, Double);

This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.

If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

Hope that helps.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

instead of localhost of '0.0.0.0', use local network address as host in case of both - the server and the client - code.

host = '192.168.12.12' port = 12345

use this host address when binding and connecting to the socket.

server.bind((host, port)) client.connect((host, port))

this change solved the issue for me.

How can I ping a server port with PHP?

You don't need any exec or shell_exec hacks to do that, it is possible to do it in PHP. The book 'You want to do WHAT with PHP?' by Kevin Schroeder, show's how.

It uses sockets and the pack() function which lets you read and write binary protocols. What you need to do is to create an ICMP packet, which you can do by using the 'CCnnnA*' format to create your packet.

How to get current time and date in Android

For a customized time and date format:

    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
    String cDateTime=dateFormat.format(new Date());

Output is like below format: 2015-06-18T10:15:56-05:00

Android - SMS Broadcast receiver

intent.getAction().equals(SMS_RECEIVED)

I have tried it out successfully.

Passing HTML to template using Flask/Jinja2

When you have a lot of variables that don't need escaping, you can use an autoescape block:

{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

Unable to read repository at http://download.eclipse.org/releases/indigo

Had this problem in Linux, and I found that the user doesn't have permission to update the eclipse directory

change the owner of eclipse folder recursively, or run eclipse with user who has write permission to the folder

Set database timeout in Entity Framework

You can use DbContext.Database.CommandTimeout = 180; // seconds

It's pretty simple and no cast required.

Javascript Confirm popup Yes, No button instead of OK and Cancel

You can't do this cross-browser with the confirm() function or similar. I highly suggest you use something like the jQuery UI dialog feature to create an HTML dialog box instead.

Python: print a generator expression?

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Node.js: socket.io close client connection

For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

Python for and if on one line

In python3 the variable i will be out of scope when you try to print it.

To get the value you want you should store the result of your operation inside a new variable:

my_list = ["one","two","three"]
result=[(i) for i in my_list if i=="two"]
print(result)

you will then the following output

['two']

In php, is 0 treated as empty?

From manual: Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string) NULL
  • FALSE array() (an empty array) var
  • $var; (a variable declared, but without a value in a class)

More: http://php.net/manual/en/function.empty.php

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

Removing duplicates from a String in Java

package com.st.removeduplicate;
 public class RemoveDuplicate {
   public static void main(String[] args) {
    String str1="shushil",str2="";      
    for(int i=0; i<=str1.length()-1;i++) {
        int count=0;
        for(int j=0;j<=i;j++) {
            if(str1.charAt(i)==str1.charAt(j)) 
                count++;
            if(count >1)
                break;
        }
        if(count==1) 
            str2=str2+str1.charAt(i);
    }
    System.out.println(str2);

}

}

How to get the current directory of the cmdlet being executed

Most answers don't work when debugging in the following IDEs:

  • PS-ISE (PowerShell ISE)
  • VS Code (Visual Studio Code)

Because in those the $PSScriptRoot is empty and Resolve-Path .\ (and similars) will result in incorrect paths.

Freakydinde's answer is the only one that resolves those situations, so I up-voted that, but I don't think the Set-Location in that answer is really what is desired. So I fixed that and made the code a little clearer:

$directorypath = if ($PSScriptRoot) { $PSScriptRoot } `
    elseif ($psise) { split-path $psise.CurrentFile.FullPath } `
    elseif ($psEditor) { split-path $psEditor.GetEditorContext().CurrentFile.Path }

Count distinct value pairs in multiple columns in SQL

Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

How to handle static content in Spring MVC?

In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)

That works for me

<mvc:default-servlet-handler/>

Regards

Ayub Malik

Why is textarea filled with mysterious white spaces?

In short: <textarea> should be closed immediately on the same line where it started.


General Practice: this will add-up line-breaks and spaces used for indentation in the code.

<textarea id="sitelink" name="sitelink">
</textarea>

Correct Practice

<textarea id="sitelink" name="sitelink"></textarea>

Subtract 1 day with PHP

Answear taken from Php manual strtotime function comments :

echo date( "Y-m-d", strtotime( "2009-01-31 -1 day"));

Or

$date = "2009-01-31";
echo date( "Y-m-d", strtotime( $date . "-1 day"));

What does 'x packages are looking for funding' mean when running `npm install`?

You can skip fund using:

npm install --no-fund YOUR PACKAGE NAME

For example :

npm install --no-fund core-js

Is there a way to perform "if" in python's lambda

The syntax you're looking for:

lambda x: True if x % 2 == 0 else False

But you can't use print or raise in a lambda.

How to add image in a TextView text?

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

jQuery Scroll To bottom of the page

$('#pagedwn').bind("click", function () {
        $('html, body').animate({ scrollTop:3031 },"fast");
        return false;
});

This solution worked for me. It is working in Page Scroll Down fastly.

What does if [ $? -eq 0 ] mean for shell scripts?

It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

How do I compile and run a program in Java on my Mac?

You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)

From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.

HTML span align center not working?

Please use the following style. margin:auto normally used to center align the content. display:table is needed for span element

<span style="margin:auto; display:table; border:1px solid red;">
    This is some text in a div element!
</span>

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Just add this

buildscript {
    repositories {
        ...
        google() 
        jcenter()
    }

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

It works...Cheers!!!

Freeing up a TCP/IP port?

As the others have said, you'll have to kill all processes that are listening on that port. The easiest way to do that would be to use the fuser(1) command. For example, to see all of the processes listening for http requests on port 80 (run as root or use sudo):

# fuser 80/tcp

If you want to kill them, then just add the -k option.

TypeScript: Creating an empty typed container array

I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.

I had

return [];

where [] was Criminal[] type.

Neither return: Criminal[] []; nor return []: Criminal[]; worked for me.

At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.

For thoroughness I'll report this solution in my answer too:

let temp: Criminal[] = [];
return temp;

Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:

return <Criminal[]>[];

Hope this will help future readers!

What is the best place for storing uploaded images, SQL database or disk file system?

This is basically I do.

  1. Store an uploaded image in temporary directory or memory.
  2. Process that image before permanently storing it. 2.1. Color corrections 2.2. Compress 2.3. Create several copies based on image dimensions 2.4. Rename with .xl, .lg, .md, .sm etc. suffixes
  3. Pack all processed image files (from a single file) inside a folder with folder name as id which will be stored in database for any row/document along with image file name (or may be random name as image name).
  4. Create yyyy/mm/d path folder if doesn't exist. For example 2016/08/21. Remember that path and store in database for same document and row.
  5. Move image id folder to path folder. (Path folder may be located in /var/web-content folder.)
  6. Flush memory buffer or delete temporary file.

When you need to access any image mentioned in a document, you have the path and id of the folder than contains images. For example /var/web-content/{{path}}/{{id}}/image-file-name.sm.jpg

This way if you have to delete all processed image files, just delete the folder and it's content recursively.

Formatting DataBinder.Eval data

There is an optional overload for DataBinder.Eval to supply formatting:

<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>

The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:

<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>

Search File And Find Exact Match And Print Line?

It's very easy:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

How to update single value inside specific array item in redux

You could use the React Immutability helpers

import update from 'react-addons-update';

// ...    

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      1: {
        text: {$set: action.payload}
      }
    }
  });

Although I would imagine you'd probably be doing something more like this?

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      [action.id]: {
        text: {$set: action.payload}
      }
    }
  });

How do I create a pause/wait function using Qt?

We've been using the below class -

class SleepSimulator{
     QMutex localMutex;
     QWaitCondition sleepSimulator;
public:
    SleepSimulator::SleepSimulator()
    {
        localMutex.lock();
    }
    void sleep(unsigned long sleepMS)
    {
        sleepSimulator.wait(&localMutex, sleepMS);
    }
    void CancelSleep()
    {
        sleepSimulator.wakeAll();
    }
};

QWaitCondition is designed to coordinate mutex waiting between different threads. But what makes this work is the wait method has a timeout on it. When called this way, it functions exactly like a sleep function, but it uses Qt's event loop for the timing. So, no other events or the UI are blocked like normal windows sleep function does.

As a bonus, we added the CancelSleep function to allows another part of the program to cancel the "sleep" function.

What we liked about this is that it lightweight, reusable and is completely self contained.

QMutex: http://doc.qt.io/archives/4.6/qmutex.html

QWaitCondition: http://doc.qt.io/archives/4.6/qwaitcondition.html

Outlets cannot be connected to repeating content iOS

Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.

Is it not possible to stringify an Error using JSON.stringify?

You can define a Error.prototype.toJSON to retrieve a plain Object representing the Error:

if (!('toJSON' in Error.prototype))
Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true,
    writable: true
});
var error = new Error('testing');
error.detail = 'foo bar';

console.log(JSON.stringify(error));
// {"message":"testing","detail":"foo bar"}

Using Object.defineProperty() adds toJSON without it being an enumerable property itself.


Regarding modifying Error.prototype, while toJSON() may not be defined for Errors specifically, the method is still standardized for objects in general (ref: step 3). So, the risk of collisions or conflicts is minimal.

Though, to still avoid it completely, JSON.stringify()'s replacer parameter can be used instead:

function replaceErrors(key, value) {
    if (value instanceof Error) {
        var error = {};

        Object.getOwnPropertyNames(value).forEach(function (key) {
            error[key] = value[key];
        });

        return error;
    }

    return value;
}

var error = new Error('testing');
error.detail = 'foo bar';

console.log(JSON.stringify(error, replaceErrors));

Loop in react-native

render() {
var myloop = [];

for (let i = 0; i < 10; i++) {
  myloop.push(
    <View key={i}>
    <Text>{i}</Text>
    </View>
  );
}

 return (

        <View >
          <Text >Welcome to React Native!</Text>
           {myloop}
        </View>


    );
  }
}

Datatables - Setting column width

you should use "bAutoWidth" property of datatable and give width to each td/column in %

 $(".table").dataTable({"bAutoWidth": false , 
aoColumns : [
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "10%"},
    ]
});

Hope this will help.

How to work offline with TFS

If the code has already been checked out by the user that if offline and they have the latest version on their local hd, then they just need to browse to the solution location and open the solution by double clicking sln file. The solution will open in disconnected mode.

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

Psql list all tables

To see the public tables you can do

list tables

\dt

list table, view, and access privileges

\dp or \z

or just the table names

select table_name from information_schema.tables where table_schema = 'public';

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

What is the difference between java and core java?

In simple language core java stands for the concepts of Inheritance, Polymorphism,Abstraction,Encapsulation,class,objects which comes under core java. Core java stands for J2SE. I hope this can clear you doubts.

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

Can you have multiline HTML5 placeholder text in a <textarea>?

For <textarea>s the spec specifically outlines that carriage returns + line breaks in the placeholder attribute MUST be rendered as linebreaks by the browser.

User agents should present this hint to the user when the element's value is the empty string and the control is not focused (e.g. by displaying it inside a blank unfocused control). All U+000D CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF) characters in the hint, must be treated as line breaks when rendering the hint.

Also reflected on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder

FWIW, when I try on Chrome 63.0.3239.132, it does indeed work as it says it should.

How to add new line into txt file

You could do it easily using

File.AppendAllText("date.txt", DateTime.Now.ToString());

If you need newline

File.AppendAllText("date.txt", 
                   DateTime.Now.ToString() + Environment.NewLine);

Anyway if you need your code do this:

TextWriter tw = new StreamWriter("date.txt", true);

with second parameter telling to append to file.
Check here StreamWriter syntax.

HTML5 best practices; section/header/aside/article elements

I'd suggest reading the W3 wiki page about structuring HTML5:

<header> Used to contain the header content of a site. <footer> Contains the footer content of a site. <nav> Contains the navigation menu, or other navigation functionality for the page.

<article> Contains a standalone piece of content that would make
sense if syndicated as an RSS item, for example a news item.

<section> Used to either group different articles into different
purposes or subjects, or to define the different sections of a single article.

<aside> Defines a block of content that is related to the main content around it, but not central to the flow of it.

They include an image that I've cleaned up here:

html5

In code, this looks like so:

<body>
  <header></header>    
  <nav></nav>    
  <section id="sidebar"></section>    
  <section id="content"></section>    
  <aside></aside>    
  <footer></footer>
</body>

Let's explore some of the HTML5 elements in more detail.

<section>

The <section> element is for containing distinct different areas of functionality or subjects area, or breaking an article or story up into different sections. So in this case: "sidebar1" contains various useful links that will persist on every page of the site, such as "subscribe to RSS" and "Buy music from store". "main" contains the main content of this page, which is blog posts. On other pages of the site, this content will change. It is a fairly generic element, but still has way more semantic meaning than the plain old <div>.

<article>

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up. In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article><!-- first blog post --></article>        
    <article><!-- second blog post --></article>        
    <article><!-- third blog post --></article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction"></section>      
  <section id="content"></section>
  <section id="summary"></section>
</article>

<header> and <footer>

as we already mentioned above, the purpose of the <header> and <footer> elements is to wrap header and footer content, respectively. In our particular example the <header> element contains a logo image, and the <footer> element contains a copyright notice, but you could add more elaborate content if you wished. Also note that you can have more than one header and footer on each page - as well as the top level header and footer we have just discussed, you could also have a <header> and <footer> element nested inside each <article>, in which case they would just apply to that particular article. Adding to our above example:

<article>
  <header></header>    
  <section id="introduction"></section>      
  <section id="content"></section>      
  <section id="summary"></section>      
  <footer></footer>
</article>

<nav>

The <nav> element is for marking up the navigation links or other constructs (eg a search form) that will take you to different pages of the current site, or different areas of the current page. Other links, such as sponsored links, do not count. You can of course include headings and other structuring elements inside the <nav>, but it's not compulsory.

<aside>

you may have noticed that we used an <aside> element to markup the 2nd sidebar: the one containing latest gigs and contact details. This is perfectly appropriate, as <aside> is for marking up pieces of information that are related to the main flow, but don't fit in to it directly. And the main content in this case is all about the band! Other good choices for an <aside> would be information about the author of the blog post(s), a band biography, or a band discography with links to buy their albums.

Where does that leave <div>?

So, with all these great new elements to use on our pages, the days of the humble <div> are numbered, surely? NO. In fact, the <div> still has a perfectly valid use. You should use it when there is no other more suitable element available for grouping an area of content, which will often be when you are purely using an element to group content together for styling/visual purposes. A common example is using a <div> to wrap all of the content on the page, and then using CSS to centre all the content in the browser window, or apply a specific background image to the whole content.

Oracle date "Between" Query

You need to convert those to actual dates instead of strings, try this:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('2010-01-15','YYYY-MM-DD') AND TO_DATE('2010-01-17', 'YYYY-MM-DD');

Edited to deal with format as specified:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('15-JAN-10','DD-MON-YY') AND TO_DATE('17-JAN-10','DD-MON-YY');

MySQL error: key specification without a key length

Another excellent way of dealing with this is to create your TEXT field without the unique constraint and add a sibling VARCHAR field that is unique and contains a digest (MD5, SHA1, etc.) of the TEXT field. Calculate and store the digest over the entire TEXT field when you insert or update the TEXT field then you have a uniqueness constraint over the entire TEXT field (rather than some leading portion) that can be searched quickly.

Quicksort with Python

Partition - Split an array by a pivot that smaller elements move to the left and greater elemets move to the right or vice versa. A pivot can be an random element from an array. To make this algorith we need to know what is begin and end index of an array and where is a pivot. Then set two auxiliary pointers L, R.

So we have an array user[...,begin,...,end,...]

The start position of L and R pointers
[...,begin,next,...,end,...]
     R       L

while L < end
  1. If a user[pivot] > user[L] then move R by one and swap user[R] with user[L]
  2. move L by one

After while swap user[R] with user[pivot]

Quick sort - Use the partition algorithm until every next part of the split by a pivot will have begin index greater or equals than end index.

def qsort(user, begin, end):

    if begin >= end:
        return

    # partition
    # pivot = begin
    L = begin+1
    R = begin
    while L < end:
        if user[begin] > user[L]:
            R+=1
            user[R], user[L] = user[L], user[R]
        L+= 1
    user[R], user[begin] = user[begin], user[R]

    qsort(user, 0, R)
    qsort(user, R+1, end)

tests = [
    {'sample':[1],'answer':[1]},
    {'sample':[3,9],'answer':[3,9]},
    {'sample':[1,8,1],'answer':[1,1,8]},
    {'sample':[7,5,5,1],'answer':[1,5,5,7]},
    {'sample':[4,10,5,9,3],'answer':[3,4,5,9,10]},
    {'sample':[6,6,3,8,7,7],'answer':[3,6,6,7,7,8]},
    {'sample':[3,6,7,2,4,5,4],'answer':[2,3,4,4,5,6,7]},
    {'sample':[1,5,6,1,9,0,7,4],'answer':[0,1,1,4,5,6,7,9]},
    {'sample':[0,9,5,2,2,5,8,3,8],'answer':[0,2,2,3,5,5,8,8,9]},
    {'sample':[2,5,3,3,2,0,9,0,0,7],'answer':[0,0,0,2,2,3,3,5,7,9]}
]

for test in tests:

    sample = test['sample'][:]
    answer = test['answer']

    qsort(sample,0,len(sample))

    print(sample == answer)

What command means "do nothing" in a conditional in Bash?

Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.

I try to give a general rule by using the OPs example

do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"

we have to avoid a branch where $a gets more than 10, so $a < 10 as a general condition can be applied to every other, following condition.

In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.

So the OPs example with the rule applied may be restructured as:

if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
    echo "1"
elif [ "$a" -lt 10 ]
then
    echo "2"
fi

Just a variation of the above, enclosing everything in the $a < 10 condition:

if [ "$a" -lt 10 ]
then
    if [ "$a" -le 5 ]
    then
        echo "1"
    else
        echo "2"
    fi
fi

(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)

how to add css class to html generic control div?

If you're going to be repeating this, might as well have an extension method:

// appends a string class to the html controls class attribute
public static void AddClass(this HtmlControl control, string newClass)
{
    if (control.Attributes["class"].IsNotNullAndNotEmpty())
    {
        control.Attributes["class"] += " " + newClass;
    }
    else
    {
        control.Attributes["class"] = newClass;
    }
}

Mapping list in Yaml to list of objects in Spring Boot

for me the fix was to add the injected class as inner class in the one annotated with @ConfigurationProperites, because I think you need @Component to inject properties.

What is an 'undeclared identifier' error and how do I fix it?

Another possible situation: accessing parent (a template class) member in a template class.

Fix method: using the parent class member by its full name (by prefixing this-> or parentClassName:: to the name of the member).

see: templates: parent class member variables not visible in inherited class

Migration: Cannot add foreign key constraint

It also may be your the ordering of creation migration. If you firstly create priorities table, and after users table then it will be wrong. Because of first migration looking for users table. So, you have to change the ordering of migration on

app/database/migrations

directory

Setting Java heap space under Maven 2 on Windows

You are looking for 2 options to java:

  • -Xmx maximum heap size
  • -Xms starting heap size

Put them in your command line invocation of the java executable, like this:

java -Xms512M -Xmx1024M my.package.MainClass

Keep in mind that you may want the starting and max heap sizes to be the same, depending on the application, as it avoids resizing the heap during runtime (which can take up time in applications that need to be responsive). Resizing the heap can entail moving a lot of objects around and redoing bookkeeping.

For every-day projects, make them whatever you think is good enough. Profile for help.

python save image from url

It is the simplest way to download and save the image from internet using urlib.request package.

Here, you can simply pass the image URL(from where you want to download and save the image) and directory(where you want to save the download image locally, and give the image name with .jpg or .png) Here I given "local-filename.jpg" replace with this.

Python 3

import urllib.request
imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"

urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")

You can download multiple images as well if you have all the image URLs from the internet. Just pass those image URLs in for loop, and the code automatically download the images from the internet.

Applying a single font to an entire website with CSS

* { font-family: Algerian; }

The universal selector * refers to any element.

Node Version Manager (NVM) on Windows

I created a universal nvm that works on both Unix (bash) and Windows, base on another simple nvm.

It doesn't need admin on Windows, but requires PowerShell 4+ and the right to execute scripts.

https://www.npmjs.com/package/@jchip/nvm#installation

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

This is one of the basic differences not mentioned in previous comments:
Readonly property will work with textbox for and it will not work with EditorFor.

@Html.TextBoxFor(model => model.DateSoldOn, new { @readonly = "readonly" })

Above code works, where as with following you can't make control to readonly.

@Html.EditorFor(model => model.DateSoldOn, new { @readonly = "readonly" })

How to print a string at a fixed width?

>>> print(f"{'123':<4}56789")
123 56789

How to remove html special chars?

It looks like what you really want is:

function xmlEntities($string) {
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

    foreach ($translationTable as $char => $entity) {
        $from[] = $entity;
        $to[] = '&#'.ord($char).';';
    }
    return str_replace($from, $to, $string);
}

It replaces the named-entities with their number-equivalent.

Outputting data from unit test in Python

Another option - start a debugger where the test fails.

Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.

Here's a terminal session on windows:

C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
  1     from unittest import TestCase
  2     class MyTests(TestCase):
  3       def test_foo(self):
  4         x = 1
  5         y = 2
  6  ->     self.assertEqual(x, y)
[EOF]
(Pdb)

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

Changing the default icon in a Windows Forms application

The icons you are seeing on desktop is not a icon file. They are either executable files .exe or shortcuts of any application .lnk. So can only set icon which have .ico extension.

Go to Project Menu -> Your_Project_Name Properties -> Application TAB -> Resources -> Icon

browse for your Icon, remember it must have .ico extension

You can make your icon in Visual Studio

Go to Project Menu -> Add New Item -> Icon File

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Syntax: error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
Default:    
error_log logs/error.log error;
Context:    main, http, stream, server, location

http://nginx.org/en/docs/ngx_core_module.html#error_log

Don't use: /dev/stderr This will break your setup if you're going to use systemd-nspawn.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

How to pass arguments to a Button command in Tkinter?

This can also be done by using partial from the standard library functools, like this:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Here I am using iTextSharp dll for generating PDF file. I want to open PDF file instead of downloading it. So I am using below code which is working fine for me. Now pdf file is opening in browser ,now dowloading

        Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        Paragraph Text = new Paragraph("Hi , This is Test Content");
        pdfDoc.Add(Text);
        pdfWriter.CloseStream = false;
        pdfDoc.Close();
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.End();

If you want to download file, add below line, after this Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");   

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

Search for exact match of string in excel row using VBA Macro

Use worksheet.find (worksheet is your worksheet) and use the row-range for its range-object. You can get the rangeobject like: worksheet.rows(rowIndex) as example

Then give find the required parameters it should find it for you fine. If I recall correctly, find returns the first match per default. I have no Excel at hand, so you have to look up find for yourself, sorry

I would advise against using a for-loop it is more fragile and ages slower than find.

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

In Java how does one turn a String into a char or a char into a String?

String g = "line";
//string to char
char c = g.charAt(0);
char[] c_arr = g.toCharArray();
//char to string
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
//(or iterate the charArray and append each character to str -> str+=charArray[i])

//or String s= new String(chararray);

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

How do you add swap to an EC2 instance?

A fix for this problem is to add swap (i.e. paging) space to the instance.

Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however much more of it is available.

To add this extra space to your instance you type:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1

If you need more than 1024 then change that to something higher.

To enable it by default after reboot, add this line to /etc/fstab:

/var/swap.1   swap    swap    defaults        0   0

File upload from <input type="file">

Try this small lib, works with Angular 5.0.0

Quickstart example with ng2-file-upload 1.3.0:

User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

app.module.ts:

import {FileUploadModule} from "ng2-file-upload";

your.component.html:

...
  <button mat-button onclick="document.getElementById('myFileInputField').click()" >
    Select and upload file
  </button>
  <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...

your.component.ts:

import {FileUploader} from 'ng2-file-upload';
...    
uploader: FileUploader;
...
constructor() {
   this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
   this.uploader.onErrorItem = item => {
       console.error("Failed to upload");
       this.clearUploadField();
   };
   this.uploader.onCompleteItem = (item, response) => {
       console.info("Successfully uploaded");
       this.clearUploadField();

       // (Optional) Parsing of response
       let responseObject = JSON.parse(response) as MyCustomClass;

   };

   // Asks uploader to start upload file automatically after selecting file
  this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}

private clearUploadField(): void {
    (<HTMLInputElement>window.document.getElementById('myFileInputField'))
    .value = "";
}

Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Set the space between Elements in Row Flutter

You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.

Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex container, like Row or Column.

In a row, if we want to put space between two widgets such that it occupies all remaining space.

    widget = Row (
    children: <Widget>[
      Spacer(flex: 20),
      Text(
        "Item #1",
      ),
      Spacer(),  // Defaults to flex: 1
      Text(
        "Item #2",
      ),
      Spacer(flex: 20),
    ]
  );

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

android:drawableLeft margin and/or padding

android:drawablePadding is the easiest way to give padding to drawable icon but You can not give specific one side padding like paddingRight or paddingLeft of drawable icon.To achieve that you have to dig into it. And If you apply paddingLeft or paddingRight to EditText then it will place padding to entire EditText along with drawable icon.

<TextView android:layout_width="match_parent"
    android:padding="5dp"
    android:id="@+id/date"
    android:gravity="center|start"
    android:drawableEnd="@drawable/ic_calendar"
    android:background="@drawable/edit_background"
    android:hint="Not Selected"
    android:drawablePadding="10dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:textColor="@color/black"
    android:layout_height="wrap_content"/>

adding and removing classes in angularJs using ng-click

I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):

<div class="form-group col-md-12">
    <div ng-class="{'bg-info':     (!transport_type)}"    ng-click="transport_type=false">CARS</div>
    <div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
    <div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>

What does the 'b' character do in front of a string literal?

You can use JSON to convert it to dictionary

import json
data = b'{"key":"value"}'
print(json.loads(data))

{"key":"value"}


FLASK:

This is an example from flask. Run this on terminal line:

import requests
requests.post(url='http://localhost(example)/',json={'key':'value'})

In flask/routes.py

@app.route('/', methods=['POST'])
def api_script_add():
    print(request.data) # --> b'{"hi":"Hello"}'
    print(json.loads(request.data))
return json.loads(request.data)

{'key':'value'}

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:

  1. How to I score a multiclass problem?
  2. How do I deal with unbalanced data?

1.

You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:

from sklearn.metrics import precision_recall_fscore_support as score

predicted = [1,2,3,4,5,1,2,1,1,4,5] 
y_test = [1,2,3,4,5,1,2,1,1,4,1]

precision, recall, fscore, support = score(y_test, predicted)

print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))

This way you end up with tangible and interpretable numbers for each of the classes.

| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1     | 94%       | 83%    | 0.88   | 204     |
| 2     | 71%       | 50%    | 0.54   | 127     |
| ...   | ...       | ...    | ...    | ...     |
| 4     | 80%       | 98%    | 0.89   | 838     |
| 5     | 93%       | 81%    | 0.91   | 1190    |

Then...

2.

... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.

Convert decimal to binary in python

all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10

Returning JSON from PHP to JavaScript?

Usually you would be interested in also having some structure to your data in the receiving end:

json_encode($result)

This will preserve the array keys as well.

Do remember that json_encode only works on utf8 -encoded data.

How to block calls in android

You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.

Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.

How to change the new TabLayout indicator color and height

Just put this line in your code. If you change the color then change the color value in parentheses.

tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));

Using %f with strftime() in Python to get microseconds

You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

How to center canvas in html5

Use this code:

<!DOCTYPE html>
<html>
<head>
<style>
.text-center{
    text-align:center;
    margin-left:auto;
    margin-right:auto;
}
</style>
</head>
<body>

<div class="text-center">
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>

</body>
</html>

Remove the legend on a matplotlib figure

You could use the legend's set_visible method:

ax.legend().set_visible(False)
draw()

This is based on a answer provided to me in response to a similar question I had some time ago here

(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

Delete specific line number(s) from a text file using sed?

If you want to delete lines 5 through 10 and 12:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will back the file up to file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

How to highlight a current menu item?

There is a ng-class directive, which binds variable and css class. It also accepts the object (className vs bool value pairs).

Here is the example, http://plnkr.co/edit/SWZAqj