Programs & Examples On #Circular list

In a circularly linked list, all nodes are linked in a continuous circle, without using null. For lists with a front and a back (such as a queue), one stores a reference to the last node in the list.

Vue - Deep watching an array of objects and calculating the change?

I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

new Vue({
  methods: {
    setValue: function() {
      this.$data.oldPeople = _.cloneDeep(this.$data.people);
    },
  },
  mounted() {
    this.setValue();
  },
  el: '#app',
  data: {
    people: [
      {id: 0, name: 'Bob', age: 27},
      {id: 1, name: 'Frank', age: 32},
      {id: 2, name: 'Joe', age: 38}
    ],
    oldPeople: []
  },
  watch: {
    people: {
      handler: function (after, before) {
        // Return the object that changed
        var vm = this;
        let changed = after.filter( function( p, idx ) {
          return Object.keys(p).some( function( prop ) {
            return p[prop] !== vm.$data.oldPeople[idx][prop];
          })
        })
        // Log it
        vm.setValue();
        console.log(changed)
      },
      deep: true,
    }
  }
})

See the updated codepen

How can I initialize a MySQL database with schema in a Docker container?

After Aug. 4, 2015, if you are using the official mysql Docker image, you can just ADD/COPY a file into the /docker-entrypoint-initdb.d/ directory and it will run with the container is initialized. See github: https://github.com/docker-library/mysql/commit/14f165596ea8808dfeb2131f092aabe61c967225 if you want to implement it on other container images

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

How do I read / convert an InputStream into a String in Java?

Use:

InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;

while ((read=br.readLine()) != null) {
    //System.out.println(read);
    sb.append(read);
}

br.close();
return sb.toString();

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

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

I have same idea with user KM. but do not need extra table Number. Just this function only.

CREATE FUNCTION [dbo].[FN_ListToTable]
(
    @SplitOn              char(1)              --REQUIRED, the character to split the @List string on
   ,@List                 varchar(8000)        --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
    ListValue varchar(500)
)
AS
BEGIN
    DECLARE @number int = 0
    DECLARE @childString varchar(502) = ''
    DECLARE @lengthChildString int = 0
    DECLARE @processString varchar(502) = @SplitOn + @List + @SplitOn

    WHILE @number < LEN(@processString)
    BEGIN
        SET @number = @number + 1
        SET @lengthChildString = CHARINDEX(@SplitOn, @processString, @number + 1) - @number - 1
        IF @lengthChildString > 0
        BEGIN
            SET @childString = LTRIM(RTRIM(SUBSTRING(@processString, @number + 1, @lengthChildString)))

            IF @childString IS NOT NULL AND @childString != ''
            BEGIN
                INSERT INTO @ParsedList(ListValue) VALUES (@childString)
                SET @number = @number + @lengthChildString - 1
            END
        END
    END

RETURN

END

And here is the test:

SELECT ListValue FROM dbo.FN_ListToTable('/','a/////bb/c')

Result:

   ListValue
______________________
   a
   bb
   c

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:

File Source control > Advanced > Exclude web.config from source control

... and boom; your file is permanently excluded from source control.

member names cannot be the same as their enclosing type C#

Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.

Is there a Mutex in Java?

Mistake in original post is acquire() call set inside the try loop. Here is a correct approach to use "binary" semaphore (Mutex):

semaphore.acquire();
try {
   //do stuff
} catch (Exception e) {
   //exception stuff
} finally {
   semaphore.release();
}

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

After all else failed...

My solution was to change the layout file from

= stylesheet_link_tag "reset-min", 'application'

to

= stylesheet_link_tag 'application'

And it worked! (You can put the reset file inside the manifest.)

How to get the containing form of an input?

function doSomething(element) {
  var form = element.form;
}

and in the html, you need to find that element, and add the attribut "form" to connect to that form, please refer to http://www.w3schools.com/tags/att_input_form.asp but this form attr doesn't support IE, for ie, you need to pass form id directly.

Check if PHP session has already started

@ before a function call suppresses any errors that may be reported during the function call.

Adding a @ before session_start tells PHP to avoid printing error messages.

For example:

Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start() will still fail in this case, but the error message is not printed on screen.

Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.

This code can be used in all cases:


    <?php 
        if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
            session_start(); 
        }
    ?>

What's a Good Javascript Time Picker?

Sorry guys.. maybe it's a bit late.. I've been using NoGray.. it's cool..

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')

How can I determine whether a specific file is open in Windows?

One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:

c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
   10: File  (RW-)   C:\Windows
   1C: File  (RW-)   D:\some\locked\path\OpenFile.txt
[...]

c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls

  Base        Size      Version         Path
  0x00400000  0x29000   2.25.0000.0000  D:\opt\SysinternalsSuite\Listdlls.exe
  0x76ed0000  0x180000  6.01.7601.17725  C:\Windows\SysWOW64\ntdll.dll
[...]

c:\SysInternals>listdlls

Unfortunately, you have to "run as Administrator" to be able to use them.

Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename> should get you very close with both utilities, though

c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
  188: File  (RW-)   D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]

Here we can see that gvim.exe is the one having this file open.

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

What is an efficient way to implement a singleton pattern in Java?

There are four ways to create a singleton in Java.

  1. Eager initialization singleton

     public class Test {
         private static final Test test = new Test();
    
         private Test() {
         }
    
         public static Test getTest() {
             return test;
         }
     }
    
  2. Lazy initialization singleton (thread safe)

     public class Test {
          private static volatile Test test;
    
          private Test() {
          }
    
          public static Test getTest() {
             if(test == null) {
                 synchronized(Test.class) {
                     if(test == null) {
                         test = new Test();
                     }
                 }
             }
             return test;
         }
     }
    
  3. Bill Pugh singleton with holder pattern (preferably the best one)

     public class Test {
    
         private Test() {
         }
    
         private static class TestHolder {
             private static final Test test = new Test();
         }
    
         public static Test getInstance() {
             return TestHolder.test;
         }
     }
    
  4. Enum singleton

     public enum MySingleton {
         INSTANCE;
    
         private MySingleton() {
             System.out.println("Here");
         }
     }
    

'dependencies.dependency.version' is missing error, but version is managed in parent

What just worked for was to delete the settings.xml in the .m2 folder: this file was telling the project to look for a versión of spring mvc and web that didn't exist.

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

AngularJS sorting by property

Here is what i did and it works.
I just used a stringified object.

$scope.thread = [ 
  {
    mostRecent:{text:'hello world',timeStamp:12345678 } 
    allMessages:[]
  }
  {MoreThreads...}
  {etc....}
]

<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >

if i wanted to sort by text i would do

orderBy : 'mostRecent.text'

How to generate a random number between a and b in Ruby?

rand(3..10)

Kernel#rand

When max is a Range, rand returns a random number where range.member?(number) == true.

PowerShell equivalent to grep -f

but select-String doesn't seem to have this option.

Correct. PowerShell is not a clone of *nix shells' toolset.

However it is not hard to build something like it yourself:

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

What is an Android PendingIntent?

In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent class.

And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent is, and that was the thing gave me the big picture of this.

Below is just transcription of above video (from 15:24).

So what's a pending intent?

It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.

