Programs & Examples On #Reorganize

Try-catch block in Jenkins pipeline script

You're using the declarative style of specifying your pipeline, so you must not use try/catch blocks (which are for Scripted Pipelines), but the post section. See: https://jenkins.io/doc/book/pipeline/syntax/#post-conditions

Printing Batch file results to a text file

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

this command

chdir > test.txt

This command will redirect result to test.txt.

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

How do I find the date a video (.AVI .MP4) was actually recorded?

Have a try to exiftools or mediainfo, which provides you an export function as text. Just pay attention to daylight saving.

Is it possible to forward-declare a function in Python?

I apologize for reviving this thread, but there was a strategy not discussed here which may be applicable.

Using reflection it is possible to do something akin to forward declaration. For instance lets say you have a section of code that looks like this:

# We want to call a function called 'foo', but it hasn't been defined yet.
function_name = 'foo'
# Calling at this point would produce an error

# Here is the definition
def foo():
    bar()

# Note that at this point the function is defined
    # Time for some reflection...
globals()[function_name]()

So in this way we have determined what function we want to call before it is actually defined, effectively a forward declaration. In python the statement globals()[function_name]() is the same as foo() if function_name = 'foo' for the reasons discussed above, since python must lookup each function before calling it. If one were to use the timeit module to see how these two statements compare, they have the exact same computational cost.

Of course the example here is very useless, but if one were to have a complex structure which needed to execute a function, but must be declared before (or structurally it makes little sense to have it afterwards), one can just store a string and try to call the function later.

Can you change what a symlink points to after it is created?

Just a warning to the correct answers above:

Using the -f / --force Method provides a risk to lose the file if you mix up source and target:

mbucher@server2:~/test$ ls -la
total 11448
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:27 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
-rw-r--r--  1 mbucher www-data 7582480 May 25 15:27 otherdata.tar.gz
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ln -s -f thesymlink otherdata.tar.gz 
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ls -la
total 4028
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:28 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
lrwxrwxrwx  1 mbucher www-data      10 May 25 15:28 otherdata.tar.gz -> thesymlink
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz

Of course this is intended, but usually mistakes occur. So, deleting and rebuilding the symlink is a bit more work but also a bit saver:

