Programs & Examples On #Paperclip

Paperclip is a library for the Ruby on Rails framework which makes dealing with file attachments easier. In addition to dealing with standalone files, the library provides convenience methods for creating image thumbnails. Paperclip is now deprecated - the authors recommend using ActiveStorage (they have provided a migration guide)

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

The creation of pdf-documents with the rails-latex-gem lead to a similar problem. I solved this by modifying layouts/application.pdf.erb to

\begin{document}

<%= yield.force_encoding("UTF-8") %>


\end{document}

How can I download a file from a URL and save it in Rails?

Check out Net::HTTP in the standard library. The documentation provides several examples on how to download documents using HTTP.

Quick easy way to migrate SQLite3 to MySQL?

Probably the quick easiest way is using the sqlite .dump command, in this case create a dump of the sample database.

sqlite3 sample.db .dump > dump.sql

You can then (in theory) import this into the mysql database, in this case the test database on the database server 127.0.0.1, using user root.

mysql -p -u root -h 127.0.0.1 test < dump.sql

I say in theory as there are a few differences between grammars.

In sqlite transactions begin

BEGIN TRANSACTION;
...
COMMIT;

MySQL uses just

BEGIN;
...
COMMIT;

There are other similar problems (varchars and double quotes spring back to mind) but nothing find and replace couldn't fix.

Perhaps you should ask why you are migrating, if performance/ database size is the issue perhaps look at reoginising the schema, if the system is moving to a more powerful product this might be the ideal time to plan for the future of your data.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

CSS Printing: Avoiding cut-in-half DIVs between pages?

One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid works fine on Chrome for me.

How to get the root dir of the Symfony2 application?

Since Symfony 3.3 you can use binding, like

services:
_defaults:
    autowire: true      
    autoconfigure: true
    bind:
        $kernelProjectDir: '%kernel.project_dir%'

After that you can use parameter $kernelProjectDir in any controller OR service. Just like