This explanation becomes more clear with this snippet of code(which is included in the session's slide).

PendingIntent mIntent = PendingIntent.getService(...);

mLocationClient.requestLocationUpdates(locationRequest, mIntent);

public void onHandleIntent(Intent intent) {   
    String action = intent.getAction();   
    if (ACTION_LOCATION.equals(action)) {       
        Location location = intent.getParcelableExtra(...)   
    }
}

MySQL - how to front pad zip code with "0"?

CHAR(5)

or

MEDIUMINT (5) UNSIGNED ZEROFILL

The first takes 5 bytes per zip code.

The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.

Writing a Python list of lists to a csv file

You could use pandas:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

What's the -practical- difference between a Bare and non-Bare repository?

This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).

Using Git Bash just try:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/

me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 .git/

me@pc MINGW64 /c/Test (master)
$ cd .git

me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr  1 11:35 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:35 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:35 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 objects/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 refs/

Same with git --bare:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/

me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr  1 11:36 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:36 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:36 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 objects/

Server certificate verification failed: issuer is not trusted

If you are using svn with Jenkins on a Windows Server, you must accept https certificate using the same Jenkins's Windows service user.
So , if your Jenkins service runs as "MYSERVER\Administrator", you must use this command before all others, only one time of course :

runas /user:MYSERVER\Administrator "svn --username user --password password list https://myserver/svn/REPO "

svn asks you to accept the certificate and stores it in the right path.

After this you'll be able to use svn in jenkins job directly in a Windows batch command step.

bash string compare to multiple correct values

Here's my solution

if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

What's the easiest way to install a missing Perl module?

Many times it does happen that cpan install command fails with the message like "make test had returned bad status, won't install without force"

In that case following is the way to install the module:

perl -MCPAN -e "CPAN::Shell->force(qw(install Foo::Bar));"

How to get the caller class in Java

To get caller/called class name use below code, it works fine for me.

String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();

Create an Array of Arraylists

As per Oracle Documentation:

"You cannot create arrays of parameterized types"

Instead, you could do:

ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);

As suggested by Tom Hawting - tackline, it is even better to do:

List<List<Individual>> group = new ArrayList<List<Individual>>(4);

Initializing a static std::map<int, int> in C++

For example:

const std::map<LogLevel, const char*> g_log_levels_dsc =
{
    { LogLevel::Disabled, "[---]" },
    { LogLevel::Info,     "[inf]" },
    { LogLevel::Warning,  "[wrn]" },
    { LogLevel::Error,    "[err]" },
    { LogLevel::Debug,    "[dbg]" }
};

If map is a data member of a class, you can initialize it directly in header by the following way (since C++17):

// Example

template<>
class StringConverter<CacheMode> final
{
public:
    static auto convert(CacheMode mode) -> const std::string&
    {
        // validate...
        return s_modes.at(mode);
    }

private:
    static inline const std::map<CacheMode, std::string> s_modes =
        {
            { CacheMode::All, "All" },
            { CacheMode::Selective, "Selective" },
            { CacheMode::None, "None" }
            // etc
        };
}; 

What is the Simplest Way to Reverse an ArrayList?

A little more readable :)

public static <T> ArrayList<T> reverse(ArrayList<T> list) {
    int length = list.size();
    ArrayList<T> result = new ArrayList<T>(length);

    for (int i = length - 1; i >= 0; i--) {
        result.add(list.get(i));
    }

    return result;
}

Twitter Bootstrap carousel different height images cause bouncing arrows

 .className{
 width: auto;
  height: 200px;
  max-height: 200px;
   max-width:200px
   object-fit: contain;
}

How to create Python egg file

For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.

python myapp.zip

Where myapp.zip is a zip containing a __main__.py file which is executed as the script file to be executed. Your package dependencies can also be included in the file:

__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py

You can also execute an egg, but the incantation is not as nice:

# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows 
set PYTHONPATH=myapp.egg
python -m myapp

This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:

myapp/__init__.py
myapp/somelibfile.py

And python will run __init__.py (you should check that __file__=='__main__' in your app for command line use).

Egg files are just zip files so you might be able to add __main__.py to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg instead of the above incantation where the PYTHONPATH environment variable is set.

More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to get the scroll bar with CSS overflow on iOS

::-webkit-scrollbar {
    width: 15px;
    height: 15px;
}

::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #C3C3C3;
    border: 2px solid #eee;
}

Use this code, it work in ios/android APP webview; It delete some not portable css code;

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

How to ignore SSL certificate errors in Apache HttpClient 4.0

If all you want to do is get rid of invalid hostname errors you can just do:

HttpClient httpClient = new DefaultHttpClient();
SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
    .getSchemeRegistry().getScheme("https").getSocketFactory();
sf.setHostnameVerifier(new AllowAllHostnameVerifier());

Check if a string is a valid date using DateTime.TryParse

Use DateTime.TryParseExact() if you want to match against a specific date format

 string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
{
    Console.WriteLine(dateTime);
}
else
{
    Console.WriteLine("Not a date");
}

How to get Exception Error Code in C#

You should look at the members of the thrown exception, particularly .Message and .InnerException.

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

adding noise to a signal in python

AWGN Similar to Matlab Function

def awgn(sinal):
    regsnr=54
    sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
    sigpower=sigpower/len(sinal)
    noisepower=sigpower/(math.pow(10,regsnr/10))
    noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
    return noise

Codeigniter - no input file specified

I found the answer to this question here..... The problem was hosting server... I thank all who tried .... Hope this will help others

Godaddy Installation Tips

Pandas How to filter a Series

In my case I had a panda Series where the values are tuples of characters:

Out[67]
0    (H, H, H, H)
1    (H, H, H, T)
2    (H, H, T, H)
3    (H, H, T, T)
4    (H, T, H, H)

Therefore I could use indexing to filter the series, but to create the index I needed apply. My condition is "find all tuples which have exactly one 'H'".

series_of_tuples[series_of_tuples.apply(lambda x: x.count('H')==1)]

I admit it is not "chainable", (i.e. notice I repeat series_of_tuples twice; you must store any temporary series into a variable so you can call apply(...) on it).

There may also be other methods (besides .apply(...)) which can operate elementwise to produce a Boolean index.

Many other answers (including accepted answer) using the chainable functions like:

  • .compress()
  • .where()
  • .loc[]
  • []

These accept callables (lambdas) which are applied to the Series, not to the individual values in those series!

Therefore my Series of tuples behaved strangely when I tried to use my above condition / callable / lambda, with any of the chainable functions, like .loc[]:

series_of_tuples.loc[lambda x: x.count('H')==1]

Produces the error:

KeyError: 'Level H must be same as name (None)'

I was very confused, but it seems to be using the Series.count series_of_tuples.count(...) function , which is not what I wanted.

I admit that an alternative data structure may be better:

  • A Category datatype?
  • A Dataframe (each element of the tuple becomes a column)
  • A Series of strings (just concatenate the tuples together):

This creates a series of strings (i.e. by concatenating the tuple; joining the characters in the tuple on a single string)

series_of_tuples.apply(''.join)

So I can then use the chainable Series.str.count

series_of_tuples.apply(''.join).str.count('H')==1

How to do while loops with multiple conditions

use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

How to find file accessed/created just few minutes ago

If you know the file is in your current directory, I would use:

ls -lt | head

This lists your most recently modified files and directories in order. In fact, I use it so much I have it aliased to 'lh'.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Shortcut to open file in Vim

In GVIM, The file can be browsed using open / read / write dialog;

:browse {command}