mbucher@server2:~/test$ rm thesymlink && ln -s thesymlink otherdata.tar.gz 
ln: creating symbolic link `otherdata.tar.gz': File exists

which at least keeps my file.

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

python capitalize first letter only

Here is a one-liner that will uppercase the first letter and leave the case of all subsequent letters:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

This will result in WordsWithOtherUppercaseLetters

How to ping a server only once from within a batch file?

Just write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator

Which sort algorithm works best on mostly sorted data?

ponder Try Heap. I believe it's the most consistent of the O(n lg n) sorts.

Concatenate String in String Objective-c

Variations on a theme:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];

How can I determine if a variable is 'undefined' or 'null'?

With the solution below:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

I'm able to check for the following:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false

Calling a particular PHP function on form submit

If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form you can do that as :

<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
       display();
} 
?>
</body>
</html>

htaccess remove index.php from url

This will work, use the following code in .htaccess file RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

Playing Sound In Hidden Tag

That's how I achieved it, which is not visible (HORRIBLE SOUND....)

<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

What is the difference between MacVim and regular Vim?

It's all about the key bindings which one can simply achieve from .vimrc configurations. As far as clipboard is concerned you can use :set clipboard unnamed and the yank from vim will go to system clipboard. Anyways, whichever one you end up using I suggest using this vimrc config , it contains a whole lot of plugins and bindings which will make your experience smooth.

Whitespaces in java

From sun docs:

\s A whitespace character: [ \t\n\x0B\f\r]

The simplest way is to use it with regex.

Print very long string completely in pandas dataframe

In the newer version of pandas, use:

pd.set_option('display.max_colwidth', None)

Is it possible to play music during calls so that the partner can hear it ? Android

I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "

How do I run Python code from Sublime Text 2?

On Mac OS X, save your file with a .py extension. Press ? + B. It runs in a window below.

enter image description here

Having a UITextField in a UITableViewCell

I ran into the same problem. It seems that setting the cell.textlabel.text property brings the UILabel to the front of the contentView of the cell. Add the textView after setting textLabel.text, or (if that's not possible) call this:

[cell.contentView bringSubviewToFront:textField]

How to open VMDK File of the Google-Chrome-OS bundle 2012?

VMDK is a virtual disk file, what you need is a VMX file. Cruise on over to EasyVMX and have it create one for you, then just replace the VMDK file it gives you with the Cnrome OS one.

EasyVMX is good since VMWare Player has no VM creation stuff in it (at least in version 2, not sure about 3). You had to use one of VMWare's other products to do that.

space between divs - display table-cell

Use transparent borders if possible.

JSFiddle Demo

https://jsfiddle.net/74q3na62/

HTML

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
        <div class="cell">Cell 3</div>
    </div>
</div>

CSS

.table {
  display: table;
  border: 1px solid black;
}

.row { display:table-row; }

.cell {
  display: table-cell;
  background-clip: padding-box;
  background-color: gold;
  border-right: 10px solid transparent;
}

.cell:last-child {
  border-right: 0 none;
}

Explanation

You could use the border-spacing property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.

If you don't need visible borders on your table cells you should therefore use transparent borders to generate cell margins. Transparent borders require setting background-clip: padding-box; because otherwise the background color of the table cells is displayed on the border.

Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip out.

How to run java application by .bat file

If You have jar file then create bat file with:

java -jar NameOfJar.jar

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

Is it possible to run one logrotate check manually?

If you want to force-run a single specific directory or daemon's log files, you can usually find the configuration in /etc/logrotate.d, and they will work standalone.

Keep in mind that global configuration specified in /etc/logrotate.conf will not apply, so if you do this you should ensure you specify all the options you want in the /etc/logrotate.d/[servicename] config file specifically.

You can try it out with -d to see what would happen:

logrotate -df /etc/logrotate.d/nginx

Then you can run (using nginx as an example):

logrotate -f /etc/logrotate.d/nginx

And the nginx logs alone will be rotated.

base64 encode in MySQL

Looks like no, though it was requested, and there’s a UDF for it.

Edit: Or there’s… this. Ugh.

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

How to combine GROUP BY, ORDER BY and HAVING

ORDER BY is always last...

However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT * and GROUP BY Email will give you RANDOM VALUES for all the fields but Email. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC

How do I do a HTTP GET in Java?

If you want to stream any webpage, you can use the method below.

import java.io.*;
import java.net.*;

public class c {

   public static String getHTML(String urlToRead) throws Exception {
      StringBuilder result = new StringBuilder();
      URL url = new URL(urlToRead);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      try (var reader = new BufferedReader(
                  new InputStreamReader(conn.getInputStream()))) {
          for (String line; (line = reader.readLine()) != null; ) {
              result.append(line);
          }
      }
      return result.toString();
   }

   public static void main(String[] args) throws Exception
   {
     System.out.println(getHTML(args[0]));
   }
}

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

Multiple WHERE Clauses with LINQ extension methods

If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:

// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();

if (condition1)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}

if (condition2)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}

if (condition3)
{
    predicate = predicate.And(d => d.SomeIntProperty >= 4);
}

return originalCollection.Where<YourDataClass>(predicate.Compile());

The full source of mentioned PredicateBuilder is bellow (but you could also check the original page with a few more examples):

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

Note: I've tested this approach with Portable Class Library project and have to use .Compile() to make it work:

Where(predicate .Compile() );

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

ImportError: No Module Named bs4 (BeautifulSoup)

Try this:

sudo python3 -m pip install bs4

How to append contents of multiple files into one file

if you have a certain output type then do something like this

cat /path/to/files/*.txt >> finalout.txt

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

MySQL error - #1062 - Duplicate entry ' ' for key 2

you can try adding

$db['db_debug'] = FALSE; 

in "your database file".php after that you can modify your database as you like.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

To do this easily, the use of Stack is better. Create a Stack Then inside Stack add Align or Positioned and set position according to your needed, You can add multiple Container.

Container
  child: Stack(
    children: <Widget>[
      Align(
         alignment: FractionalOffset.center,
         child: Text(
            "? 1000",
         )
      ),
      Positioned(
        bottom: 0,
        child: Container(
           width: double.infinity,
           height: 30,
           child: Text(
             "Balance", ,
           )
         ),
       )
    ],
  )
)

enter image description here

Stack a widget that positions its children relative to the edges of its box.

Stack class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

Error "library not found for" after putting application in AdMob

If error is like following

ld: library not found for -lpods

I found that a file "libPods.a" which is in red colour(like missing files) was created somehow in the Framework group of the project. I just simply removed that file and everything got fine.

EDIT: Another Solution

Another Solution that I have already answered in the similar question is in this link

Integrating CSS star rating into an HTML form

Here is the solution.

The HTML:

<div class="rating">
<span>?</span><span>?</span><span>?</span><span>?</span><span>?</span>
</div>

The CSS:

.rating {
  unicode-bidi: bidi-override;
  direction: rtl;
}
.rating > span {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
   content: "\2605";
   position: absolute;
}

Hope this helps.

Source

How to add a new row to datagridview programmatically

Like this:

 dataGridView1.Columns[0].Name = "column2";
 dataGridView1.Columns[1].Name = "column6";

 string[] row1 = new string[] { "column2 value", "column6 value" };
 dataGridView1.Rows.Add(row1);

Or you need to set there values individually use the propery .Rows(), like this:

 dataGridView1.Rows[1].Cells[0].Value = "cell value";

Bootstrap col-md-offset-* not working

Kindly use offset-md-4 instead of col-md-offset-4 in bootstrap 4. It's little changes adopted in bootstrap 4.

For more info

Importing a function from a class in another file?

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:
    run()'''
    eval(chooser())()

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

Project Links do not work on Wamp Server

In order to access project from the homepage you need to create a Virtual Host first.

Most easiest way to do this is to use Wamp's Add a Virtual Host Utility.

Just follow these steps:

  1. Create a folder inside "C:\wamp\www\" directory and give it a name that you want to give to your site for eg. 'mysite'. So the path would be "C:\wamp\www\mysite".
  2. Now open localhost's homepage in your browser, under Tools menu click on Add a Virtual Host link.
  3. Enter the name of the virtual host, that name must be the name of the folder we created inside www directory i.e. 'mysite'.
  4. Enter absolute path of the virtual host i.e. "C:\wamp\www\mysite\" without quotes and click the button below saying 'Start the creation of the VirtualHost'.
  5. Virtual Host created, now you just need to 'Restart DNS'. To do this right click the wamp server's tray menu icon, click on Tools > Restart DNS and let the tray menu icon become green again.
  6. All set! Now just create 'index.php' page inside "C:\wamp\www\mysite\" directory. Add some code in 'index.php' file, like
    <?php echo "<h1>Hello World</h1>"; ?>

Now you can access the projects from the localhost's homepage. Just click the project link and you'll see 'Hello World' printed on your screen.

Convert Pixels to Points

Starting with the given:

  • There are 72 points in an inch (that is what a point is, 1/72 of an inch)
  • on a system set for 150dpi, there are 150 pixels per inch.
  • 1 in = 72pt = 150px (for 150dpi setting)

If you want to find points (pt) based on pixels (px):

 72 pt    x pt
------ = -----                  (1) for 150dpi system
150 px    y px

Rearranging:

x = (y/150) * 72                (2) for 150dpi system

so:

points = (pixels / 150) * 72    (3) for 150dpi system

How to define an empty object in PHP

You can also get an empty object by parsing JSON:

$blankObject= json_decode('{}');

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Altering a column: null to not null

For Oracle 11g, I was able to change the column attribute as follows:

ALTER TABLE tablename MODIFY columnname datatype NOT NULL;

Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.

WCF error: The caller was not authenticated by the service

I was able to resolve the shared issue by following below steps:

  1. Go to IIS-->Sites-->Your Site-->
  2. Features View Pane-->Authentication
  3. Set Anonymous Authentication to Disabled
  4. Set Windows Authentication to Enabled

enter image description here

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

  1. On Windows: Add the path to the library to the PATH environment variable.
  2. On Linux: Add the path to the library to the LD_LIBRARY_PATH environment variable.
  3. On Mac: Add the path to the library to the DYLD_LIBRARY_PATH environment variable.

java.library.path is initilized with the values of the variables above on its corresponding platform.

This should work on any IDE.

You can test if the value is what you expect by calling java -XshowSettings:properties

How to increase font size in NeatBeans IDE?

Alt + scroll wheel will increase / decrease the font size of the main code window

__init__() missing 1 required positional argument

You should possibly make data a keyword parameter with a default value of empty dictionary:

class DHT:
    def __init__(self, data=dict()):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__': 
    DHT().showData()

Django Model() vs Model.objects.create()

The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:

from django.db import models

class Test(models.Model):

    added = models.DateTimeField(auto_now_add=True)

And you create a first object:

foo = Test.objects.create(pk=1)

Then you try to create an object with the same primary key:

foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")

foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")

What causes a SIGSEGV

The initial source cause can also be an out of memory.

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

How do you return a JSON object from a Java Servlet

You may use bellow like.

If you want use json array:

  1. download json-simple-1.1.1.jar & add to your project class path
  2. Create A class named Model like bellow

    public class Model {
    
     private String id = "";
     private String name = "";
    
     //getter sertter here
    }
    
  3. In sevlet getMethod you can use like bellow

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
      //begin get data from databse or other source
      List<Model> list = new ArrayList<>();
      Model model = new Model();
      model.setId("101");
      model.setName("Enamul Haque");
      list.add(model);
    
      Model model1 = new Model();
      model1.setId("102");
      model1.setName("Md Mohsin");
      list.add(model1);
      //End get data from databse or other source
    try {
    
        JSONArray ja = new JSONArray();
        for (Model m : list) {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("id", m.getId());
            jSONObject.put("name", m.getName());
            ja.add(jSONObject);
        }
        System.out.println(" json ja = " + ja);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(ja.toString());
        response.getWriter().flush();
       } catch (Exception e) {
         e.printStackTrace();
      }
    
     }
    
  4. Output:

        [{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
    

I you want json Object just use like:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        JSONObject json = new JSONObject();
        json.put("id", "108");
        json.put("name", "Enamul Haque");
        System.out.println(" json JSONObject= " + json);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        // System.out.println("Response Completed... ");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Above function Output:

{"name":"Enamul Haque","id":"108"}

Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

Using a dictionary to select function to execute

Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.

class P:

     def p1(self):
         print('Start')

     def p2(self):
         print('Help')

     def ps(self):
         print('Settings')

     def d(self):
         print('Default function')

     myDict = {
         "start": p1,
         "help": p2,
         "settings": ps
     }

     def call_it(self):
         name = 'start'
         f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
         f(self, name)


 p = P()
 p.call_it()

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

Laravel 5.2 - pluck() method returns array

In Laravel 5.1+, you can use the value() instead of pluck.

To get first occurence, You can either use

DB::table('users')->value('name');

or use,

DB::table('users')->where('id', 1)->pluck('name')->first();

SVN repository backup strategies

We use svnadmin hotcopy, e.g.:

svnadmin hotcopy C:\svn\repo D:\backups\svn\repo

As per the book:

You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository.

You can of course ZIP (preferably 7-Zip) the backup copy. IMHO It's the most straightforward of the backup options: in case of disaster there's little to do other than unzip it back into position.

html script src="" triggering redirection with button

your folder name is scripts..

and you are Referencing it like ../script/login.js

Also make sure that script folder is in your project directory

Thanks

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

PHP - Indirect modification of overloaded property

All you need to do is add "&" in front of your __get function to pass it as reference:

public function &__get ( $index )

Struggled with this one for a while.

Creating executable files in Linux

It's really not that big of a deal. You could just make a script with the single command:

chmod a+x *.pl

And run the script after creating a perl file. Alternatively, you could open a file with a command like this:

touch filename.pl && chmod a+x filename.pl && vi filename.pl # choose your favorite editor

Filter items which array contains any of given values

Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz

You'll probably want a Bool Query (or more likely Filter alongside another query), with a should clause.

The bool query has three main properties: must, should, and must_not. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should clause may specify a list filters, a match against any one of which will return the document you're looking for.

From the docs:

In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

Here's an example of what that Bool query might look like in isolation:

{
  "bool": {
    "should": [
      { "term": { "tag": "c" }},
      { "term": { "tag": "d" }}
    ]
  }
}

And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "bool": {
        "should": [
          { "term": { "tag": "c" }},
          { "term": { "tag": "d" }}
        ]
      }
    }
  }
}

Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.

It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.

Elasticsearch blog: All About Elasticsearch Filter Bitsets

Update with a refactored query...

Now, with all of that out of the way, the terms query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool + should using the minimum_should_match options, and overall is a bit more terse.

Here's that last query refactored a bit:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tag": [ "c", "d" ],
        "minimum_should_match": 1
      }
    }
  }
}

Protecting cells in Excel but allow these to be modified by VBA script

A basic but simple to understand answer:

Sub Example()
    ActiveSheet.Unprotect
    Program logic...
    ActiveSheet.Protect
End Sub

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

Delimiters in MySQL

You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/ 
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
    
    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;

ASP.NET MVC JsonResult Date Format

Override the controllers Json/JsonResult to return JSON.Net:

This works a treat

What's the advantage of a Java enum versus a class with public static final fields?

example:

public class CurrencyDenom {
   public static final int PENNY = 1;
 public static final int NICKLE = 5;
 public static final int DIME = 10;
public static final int QUARTER = 25;}

Limitation of java Constants

1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to int e.g. 99 though there is no coin to represent that value.

2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Advantage of enum

1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Currency coin = Currency.PENNY; coin = 1; //compilation error

2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.

3) You can specify values of enum constants at the creation time as shown in below example: public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)}; But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.

public enum Currency {
    PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
    private int value;

    private Currency(int value) {
            this.value = value;
    }
}; 

Reference: https://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

how to run or install a *.jar file in windows?

The UnsupportedClassVersionError means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.

Get protocol + host name from URL

If it contains less than 3 slashes thus you've it got and if not then we can find the occurrence between it:

import re

link = http://forum.unisoftdev.com/something

slash_count = len(re.findall("/", link))
print slash_count # output: 3

if slash_count > 2:
   regex = r'\:\/\/(.*?)\/'
   pattern  = re.compile(regex)
   path = re.findall(pattern, url)

   print path

Scroll to a specific Element Using html

<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>

/*CSS*/
html { scroll-behavior: smooth; } 

Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.

How can I access global variable inside class in Python

It is very simple to make a variable global in a class:

a = 0

class b():
    global a
    a = 10

>>> a
10

Why doesn't "System.out.println" work in Android?

if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:

try{
    Field outField = System.class.getDeclaredField("out");
    Field modifiersField = Field.class.getDeclaredField("accessFlags");
    modifiersField.setAccessible(true);
    modifiersField.set(outField, outField.getModifiers() & ~Modifier.FINAL);
    outField.setAccessible(true);
    outField.set(null, new PrintStream(new RedirectLogOutputStream()); 
}catch(NoSuchFieldException e){
    e.printStackTrace(); 
}catch(IllegalAccessException e){
    e.printStackTrace(); 
}

RedirectLogOutputStream class:

public class RedirectLogOutputStream extends OutputStream{
    private String mCache;

    @Override
    public void write(int b) throws IOException{
        if(mCache == null) mCache = "";

        if(((char) b) == '\n'){
            Log.i("redirect from system.out", mCache);
            mCache = "";
        }else{
            mCache += (char) b;
        }
    }
}

Select first and last row from grouped data

There is probably a faster way:

df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  filter(row_number()==1 | row_number()==n())

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Foreign key constraint may cause cycles or multiple cascade paths?

My solution to this problem encountered using ASP.NET Core 2.0 and EF Core 2.0 was to perform the following in order:

  1. Run update-database command in Package Management Console (PMC) to create the database (this results in the "Introducing FOREIGN KEY constraint ... may cause cycles or multiple cascade paths." error)

  2. Run script-migration -Idempotent command in PMC to create a script that can be run regardless of the existing tables/constraints

  3. Take the resulting script and find ON DELETE CASCADE and replace with ON DELETE NO ACTION

  4. Execute the modified SQL against the database

Now, your migrations should be up-to-date and the cascading deletes should not occur.

Too bad I was not able to find any way to do this in Entity Framework Core 2.0.

Good luck!

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host=127.0.0.1 -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';

mysql>FLUSH PRIVILEGES;

mysql> SELECT host FROM mysql.user WHERE User = 'root';

jQuery: Adding two attributes via the .attr(); method

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})

Change tab bar tint color on iOS 7

After trying out all the suggested solutions, I couldn't find any very helpful.

I finally tried the following:

[self.tabBar setTintColor:[UIColor orangeColor]];

which worked out perfectly.

I only provided one image for every TabBarItem. Didn't even need a selectedImage.

I even used it inside the Child-ViewControllers to set different TintColors:

UIColor *theColorYouWish = ...;
if ([[self.parentViewController class] isSubclassOfClass:[UITabBarController class]]){
    UITabBarController *tbc = (UITabBarController *) self.parentViewController;
    [tbc.tabBar setTintColor:theColorYouWish];
}

Wait some seconds without blocking UI execution

i really disadvise you against using Thread.Sleep(2000), because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.

I recommend to use a C# Timer instead of Thread.Sleep(). Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); method.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

For anyone looking at this and had no result with adding the Access-Control-Allow-Origin try also adding the Access-Control-Allow-Headers. May safe somebody from a headache.

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.

winpty docker exec -it <container-id> //bin//sh

How to check if a text field is empty or not in swift

As now in swift 3 / xcode 8 text property is optional you can do it like this:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

or:

if (textField.text?.isEmpty ?? true) {
    // is empty
}

Alternatively you could make an extenstion such as below and use it instead:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

ExpressionChangedAfterItHasBeenCheckedError Explained

I was struggling with this issue for a while, primarily while running tests in my dev environment. I was able to resolve the issue with a simple setTimeout around a service call response!

Python glob multiple filetypes

this worked for me:

import glob
images = glob.glob('*.JPG' or '*.jpg' or '*.png')

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Check the localhost_yyyy_mm_dd.log OR localhost.yyyy-mm-dd.log logs that Tomcat creates, these typically store that type of info. I wouldn't expect the full stacktrace to be dumped to standard out.

How can I sort generic list DESC and ASC?

without linq, use Sort() and then Reverse() it.

Can't start Tomcat as Windows Service

  1. Check the apache tomcat catalina log: ../logs/catalina.log
  2. If in the log you find the "port was used" exception, then Check windows used ports and processes with following command: Run cmd netstat -ao it will list all listening ports and corresponding process Id, you can find the port which was used by Tomcat from the configuration file: ../conf/server.xml

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
    

and kill the process which use the tomcat port

The project description file (.project) for my project is missing

I am using Eclipse 3.5.1 on Ubuntu. After rebooting my machine my projects in PHP Explorer view were giving the warning that the .project file was missing. The problem was that the external directory where my projects are hosted was not mounted on reboot. So I did a mount -a from the command line and the Eclipse recognized the files.

Find closing HTML tag in Sublime Text

There is a shortcut (Ctrl+Shift+A for Windows and Linux users, Command+Shift+A for Mac users) to select the whole block within the currently selected tag.

For example, if you pressed this while your text cursor was within the outer div tag in the code below, all the divs with class selected would be selected.

<div class='current_tag_block'>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
</div>

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}

Contain will help in getting Complete Image displayed inside Card.

Adjust height "30vh" according to your need!

How to print a linebreak in a python function?

for pair in zip(A, B):
    print ">"+'\n'.join(pair)

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

Suppress command line output

You can do this instead too:

tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

setting y-axis limit in matplotlib

Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

Take a look at the documentation for xlim and for ylim

ActiveRecord find and only return selected columns

In Rails 2

l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...

l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

In Rails 3 w/ActiveRecord Query Interface

l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

How to insert data using wpdb

$wpdb->query("insert into ".$table_name." (name, email, country, country, course, message, datesent) values ('$name','$email', '$phone', '$country', '$course', '$message', )");

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

How can I use a search engine to search for special characters?

A great search engine for special characters that I recenetly found: amp-what?

You can even search by object name, like "arrow", "chess", etc...

sort csv by column

To sort by MULTIPLE COLUMN (Sort by column_1, and then sort by column_2)

with open('unsorted.csv',newline='') as csvfile:
    spamreader = csv.DictReader(csvfile, delimiter=";")
    sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)


with open('sorted.csv', 'w') as f:
    fieldnames = ['column_1', 'column_2', column_3]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for row in sortedlist:
        writer.writerow(row)

How can I show a combobox in Android?

Here is an example of custom combobox in android:

package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

public class ComboBox extends LinearLayout {

   private AutoCompleteTextView _text;
   private ImageButton _button;

   public ComboBox(Context context) {
       super(context);
       this.createChildControls(context);
   }

   public ComboBox(Context context, AttributeSet attrs) {
       super(context, attrs);
       this.createChildControls(context);
}

 private void createChildControls(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

   _text = new AutoCompleteTextView(context);
   _text.setSingleLine();
   _text.setInputType(InputType.TYPE_CLASS_TEXT
                   | InputType.TYPE_TEXT_VARIATION_NORMAL
                   | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                   | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                   | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
   _text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
   this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT, 1));

   _button = new ImageButton(context);
   _button.setImageResource(android.R.drawable.arrow_down_float);
   _button.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                   _text.showDropDown();
           }
   });
   this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));
 }

/**
    * Sets the source for DDLB suggestions.
    * Cursor MUST be managed by supplier!!
    * @param source Source of suggestions.
    * @param column Which column from source to show.
    */
 public void setSuggestionSource(Cursor source, String column) {
    String[] from = new String[] { column };
    int[] to = new int[] { android.R.id.text1 };
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
                   android.R.layout.simple_dropdown_item_1line, source, from, to);
    // this is to ensure that when suggestion is selected
    // it provides the value to the textbox
    cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
    _text.setAdapter(cursorAdapter);
 }

/**
    * Gets the text in the combo box.
    *
    * @return Text.
    */
public String getText() {
    return _text.getText().toString();
 }

/**
    * Sets the text in combo box.
    */
public void setText(String text) {
    _text.setText(text);
   }
}

Hope it helps!!

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

How can I use ":" as an AWK field separator?

-F is an argument to awk itself:

$echo "1: " | awk -F":" '/1/ {print $1}'
1

Clear text from textarea with selenium

for java

driver.findelement(By.id('foo').clear();

or

webElement.clear();

If this element is a text entry element, this will clear the value.

Trim characters in Java

Hand made for the first option:

public class Rep {
    public static void main( String [] args ) {
       System.out.println( trimChar( '\\' , "\\\\\\joe\\jill\\\\\\\\" )  ) ;
       System.out.println( trimChar( '\\' , "joe\\jill" )  ) ;
    }
    private static String trimChar( char toTrim, String inString ) { 
        int from = 0;
        int to = inString.length();

        for( int i = 0 ; i < inString.length() ; i++ ) {
            if( inString.charAt( i ) != toTrim) {
                from = i;
                break;
            }
        }
        for( int i = inString.length()-1 ; i >= 0 ; i-- ){ 
            if( inString.charAt( i ) != toTrim ){
                to = i;
                break;
            }
        }
        return inString.substring( from , to );
    }
}

Prints

joe\jil

joe\jil

How to define an enum with string value?

You can't do this with enums, but you can do it like that:

public static class SeparatorChars
{
    public static string Comma = ",";

    public static string Tab = "\t";

    public static string Space = " ";
}

How can I share Jupyter notebooks with non-programmers?

The "best" way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it's certainly more complex; there's no built-in way to do this in Jupyter alone, but a couple of options are:

Host your own nbviewer

GitHub and the Jupyter Notebook Veiwer both use the same tool to render .ipynb files into static HTML, this tool is nbviewer.

The installation instructions are more complex than I'm willing to go into here but if your company/team has a shared server that doesn't require password access then you could host the nbviewer on that server and direct it to load from your credentialed server. This will probably require some more advanced configuration than you're going to find in the docs.

Set up a deployment script

If you don't necessarily need live updating HTML then you could set up a script on your credentialed server that will simply use Jupyter's built-in export options to create the static HTML files and then send those to a more publicly accessible server.

How to set text color in submit button?

you try this:

<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I didn't want to upgrade react-scripts, so I used the 3rd party reinstall npm module to reinstall it, and it worked.

npm i -g npm-reinstall
reinstall react-scripts

Importing PNG files into Numpy?

Using just scipy, glob and having PIL installed (pip install pillow) you can use scipy's imread method:

from scipy import misc
import glob

for image_path in glob.glob("/home/adam/*.png"):
    image = misc.imread(image_path)
    print image.shape
    print image.dtype

UPDATE

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead. See the answer by Charles.

Unit Testing C Code

Cmockery is a recently launched project that consists on a very simple to use C library for writing unit tests.

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

annotation to make a private method public only for test classes

An article on Testing Private Methods lays out some approaches to testing private code. using reflection puts extra burden on the programmer to remember if refactoring is done, the strings aren't automatically changed, but I think it's the cleanest approach.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

SQL like search string starts with

COLLATE UTF8_GENERAL_CI will work as ignore-case. USE:

SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';

or

SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';

Sql Server equivalent of a COUNTIF aggregate function

I would use this syntax. It achives the same as Josh and Chris's suggestions, but with the advantage it is ANSI complient and not tied to a particular database vendor.

select count(case when myColumn = 1 then 1 else null end)
from   AD_CurrentView

How do you do relative time in Rails?

You can use the arithmetic operators to do relative time.

Time.now - 2.days 

Will give you 2 days ago.

What is the difference between HTML tags and elements?

HTML Elements

An HTML element usually consists of a start tag and end tag, with the content inserted in between:

<tagname>Content goes here...</tagname>

The HTML element is everything from the start tag to the end tag. Source

HTML Attributes

An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts: a name and a value.

  • All HTML elements can have attributes
  • Attributes provide additional information about an element
  • Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like: name="value" Source

HTML Tag vs Element

"Elements" and "tags" are terms that are widely confused. HTML documents contain tags, but do not contain the elements. The elements are only generated after the parsing step, from these tags. Source: wikipedia > HTML_element

An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.

For example <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.

Source:tutorialspoint > html_elements

how to show progress bar(circle) in an activity having a listview before loading the listview with data

There are several methods of showing a progress bar (circle) while loading an activity. In your case, one with a ListView in it.

IN ACTIONBAR

If you are using an ActionBar, you can call the ProgressBar like this (this could go in your onCreate()

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
setProgressBarIndeterminateVisibility(true);

And after you are done displaying the list, to hide it.

setProgressBarIndeterminateVisibility(false);

IN THE LAYOUT (The XML)

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:divider="#00000000"
        android:dividerHeight="0dp"
        android:fadingEdge="none"
        android:persistentDrawingCache="scrolling"
        android:smoothScrollbar="false" >
    </ListView>
</LinearLayout>

And in your activity (Java) I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute() I use something like this:

// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

@Override
protected void onPreExecute() {    
    // SHOW THE SPINNER WHILE LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.VISIBLE);
}

and in the onPostExecute(), after setting the adapter to the ListView:

@Override
protected void onPostExecute(Void result) {     
    // SET THE ADAPTER TO THE LISTVIEW
    lv.setAdapter(adapter);

    // CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
    loadingMore = false;

    // HIDE THE SPINNER AFTER LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.GONE);
}

EDIT: This is how it looks in my app while loading one of several ListViews

enter image description here

CodeIgniter - Correct way to link to another page in a view

Best and easiest way is to use anchor tag in CodeIgniter like eg.

<?php 
    $this->load->helper('url'); 
    echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => '')); 
?>

Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details

This will surely work.

Writing outputs to log file and console

I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a), because I was wondering how to accomplish this using exec. I came across a creative solution using here-doc syntax and .: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script

I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:

#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor 
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged

It is not as readable as the exec solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh implements multios, but it may have less overhead than tee. Unfortunately it seems that one cannot use multios with exec.

Replace words in the body text

To replace a string in your HTML with another use the replace method on innerHTML:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

Note that this will replace the first instance of hello throughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution - for better results, try restricting the scope of your replacement by targeting your code using document.getElementById or similar.

To replace all instances of the target string, use a simple regular expression with the global flag:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

What is the maximum length of a valid email address?

user

The maximum total length of a user name is 64 characters.

domain

Maximum of 255 characters in the domain part (the one after the “@”)

However, there is a restriction in RFC 2821 reading:

The maximum total length of a reverse-path or forward-path is 256 characters, including the punctuation and element separators”. Since addresses that don’t fit in those fields are not normally useful, the upper limit on address lengths should normally be considered to be 256, but a path is defined as: Path = “<” [ A-d-l “:” ] Mailbox “>” The forward-path will contain at least a pair of angle brackets in addition to the Mailbox, which limits the email address to 254 characters.

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

get parent's view from a layout

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

You should use this example with AUTHID CURRENT_USER :

CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
   AUTHID CURRENT_USER
IS
   SEQ_NAME       VARCHAR2 (100);
   FINAL_QUERY    VARCHAR2 (100);
   COUNT_NUMBER   NUMBER := 0;
   cur_id         NUMBER;
BEGIN
   SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;

   SELECT COUNT (*)
     INTO COUNT_NUMBER
     FROM USER_SEQUENCES
    WHERE SEQUENCE_NAME = SEQ_NAME;

   DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);

   IF COUNT_NUMBER = 0
   THEN
      --DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
      -- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
      -- ELSE
      SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
        INTO FINAL_QUERY
        FROM DUAL;

      DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
      cur_id := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
      DBMS_SQL.CLOSE_CURSOR (cur_id);
   -- EXECUTE IMMEDIATE FINAL_QUERY;

   END IF;

   COMMIT;
END;
/

Iif equivalent in C#

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";

How to pass table value parameters to stored procedure from .net code

Use this code to create suitable parameter from your type:

private SqlParameter GenerateTypedParameter(string name, object typedParameter)
{
    DataTable dt = new DataTable();

    var properties = typedParameter.GetType().GetProperties().ToList();
    properties.ForEach(p =>
    {
        dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
    });
    var row = dt.NewRow();
    properties.ForEach(p => { row[p.Name] = (p.GetValue(typedParameter) ?? DBNull.Value); });
    dt.Rows.Add(row);

    return new SqlParameter
    {
        Direction = ParameterDirection.Input,
        ParameterName = name,
        Value = dt,
        SqlDbType = SqlDbType.Structured
    };
}

Sending Email in Android using JavaMail API without using the default/built-in app

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("[email protected]", "yourPassword")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("smtp.gmail.com", 465)
    
    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private val server: String, private val port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

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

Generate an integer that is not among four billion given ones

EDIT Ok, this wasn't quite thought through as it assumes the integers in the file follow some static distribution. Apparently they don't need to, but even then one should try this:


There are ˜4.3 billion 32-bit integers. We don't know how they are distributed in the file, but the worst case is the one with the highest Shannon entropy: an equal distribution. In this case, the probablity for any one integer to not occur in the file is

( (2³²-1)/2³² )4 °°° °°° °°° ˜ .4

The lower the Shannon entropy, the higher this probability gets on the average, but even for this worst case we have a chance of 90% to find a nonoccurring number after 5 guesses with random integers. Just create such numbers with a pseudorandom generator, store them in a list. Then read int after int and compare it to all of your guesses. When there's a match, remove this list entry. After having been through all of the file, chances are you will have more than one guess left. Use any of them. In the rare (10% even at worst case) event of no guess remaining, get a new set of random integers, perhaps more this time (10->99%).

Memory consumption: a few dozen bytes, complexity: O(n), overhead: neclectable as most of the time will be spent in the unavoidable hard disk accesses rather than comparing ints anyway.


The actual worst case, when we do not assume a static distribution, is that every integer occurs max. once, because then only 1 - 4000000000/2³² ˜ 6% of all integers don't occur in the file. So you'll need some more guesses, but that still won't cost hurtful amounts of memory.

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

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

EDIT: 2020 PHP 5.4+ and 7+

As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just used.


Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `__call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.