class SomeControllerOrService
{
    public function someAction(...., $kernelProjectDir)
    {
          .....

Getting Access Denied when calling the PutObject operation with bucket-level permission

I encountered the same issue. My bucket was private and had KMS encryption. I was able to resolve this issue by putting in additional KMS permissions in the role. The following list is the bare minimum set of roles needed.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "AllowAttachmentBucketWrite",
        "Effect": "Allow",
        "Action": [
            "s3:PutObject",
            "kms:Decrypt",
            "s3:AbortMultipartUpload",
            "kms:Encrypt",
            "kms:GenerateDataKey"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name/*",
            "arn:aws:kms:kms-key-arn"
        ]
    }
  ]
}

Reference: https://aws.amazon.com/premiumsupport/knowledge-center/s3-large-file-encryption-kms-key/

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I had the same problem for Visual Studio 2019 v16.8.6. It was fixed after repair Visual Studio from Visual Studio Installer.

calling server side event from html button control

If you are OK with converting the input button to a server side control by specifying runat="server", and you are using asp.net, an option could be using the HtmlButton.OnServerClick property.

<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />

This should work and call foo_OnClick in your server side code. Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Cannot find name 'require' after upgrading to Angular4

Finally I got solution for this, check my App module file :

import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from '@angular/material';
import 'hammerjs';
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'highcharts';
import { HighchartsStatic } from 'angular2-highcharts/dist/HighchartsService';

import { AppRouting } from './app.routing';
import { AppComponent } from './app.component';

declare var require: any;


export function highchartsFactory() {
      const hc = require('highcharts');
      const dd = require('highcharts/modules/drilldown');
      dd(hc);

      return hc;
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRouting,
    BrowserAnimationsModule,
    MaterialModule,
    ChartModule
  ],
  providers: [{
      provide: HighchartsStatic,
      useFactory: highchartsFactory
    }],
  bootstrap: [AppComponent]
})
export class AppModule { }

Notice declare var require: any; in the above code.

How to remove a branch locally?

The Github application for Windows shows all remote branches of a repository. If you have deleted the branch locally with $ git branch -d [branch_name], the remote branch still exists in your Github repository and will appear regardless in the Windows Github application.

If you want to delete the branch completely (remotely as well), use the above command in combination with $ git push origin :[name_of_your_new_branch]. Warning: this command erases all existing branches and may cause loss of code. Be careful, I do not think this is what you are trying to do.

However every time you delete the local branch changes, the remote branch will still appear in the application. If you do not want to keep making changes, just ignore it and do not click, otherwise you may clone the repository. If you had any more questions, please let me know.

TypeError : Unhashable type

You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

A list comprehension returns a list, you don't need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

What is the "Temporary ASP.NET Files" folder for?

These are what's known as Shadow Copy Folders.

Simplistically....and I really mean it:

When ASP.NET runs your app for the first time, it copies any assemblies found in the /bin folder, copies any source code files (found for example in the App_Code folder) and parses your aspx, ascx files to c# source files. ASP.NET then builds/compiles all this code into a runnable application.

One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.

ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.

Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.

This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation

Java - Convert integer to string

This will do. Pretty trustworthy. : )

    ""+number;

Just to clarify, this works and acceptable to use unless you are looking for micro optimization.

Create a date from day month and year with T-SQL

Try this query:

    SELECT SUBSTRING(CONVERT(VARCHAR,JOINGDATE,103),7,4)AS
    YEAR,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),1,2)AS
MONTH,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),4,3)AS DATE FROM EMPLOYEE1

Result:

2014    Ja    1
2015    Ja    1
2014    Ja    1
2015    Ja    1
2012    Ja    1
2010    Ja    1
2015    Ja    1

Spring Security with roles and permissions

To implement that, it seems that you have to:

  1. Create your model (user, role, permissions) and a way to retrieve permissions for a given user;
  2. Define your own org.springframework.security.authentication.ProviderManager and configure it (set its providers) to a custom org.springframework.security.authentication.AuthenticationProvider. This last one should return on its authenticate method a Authentication, which should be setted with the org.springframework.security.core.GrantedAuthority, in your case, all the permissions for the given user.

The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the Authentication.authorities object.

For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with org.springframework.security.ldap.authentication.LdapAuthenticationProvider setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.

Hope this time I got what you are looking for. Good luck.

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

Regex: Check if string contains at least one digit

In perl:

if($testString =~ /\d/) 
{
    print "This string contains at least one digit"
}

where \d matches to a digit.

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

Calling a method every x minutes

Using a DispatcherTimer:

 var _activeTimer = new DispatcherTimer {
   Interval = TimeSpan.FromMinutes(5)
 };
 _activeTimer.Tick += delegate (object sender, EventArgs e) { 
   YourMethod(); 
 };
 _activeTimer.Start();          

How do I update Anaconda?

I'm using Windows 10. The following updates everything and also installs some new packages, including a Python update (for me it was 3.7.3).

At the shell, try the following (be sure to change where your Anaconda 3 Data is installed). It takes some time to update everything.

conda update --prefix X:\XXXXData\Anaconda3 anaconda

Printing Batch file results to a text file

For showing result of batch file in text file, you can use

this command

chdir > test.txt

This command will redirect result to test.txt.

When you open test.txt you will found current path of directory in test.txt

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

Find index of last occurrence of a sub-string using T-SQL

I came across this thread while searching for a solution to my similar problem which had the exact same requirement but was for a different kind of database that was also lacking the REVERSE function.

In my case this was for a OpenEdge (Progress) database, which has a slightly different syntax. This made the INSTR function available to me that most Oracle typed databases offer.

So I came up with the following code:

SELECT 
  INSTR(foo.filepath, '/',1, LENGTH(foo.filepath) - LENGTH( REPLACE( foo.filepath, '/',  ''))) AS IndexOfLastSlash 
FROM foo

However, for my specific situation (being the OpenEdge (Progress) database) this did not result into the desired behaviour because replacing the character with an empty char gave the same length as the original string. This doesn't make much sense to me but I was able to bypass the problem with the code below:

SELECT 
  INSTR(foo.filepath, '/',1, LENGTH( REPLACE( foo.filepath, '/',  'XX')) - LENGTH(foo.filepath))  AS IndexOfLastSlash 
FROM foo

Now I understand that this code won't solve the problem for T-SQL because there is no alternative to the INSTR function that offers the Occurence property.

Just to be thorough I'll add the code needed to create this scalar function so it can be used the same way like I did in the above examples.

  -- Drop the function if it already exists
  IF OBJECT_ID('INSTR', 'FN') IS NOT NULL
    DROP FUNCTION INSTR
  GO

  -- User-defined function to implement Oracle INSTR in SQL Server
  CREATE FUNCTION INSTR (@str VARCHAR(8000), @substr VARCHAR(255), @start INT, @occurrence INT)
  RETURNS INT
  AS
  BEGIN
    DECLARE @found INT = @occurrence,
            @pos INT = @start;

    WHILE 1=1 
    BEGIN
        -- Find the next occurrence
        SET @pos = CHARINDEX(@substr, @str, @pos);

        -- Nothing found
        IF @pos IS NULL OR @pos = 0
            RETURN @pos;

        -- The required occurrence found
        IF @found = 1
            BREAK;

        -- Prepare to find another one occurrence
        SET @found = @found - 1;
        SET @pos = @pos + 1;
    END

    RETURN @pos;
  END
  GO

To avoid the obvious, when the REVERSE function is available you do not need to create this scalar function and you can just get the required result like this:

SELECT
  LEN(foo.filepath) - CHARINDEX('/', REVERSE(foo.filepath))+1 AS LastIndexOfSlash 
FROM foo

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

How to convert a HTMLElement to a string

Suppose your element is entire [object HTMLDocument]. You can convert it to a String this way:

_x000D_
_x000D_
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]

const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);
_x000D_
_x000D_
_x000D_

How to check if BigDecimal variable == 0 in java?

I usually use the following:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0) { ... }

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

Struct with template variables in C++

The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")

In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.

Do it like Andrey shows.

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

Set Google Chrome as the debugging browser in Visual Studio

For MVC developers,

  • click on a folder in Solution Explorer (say, Controllers)
  • Select Browse With...
  • Select desired browser
  • (Optionally click ) set as Default

I get exception when using Thread.sleep(x) or wait()

Alternatively, if you don't want to deal with threads, try this method:

public static void pause(int seconds){
    Date start = new Date();
    Date end = new Date();
    while(end.getTime() - start.getTime() < seconds * 1000){
        end = new Date();
    }
}

It starts when you call it, and ends when the number of seconds have passed.

how to redirect to home page

strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";

Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);

Put this code in Page Load.

Decreasing height of bootstrap 3.0 navbar

Wanted to added my 2 pence and a thank you to James Poulose for his original answer it was the only one that worked for my particular project (MVC 5 with the latest version of Bootstrap 3).

This is mostly aimed at beginners, for clarity and to make future edits easier I suggest you add a section at the bottom of your CSS file for your project for example I like to do this:

/* Bootstrap overrides */

.some-class-here {
}

Taking James Poulose's answer above I did this:

/* Bootstrap overrides */   
.navbar-nav > li > a { padding-top: 8px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 8px; padding-bottom: 10px; padding-left: 10px; }

I changed the padding-top values to push the text down on my navbar element. You can pretty much override any Bootstrap element like this and its a good way of making changes without screwing up the Boostrap base classes because the last thing you want to do is make a change in there and then lose it when you updated Bootstrap!

Finally for even more separation I like to split up my CSS files and use @import declarations to import your sub-files into one main CSS File for easy management for example:

@import url('css/mysubcssfile.css');

note: if you're pulling in multiple files you need to make sure they load in the right order.

Hope this helps someone.

Really killing a process in Windows

"End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process.

If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.

Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx

Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals).

Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.

Passing functions with arguments to another function in Python?

Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.

for func in [Action1, partial(Action2, p), partial(Action3, p, r)]:
  func()

What is the most efficient way to store a list in the Django models?

Using one-to-many relation (FK from Friend to parent class) will make your app more scalable (as you can trivially extend the Friend object with additional attributes beyond the simple name). And thus this is the best way

Callback to a Fragment from a DialogFragment

I followed this simple steps to do this stuff.

  1. Create interface like DialogFragmentCallbackInterface with some method like callBackMethod(Object data). Which you would calling to pass data.
  2. Now you can implement DialogFragmentCallbackInterface interface in your fragment like MyFragment implements DialogFragmentCallbackInterface
  3. At time of DialogFragment creation set your invoking fragment MyFragment as target fragment who created DialogFragment use myDialogFragment.setTargetFragment(this, 0) check setTargetFragment (Fragment fragment, int requestCode)

    MyDialogFragment dialogFrag = new MyDialogFragment();
    dialogFrag.setTargetFragment(this, 1); 
    
  4. Get your target fragment object into your DialogFragment by calling getTargetFragment() and cast it to DialogFragmentCallbackInterface.Now you can use this interface to send data to your fragment.

    DialogFragmentCallbackInterface callback = 
               (DialogFragmentCallbackInterface) getTargetFragment();
    callback.callBackMethod(Object data);
    

    That's it all done! just make sure you have implemented this interface in your fragment.

Active Menu Highlight CSS

Maybe it is very very bad way and just for lazy person but I decided to say it.

I used PHP and bootstrap and fontawsome too

for simple I have 2 pages: 1.index and 2.create-user

put this code above your code

<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
    case "create-user":
        $a = 2;
        break;
    case "index":
        $a = 1;
        break;
    default:
        $a=1;
}
?>

and in menu you add <?php if($a==1){echo "active";} ?> in class for menu1 and for menu2 you add <?php if($a==2){echo "active";} ?>

<ul id="menu" class="navbar-nav  flex-column text-right mt-3 p-1">
                        <li class="nav-item mb-2">
                            <a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
                                        class="fas fa-home fa-lg text-light ml-3"></i>dashbord</a>
                        </li>
                        <li class="nav-item mb-2">
                            <a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
                               class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
                                <i class="fas fa-user fa-lg text-light ml-3"></i>manage users
                                <span class="float-left"><i class="fas fa-angle-down"></i></span>
                            </a>