{command} - open / read / write

open - Opens the file read - Appends the file write - SaveAs dialog

Check if two unordered lists are equal

sorted(x) == sorted(y)

Copying from here: Check if two unordered lists are equal

I think this is the best answer for this question because

  1. It is better than using counter as pointed in this answer
  2. x.sort() sorts x, which is a side effect. sorted(x) returns a new list.

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

Using Mysql WHERE IN clause in codeigniter

$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query =  $this->db->get();
return $query->result_array();

AWS : The config profile (MyName) could not be found

In my case, I had the variable named "AWS_PROFILE" on Environment variables with an old value.

enter image description here

How to upgrade Angular CLI project?

Solution that worked for me:

  • Delete node_modules and dist folder
  • (in cmd)>> ng update --all --force
  • (in cmd)>> npm install typescript@">=3.4.0 and <3.5.0" --save-dev --save-exact
  • (in cmd)>> npm install --save core-js
  • Commenting import 'core-js/es7/reflect'; in polyfill.ts
  • (in cmd)>> ng serve

Found shared references to a collection org.hibernate.HibernateException

Consider an entity:

public class Foo{
private<user> user;
/* with getters and setters */
}

And consider an Business Logic class:

class Foo1{
List<User> user = new ArrayList<>();
user = foo.getUser();
}

Here the user and foo.getUser() share the same reference. But saving the two references creates a conflict.

The proper usage should be:

class Foo1 {
List<User> user = new ArrayList<>();
user.addAll(foo.getUser);
}

This avoids the conflict.

MVC 5 Access Claims Identity User Data

Try this:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

How to COUNT rows within EntityFramework without loading contents?

Well, even the SELECT COUNT(*) FROM Table will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).

Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:

SELECT 
    SUM(used_page_count) * 8 AS SizeKB,
    SUM(row_count) AS [RowCount], 
    OBJECT_NAME(OBJECT_ID) AS TableName
FROM 
    sys.dm_db_partition_stats
WHERE 
    OBJECT_ID = OBJECT_ID('YourTableNameHere')
    AND (index_id = 0 OR index_id = 1)
GROUP BY 
    OBJECT_ID

This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).

It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).

Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.

Marc

How do I cancel a build that is in progress in Visual Studio?

Ctrl + Break works, but only if the Build window is active. Also, interrupting the build will sometimes leave a corrupted .obj file that will have to be manually deleted in order for the build to proceed.

When using a Settings.settings file in .NET, where is the config actually stored?

It is in a folder with your application's name in Application Data folder in User's home folder (C:\documents and settings\user on xp and c:\users\user on Windows Vista).

There is some information here also.

PS:- try accessing it by %appdata% in run box!

How to get the directory of the currently running file?

os.Executable: https://tip.golang.org/pkg/os/#Executable

filepath.EvalSymlinks: https://golang.org/pkg/path/filepath/#EvalSymlinks

Full Demo:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    var dirAbsPath string
    ex, err := os.Executable()
    if err == nil {
        dirAbsPath = filepath.Dir(ex)
        fmt.Println(dirAbsPath)
        return
    }

    exReal, err := filepath.EvalSymlinks(ex)
    if err != nil {
        panic(err)
    }
    dirAbsPath = filepath.Dir(exReal)
    fmt.Println(dirAbsPath)
}

How to append output to the end of a text file

I'd suggest you do two things:

  1. Use >> in your shell script to append contents to particular file. The filename can be fixed or using some pattern.
  2. Setup a hourly cronjob to trigger the shell script

getting the screen density programmatically in android?

Try this:

DisplayMetrics dm = context.getResources().getDisplayMetrics();
int densityDpi = dm.densityDpi;

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I landed here because of an XCTestCase, in which I'd disabled most of the tests by prefixing them with 'no_' as in no_testBackgroundAdding. Once I noticed that most of the answers had something to do with locks and threading, I realized the test contained a few instances of XCTestExpectation with corresponding waitForExpectations. They were all in the disabled tests, but apparently Xcode was still evaluating them at some level.

In the end I found an XCTestExpectation that was defined as @property but lacked the @synthesize. Once I added the synthesize directive, the EXC_BAD_INSTRUCTION disappeared.

How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    

How to parse dates in multiple formats using SimpleDateFormat

You'll need to use a different SimpleDateFormat object for each different pattern. That said, you don't need that many different ones, thanks to this:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

So, you'll need these formats:

  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

So, my advice would be to write a method that works something like this (untested):

// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...

Date tryParse(String dateString)
{
    for (String formatString : formatStrings)
    {
        try
        {
            return new SimpleDateFormat(formatString).parse(dateString);
        }
        catch (ParseException e) {}
    }

    return null;
}

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Swift 4 & iOs 11+

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, handler in

        handler(true)
        // handle deletion here
    }

    let more = UIContextualAction(style: .normal, title: "More") { _, _, handler in

        handler(true)
        // handle more here
    }

    return UISwipeActionsConfiguration(actions: [delete, more])
}

Java Webservice Client (Best way)

Some ideas in the following answer:

Steps in creating a web service using Axis2 - The client code

Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.

There are lots of web service frameworks out there...

.NET - Get protocol, host, and port

Even shorter way, may require newer ASP.Net:

string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)

The UriComponents enum lets you specify which component(s) of the URI you want to include.

Mercurial — revert back to old version and continue from there

IMHO, hg strip -r 39 suits this case better.

It requires the mq extension to be enabled and has the same limitations as the "cloning repo method" recommended by Martin Geisler: If the changeset was somehow published, it will (probably) return to your repo at some point in time because you only changed your local repo.

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

Php multiple delimiters in explode

You can try this solution.... It works great