Exact answer

No you can't, respectively, not really, as manual of extends keyword says:

An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.

Real answer

However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.

You CAN extend one class, with another and another with another and so on...

So pretty simple example on this would be:

class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...

Important note

As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.

...And finally example with some output:

class A{
  function a_hi(){
    echo "I am a of A".PHP_EOL."<br>".PHP_EOL;  
  }
}

class B extends A{
  function b_hi(){
    echo "I am b of B".PHP_EOL."<br>".PHP_EOL;  
  }
}

class C extends B{
  function c_hi(){
    echo "I am c of C".PHP_EOL."<br>".PHP_EOL;  
  }
}

$myTestInstance = new C();

$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();

Which outputs

I am a of A 
I am b of B 
I am c of C 

Extracting time from POSIXct

The data.table package has a function 'as.ITime', which can do this efficiently use below:

library(data.table)
x <- "2012-03-07 03:06:49 CET"
as.IDate(x) # Output is "2012-03-07"
as.ITime(x) # Output is "03:06:49"

Get specific objects from ArrayList when objects were added anonymously?

If you want to lookup objects based on their String name, this is a textbook case for a Map, say a HashMap. You could use a LinkedHashMap and convert it to a List or Array later (Chris has covered this nicely in the comments below).

LinkedHashMap because it lets you access the elements in the order you insert them if you want to do so. Otherwise HashMap or TreeMap will do.