                            <ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
                                <li class="nav-item mb-2">
                                    <a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
                                </li>

                                <li class="nav-item mb-2">
                                    <a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
                                </li>

                            </ul>
                        </li>

                    </ul>

and add in css

.customlihamid {
    transition: all .4s;
}

.customlihamid:hover {
    background-color: #8a8a8a;
    border-radius: 5px;
    color: #00cc99;
}
.nav-item > .nav-link.active  {
    background-color: #00cc99;
    border-radius: 7px;
    box-shadow: 5px 7px 10px #111;
    transition: all .3s;
}
.nav-item > .nav-link.active:hover  {
    background-color: #8eccc1;
    border-radius: 7px;
    box-shadow: 5px 7px 20px #111;
    transform: translateY(-1px);
}

and in js add

$(document).ready(function () {
   $('.navbar-nav .nav-link').click(function(){
      $('.navbar-nav .nav-link').removeClass('active');
      $(this).addClass('active');
   })
});

first check your work without js code to understand js code for what

How to set DialogFragment's width and height?

I fixed it setting the root element layout parameters.

int width = activity.getResources().getDisplayMetrics().widthPixels;
int height = activity.getResources().getDisplayMetrics().heightPixels;
content.setLayoutParams(new LinearLayout.LayoutParams(width, height));

error: pathspec 'test-branch' did not match any file(s) known to git

The modern Git should able to detect remote branches and create a local one on checkout.

However if you did a shallow clone (e.g. with --depth 1), try the following commands to correct it:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch --all

and try to checkout out the branch again.

Alternatively try to unshallow your clone, e.g. git fetch --unshallow and try again.

See also: How to fetch all remote branches?

How to use wait and notify in Java without IllegalMonitorStateException?

Let's say you have 'black box' application with some class named BlackBoxClass that has method doSomething();.

Further, you have observer or listener named onResponse(String resp) that will be called by BlackBoxClass after unknown time.

The flow is simple:

private String mResponse = null; 
 ...
BlackBoxClass bbc = new BlackBoxClass();
   bbc.doSomething();
...
@override
public void onResponse(String resp){        
      mResponse = resp;       
}

Lets say we don't know what is going on with BlackBoxClass and when we should get answer but you don't want to continue your code till you get answer or in other word get onResponse call. Here enters 'Synchronize helper':

public class SyncronizeObj {
public void doWait(long l){
    synchronized(this){
        try {
            this.wait(l);
        } catch(InterruptedException e) {
        }
    }
}

public void doNotify() {
    synchronized(this) {
        this.notify();
    }
}

public void doWait() {
    synchronized(this){
        try {
            this.wait();
        } catch(InterruptedException e) {
        }
    }
}
}

Now we can implement what we want:

public class Demo {

private String mResponse = null; 
 ...
SyncronizeObj sync = new SyncronizeObj();

public void impl(){

BlackBoxClass bbc = new BlackBoxClass();
   bbc.doSomething();

   if(mResponse == null){
      sync.doWait();
    }

/** at this momoent you sure that you got response from  BlackBoxClass because
  onResponse method released your 'wait'. In other cases if you don't want wait too      
  long (for example wait data from socket) you can use doWait(time) 
*/ 
...

}


@override
public void onResponse(String resp){        
      mResponse = resp;
      sync.doNotify();       
   }

}

Error: could not find function "%>%"

One needs to install magrittr as follows

install.packages("magrittr")

Then, in one's script, don't forget to add on top

library(magrittr)

For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?

Note that the same operator would also work with the library dplyr, as it imports from magrittr.

dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)

ImportError: No module named google.protobuf

You should run:

pip install protobuf

That will install Google protobuf and after that you can run that Python script.

As per this link.

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

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

It's easy maybe you have error in the configuration.

For Example: Manifest.xml

enter image description here

But in my configuration have for default Activity .Splash

enter image description here

you need check this configuration and the file Manifest.xml

Good Luck

Android background music service

Create a foreground service with the START_STICKY flag.

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
                   handlePauseRequest();
               }
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               }
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);
           }
       }
   }

   return START_STICKY;
}

This can then be called from any activity to play some music

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)

You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.

Here's a good tutorial about Playing music in the background on Android

How to rotate the background image in the container?

Very easy method, you rotate one way, and the contents the other. Requires a square though

#element{
    background : url('someImage.jpg');
}
#element:hover{
    transform: rotate(-30deg);
}
#element:hover >*{
    transform: rotate(30deg);
}

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

For..In loops in JavaScript - key value pairs

for (var key in myMap) {
    if (myMap.hasOwnProperty(key)) {
        console.log("key =" + key);
        console.log("value =" + myMap[key]);
    }
}

In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. The use of hasOwnProperty() filters these out.

Getting the array length of a 2D array in Java

public class Array_2D {
int arr[][];
public Array_2D() {
    Random r=new Random(10);
     arr = new int[5][10];
     for(int i=0;i<5;i++)
     {
         for(int j=0;j<10;j++)
         {
             arr[i][j]=(int)r.nextInt(10);
         }
     }
 }
  public void display()
  {
         for(int i=0;i<5;i++)

         {
             for(int j=0;j<10;j++)
             {
                 System.out.print(arr[i][j]+" "); 
             }
             System.out.println("");
         }
   }
     public static void main(String[] args) {
     Array_2D s=new Array_2D();
     s.display();
   }  
  }

Convert a list to a dictionary in Python

Something i find pretty cool, which is that if your list is only 2 items long:

ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}

Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.

Safely casting long to int in Java

DONT: This is not a solution!

My first approach was:

public int longToInt(long theLongOne) {
  return Long.valueOf(theLongOne).intValue();
}

But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.


The drawbacks

  1. Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].

  2. The intValue implementation does nothing more than:

    return (int)value;
    

So this can be considered even worse than just casting the long to int.

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

How to get the width of a react element

    class MyComponent extends Component {
      constructor(props){
        super(props)
        this.myInput = React.createRef()
      }

      componentDidMount () {
        console.log(this.myInput.current.offsetWidth)
      }

      render () {
        return (
        // new way - as of [email protected]
        <div ref={this.myInput}>some elem</div>
        // legacy way
        // <div ref={(ref) => this.myInput = ref}>some elem</div>
        )
      }
    }

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

How to read a text file in project's root directory?

From Solution Explorer, right click on myfile.txt and choose "Properties"

From there, set the Build Action to content and Copy to Output Directory to either Copy always or Copy if newer

enter image description here

List all indexes on ElasticSearch server?

Accessing the Secured Elastic Search though Curl (Update 2020)

If the Elastic Search is secured, You can use this command to list indices

curl http://username:password@localhost:9200/_aliases?pretty=true

Command to collapse all sections of code?

To collapse all use:

Ctrl + M and Ctrl+A

All shortcuts for VS 2012/2013/2015 available at http://visualstudioshortcuts.com/2013/