function explodeX( $delimiters, $string )
{
    return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';

$exploded = explodeX( array('&', ',', '|' ), $list );

echo '<pre>';
print_r($exploded);
echo '</pre>';

Source : http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

How to disable text selection highlighting

For those who have trouble achieving the same in the Android browser with the touch event, use:

html, body {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    -webkit-tap-highlight-color: transparent;
}

Null or empty check for a string variable

Use This way is Better

if LEN(ISNULL(@Value,''))=0              

This check the field is empty or NULL

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Authentication plugin 'caching_sha2_password' cannot be loaded

Just downloaded the latest mysqlworkbench which is compatible with the latest encryption:

https://downloads.mysql.com/archives/workbench/

Note: On Mac big Sur, the latest two versions: 8.0.22 and 8.0.23 are buggy and do not work.

Use 8.0.21 until these are fixed

Testing if value is a function

  if ( window.onsubmit ) {
     //
  } else {
     alert("Function does not exist.");
  }

How to check if smtp is working from commandline (Linux)

[root@piwik-dev tmp]# mail -v root@localhost
Subject: Test
Hello world
Cc:  <Ctrl+D>

root@localhost... Connecting to [127.0.0.1] via relay...
220 piwik-dev.example.com ESMTP Sendmail 8.13.8/8.13.8; Thu, 23 Aug 2012 10:49:40 -0400
>>> EHLO piwik-dev.example.com
250-piwik-dev.example.com Hello localhost.localdomain [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP
>>> MAIL From:<[email protected]> SIZE=46
250 2.1.0 <[email protected]>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 q7NEneju002633 Message accepted for delivery
root@localhost... Sent (q7NEneju002633 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 piwik-dev.example.com closing connection

npm throws error without sudo

I Solve it by changing the owner from root to my user-name

sudo chown -R me:me /home/me/.config/configstore/

change me with your user-name and group .

env: node: No such file or directory in mac

I was getting this env: node: No such file or directory error when running the job through Jenkins.

What I did to fix it - added export PATH="$PATH:"/usr/local/bin/ at the beginning of the script that Jenkins job executes.

Change/Get check state of CheckBox

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

When is it appropriate to use UDP instead of TCP?

We know that the UDP is a connection-less protocol, so it is

  1. suitable for process that require simple request-response communication.
  2. suitable for process which has internal flow ,error control
  3. suitable for broad casting and multicasting

Specific examples:

  • used in SNMP
  • used for some route updating protocols such as RIP

How to swap two variables in JavaScript

Swap using Bitwise

let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;

Single line Swap "using Array"

[a, b] = [b, a]

'module' object has no attribute 'DataFrame'

For me he problem was that my script was called pandas.py in the folder pandas which obviously messed up my imports.

How to change default timezone for Active Record in Rails?

adding following to application.rb works

 config.time_zone = 'Eastern Time (US & Canada)'
 config.active_record.default_timezone = :local # Or :utc

Create Excel files from C# without office

Use OleDB, you can create, read, and edit excel files pretty easily. Read the MSDN docs for more info:

http://msdn.microsoft.com/en-us/library/aa288452(VS.71).aspx

I've used OleDB to read from excel files and I know you can create them, but I haven't done it firsthand.

How to index into a dictionary?

oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!

Try this:

colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}

Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.

For example,

colors[1][0]
// returns 'blue'

colors[3][1]
// returns '8'

Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.

colors_key = {'blue': 1, 'red': 6, 'yllow': 8}

Then, you will be able to also look up the colors key if you need to.

colors[colors_key['blue']][0] will return 'blue'

Something like that.

And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.

values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}

Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.

Or you could use a list of lists.

Good luck!

What data type to use for hashed password field and what length?

I've always tested to find the MAX string length of an encrypted string and set that as the character length of a VARCHAR type. Depending on how many records you're going to have, it could really help the database size.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I landed up here, tried your ways and could not figure out.

I was actually working on a pregiven code where

pickle.load(path)

was used so i replaced it with

np.load(path, allow_pickle=True)

How to get parameters from a URL string?

$web_url = 'http://www.writephponline.com?name=shubham&[email protected]';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);

echo "Name: " . $queryArray['name'];  // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:[email protected]

Creating an instance of class

Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.

In Line 7, you create an object inside the argument call. So its an error.

And Lines 5 and 6 are invitation for memory leak.

Alter user defined type in SQL Server

This is what I normally use, albeit a bit manual:

/* Add a 'temporary' UDDT with the new definition */ 
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL 


/* Build a command to alter all the existing columns - cut and 
** paste the output, then run it */ 
select 'alter table dbo.' + TABLE_NAME + 
       ' alter column ' + COLUMN_NAME + ' t_myudt_tmp' 
from INFORMATION_SCHEMA.COLUMNS 
where DOMAIN_NAME = 't_myudt' 

/* Remove the old UDDT */ 
exec sp_droptype t_mydut


/* Rename the 'temporary' UDDT to the correct name */ 
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE' 

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Doctrine - How to print out the real sql, not just the prepared statement?

A working example:

$qb = $this->createQueryBuilder('a');
$query=$qb->getQuery();
// SHOW SQL: 
echo $query->getSQL(); 
// Show Parameters: 
echo $query->getParameters();

Cancel a UIView animation?

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

How to do 3 table JOIN in UPDATE query?

An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}

Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use https://pythonhosted.org/pyserial/ for more examples

How to check if a radiobutton is checked in a radiogroup in Android?

try to use this

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:orientation="horizontal"
>    
    <RadioButton
        android:id="@+id/standard_delivery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Standard_delivery"
        android:checked="true"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="15dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"   
    />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Midnight_delivery"
        android:checked="false"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:textSize="12dp"
        android:onClick="onRadioButtonClicked"
        android:id="@+id/midnight_delivery"
    />    
</RadioGroup>

this is java class

public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.standard_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
                    break;
            case R.id.midnight_delivery:
                if (checked)
                    Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
                    break;
        }
    }

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

Angular 2 - Redirect to an external URL and open in a new tab

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.

jQuery.click() vs onClick

IMHO, onclick is the preferred method over .click only when the following conditions are met:

  • there are many elements on the page
  • only one event to be registered for the click event
  • You're worried about mobile performance/battery life

I formed this opinion because of the fact that the JavaScript engines on mobile devices are 4 to 7 times slower than their desktop counterparts which were made in the same generation. I hate it when I visit a site on my mobile device and receive jittery scrolling because the jQuery is binding all of the events at the expense of my user experience and battery life. Another recent supporting factor, although this should only be a concern with government agencies ;) , we had IE7 pop-up with a message box stating that JavaScript process is taking to long...wait or cancel process. This happened every time there were a lot of elements to bind to via jQuery.

Bogus foreign key constraint fail

hopefully its work

SET foreign_key_checks = 0; DROP TABLE table name; SET foreign_key_checks = 1;

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Boxplot in R showing the mean

With ggplot2:

p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

Recording video feed from an IP camera over a network

I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.

Andrew

Make HTML5 video poster be same size as video itself

I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.

Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".

HTML/HTML5:

<div class="video_poster">
    <video poster="dasdsadsakaslmklda.jpg" controls>
        <source src="videos/myvideo.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
<div>

CSS:

video{
    width:694px;
    height:390px;
}
.video_poster{
    width:694px;
    height:390px;
    background-size:694px 390px;
    background-image:url(images/myvideo_poster.jpg);
}

Textarea that can do syntax highlighting on the fly?

It's not possible to achieve the required level of control over presentation in a regular textarea.

If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).

From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors

How do I remove objects from an array in Java?

EDIT:

The point with the nulls in the array has been cleared. Sorry for my comments.

Original:

Ehm... the line

array = list.toArray(array);

replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!

If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:

        String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

        System.out.println(Arrays.toString(array));

        Set<String> asSet = new HashSet<String>(Arrays.asList(array));
        asSet.remove("a");
        array = asSet.toArray(new String[] {});

        System.out.println(Arrays.toString(array));

Gives:

[a, bc, dc, a, ef]
[dc, ef, bc]

Where as the current accepted answer from Chris Yester Young outputs:

[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]

with the code

    String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

    System.out.println(Arrays.toString(array));

    List<String> list = new ArrayList<String>(Arrays.asList(array));
    list.removeAll(Arrays.asList("a"));
    array = list.toArray(array);        

    System.out.println(Arrays.toString(array));

without any null values left behind.

java.text.ParseException: Unparseable date

Your pattern does not correspond to the input string at all... It is not surprising that it does not work. This would probably work better:

SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
                                            Locale.ENGLISH);

Then to print with your required format you need a second SimpleDateFormat:

Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));

Notes:

  • you should include the locale as if your locale is not English, the day name might not be recognised
  • IST is ambiguous and can lead to problems so you should use the proper time zone name if possible in your input.

Escape quotes in JavaScript

You need to escape quotes with double backslashes.