You could get this to work with List as the others are suggesting, but that feels Hacky to me.. and this will be cleaner both in short and long run.

If you MUST use a list for the object, you could still store a Map of the object name to the index in the array. This is a bit uglier, but you get almost the same performance as a plain Map.

Android: How to get a custom View's height and width?

Don't try to get them inside its constructor. Try Call them in onDraw() method.

How to make an "alias" for a long path?

First off, you need to remove the quotes:

bashboy@host:~$ myFolder=~/Files/Scripts/Main

The quotes prevent the shell from expanding the tilde to its special meaning of being your $HOME directory.

You could then use $myFolder an environment a shell variable:

bashboy@host:~$ cd $myFolder
bashboy@host:~/Files/Scripts/Main$

To make an alias, you need to define the alias:

alias myfolder="cd $myFolder"

You can then treat this sort of like a command:

bashboy@host:~$ myFolder
bashboy@host:~/Files/Scripts/Main$

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

How to create a new branch from a tag?

My branch list (only master now)

branch list

My tag list (have three tags)

tag list

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec

switch to branch

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

How to print pthread_t

In this case, it depends on the operating system, since the POSIX standard no longer requires pthread_t to be an arithmetic type:

IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/26 is applied, adding pthread_t to the list of types that are not required to be arithmetic types, thus allowing pthread_t to be defined as a structure.