MongoDB and "joins"

The first example you link to shows how MongoDB references behave much like lazy loading not like a join. There isn't a query there that's happening on both collections, rather you query one and then you lookup items from another collection by reference.

Renaming part of a filename

I like to do this with sed. In you case:

for x in DET01-*.dat; do
    echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e

It is best to omit the "sh -e" part first to see what will be executed.

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

How do you find the row count for all your tables in Postgres

If you don't mind potentially stale data, you can access the same statistics used by the query optimizer.

Something like:

SELECT relname, n_tup_ins - n_tup_del as rowcount FROM pg_stat_all_tables;

Understanding string reversal via slicing

I would do it like this:

variable = "string"
message = ""
for b in variable:
    message = b+message
print (message)

and it prints: gnirts

Reset all changes after last commit in git

How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?

  1. You can undo changes to tracked files with:

    git reset HEAD --hard
    
  2. You can remove untracked files with:

    git clean -f
    
  3. You can remove untracked files and directories with:

    git clean -fd
    

    but you can't undo change to untracked files.

  4. You can remove ignored and untracked files and directories

    git clean -fdx
    

    but you can't undo change to ignored files.

You can also set clean.requireForce to false:

git config --global --add clean.requireForce false

to avoid using -f (--force) when you use git clean.

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

How to load all the images from one of my folder into my web page, using Jquery/Javascript

In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.

Date difference in minutes in Python

As was kind of said already, you need to use datetime.datetime's strptime method:

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

daysDiff = (d2-d1).days

# convert days to minutes
minutesDiff = daysDiff * 24 * 60

print minutesDiff

How can I display an RTSP video stream in a web page?

It’s not easy to display live video stream from an IP camera on a web page because you need wide internet bandwidth and a great video player that is compatible with the major browsers.

But fortunately there are some cloud based services that can do this job for us. One of the best is IPCamLive. This service can receive RTSP/H264 video stream from an IP Camera and can broadcast it to the viewers. IPCamLive has Flash/HTML5 video player component that will display the video on PC, MAC, tablet or mobile. The greatest thing is that this site generates the needed HTML snippet for embedding the live video like this:

<iframe src="http://ipcamlive.com/player/player.php?alias=szekesfehervar" width="800px" height="600px"/>

So we just need to copy paste it into our HTML file without any modification.

535-5.7.8 Username and Password not accepted

I did everything from visiting http://www.google.com/accounts/DisplayUnlockCaptcha to setting up 2-fa and creating an application password. The only thing that worked was logging into http://mail.google.com and sending an email from the server itself.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

This works for me: http://gitblit.com/setup_client.html

Eclipse/EGit/JGit

Window->Preferences->Team->Git->Configuration
Click the New Entry button

Key = http.sslVerify
Value = false

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

The request was rejected because no multipart boundary was found in springboot

This worked for me: Uploading a file via Postman, to a SpringMVC backend webapp:

Backend: Endpoint controller definition

Postman: Headers setup POST Body setup

client denied by server configuration

in my case,

i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.

Require all granted

Hope the full virtual host setup structure will save you.

<VirtualHost *:80>
    DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
    ServerName project.loc

    <Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
        Require all granted
    </Directory>

    ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
    CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common
</VirtualHost>

all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.

MySQL Database won't start in XAMPP Manager-osx

on

macOs High Sierra

if mysql is not getting started from manager- oxs and have tried direct command i.e

sudo /Applications/XAMPP/bin/mysql.server start

too than go to path edit

/Applications/XAMPP/xamppfiles/etc/

find file :

my.cnf

edit it

under the [mysqld] section, add following line:

innodb_force_recovery = 1

after it save and run or can be done from manager-osx

sudo /Applications/XAMPP/bin/mysql.server start

it should start the mysql.

once its run you need to again edit the

my.cnf

file and remove the line just added

innodb_force_recovery = 1

stop and start mysql again. by command

sudo /Applications/XAMPP/bin/mysql.server start 

or by manager-osx

it will be working fine.

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

How to make for loops in Java increase by increments other than 1

for(j = 0; j<=90; j = j+3)
{

}

j+3 will not assign the new value to j, add j=j+3 will assign the new value to j and the loop will move up by 3.

j++ is like saying j = j+1, so in that case your assigning the new value to j just like the one above.

Find the number of employees in each department - SQL Oracle

Try the query below:

select count(*),d.dname from emp e , dept d where d.deptno = e.deptno
group by d.dname

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

JQuery style display value

Just call css with one argument

  $('#idDetails').css('display');

If I understand your question. Otherwise, you want cletus' answer.

CSS scale down image to fit in containing div, without specifing original size

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>

How can I get the executing assembly version?

Two options... regardless of application type you can always invoke:

Assembly.GetExecutingAssembly().GetName().Version

If a Windows Forms application, you can always access via application if looking specifically for product version.

Application.ProductVersion

Using GetExecutingAssembly for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:

// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
    public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
    public static readonly Version Version = Reference.GetName().Version;
}

Then I can cleanly reference CoreAssembly.Version in my code as required.

Http Servlet request lose params from POST body after read it once

I found good solution for any format of request body. I tested for application/x-www-form-urlencoded and application/json both worked very well. Problem of ContentCachingRequestWrapper that is designed only for x-www-form-urlencoded request body, but not work with e.g. json. I found solution for json link. It had trouble that it didn't support x-www-form-urlencoded. I joined both in my code:

import org.apache.commons.io.IOUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyContentCachingRequestWrapper extends ContentCachingRequestWrapper {

    private byte[] body;

    public MyContentCachingRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        super.getParameterMap(); // init cache in ContentCachingRequestWrapper
        body = super.getContentAsByteArray(); // first option for application/x-www-form-urlencoded
        if (body.length == 0) {
          try {
            body = IOUtils.toByteArray(super.getInputStream()); // second option for other body formats
          } catch (IOException ex) {
            body = new byte[0];
          }
        }
    }

    public byte[] getBody() {
        return body;
    }

    @Override
    public ServletInputStream getInputStream() {
        return new RequestCachingInputStream(body);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
    }

    private static class RequestCachingInputStream extends ServletInputStream {

        private final ByteArrayInputStream inputStream;

        public RequestCachingInputStream(byte[] bytes) {
            inputStream = new ByteArrayInputStream(bytes);
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }

        @Override
        public boolean isFinished() {
            return inputStream.available() == 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readlistener) {
        }

    }

}

Where is the php.ini file on a Linux/CentOS PC?

#php -i | grep php.ini also will work too!

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Limit Decimal Places in Android EditText

Like others said, I added this class in my project and set the filter to the EditText Simpler solution without using regex:

public class DecimalDigitsInputFilter implements InputFilter {
int digitsBeforeZero =0;
int digitsAfterZero=0;

public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
this.digitsBeforeZero=digitsBeforeZero;
this.digitsAfterZero=digitsAfterZero;
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if(dest!=null && dest.toString().trim().length()<(digitsBeforeZero+digitsAfterZero)){
    String value=dest.toString().trim();
    if(value.contains(".") && (value.substring(value.indexOf(".")).length()<(digitsAfterZero+1))){
        return ((value.indexOf(".")+1+digitsAfterZero)>dstart)?null:"";
    }else if(value.contains(".") && (value.indexOf(".")<dstart)){
        return "";
    }else if(source!=null && source.equals(".")&& ((value.length()-dstart)>=(digitsAfterZero+1))){
        return "";
    }

}else{
    return "";
}
    return null;
}

}

applying filter:

edittext.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

Online Internet Explorer Simulators

Here is another idea for you. It is also online w/ no download. It uses window 7 + ie9 with no flash support though ie9 online

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In windows, you need to use double quotes "". So the command would be

git commit -m "t"

return string with first match Regex

I'd go with:

r = re.search("\d+", ch)
result = return r.group(0) if r else ""

re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

java: run a function after a specific number of seconds

ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.

Timer also has this ability but opens several thread even if used only once.

Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // The while is just to ignore interruption.
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

Test:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

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');

Simple (I think) Horizontal Line in WPF?

I had the same issue and eventually chose to use a Rectangle element:

<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4"/>

In my opinion it's somewhat easier to modify/shape than a separator. Of course the Separator is a very easy and neat solution for simple separations :)

Jquery mouseenter() vs mouseover()

The mouseenter event differs from mouseover in the way it handles event bubbling. The mouseenter event, only triggers its handler when the mouse enters the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseenter/

The mouseleave event differs from mouseout in the way it handles event bubbling. The mouseleave event, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseleave/

Can't connect to localhost on SQL Server Express 2012 / 2016

in SQL SERVER EXPRESS 2012 you should use "(localdb)\MSSQLLocalDB" as Data Source name for example you can use connection string like this

Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;

Add JsonArray to JsonObject

I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you're in a Navigation Controller:

ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

or if you just want to present a new view:

ViewController *viewController = [[ViewController alloc] init];    
[self presentViewController:viewController animated:YES completion:nil];

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Relative imports for the billionth time

To make Python not return to me "Attempted relative import in non-package". package/

init.py subpackage1/ init.py moduleX.py moduleY.py subpackage2/ init.py moduleZ.py moduleA.py

This error occurs only if you are applying relative import to the parent file. For example parent file already returns main after you code "print(name)" in moduleA.py .so THIS file is already main it cannot return any parent package further on. relative imports are required in files of packages subpackage1 and subpackage2 you can use ".." to refer to the parent directory or module .But parent is if already top level package it cannot go further above that parent directory(package). Such files where you are applying relative importing to parents can only work with the application of absolute import. If you will use ABSOLUTE IMPORT IN PARENT PACKAGE NO ERROR will come as python knows who is at the top level of package even if your file is in subpackages because of the concept of PYTHON PATH which defines the top level of the project

What represents a double in sql server?

You should map it to FLOAT(53)- that's what LINQ to SQL does.

Making a POST call instead of GET using urllib2

The requests module may ease your pain.

url = 'http://myserver/post_service'
data = dict(name='joe', age='10')

r = requests.post(url, data=data, allow_redirects=True)
print r.content

How can I use tabs for indentation in IntelliJ IDEA?

File > Settings > Editor > Code Style > Java > Tabs and Indents > Use tab character

Substitute weapon of choice for Java as required.

Pure CSS collapse/expand div

Using <summary> and <details>

Using <summary> and <details> elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.

_x000D_
_x000D_
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
  color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
  outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
  <summary>Summary, caption, or legend for the content</summary>_x000D_
  Content goes here._x000D_
</details>
_x000D_
_x000D_
_x000D_

See also how to style the <details> element (HTML5 Doctor) (little bit tricky).

Pure CSS3

The :target selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.

_x000D_
_x000D_
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
  display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
  display: block;_x000D_
}
_x000D_
<div>_x000D_
  <a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
  <a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
  <a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
  <a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

sprintf like functionality in Python

You can use string formatting:

>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'

But this is removed in Python 3, you should use "str.format()":

>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'

Checking something isEmpty in Javascript?

Check for undefined:

if (typeof response.photo == "undefined")
{
    // do something
}

This would do the equivelant of vb's IsEmpty. If myvar contains any value, even null, empty string, or 0, it is not "empty".

To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator.

if ("photo" in response)
{
    // do something
}

How to make Twitter Bootstrap menu dropdown on hover rather than click

Overwrite bootstrap.js with this script.

jQuery(document).ready(function ($) {
$('.navbar .dropdown').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

$('.dropdown-submenu').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

}); 

How to use onClick with divs in React.js

I just needed a simple testing button for react.js. Here is what I did and it worked.

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

How can I change the size of a Bootstrap checkbox?

It is possible to implement custom bootstrap checkbox for the most popular browsers nowadays.

You can check my Bootstrap-Checkbox project in GitHub, which contains simple .less file. There is a good article in MDN describing some techniques, where the two major are:

  1. Label redirects a click event.

    Label can redirect a click event to its target if it has the for attribute like in <label for="target_id">Text</label> <input id="target_id" type="checkbox" />, or if it contains input as in Bootstrap case: <label><input type="checkbox" />Text</label>.

    It means that it is possible to place a label in one corner of the browser, click on it, and then the label will redirect click event to the checkbox located in other corner producing check/uncheck action for the checkbox.

    We can hide original checkbox visually, but make it is still working and taking click event from the label. In the label itself we can emulate checkbox with a tag or pseudo-element :before :after.

  2. General non supported tag for old browsers

    Some old browsers does not support several CSS features like selecting siblings p+p or specific search input[type=checkbox]. According to the MDN article browsers that support these features also support :root CSS selector, while others not. The :root selector just selects the root element of a document, which is html in a HTML page. Thus it is possible to use :root for a fallback to old browsers and original checkboxes.

    Final code snippet:

_x000D_
_x000D_
:root {_x000D_
  /* larger checkbox */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] {_x000D_
  /* hide original check box */_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  /* find the nearest span with checkbox-placeholder class and draw custom checkbox */_x000D_
  /* draw checkmark before the span placeholder when original hidden input is checked */_x000D_
  /* disabled checkbox style */_x000D_
  /* disabled and checked checkbox style */_x000D_
  /* when the checkbox is focused with tab key show dots arround */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 14px;_x000D_
  height: 14px;_x000D_
  border: 1px solid;_x000D_
  border-radius: 3px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
  display: inline-block;_x000D_
  cursor: pointer;_x000D_
  margin: 0 7px 0 -20px;_x000D_
  vertical-align: middle;_x000D_
  text-align: center;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder {_x000D_
  background: #0ccce4;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  vertical-align: text-top;_x000D_
  width: 5px;_x000D_
  height: 9px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  /*can be done with post css autoprefixer*/_x000D_
  -webkit-transform: rotate(45deg);_x000D_
  -moz-transform: rotate(45deg);_x000D_
  -ms-transform: rotate(45deg);_x000D_
  -o-transform: rotate(45deg);_x000D_
  transform: rotate(45deg);_x000D_
  content: "";_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:disabled + span.checkbox-placeholder {_x000D_
  background: #ececec;_x000D_
  border-color: #c3c2c2;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked:disabled + span.checkbox-placeholder {_x000D_
  background: #d6d6d6;_x000D_
  border-color: #bdbdbd;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:focus:not(:hover) + span.checkbox-placeholder {_x000D_
  outline: 1px dotted black;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 26px;_x000D_
  height: 26px;_x000D_
  border: 2px solid;_x000D_
  border-radius: 5px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  width: 9px;_x000D_
  height: 15px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 3px 3px 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<p>_x000D_
 Original checkboxes:_x000D_
</p>_x000D_
<div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked_x000D_
      </label>_x000D_
 </div>_x000D_
  <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked and disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap checkbox-lg">                           _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Large checkbox unchecked_x000D_
      </label>_x000D_
 </div>_x000D_
  <br/>_x000D_
<p>_x000D_
 Inline checkboxes:_x000D_
</p>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox">_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline _x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" checked disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline checked and disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap checkbox-lg">_x000D_
  <input type="checkbox" checked>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Large inline checked_x000D_
</label>
_x000D_
_x000D_
_x000D_

When do you use map vs flatMap in RxJava?

In your case you need map, since there is only 1 input and 1 output.

map - supplied function simply accepts an item and returns an item which will be emitted further (only once) down.

flatMap - supplied function accepts an item then returns an "Observable", meaning each item of the new "Observable" will be emitted separately further down.

May be code will clear things up for you:

Observable.just("item1").map( str -> {
    System.out.println("inside the map " + str);
    return str;
}).subscribe(System.out::println);

Observable.just("item2").flatMap( str -> {
    System.out.println("inside the flatMap " + str);
    return Observable.just(str + "+", str + "++" , str + "+++");
}).subscribe(System.out::println);

Output:

inside the map item1
item1
inside the flatMap item2
item2+
item2++
item2+++

How to determine the version of android SDK installed in computer?

Type in android list target into your command line to see what android API you are using.

Mark error in form using Bootstrap

Bootstrap V3:

Official Doc Link 1
Official Doc Link 2

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess" />
  <span class="help-block">Woohoo!</span>
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
  <span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

Smooth scrolling when clicking an anchor link

This solution will also work for the following URLs, without breaking anchor links to different pages.

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

etc.

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

I haven't tested this in all browsers, yet.

Why do we need the "finally" clause in Python?

It makes a difference if you return early:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   # The finally block is run before the method returns
finally:
    other_code()

Compare to this:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   

other_code()  # This doesn't get run if there's an exception.

Other situations that can cause differences:

  • If an exception is thrown inside the except block.
  • If an exception is thrown in run_code1() but it's not a TypeError.
  • Other control flow statements such as continue and break statements.

Get Cell Value from a DataTable in C#

You can call the indexer directly on the datatable variable as well:

var cellValue = dt[i].ColumnName

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Can you write nested functions in JavaScript?

Is this really possible.

Yes.

_x000D_
_x000D_
function a(x) {    // <-- function_x000D_
  function b(y) { // <-- inner function_x000D_
    return x + y; // <-- use variables from outer scope_x000D_
  }_x000D_
  return b;       // <-- you can even return a function._x000D_
}_x000D_
console.log(a(3)(4));
_x000D_
_x000D_
_x000D_

Cast received object to a List<object> or IEnumerable<object>

C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like

IList collection = (IList)myObject;

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

Javascript Array.sort implementation?

There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays.

V8 Engine Source

From Lines 807 - 891

  var QuickSort = function QuickSort(a, from, to) {
    var third_index = 0;
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
      }
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
      // Find a pivot as the median of first, last and middle element.
      var v0 = a[from];
      var v1 = a[to - 1];
      var v2 = a[third_index];
      var c01 = comparefn(v0, v1);
      if (c01 > 0) {
        // v1 < v0, so swap them.
        var tmp = v0;
        v0 = v1;
        v1 = tmp;
      } // v0 <= v1.
      var c02 = comparefn(v0, v2);
      if (c02 >= 0) {
        // v2 <= v0 <= v1.
        var tmp = v0;
        v0 = v2;
        v2 = v1;
        v1 = tmp;
      } else {
        // v0 <= v1 && v0 < v2
        var c12 = comparefn(v1, v2);
        if (c12 > 0) {
          // v0 <= v2 < v1
          var tmp = v1;
          v1 = v2;
          v2 = tmp;
        }
      }
      // v0 <= v1 <= v2
      a[from] = v0;
      a[to - 1] = v2;
      var pivot = v1;
      var low_end = from + 1;   // Upper bound of elements lower than pivot.
      var high_start = to - 1;  // Lower bound of elements greater than pivot.
      a[third_index] = a[low_end];
      a[low_end] = pivot;

      // From low_end to i are elements equal to pivot.
      // From i to high_start are elements that haven't been compared yet.
      partition: for (var i = low_end + 1; i < high_start; i++) {
        var element = a[i];
        var order = comparefn(element, pivot);
        if (order < 0) {
          a[i] = a[low_end];
          a[low_end] = element;
          low_end++;
        } else if (order > 0) {
          do {
            high_start--;
            if (high_start == i) break partition;
            var top_elem = a[high_start];
            order = comparefn(top_elem, pivot);
          } while (order > 0);
          a[i] = a[high_start];
          a[high_start] = element;
          if (order < 0) {
            element = a[i];
            a[i] = a[low_end];
            a[low_end] = element;
            low_end++;
          }
        }
      }
      if (to - high_start < low_end - from) {
        QuickSort(a, high_start, to);
        to = low_end;
      } else {
        QuickSort(a, from, low_end);
        from = high_start;
      }
    }
  };

Update As of 2018 V8 uses TimSort, thanks @celwell. Source

How to make scipy.interpolate give an extrapolated result beyond the input range?

1. Constant extrapolation

You can use interp function from scipy, it extrapolates left and right values as constant beyond the range:

>>> from scipy import interp, arange, exp
>>> x = arange(0,10)
>>> y = exp(-x/3.0)
>>> interp([9,10], x, y)
array([ 0.04978707,  0.04978707])

2. Linear (or other custom) extrapolation

You can write a wrapper around an interpolation function which takes care of linear extrapolation. For example:

from scipy.interpolate import interp1d
from scipy import arange, array, exp

def extrap1d(interpolator):
    xs = interpolator.x
    ys = interpolator.y

    def pointwise(x):
        if x < xs[0]:
            return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
        elif x > xs[-1]:
            return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
        else:
            return interpolator(x)

    def ufunclike(xs):
        return array(list(map(pointwise, array(xs))))

    return ufunclike

extrap1d takes an interpolation function and returns a function which can also extrapolate. And you can use it like this:

x = arange(0,10)
y = exp(-x/3.0)
f_i = interp1d(x, y)
f_x = extrap1d(f_i)

print f_x([9,10])

Output:

[ 0.04978707  0.03009069]

How to show the text on a ImageButton?

Actually, android:text is not an argument accepted by ImageButton but, If you're trying to get a button with a specified background (not android default) use the android:background xml attribute, or declare it from the class with .setBackground();

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Ascii/Hex convert in bash

Finally got the correct thing

echo "Hello, world!" | tr -d '\n' | xxd -ps -c 200

Python: How would you save a simple settings/config file?

ConfigParser Basic example

The file can be loaded and used like this:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

which outputs

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

Writing configuration

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

results in

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML Basic example

Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

where the config.xml might look like this

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

Is there any good dynamic SQL builder library in Java?

Hibernate Criteria API (not plain SQL though, but very powerful and in active development):

List sales = session.createCriteria(Sale.class)
         .add(Expression.ge("date",startDate);
         .add(Expression.le("date",endDate);
         .addOrder( Order.asc("date") )
         .setFirstResult(0)
         .setMaxResults(10)
         .list();

Using jQuery to center a DIV on the screen

I would recommend jQueryUI Position utility

$('your-selector').position({
    of: $(window)
});

which gives you much more possibilities than only centering ...

Why is Android Studio reporting "URI is not registered"?

Ran into this recently trying to migrating an existing app to material design. All I had to do to fix it was change the project's Compile SDK Version. File | Project Settings. Select app and pick a Compile SDK version for Lollipop or higher.

Converting a Uniform Distribution to a Normal Distribution

The Ziggurat algorithm is pretty efficient for this, although the Box-Muller transform is easier to implement from scratch (and not crazy slow).

What is TypeScript and why would I use it in place of JavaScript?

TypeScript does something similar to what less or sass does for CSS. They are super sets of it, which means that every JS code you write is valid TypeScript code. Plus you can use the other goodies that it adds to the language, and the transpiled code will be valid js. You can even set the JS version that you want your resulting code on.

Currently TypeScript is a super set of ES2015, so might be a good choice to start learning the new js features and transpile to the needed standard for your project.

linq query to return distinct field values from a list of objects

I wanted to bind a particular data to dropdown and it should be distinct. I did the following:

List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

Uncaught SyntaxError: Unexpected token < On Chrome

I faced similar issue when I moved some of the js files into folders then deployed into production, after some struggle I found out that the js files were not actually got deployed to production. So

  1. make sure that the file for which the error is shown does exist in the server
  2. the path given is correct

So, In the absence of js file, the server then server responds with as below

<!doctype html>
    <html>
        <someTag />
        <AnotherTag />
    </html>

Thats why we get Uncaught SyntaxError: Unexpected token <

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

Got it! Solved the issue modifying the user properties in security session of SQL Server. In SQL Server Management, go into security -> Logon -> Choose the user used for DB connection and go into his properties. Go to "Securators" tab and look for line "Connect SQL", mark "Grant" option and take a try. It works for me!

Regards

When should use Readonly and Get only properties

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

How to get screen width without (minus) scrollbar?

You can use vanilla javascript by simply writing:

var width = el.clientWidth;

You could also use this to get the width of the document as follows:

var docWidth = document.documentElement.clientWidth || document.body.clientWidth;

Source: MDN

You can also get the width of the full window, including the scrollbar, as follows:

var fullWidth = window.innerWidth;

However this is not supported by all browsers, so as a fallback, you may want to use docWidth as above, and add on the scrollbar width.

Source: MDN

How to use vim in the terminal?

You can definetely build your code from Vim, that's what the :make command does.

However, you need to go through the basics first : type vimtutor in your terminal and follow the instructions to the end.

After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.

For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.

In a few months you'll find yourself hitting o, v and i all the time in every textfield everywhere.

Have fun!

Spring schemaLocation fails when there is no internet connection

If you are using eclipse for your development , it helps if you install STS plugin for Eclipse [ from the marketPlace for the specific version of eclipse .

Now When you try to create a new configuration file in a folder(normally resources) inside the project , the options would have a "Spring Folder" and you can choose a "Spring Bean Definition File " option Spring > Spring Bean Configuation File .

With this option selected , when you follow steps , it asks you to select for namespaces and the specific versions :

And so the possibility of having a non-existent jar Or old version can be eliminated .

Would have posted images as well , but my reputation is pretty low.. :(

Disable beep of Linux Bash on Windows 10

@Andrea Tulimiero 's answer works for local, but when you ssh to a remote server, the beep turns on again. My suggestion is to disable from the Windows 10 taskbar. There is volume mixer in the right bottom corner, which works for me.

MYSQL query between two timestamps

You just need to convert your dates to UNIX_TIMESTAMP. You can write your query like this:

SELECT *
FROM eventList
WHERE
  date BETWEEN
      UNIX_TIMESTAMP('2013/03/26')
      AND
      UNIX_TIMESTAMP('2013/03/27 23:59:59');

When you don't specify the time, MySQL will assume 00:00:00 as the time for the given date.

Is key-value pair available in Typescript?

Not for the questioner, but for all others, which are interested: See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The solution is therefore:

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

Cheers!

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

Return only string message from Spring MVC 3 Controller

Simplest solution:

Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.

@PostMapping("/create")
public String foo()
{
    String result = "something"
    return "\"" + result + "\"";
}

How to initialize all the elements of an array to any specific value in java

Using Java 8, you can simply use ncopies of Collections class:

Object[] arrays = Collections.nCopies(size, object).stream().toArray();

In your case it will be:

Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.

Here is a detailed answer of a similar case of yours.

Calling a parent window function from an iframe

While some of these solutions may work, none of them follow best practices. Many assign global variables and you may find yourself making calls to multiple parent variables or functions, leading to a cluttered, vulnerable namespace.

To avoid this, use a module pattern. In the parent window:

var myThing = {
    var i = 0;
    myFunction : function () {
        // do something
    }
};

var newThing = Object.create(myThing);

Then, in the iframe:

function myIframeFunction () {
    parent.myThing.myFunction();
    alert(parent.myThing.i);
};

This is similar to patterns described in the Inheritance chapter of Crockford's seminal text, "Javascript: The Good Parts." You can also learn more at w3's page for Javascript's best practices. https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals

jQuery - Increase the value of a counter when a button is clicked

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

React ignores 'for' attribute of the label element

Yes, for react,

for becomes htmlFor

class becomes className

etc.

see full list of how HTML attributes are changed here:

https://facebook.github.io/react/docs/dom-elements.html

How to use a variable in the replacement side of the Perl substitution operator?

I'm not certain on what it is you're trying to achieve. But maybe you can use this:

$var =~ s/^start/foo/;
$var =~ s/end$/bar/;

I.e. just leave the middle alone and replace the start and end.

Git Pull is Not Possible, Unmerged Files

If you ever happen to get this issue after running a git fetch and then git is not allowing you to run git pull because of a merge conflict (both modified / unmerged files, and to make you more frustrated, it won't show you any conflict markers in the file since it's not yet merged). If you do not wish to lose your work, you can do the following.

stage the file.

$ git add filename

then stash the local changes.

$ git stash

pull and update your working directory

$ git pull

restore your local modified file (git will automatically merge if it can, otherwise resolve it)

$ git stash pop

Hope it will help.

Removing unwanted table cell borders with CSS

You need to add this to your CSS:

table { border-collapse:collapse }

Getting next element while cycling through a list

Use the zip method in Python. This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         

Reset local repository branch to be just like remote repository HEAD

If you don't mind saving your local changes, yet still want to update your repository to match origin/HEAD, you can simply stash your local changes and then pull:

git stash
git pull

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

How to edit a JavaScript alert box title?

To answer the questions in terms of how you asked it.

This is actually REALLY easy (in Internet Explorer, at least), i did it in like 17.5 seconds.

If you use the custom script that cxfx provided: (place it in your apsx file)

<script language="VBScript">
Sub myAlert(title, content)
MsgBox content, 0, title 
End Sub 
</script>

You can then call it just like you called the regular alert. Just modify your code to the following.

Response.Write("<script language=JavaScript> myAlert('Message Header Here','Hi select a valid date'); </script>");

Hope that helps you, or someone else!

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

Convert an integer to a float number

There is no float type. Looks like you want float64. You could also use float32 if you only need a single-precision floating point value.

package main

import "fmt"

func main() {
    i := 5
    f := float64(i)
    fmt.Printf("f is %f\n", f)
}

Set LIMIT with doctrine 2?

 $qb = $this->getDoctrine()->getManager()->createQueryBuilder();  
 $qb->select('p') ->from('Pandora\UserBundle\Entity\PhoneNumber', 'p');
$qb->where('p.number = :number');
$qb->OrWhere('p.validatedNumber=:number');
$qb->setMaxResults(1);
$qb->setParameter('number',$postParams['From'] );
$result = $qb->getQuery()->getResult();
 $data=$result[0];

how to get the value of a textarea in jquery?

all Values is always taken with .val().

see the code bellow:

var message = $('#message').val();

How to create windows service from java jar?

With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:

set PR_PATH=%CD%
SET PR_SERVICE_NAME=MyService
SET PR_JAR=MyService.jar
SET START_CLASS=org.my.Main
SET START_METHOD=main
SET STOP_CLASS=java.lang.System
SET STOP_METHOD=exit
rem ; separated values
SET STOP_PARAMS=0
rem ; separated values
SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%

I presume to

  • run this from the same directory where the jar and prunsrv.exe is
  • the jar has its working MANIFEST.MF
  • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
  • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

Check the procrun manual and this tutorial for more information.

jQuery - selecting elements from inside a element

Why not just use:

$("#foo span")

or

$("#foo > span")

$('span', $('#foo')); works fine on my machine ;)

How to sort with a lambda?

To much code, you can use it like this:

#include<array>
#include<functional>

int main()
{
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

    std::sort(std::begin(vec), 
              std::end(vec), 
              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;
}

Replace "vec" with your class and that's it.

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

How to remove first 10 characters from a string?

Use substring method.

string s = "hello world";
s=s.Substring(10, s.Length-10);

Where IN clause in LINQ

This expression should do what you want to achieve.

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))

Add a list item through javascript

I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...

var firstname = $('#firstname').val();

$('ol').append( '<li>' + firstname + '</li>' );

Store the firstname value and then use append to add that value as an li to the ol. I hope this helps :)

Html.RenderPartial() syntax with Razor

If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.

CONVERT Image url to Base64

imageToBase64 = (URL) => {
    let image;
    image = new Image();
    image.crossOrigin = 'Anonymous';
    image.addEventListener('load', function() {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 0, 0);
        try {
            localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
        } catch (err) {
            console.error(err)
        }
    });
    image.src = URL;
};

imageToBase64('image URL')

Change Background color (css property) using Jquery

$("#co").click(function(){
   $(this).css({"backgroundColor" : "blue"});
});

Generating random, unique values C#

You could also use a dataTable storing each random value, then simply perform the random method while != values in the dataColumn

How can I select the row with the highest ID in MySQL?

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

Assembly code vs Machine code vs Object code?

8B 5D 32 is machine code

mov ebx, [ebp+32h] is assembly

lmylib.so containing 8B 5D 32 is object code

Setting onClickListener for the Drawable right of an EditText

This has been already answered but I tried a different way to make it simpler.

The idea is using putting an ImageButton on the right of EditText and having negative margin to it so that the EditText flows into the ImageButton making it look like the Button is in the EditText.

enter image description here

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Pin"
            android:singleLine="true"
            android:textSize="25sp"
            android:paddingRight="60dp"
            />
        <ImageButton
            android:id="@+id/pastePin"
            android:layout_marginLeft="-60dp"
            style="?android:buttonBarButtonStyle"
            android:paddingBottom="5dp"
            android:src="@drawable/ic_action_paste"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

Also, as shown above, you can use a paddingRight of similar width in the EditText if you don't want the text in it to be flown over the ImageButton.

I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton and set the margin programatically.

Select all 'tr' except the first one

You could create a class and use the class when you define all of your future 's that you want (or don't want) to be selected by the CSS.

This would be done by writing

<tr class="unselected">

and then in your css having the lines (and using the text-align command as an example) :

unselected {
  text-align:center;
}



selected {
  text-align:right;
}

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

How do I configure PyCharm to run py.test tests?

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the 'unittests' test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

How to find text in a column and saving the row number where it is first found - Excel VBA

A few comments:

  1. Since the search position is important you should specify where you start the search. I use ws.[a1] and xlNext below so my search starts in A2 of the specified sheet.
  2. Some of Finds arguments - including lookat use the prior search settings. So you should always specify xlWhole or xlPart to match all or part a string respectively.
  3. You can do all you want - including inserting a row, and prompting the user for a new value (my code will suggest 20 if the prior value was 19) without using Select or Activate

suggested code

Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub

How to mock a final class with mockito

Yes same problem here, we cannot mock a final class with Mockito. To be accurate, Mockito cannot mock/spy following:

  • final classes
  • anonymous classes
  • primitive types

But using a wrapper class seems to me a big price to pay, so get PowerMockito instead.

How to close a JavaFX application on window close?

For me only following is working:

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {

        Platform.exit();

        Thread start = new Thread(new Runnable() {
            @Override
            public void run() {
                //TODO Auto-generated method stub
                system.exit(0);     
            }
        });

        start.start();
    }
});

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Just had this in VS 2010.

Fixed by editing the .sln file and changing the TargetFrameworkMoniker to have the value ".NETFramework,Version%3Dv4.0" assigned to it.

pip3: command not found

Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage. This worked well for me when I had trouble with pip.

How to check if a network port is open on linux?

If you only care about the local machine, you can rely on the psutil package. You can either:

  1. Check all ports used by a specific pid:

    proc = psutil.Process(pid)
    print proc.connections()
    
  2. Check all ports used on the local machine:

    print psutil.net_connections()
    

It works on Windows too.

https://github.com/giampaolo/psutil