This fails (produced by PHP's json_encode):

<script>
  var jsonString = '[{"key":"my \"value\" "}]';
  var parsedJson = JSON.parse(jsonString);
</script>

This works:

<script>
  var jsonString = '[{"key":"my \\"value\\" "}]';
  var parsedJson = JSON.parse(jsonString);
</script>

How to change the buttons text using javascript

I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.

1- innerHTML

document.getElementById("ShowButton").innerHTML = 'Show Filter';

You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.

2- innerText

document.getElementById("ShowButton").innerText = 'Show Filter';

This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here

3- textContent

document.getElementById("ShowButton").textContent = 'Show Filter';

This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.

So if a text has to be added like above, then its better to use textContent.

How can I get the executing assembly version?

Product Version may be preferred if you're using versioning via GitVersion or other versioning software.

To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here

show loading icon until the page is load?

Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.

<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
    jQuery("#" + id).html(jQuery("#loading").html());
    jQuery("#" + id).show();
}

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

We have come across this issue in desktop app.

Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.

enter image description here

Return value from nested function in Javascript

Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.

var updater = {};

function geoCodeCity(goocoord) { 
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': goocoord
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            updater.currentLocation = results[1].formatted_address;
        } else {
            if (status == "ERROR") { 
                    console.log(status);
                }
        }
    });
};

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

Warning about `$HTTP_RAW_POST_DATA` being deprecated

If the .htaccess file not avilable create it on root folder and past this line of code.

Put this in .htaccess file (tested working well for API)

<IfModule mod_php5.c>
    php_value always_populate_raw_post_data -1
</IfModule>

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

enumerate() for dictionary in python

That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.

What is the standard Python docstring format?

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