You will need to look in your sys/types.h header and see how pthread_t is implemented; then you can print it how you see fit. Since there isn't a portable way to do this and you don't say what operating system you are using, there's not a whole lot more to say.

Edit: to answer your new question, GDB assigns its own thread ids each time a new thread starts:

For debugging purposes, gdb associates its own thread number—always a single integer—with each thread in your program.

If you are looking at printing a unique number inside of each thread, your cleanest option would probably be to tell each thread what number to use when you start it.

How do I make the scrollbar on a div only visible when necessary?

try

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Convert an image (selected by path) to base64 string

Something like that

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function

Adding the "Clear" Button to an iPhone UITextField

This button is a built-in overlay that is provided by the UITextField class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder. You have to enable it programmatically.

Add this line of code somewhere (viewDidLoad, for example):

Objective-C

myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

Swift 5.0

myUITextField.clearButtonMode = .whileEditing

Best Practices for Custom Helpers in Laravel 5

my initial thought was the composer autoload as well, but it didn't feel very Laravel 5ish to me. L5 makes heavy use of Service Providers, they are what bootstraps your application.

To start off I created a folder in my app directory called Helpers. Then within the Helpers folder I added files for functions I wanted to add. Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable.

Next I created a HelperServiceProvider.php by running the artisan command:

artisan make:provider HelperServiceProvider

Within the register method I added this snippet

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

lastly register the service provider in your config/app.php in the providers array

'providers' => [
    'App\Providers\HelperServiceProvider',
]

now any file in your Helpers directory is loaded, and ready for use.

UPDATE 2016-02-22

There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. You can either use the package for inspiration or feel free to download it with Composer as well. It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. Feedback and PRs are much appreciated!

composer require browner12/helpers

Github: browner12/helpers

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How can I change the class of an element with jQuery>

Use jQuery's

$(this).addClass('showhideExtra_up_hover');

and

$(this).addClass('showhideExtra_down_hover');

pdftk compression option

If file size is still too large it could help using ps2pdf to downscale the resolution of the produced pdf file:

pdf2ps input.pdf tmp.ps
ps2pdf -dPDFSETTINGS=/screen -dDownsampleColorImages=true -dColorImageResolution=200 -dColorImageDownsampleType=/Bicubic tmp.ps output.pdf

Adjust the value of the -dColorImageResolution option to achieve a result that fits your needs (the value describes the image resolution in DPIs). If your input file is in grayscale, replacing Color through Gray or using both options in the above command could also help. Further fine-tuning is possible by changing the -dPDFSETTINGS option to /default or /printer. For explanations of the all possible options consult the ps2pdf manual.

MySQL error 2006: mysql server has gone away

It was RAM problem for me.

I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

And, it fixed everything. I have set it under cron to run every hour.

crontab -e

0 * * * * bash /root/ram.sh;

And, you can use this command to check how much free RAM available:

free -h

And, you will get something like this:

             total       used       free     shared    buffers     cached
Mem:           31G        12G        18G        59M       1.9G       973M
-/+ buffers/cache:       9.9G        21G
Swap:         8.0G       368M       7.6G

PHP server on local machine?

MAMP if you are on a MAC MAMP

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

jQuery $.ajax(), pass success data into separate function

this is how I do it

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

How can I see what I am about to push with git?

For a list of files to be pushed, run:

git diff --stat --cached [remote/branch]

example:

git diff --stat --cached origin/master

For the code diff of the files to be pushed, run:

git diff [remote repo/branch]

To see full file paths of the files that will change, run:

git diff --numstat [remote repo/branch]

If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.

Android get current Locale, not default

Android N (Api level 24) update (no warnings):

   Locale getCurrentLocale(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            return context.getResources().getConfiguration().getLocales().get(0);
        } else{
            //noinspection deprecation
            return context.getResources().getConfiguration().locale;
        }
    }

Most common C# bitwise operations on enums

@Drew

Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

[Flags]
public enum TestFlags
{
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512
}


class Program
{
    static void Main(string[] args)
    {
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            result |= f.HasFlag(TestFlags.Three);
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        s.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            result |= (f & TestFlags.Three) != 0;
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        

        Console.ReadLine();
    }
}

Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

HTML input arrays

It's just PHP, not HTML.

It parses all HTML fields with [] into an array.

So you can have

<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />

and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

echo $_POST['food'][0]; // would output first checkbox selected

or to see all values selected:

foreach( $_POST['food'] as $value ) {
    print $value;
}

Anyhow, don't think there is a specific name for it

Regular Expression: Any character that is NOT a letter or number

To match anything other than letter or number you could try this:

[^a-zA-Z0-9]

And to replace:

var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Replacing all non-alphanumeric characters with empty strings

Guava's CharMatcher provides a concise solution:

output = CharMatcher.javaLetterOrDigit().retainFrom(input);

Jquery click not working with ipad

Probably rather than defining both the events click and touch you could define a an handler which will look if the device will work with click or touch.

var handleClick= 'ontouchstart' in document.documentElement ? 'touchstart': 'click';
$(document).on(handleClick,'.button',function(){
alert('Click is now working with touch and click both');
});

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

Using colors with printf

man printf.1 has a note at the bottom: "...your shell may have its own version of printf...". This question is tagged for bash, but if at all possible, I try to write scripts portable to any shell. dash is usually a good minimum baseline for portability - so the answer here works in bash, dash, & zsh. If a script works in those 3, it's most likely portable to just about anywhere.

The latest implementation of printf in dash[1] doesn't colorize output given a %s format specifier with an ANSI escape character \e -- but, a format specifier %b combined with octal \033 (equivalent to an ASCII ESC) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf to use the ASCII octal subset at a bare minimum.

To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b format specifier for printf (as referenced in an earlier answer from @Vlad) with an octal escape \033.


portable-color.sh

#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"

Outputs:

$ ./portable-color.sh
-> This is \033[1;34m blue   \033[0m text
-> This is  blue    text

...and 'blue' is blue in the second line.

The %-6s format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.


[1] Ref: man dash Section "Builtins" :: "printf" :: "Format"

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

I had this problem, it is for foreign-key

Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key

enter image description here

Hope that works!

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Move top 1000 lines from text file to a new file using Unix shell commands

Perl approach:

perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in

How to close activity and go back to previous activity in android

You are making this too hard. If I understand what you are trying to do correctly, the built-in 'back' button and Android itself will do all the work for you: http://developer.android.com/guide/components/tasks-and-back-stack.html

Also, implementing a custom "back" button violates Core App Quality Guideline UX-N1: http://developer.android.com/distribute/googleplay/quality/core.html

How do I import a .sql file in mysql database using PHP?

// Import data 
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);

function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
    $connection = mysqli_connect($host,$uname,$pass)
    or die("Database Connection Failed");
    $selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected"); 

$templine = '';
$lines = file($filename); // Read entire file

foreach ($lines as $line){
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
        continue;

        // Add this line to the current segment
        $templine .= $line;
        // If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';')
        {
            mysqli_query($connection, $templine)
            or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
            $templine = '';
        }
    }
    echo "Tables imported successfully";
}




// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');

function backup_tables($host,$user,$pass,$name,$tables = '*'){
    $link = mysqli_connect($host,$user,$pass);
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_select_db($link,$name);
    //get all of the tables
    if($tables == '*'){
        $tables = array();
        $result = mysqli_query($link,'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }else{
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    foreach($tables as $table)
    {
        $result = mysqli_query($link,'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
        $row2 = mysqli_fetch_row($row_query);
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysqli_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j < $num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n", '\n', $row[$j]);
                    if (isset($row[$j])) { 
                        $return.= '"'.$row[$j].'"' ; 
                    } else { 
                        $return.= '""'; 
                    }
                    if ($j < ($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

Mongodb: failed to connect to server on first connect

For me,issue was mongo was not running.So first i started "mongod" command in the console.And later in another console tab I have run "mongo". Now the connection is successful. Now run your app your problem should be solved.

How to run a command in the background on Windows?

If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.

using System;
using System.Linq;
using System.Diagnostics;
using System.IO;

namespace BgRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: " + String.Join(" ", args));
            String arguments = String.Join(" ", args.Skip(1).ToArray());
            String command = args[0];

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(command);
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.Start();
        }
    }
}

Examples of usage:

BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx

How can I make a button redirect my page to another page?

Just add an onclick event to the button:

<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>

But you shouldn't really have it inline like that, instead, put it in a JS block and give the button an ID:

<button id="myButton" class="float-left submit-button" >Home</button>

<script type="text/javascript">
    document.getElementById("myButton").onclick = function () {
        location.href = "www.yoursite.com";
    };
</script>

Include files from parent or other directory

You may interest in using php's inbuilt function realpath(). and passing a constant DIR

for example: $TargetDirectory = realpath(__DIR__."/../.."); //Will take you 2 folder's back

String realpath() :: Returns canonicalized absolute pathname ..

Create directories using make file

make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget

This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

# The pipe symbol tells make that the following prerequisites are order-only
#                           |
#                           v
outDir/someTarget: Makefile | outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

This correctly yields:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.

TL;DR:

Write a rule to create the directory:

$(OUT_DIR):
    mkdir -p $(OUT_DIR)

And have the targets for the stuff inside depend on the directory order-only:

$(OUT_DIR)/someTarget: ... | $(OUT_DIR)

Make virtualenv inherit specific packages from your global site-packages

Install virtual env with

virtualenv --system-site-packages

and use pip install -U to install matplotlib

Android Completely transparent Status Bar?

The following code will create a fully transparent status bar:

package com.demo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
            setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
        }
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public static void setWindowFlag(Activity activity, final int bits, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}

How to convert byte array to string and vice versa?

Try to specify an 8-bit charset in both conversions. ISO-8859-1 for instance.

Mapping over values in a python dictionary

There is no such function; the easiest way to do this is to use a dict comprehension:

my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

As such, you could use the map() function for processing your dict as well:

my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))

but that's not that readable, really.

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)