def sq(n):
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n):
    """Return the squared result. 
    ...

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

Overlay normal curve to histogram in R

You just need to find the right multiplier, which can be easily calculated from the hist object.

myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]

plot(myhist)
lines(mydensity)

enter image description here

A more complete version, with a normal density and lines at each standard deviation away from the mean (including the mean):

myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]

plot(myhist)
lines(mydensity)

myx <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out= 100)
mymean <- mean(mtcars$mpg)
mysd <- sd(mtcars$mpg)

normal <- dnorm(x = myx, mean = mymean, sd = mysd)
lines(myx, normal * multiplier[1], col = "blue", lwd = 2)

sd_x <- seq(mymean - 3 * mysd, mymean + 3 * mysd, by = mysd)
sd_y <- dnorm(x = sd_x, mean = mymean, sd = mysd) * multiplier[1]

segments(x0 = sd_x, y0= 0, x1 = sd_x, y1 = sd_y, col = "firebrick4", lwd = 2)

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

Why does 2 mod 4 = 2?

mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.

Asynchronous Requests with Python requests

I know this has been closed for a while, but I thought it might be useful to promote another async solution built on the requests library.

list_of_requests = ['http://moop.com', 'http://doop.com', ...]

from simple_requests import Requests
for response in Requests().swarm(list_of_requests):
    print response.content

The docs are here: http://pythonhosted.org/simple-requests/

How to open html file?

CODE:

import codecs

path="D:\\Users\\html\\abc.html" 
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)

httpd-xampp.conf: How to allow access to an external IP besides localhost?

In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .

i hope this will resolve your problem

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

How can I change the default Django date template format?

Set both DATE_FORMAT and USE_L10N

To make changes for the entire site in Django 1.4.1 add:

DATE_FORMAT = "Y-m-d"

to your settings.py file and edit:

USE_L10N = False

since l10n overrides DATE_FORMAT

This is documented at: https://docs.djangoproject.com/en/dev/ref/settings/#date-format

Fastest way to check a string contain another substring in JavaScript?

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

How to set default vim colorscheme

You can try too to put this into your ~/.vimrc file:

colorscheme Solarized

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I don't know ASP.NET very well, but can you use the ternary operator?

http://en.wikipedia.org/wiki/Ternary_operation

Something like: (x=Eval("item")) == Null ? 0 : x

Why use 'virtual' for class properties in Entity Framework model definitions?

It’s quite common to define navigational properties in a model to be virtual. When a navigation property is defined as virtual, it can take advantage of certain Entity Framework functionality. The most common one is lazy loading.

Lazy loading is a nice feature of many ORMs because it allows you to dynamically access related data from a model. It will not unnecessarily fetch the related data until it is actually accessed, thus reducing the up-front querying of data from the database.

From book "ASP.NET MVC 5 with Bootstrap and Knockout.js"

Which header file do you include to use bool type in c in linux?

bool is just a macro that expands to _Bool. You can use _Bool with no #include very much like you can use int or double; it is a C99 keyword.

The macro is defined in <stdbool.h> along with 3 other macros.

The macros defined are

  • bool: macro expands to _Bool
  • false: macro expands to 0
  • true: macro expands to 1
  • __bool_true_false_are_defined: macro expands to 1

Remove characters from NSString?

if the string is mutable, then you can transform it in place using this form:

[string replaceOccurrencesOfString:@" "
                        withString:@""
                           options:0
                             range:NSMakeRange(0, string.length)];

this is also useful if you would like the result to be a mutable instance of an input string:

NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
                        withString:@""
                           options:0
                             range:NSMakeRange(0, string.length)];

How do I tell if an object is a Promise?

I use this function as a universal solution:

function isPromise(value) {
  return value && value.then && typeof value.then === 'function';
}

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

Excel Date to String conversion

The selected answer did not work for me as Excel was still not converting the text to date. Here is my solution.

Say that in the first column, A, you have data of the type 2016/03/25 21:20:00 but is stored as text. Then in column B write =DATEVALUE(A1) and in column C write =TIMEVALUE(A1).

Then in column D do =B1+C1 to add the numerical formats of the date and time.

Finally, copy the values from D into column E by right clicking in column E and select Paste Special -> Paste as Values.

Highlight the numerical values in column E and change the data type to date - I prefer using a custom date of the form YYYY-MM-DD HH:MM:SS.

simulate background-size:cover on <video> or <img>

Old question, but in case anyone sees this, the best answer in my opinion is to convert the video into an animated GIF. This gives you much more control and you can just treat it like an image. It's also the only way for it to work on mobile, since you can't autoplay videos. I know the question is asking to do it in an <img> tag, but I don't really see the downside of using a <div> and doing background-size: cover

How to ignore the first line of data when processing CSV data?

Because this is related to something I was doing, I'll share here.

What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?

If your task is basic, such as printing or appending to a list or array, you could just use an if statement:

# Let's say there's 4 columns
with open('file.csv') as csvfile:
     csvreader = csv.reader(csvfile)
# read first line
     first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
     if len(first_line) == 4:
          array.append(first_line)
# Now we'll just iterate over everything else as usual:
     for row in csvreader:
          array.append(row)

Bootstrap 3 - How to load content in modal body via AJAX?

create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.

 $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 

        }});

once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.

You can call controller and get the page content and you can show that in your modal.

below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...

index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript">
function loadme(){
    //alert("loadig");

    $.ajax({url: "registration.html", success: function(result){
        //alert("success"+result);
          $("#contentBody").html(result);
        $("#myModal").modal('show'); 

    }});
}
</script>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body" id="contentBody">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body>
</html>

registration.html
-------------------- 
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
    border: 3px solid #f1f1f1;
    font-family: Arial;
}

.container {
    padding: 20px;
    background-color: #f1f1f1;
    width: 560px;
}

input[type=text], input[type=submit] {
    width: 100%;
    padding: 12px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

input[type=checkbox] {
    margin-top: 16px;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    border: none;
}

input[type=submit]:hover {
    opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form action="/action_page.php">
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

Generating a PDF file from React Components

This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.

As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left, this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}.

This method wraps the prerequisites in a promise and calls pdf.save() in the finally() method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.

_x000D_
_x000D_
// Get List of paged elements._x000D_
let elems = document.querySelectorAll('.elemClass');_x000D_
let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
_x000D_
// Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
pdf.scaleFactor = 2;_x000D_
_x000D_
// Create a new promise with the loop body_x000D_
let addPages = new Promise((resolve,reject)=>{_x000D_
  elems.forEach((elem, idx) => {_x000D_
    // Scaling fix set scale to 2_x000D_
    html2canvas(elem, {scale: "2"})_x000D_
      .then(canvas =>{_x000D_
        if(idx < elems.length - 1){_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          pdf.addPage();_x000D_
        } else {_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          console.log("Reached last page, completing");_x000D_
        }_x000D_
  })_x000D_
  _x000D_
  setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
})_x000D_
_x000D_
addPages.finally(()=>{_x000D_
   console.log("Saving PDF");_x000D_
   pdf.save();_x000D_
});
_x000D_
_x000D_
_x000D_

Detect and exclude outliers in Pandas data frame

If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.

df = pd.DataFrame(np.random.randn(100, 3))

from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]

description:

  • For each column, first it computes the Z-score of each value in the column, relative to the column mean and standard deviation.
  • Then is takes the absolute of Z-score because the direction does not matter, only if it is below the threshold.
  • all(axis=1) ensures that for each row, all column satisfy the constraint.
  • Finally, result of this condition is used to index the dataframe.

Filter other columns based on a single column

  • Specify a column for the zscore, df[0] for example, and remove .all(axis=1).
df[(np.abs(stats.zscore(df[0])) < 3)]

How to check if Location Services are enabled?

If you are using AndroidX, use below code to check Location Service is enabled or not:

fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))

How to define static property in TypeScript interface

Though static keyword not supported in interface in Typescript but we can achieve it by creating a function interface that has static member.

In my following code I have created a function interface Factory that has two static members serialNumber and printSerial.

// factory is a function interface
interface Factory<T> {
    (name: string, age: number): T;

    //staic property
    serialNumber: number;

    //static method
    printSrial: () => void;
}

class Dog {
    constructor(public name: string, public age: number) { }
}

const dogFactory: Factory<Dog> = (name, age) => {
    return new Dog(name, age);
}

// initialising static members

dogFactory.serialNumber = 1234;
dogFactory.printSrial = () => console.log(dogFactory.serialNumber);


//instance of Dog that DogFactory creates
const myDog = dogFactory("spike", 3);

//static property that returns 1234
console.log(dogFactory.serialNumber)

//static method that prints the serial 1234
dogFactory.printSrial();

Response Content type as CSV

In ASP.net MVC, you can use a FileContentResult and the File method:

public FileContentResult DownloadManifest() {
    byte[] csvData = getCsvData();
    return File(csvData, "text/csv", "filename.csv");
}

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.

My solution was this function:

function ifexists($varname)
{
  return(isset($$varname)?$varname:null);
}

So if I want to reference to $name and echo if exists, I simply write:

<?=ifexists('name')?>

For array elements:

function ifexistsidx($var,$index)
{
  return(isset($var[$index])?$var[$index]:null);
}

In page if I want to refer to $_REQUEST['name']:

<?=ifexistsidx($_REQUEST,'name')?>

How to Customize a Progress Bar In Android

Creating Custom ProgressBar like hotstar.

  1. Add Progress bar on layout file and set the indeterminateDrawable with drawable file.

activity_main.xml

<ProgressBar
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/player_progressbar"
    android:indeterminateDrawable="@drawable/custom_progress_bar"
    />
  1. Create new xml file in res\drawable

custom_progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate  xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="1080" >

    <shape
        android:innerRadius="35dp"
        android:shape="ring"
        android:thickness="3dp"
        android:useLevel="false" >
       <size
           android:height="80dp"
           android:width="80dp" />

       <gradient
            android:centerColor="#80b7b4b2"
            android:centerY="0.5"
            android:endColor="#f4eef0"
            android:startColor="#00938c87"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

Swift Beta performance: sorting arrays

tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].


Here is an in-place quicksort in Swift Beta:

func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
    if (end - start < 2){
        return
    }
    var p = a[start + (end - start)/2]
    var l = start
    var r = end - 1
    while (l <= r){
        if (a[l] < p){
            l += 1
            continue
        }
        if (a[r] > p){
            r -= 1
            continue
        }
        var t = a[l]
        a[l] = a[r]
        a[r] = t
        l += 1
        r -= 1
    }
    quicksort_swift(&a, start, r + 1)
    quicksort_swift(&a, r + 1, end)
}

And the same in C:

void quicksort_c(int *a, int n) {
    if (n < 2)
        return;
    int p = a[n / 2];
    int *l = a;
    int *r = a + n - 1;
    while (l <= r) {
        if (*l < p) {
            l++;
            continue;
        }
        if (*r > p) {
            r--;
            continue;
        }
        int t = *l;
        *l++ = *r;
        *r-- = t;
    }
    quicksort_c(a, r - a + 1);
    quicksort_c(l, a + n - l);
}

Both work:

var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]

quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))

// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]

Both are called in the same program as written.

var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
    x_swift[i] = CInt(random())
    x_c[i] = CInt(random())
}

let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();

let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();

This converts the absolute times to seconds:

static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;

mach_timebase_info_data_t timebase_info;

uint64_t abs_to_nanos(uint64_t abs) {
    if ( timebase_info.denom == 0 ) {
        (void)mach_timebase_info(&timebase_info);
    }
    return abs * timebase_info.numer  / timebase_info.denom;
}

double abs_to_seconds(uint64_t abs) {
    return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}

Here is a summary of the compiler's optimazation levels:

[-Onone] no optimizations, the default for debug.
[-O]     perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.

Time in seconds with [-Onone] for n=10_000:

Swift:            0.895296452
C:                0.001223848

Here is Swift's builtin sort() for n=10_000:

Swift_builtin:    0.77865783

Here is [-O] for n=10_000:

Swift:            0.045478346
C:                0.000784666
Swift_builtin:    0.032513488

As you can see, Swift's performance improved by a factor of 20.

As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:

Swift:            0.000706745
C:                0.000742374
Swift_builtin:    0.000603576

And for n=1_000_000:

Swift:            0.107111846
C:                0.114957179
Swift_sort:       0.092688548

For comparison, this is with [-Onone] for n=1_000_000:

Swift:            142.659763258
C:                0.162065333
Swift_sort:       114.095478272

So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.

It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:

A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.

They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.

BETA 3 UPDATE:

n=10_000 with [-O]:

Swift:            0.019697268
C:                0.000718064
Swift_sort:       0.002094721

Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.

FINAL UPDATE:

[-Onone]:

Swift:   0.678056695
C:       0.000973914

[-O]:

Swift:   0.001158492
C:       0.001192406

[-Ounchecked]:

Swift:   0.000827764
C:       0.001078914

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

Passing an array/list into a Python function

You can pass lists just like other types:

l = [1,2,3]

def stuff(a):
   for x in a:
      print a


stuff(l)

This prints the list l. Keep in mind lists are passed as references not as a deep copy.

Examples of GoF Design Patterns in Java's core libraries

RMI is based on Proxy.

Should be possible to cite one for most of the 23 patterns in GoF:

  1. Abstract Factory: java.sql interfaces all get their concrete implementations from JDBC JAR when driver is registered.
  2. Builder: java.lang.StringBuilder.
  3. Factory Method: XML factories, among others.
  4. Prototype: Maybe clone(), but I'm not sure I'm buying that.
  5. Singleton: java.lang.System
  6. Adapter: Adapter classes in java.awt.event, e.g., WindowAdapter.
  7. Bridge: Collection classes in java.util. List implemented by ArrayList.
  8. Composite: java.awt. java.awt.Component + java.awt.Container
  9. Decorator: All over the java.io package.
  10. Facade: ExternalContext behaves as a facade for performing cookie, session scope and similar operations.
  11. Flyweight: Integer, Character, etc.
  12. Proxy: java.rmi package
  13. Chain of Responsibility: Servlet filters
  14. Command: Swing menu items
  15. Interpreter: No directly in JDK, but JavaCC certainly uses this.
  16. Iterator: java.util.Iterator interface; can't be clearer than that.
  17. Mediator: JMS?
  18. Memento:
  19. Observer: java.util.Observer/Observable (badly done, though)
  20. State:
  21. Strategy:
  22. Template:
  23. Visitor:

I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.

Animate background image change with jQuery

I had the same problem, after loads of research and Googling, I found the following solution worked best for me! plenty of trial and error went into this one.

--- SOLVED / SOLUTION ---

JS

$(document).ready(function() {
            $("header").delay(5000).queue(function(){
                $(this).css({"background-image":"url(<?php bloginfo('template_url') ?>/img/header-boy-hover.jpg)"});
            });
        });

CSS

header {
    -webkit-transition:all 1s ease-in;
    -moz-transition:all 1s ease-in;
    -o-transition:all 1s ease-in;
    -ms-transition:all 1s ease-in;
    transition:all 1s ease-in;
}

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

GLYPHICONS - bootstrap icon font hex value

Do you mean these hex values?

.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...

You can find these in glyphicons.css here:

http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css

(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)

How do I access previous promise results in a .then() chain?

What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...

In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5

/**
 * Promise like object that allows to resolve it promise from outside code. Example:
 *
```
class Api {
  fooReady = new Deferred<Data>()
  private knower() {
    inOtherMoment(data=>{
      this.fooReady.resolve(data)
    })
  }
}
```
 */
var Deferred = /** @class */ (function () {
  function Deferred(callback) {
    var instance = this;
    this.resolve = null;
    this.reject = null;
    this.status = 'pending';
    this.promise = new Promise(function (resolve, reject) {
      instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
      instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
    });
    if (typeof callback === 'function') {
      callback.call(this, this.resolve, this.reject);
    }
  }
  Deferred.prototype.then = function (resolve) {
    return this.promise.then(resolve);
  };
  Deferred.prototype.catch = function (r) {
    return this.promise.catch(r);
  };
  return Deferred;
}());

transpiled form a typescript project of mine:

https://github.com/cancerberoSgx/misc-utils-of-mine/blob/2927c2477839f7b36247d054e7e50abe8a41358b/misc-utils-of-mine-generic/src/promise.ts#L31

For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:

https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=

How to install .MSI using PowerShell

#$computerList = "Server Name"
#$regVar = "Name of the package "
#$packageName = "Packe name "
$computerList = $args[0]
$regVar = $args[1]
$packageName = $args[2]
foreach ($computer in $computerList)
{
    Write-Host "Connecting to $computer...."
    Invoke-Command -ComputerName $computer -Authentication Kerberos -ScriptBlock {
    param(
        $computer,
        $regVar,
        $packageName
        )

        Write-Host "Connected to $computer"
        if ([IntPtr]::Size -eq 4)
        {
            $registryLocation = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"
            Write-Host "Connected to 32bit Architecture"
        }
        else
        {
            $registryLocation = Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
            Write-Host "Connected to 64bit Architecture"
        }
        Write-Host "Finding previous version of `enter code here`$regVar...."
        foreach ($registryItem in $registryLocation)
        {
            if((Get-itemproperty $registryItem.PSPath).DisplayName -match $regVar)
            {
                Write-Host "Found $regVar" (Get-itemproperty $registryItem.PSPath).DisplayName
                $UninstallString = (Get-itemproperty $registryItem.PSPath).UninstallString
                    $match = [RegEx]::Match($uninstallString, "{.*?}")
                    $args = "/x $($match.Value) /qb"
                    Write-Host "Uninstalling $regVar...."
                    [diagnostics.process]::start("msiexec", $args).WaitForExit() 
                    Write-Host "Uninstalled $regVar"
            }
        }

        $path = "\\$computer\Msi\$packageName"
        Write-Host "Installaing $path...."
        $args = " /i $path /qb"
        [diagnostics.process]::start("msiexec", $args).WaitForExit()
        Write-Host "Installed $path"
    } -ArgumentList $computer, $regVar, $packageName
Write-Host "Deployment Complete"

}

java create date object using a value string

Whenever you want to convert a String to Date object then use SimpleDateFormat#parse
Try to use

String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
        .format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);

.Additional thing is if you want to convert a Date to String then you should use SimpleDateFormat#format function.
Now the Point for you is new Date(String) is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use SimpleDateFormat#parse.

refer the official doc for more Date and Time Patterns used in SimpleDateFormat options.

Switch statement fallthrough in C#?

The "why" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java.

The workaround is to use goto, e.g.

switch (number.ToString().Length)
{
    case 3:
        ans += string.Format("{0} hundred and ", numbers[number / 100]);
        goto case 2;
    case 2:
    // Etc
}

The general design of switch/case is a little bit unfortunate in my view. It stuck too close to C - there are some useful changes which could be made in terms of scoping etc. Arguably a smarter switch which could do pattern matching etc would be helpful, but that's really changing from switch to "check a sequence of conditions" - at which point a different name would perhaps be called for.

Generate an integer that is not among four billion given ones

For the 10 MB memory constraint:

  1. Convert the number to its binary representation.
  2. Create a binary tree where left = 0 and right = 1.
  3. Insert each number in the tree using its binary representation.
  4. If a number has already been inserted, the leafs will already have been created.

When finished, just take a path that has not been created before to create the requested number.

4 billion number = 2^32, meaning 10 MB might not be sufficient.

EDIT

An optimization is possible, if two ends leafs have been created and have a common parent, then they can be removed and the parent flagged as not a solution. This cuts branches and reduces the need for memory.

EDIT II

There is no need to build the tree completely too. You only need to build deep branches if numbers are similar. If we cut branches too, then this solution might work in fact.

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

WinError 2 The system cannot find the file specified (Python)

thank you, your first error guides me here and the solution solve mine too!

for permission error, f = open('output', 'w+'), change it into f = open(output+'output', 'w+').

or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.

for sure, you could probably running python/your script as administrator to pass permission error though

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

Nesting await in Parallel.ForEach

svick's answer is (as usual) excellent.

However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async-compatible queue.

In your case, a simpler solution is to just use the async-style parallelism:

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

var customerTasks = ids.Select(i =>
  {
    ICustomerRepo repo = new CustomerRepo();
    return repo.GetCustomer(i);
  });
var customers = await Task.WhenAll(customerTasks);

foreach (var customer in customers)
{
  Console.WriteLine(customer.ID);
}

Console.ReadKey();

Selecting rows where remainder (modulo) is 1 after division by 2?

At least some versions of SQL (Oracle, Informix, DB2, ISO Standard) support:

WHERE MOD(value, 2) = 1

MySQL supports '%' as the modulus operator:

WHERE value % 2 = 1

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Neither the question nor the answers really fit my simple way of thinking about it. I'm a consultant and have synchronized these definitions with a number of Dev teams and DevOps people, but am curious about how it matches with the industry at large:

Basically I think of the agile practice of continuous delivery like a continuum:

Not continuous (everything manual) 0% ----> 100% Continuous Delivery of Value (everything automated)

Steps towards continuous delivery:

Zero. Nothing is automated when devs check in code... You're lucky if they have compiled, run, or performed any testing prior to check-in.

  1. Continuous Build: automated build on every check-in, which is the first step, but does nothing to prove functional integration of new code.

  2. Continuous Integration (CI): automated build and execution of at least unit tests to prove integration of new code with existing code, but preferably integration tests (end-to-end).

  3. Continuous Deployment (CD): automated deployment when code passes CI at least into a test environment, preferably into higher environments when quality is proven either via CI or by marking a lower environment as PASSED after manual testing. I.E., testing may be manual in some cases, but promoting to next environment is automatic.

  4. Continuous Delivery: automated publication and release of the system into production. This is CD into production plus any other configuration changes like setup for A/B testing, notification to users of new features, notifying support of new version and change notes, etc.

EDIT: I would like to point out that there's a difference between the concept of "continuous delivery" as referenced in the first principle of the Agile Manifesto (http://agilemanifesto.org/principles.html) and the practice of Continuous Delivery, as seems to be referenced by the context of the question. The principle of continuous delivery is that of striving to reduce the Inventory waste as described in Lean thinking (http://www.miconleansixsigma.com/8-wastes.html). The practice of Continuous Delivery (CD) by agile teams has emerged in the many years since the Agile Manifesto was written in 2001. This agile practice directly addresses the principle, although they are different things and apparently easily confused.

What's the easiest way to escape HTML in Python?

cgi.escape extended

This version improves cgi.escape. It also preserves whitespace and newlines. Returns a unicode string.

def escape_html(text):
    """escape strings for display in HTML"""
    return cgi.escape(text, quote=True).\
           replace(u'\n', u'<br />').\
           replace(u'\t', u'&emsp;').\
           replace(u'  ', u' &nbsp;')

for example

>>> escape_html('<foo>\nfoo\t"bar"')
u'&lt;foo&gt;<br />foo&emsp;&quot;bar&quot;'

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

I don't understand -Wl,-rpath -Wl,

One other thing. You may need to specify the -L option as well - eg

-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz

or you may end up with an error like

ld: cannot find -lbaz

How to draw a rectangle around a region of interest in python

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

Pass a JavaScript function as parameter

You can use a JSON as well to store and send JS functions.

Check the following:

var myJSON = 
{
    "myFunc1" : function (){
        alert("a");
    }, 
    "myFunc2" : function (functionParameter){
        functionParameter();
    }
}



function main(){
    myJSON.myFunc2(myJSON.myFunc1);
}

This will print 'a'.

The following has the same effect with the above:

var myFunc1 = function (){
    alert('a');
}

var myFunc2 = function (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

Which is also has the same effect with the following:

function myFunc1(){
    alert('a');
}


function myFunc2 (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

And a object paradigm using Class as object prototype:

function Class(){
    this.myFunc1 =  function(msg){
        alert(msg);
    }

    this.myFunc2 = function(callBackParameter){
        callBackParameter('message');
    }
}


function main(){    
    var myClass = new Class();  
    myClass.myFunc2(myClass.myFunc1);
}

Draw radius around a point in Google map

I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html

Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.

How can I declare enums using java

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

CSS show div background image on top of other contained elements

How about making the <div id="mainWrapperDivWithBGImage"> as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:

#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}

Then

HTML:

<div id="mainWrapperDivWithBGImage">
  <div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
  <div id="middle">
    <div id="another_div"><img src="foo.gif" /></div>
  <div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>

You may have to do position:relative; and such.

Creating a config file in PHP

If you think you'll be using more than 1 db for any reason, go with the variable because you'll be able to change one parameter to switch to an entirely different db. I.e. for testing , autobackup, etc.

Placing an image to the top right corner - CSS

You can just do it like this:

#content {
    position: relative;
}
#content img {
    position: absolute;
    top: 0px;
    right: 0px;
}

<div id="content">
    <img src="images/ribbon.png" class="ribbon"/>
    <div>some text...</div>
</div>

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

Download a single folder or directory from a GitHub repo

None of the answers helped in my situation. If you are developing for Windows, you likely don't have svn. In many situations one can't count on users to have Git installed either, or don't want to download entire repositories for other reasons. Some of the people that answered this question, such as Willem van Ketwich and aztack, made tools to accomplish this task. However, if the tool isn't written for the language you are using, or you don't want to install a third party library, these don't work.

However, there is a much easier way. GitHub has an API that allows you to download a single file or an entire directory's contents using GET requests. You can access a directory using https://api.github.com/repos/:owner/:repo_name/contents/:path that returns a JSON object enumerating all the files in the directory. Included in the enumeration is a link to the raw content of the file, the download_url parameter. The file can then be downloaded using that URL.

It's a two step process that requires the ability to make GET requests, but this can be implemented in pretty much any language, on any platform. It can be used to get files or directories.

How to delete a file or folder?

To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

Since shutil.rmtree() will only remove directories and os.remove() or os.unlink() will only remove files.

How to clear APC cache entries?

I know it's not for everyone but: why not to do a graceful Apache restart?

For e.g. in case of Centos/RedHat Linux:

sudo service httpd graceful

Ubuntu:

sudo service apache2 graceful

How to round up integer division and have int result in Java?

Google's Guava library handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.

What characters do I need to escape in XML documents?

It depends on the context. For the content, it is < and &, and ]]> (though a string of three instead of one character).

For attribute values, it is <, &, ", and '.

For CDATA, it is ]]>.

How to detect if CMD is running as Administrator/has elevated privileges?

the solution:

at >nul
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

does not work under Windows 10

for all versions of Windows can be do so:

openfiles >nul 2>&1
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Angular; with IDE keyCode deprecated warning

Functionally the same as rinku's answer but with IDE warning prevention

numericOnly(event): boolean {
    // noinspection JSDeprecatedSymbols
    const charCode = (event.which) ? event.which : event.key || event.keyCode;  // keyCode is deprecated but needed for some browsers
    return !(charCode === 101 || charCode === 69 || charCode === 45 || charCode === 43);
}

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

The warning message

[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.

means that you somehow passed -P pom.xml to Maven which means "there is a profile called pom.xml; find it and activate it". Check your environment and your settings.xml for this flag and also look at all <profile> elements inside the various XML files.

Usually, mvn help:effective-pom is also useful to see what the real POM would look like.

Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:

  1. Install Java 8
  2. Make sure Maven uses Java 8 if you have it installed. JAVA_HOME is your friend
  3. Configure the Java compiler in your pom.xml to a Java version which you actually have.

Related: