Programs & Examples On #Zbuffer

is an array used to store the maximum Z coordinate of any feature plotted at a given (X, Y) location on the screen.

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

Count rows with not empty value

A very flexible way to do that kind of things is using ARRAYFORMULA.

As an example imagine you want to count non empty strings (text fields) you can use this code:

=ARRAYFORMULA(SUM(IF(Len(B3:B14)>0, 1, 0)))

What happens here is that "ArrayFormula" let you operate over a set of values. Using the SUM function you indicates "ArrayFormula" to sum any value of the set. The "If" clause is only used to check "empty" or "not empty", 1 for not empty and 0 otherwise. "Len" returns the length of the different text fields, there is where you define the set (range) you want to check. Finally "ArrayFormula" will sum 1 for each field inside the set(range) in which "len" returns more than 0.

If you want to check any other condition, just modify the first argument of the IF clause.

CMake link to external library

Set libraries search path first:

LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)

And then just do

TARGET_LINK_LIBRARIES(GLBall mylib)

Java string to date conversion

My humble test program. I use it to play around with the formatter and look-up long dates that I find in log-files (but who has put them there...).

My test program:

package be.test.package.time;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class TimeWork {

    public static void main(String[] args) {    

        TimeZone timezone = TimeZone.getTimeZone("UTC");

        List<Long> longs = new ArrayList<>();
        List<String> strings = new ArrayList<>();

        //Formatting a date needs a timezone - otherwise the date get formatted to your system time zone.
        //Use 24h format HH. In 12h format hh can be in range 0-11, which makes 12 overflow to 0.
        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
        formatter.setTimeZone(timezone);

        Date now = new Date();

        //Test dates
        strings.add(formatter.format(now));
        strings.add("01-01-1970 00:00:00.000");
        strings.add("01-01-1970 00:00:01.000");
        strings.add("01-01-1970 00:01:00.000");
        strings.add("01-01-1970 01:00:00.000");
        strings.add("01-01-1970 10:00:00.000");
        strings.add("01-01-1970 12:00:00.000");
        strings.add("01-01-1970 24:00:00.000");
        strings.add("02-01-1970 00:00:00.000");
        strings.add("01-01-1971 00:00:00.000");
        strings.add("01-01-2014 00:00:00.000");
        strings.add("31-12-1969 23:59:59.000");
        strings.add("31-12-1969 23:59:00.000");
        strings.add("31-12-1969 23:00:00.000");

        //Test data
        longs.add(now.getTime());
        longs.add(-1L);
        longs.add(0L); //Long date presentation at - midnight 1/1/1970 UTC - The timezone is important!
        longs.add(1L);
        longs.add(1000L);
        longs.add(60000L);
        longs.add(3600000L);
        longs.add(36000000L);
        longs.add(43200000L);
        longs.add(86400000L);
        longs.add(31536000000L);
        longs.add(1388534400000L);
        longs.add(7260000L);
        longs.add(1417706084037L);
        longs.add(-7260000L);

        System.out.println("===== String to long =====");

        //Show the long value of the date
        for (String string: strings) {
            try {
                Date date = formatter.parse(string);
                System.out.println("Formated date : " + string + " = Long = " + date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        System.out.println("===== Long to String =====");

        //Show the date behind the long
        for (Long lo : longs) {
            Date date = new Date(lo);
            String string = formatter.format(date);
            System.out.println("Formated date : " + string + " = Long = " + lo);        
        }
    }
}

Test results:

===== String to long =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 01-01-1970 24:00:00.000 = Long = 86400000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 31-12-1969 23:59:59.000 = Long = -1000
Formated date : 31-12-1969 23:59:00.000 = Long = -60000
Formated date : 31-12-1969 23:00:00.000 = Long = -3600000
===== Long to String =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 31-12-1969 23:59:59.999 = Long = -1
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:00.001 = Long = 1
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 01-01-1970 02:01:00.000 = Long = 7260000
Formated date : 04-12-2014 15:14:44.037 = Long = 1417706084037
Formated date : 31-12-1969 21:59:00.000 = Long = -7260000

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

How to add http:// if it doesn't exist in the URL

nickf's solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

MyISAM versus InnoDB

I'm not a database expert, and I do not speak from experience. However:

MyISAM tables use table-level locking. Based on your traffic estimates, you have close to 200 writes per second. With MyISAM, only one of these could be in progress at any time. You have to make sure that your hardware can keep up with these transaction to avoid being overrun, i.e., a single query can take no more than 5ms.

That suggests to me you would need a storage engine which supports row-level locking, i.e., InnoDB.

On the other hand, it should be fairly trivial to write a few simple scripts to simulate the load with each storage engine, then compare the results.

Return values from the row above to the current row

You can also use =OFFSET([@column];-1;0) if you are in a named table.

How do I find out what type each object is in a ArrayList<Object>?

Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

How to add image in Flutter

their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention

assets: - images/lake.jpg // inside pubspec.yaml

How can I reverse the order of lines in a file?

It happens to me that I want to get the last n lines of a very large text file efficiently.

The first thing I tried is tail -n 10000000 file.txt > ans.txt, but I found it very slow, for tail has to seek to the location and then moves back to print the results.

When I realize it, I switch to another solution: tac file.txt | head -n 10000000 > ans.txt. This time, the seek position just needs to move from the end to the desired location and it saves 50% time!

Take home message:

Use tac file.txt | head -n n if your tail does not have the -r option.

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Python Pandas Counting the Occurrences of a Specific value

Couple of ways using count or sum

In [338]: df
Out[338]:
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2

In [336]: (df.education == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

From the JIRA knowledge base:

Symptoms

Workflow actions may be inaccessible

  1. JIRA may throw exceptions on screen
  2. One or both of the following conditions may exist:

The following appears in the atlassian-jira.log:

     2007-12-06 10:55:05,327 http-8080-Processor20 ERROR [500ErrorPage] 
     Exception caught in500 page Unable to compile class for JSP
    org.apache.jasper.JasperException: Unable to compile class for JSP
   at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:572)
   at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:305)

_

Cause:

The Tomcat container caches .java and .class files generated by the JSP parser they are used by the web application. Sometimes these get corrupted or cannot be found. This may occur after a patch or upgrade that contains modifications to JSPs.

Resolution

1.Delete the contents of the /work folder if using standalone JIRA or /work if using EAR/WAR installation . 2. Verify the user running the JIRA application process has Read/Write permission to the /work directory. 3. Restart the JIRA application container to rebuild the files.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

If you need to write line by line from string builder

StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

If you need to write all text as single line from string builder

StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

Why doesn't os.path.join() work in this case?

you can strip the '/':

>>> os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/'.strip('/'))
'/home/build/test/sandboxes/04122019/new_sandbox'

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

The latest version of the pipeline sh step allows you to do the following;

// Git committer email
GIT_COMMIT_EMAIL = sh (
    script: 'git --no-pager show -s --format=\'%ae\'',
    returnStdout: true
).trim()
echo "Git committer email: ${GIT_COMMIT_EMAIL}"

Another feature is the returnStatus option.

// Test commit message for flags
BUILD_FULL = sh (
    script: "git log -1 --pretty=%B | grep '\\[jenkins-full]'",
    returnStatus: true
) == 0
echo "Build full flag: ${BUILD_FULL}"

These options where added based on this issue.

See official documentation for the sh command.

For declarative pipelines (see comments), you need to wrap code into script step:

script {
   GIT_COMMIT_EMAIL = sh (
        script: 'git --no-pager show -s --format=\'%ae\'',
        returnStdout: true
    ).trim()
    echo "Git committer email: ${GIT_COMMIT_EMAIL}"
}

What is the use of the square brackets [] in sql statements?

During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.

So it keeps forward compatibility.

And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

Custom Date Format for Bootstrap-DatePicker

Perhaps you can check it here for the LATEST version always

http://bootstrap-datepicker.readthedocs.org/en/latest/

$('.datepicker').datepicker({
    format: 'mm/dd/yyyy',
    startDate: '-3d'
})

or

$.fn.datepicker.defaults.format = "mm/dd/yyyy";
$('.datepicker').datepicker({
    startDate: '-3d'
})

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

How do you read scanf until EOF in C?

For C users, this will also work

while ( gets(str) != NULL )

Get push notification while App in foreground iOS

For swift 5 to parse PushNotification dictionary

    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
            if application.applicationState == .active {
                if let aps1 = data["aps"] as? NSDictionary {
                    if let dict = aps1["alert"] as? NSDictionary {
                        if let strTitle = dict["title"] as? String , let strBody = dict["body"] as? String {
                            if let topVC = UIApplication.getTopViewController() {
                                //Apply your own logic as per requirement
                                print("strTitle ::\(strTitle) , strBody :: \(strBody)")
                            }
                        }
                    }
                }
            }
        }

To fetch top viewController on which we show topBanner

extension UIApplication {

    class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)

        } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return getTopViewController(base: selected)

        } else if let presented = base?.presentedViewController {
            return getTopViewController(base: presented)
        }
        return base
    }
}

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Python extending with - using super() Python 3 vs Python 2

In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.

Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.

In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).

If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):

class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.

What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.

So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).

So by doing nothing in C, you end up calling both, which is what you want.

Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.

class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.

What is the best way to determine a session variable is null or empty in C#?

Are you using .NET 3.5? Create an IsNull extension method:

public static bool IsNull(this object input)
{
    input == null ? return true : return false;
}

public void Main()
{
   object x = new object();
   if(x.IsNull)
   {
      //do your thing
   }
}

Changing the image source using jQuery

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

This solution is useful and it works but if changing the path change also the path for image and not working.

I've searching for resolve this issue but not found nothing.

The solution is putting the '\' at the beginning the path: $("#myid").attr('src', '\images/sample.gif');

This trick is very useful for me and I hope it is useful for other.

What's the difference between MyISAM and InnoDB?

MYISAM:

  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. MYISAM supports fulltext search
  7. You can use MyISAM, if the table is more static with lots of select and less update and delete.

INNODB:

  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

mysqli_real_connect(): (HY000/2002): No such file or directory

First of all, make sure the mysql service is running:

ps elf|grep mysql

you will see an output like this if is running:

4 S root      9642     1  0  80   0 -  2859 do_wai 23:08 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/tomcat-machine.local.pid
4 S mysql     9716  9642  0  80   0 - 200986 poll_s 23:08 pts/0   00:00:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/lib/mysql/tomcat-machine.local.err --pid-file=/var/lib/mysql/tomcat-machine.local.pid

then change localhost to 127.0.0.1 in config.inc.php

$cfg['Servers'][$i]['host'] = '127.0.0.1';

The default password for "root" user is empty "" do not type anything for the password

If it does not allow empty password you need to edit config.inc.php again and change:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

The problem is a combination of config settings and MySQL not running. This was what helped me to fix this error.

Back to previous page with header( "Location: " ); in PHP

try:

header('Location: ' . $_SERVER['HTTP_REFERER']);

Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.

Ideally, you will want to either:

  • Append the return address to the request as a query variable (eg. ?back=/list)
  • Define a return page in your code (ie. all successful form submissions redirect to the listing page)
  • Provide the user the option of where they want to go next (eg. Save and continue editing or just Save)

How do I stop/start a scheduled task on a remote computer programmatically?

schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword 

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

Using MySQL with Entity Framework

Be careful using connector .net, Connector 6.6.5 have a bug, it is not working for inserting tinyint values as identity, for example:

create table person(
    Id tinyint unsigned primary key auto_increment,
    Name varchar(30)
);

if you try to insert an object like this:

Person p;
p = new Person();
p.Name = 'Oware'
context.Person.Add(p);
context.SaveChanges();

You will get a Null Reference Exception:

Referencia a objeto no establecida como instancia de un objeto.:
   en MySql.Data.Entity.ListFragment.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SelectStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.InsertStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SqlFragment.ToString()
   en MySql.Data.Entity.InsertGenerator.GenerateSQL(DbCommandTree tree)
   en MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   en System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   en System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   en System.Data.Entity.Internal.InternalContext.SaveChanges()
   en System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   en System.Data.Entity.DbContext.SaveChanges()

Until now I haven't found a solution, I had to change my tinyint identity to unsigned int identity, this solved the problem but this is not the right solution.

If you use an older version of Connector.net (I used 6.4.4) you won't have this problem.

If someone knows about the solution, please contact me.

Cheers!

Oware

How to create a jQuery function (a new jQuery method or plugin)?

Yup — what you’re describing is a jQuery plugin.

To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object jQuery.fn.

E.g.

jQuery.fn.myfunction = function(param) {
    // Some code
}

Within your plugin function, the this keyword is set to the jQuery object on which your plugin was invoked. So, when you do:

$('#my_div').myfunction()

Then this inside myfunction will be set to the jQuery object returned by $('#my_div').

See http://docs.jquery.com/Plugins/Authoring for the full story.

Resolve host name to an ip address

This is hard to answer without more detail about the network architecture. Some things to investigate are:

  • Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
  • Is any of the IP addresses involved a "local" address, like 192.168.x.y or 10.x.y.z?
  • What are the host names, are they "real" DNS:able names or something more local and/or Windows-specific?
  • How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.

How can I jump to class/method definition in Atom text editor?

I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.

This package is DEPRECATED. Please check it in Github.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

If your passing id, then try to follow this method

 const routes: Routes = [
  {path:"", redirectTo:"/home", pathMatch:"full"},
  {path:"home", component:HomeComponent},
  {path:"add", component:AddComponent},
  {path:"edit/:id", component:EditComponent},
  {path:"show/:id", component:ShowComponent}
];
@NgModule({
  imports: [

    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

This works for me every time:

navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});

Though it isn't very accurate. The funny thing is that on the same device if I run this it puts me off about 100 meters (every time), but if I go to google's maps it finds my location exactly. So although I think the enableHighAccuracy: true helps it to work consistently, it doesn't seem to make it any more accurate...

What is the difference between a schema and a table and a database?

A database schema is a way to logically group objects such as tables, views, stored procedures etc. Think of a schema as a container of objects. And tables are collections of rows and columns. combination of all tables makes a db.

Package name does not correspond to the file path - IntelliJ

I had this same issue, and fixed it by modifying my project's .iml file:

From:

<content url="file://$MODULE_DIR$">
  <sourceFolder url="file://$MODULE_DIR$/src/wrong/entry/here" isTestSource="false" />
  <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
  <excludeFolder url="file://$MODULE_DIR$/target" />
</content>

To:

<content url="file://$MODULE_DIR$">
  <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
  <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
  <excludeFolder url="file://$MODULE_DIR$/target" />
</content>

Somehow a package folder became specified as the root source directory when this project was imported.

How to ignore ansible SSH authenticity checking?

I found the answer, you need to set the environment variable ANSIBLE_HOST_KEY_CHECKING to False. For example:

ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook ...

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

adb remount permission denied, but able to access super user in shell -- android

emulator -writable-system

For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858

How to truncate text in Angular2?

Like this:

{{ data.title | slice:0:20 }}

And if you want the ellipsis, here's a workaround

{{ data.title | slice:0:20 }}...

POSTing JsonObject With HttpClient From Web API

Thank you pomber but for

var result = client.PostAsync(url, content).Result;

I used

var result = await client.PostAsync(url, content);

because Result makes app lock for high request

How can I detect when the mouse leaves the window?

This worked for me. A combination of some of the answers here. And I included the code showing a model only once. And the model goes away when clicked anywhere else.

<script>
    var leave = 0
    //show modal when mouse off of page
    $("html").mouseleave(function() {
       //check for first time
       if (leave < 1) {
          modal.style.display = "block";
          leave = leave + 1;
       }
    });

    // Get the modal with id="id01"
       var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
       window.onclick = function(event) {
          if (event.target == modal) {
             modal.style.display = "none";
          }
       }
</script>

How to extract the substring between two markers?

With sed it is possible to do something like this with a string:

echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"

And this will give me 1234 as a result.

You could do the same with re.sub function using the same regex.

>>> re.sub(r'.*AAA(.*)ZZZ.*', r'\1', 'gfgfdAAA1234ZZZuijjk')
'1234'

In basic sed, capturing group are represented by \(..\), but in python it was represented by (..).

What USB driver should we use for the Nexus 5?

This worked for me:

  1. Download the Nexus 5 Drivers from Google USB Driver
  2. Extract the ZIP contents and place all files in a single folder on your desktop.
  3. Connect your device to your computer.
  4. Launch the Device Manager on your PC.
  5. Now you should see the Nexus 5 listed in the hardware list.
  6. Right-click the ‘Nexus 5' line and then click on Update Driver Software.
  7. Next, click the ‘browse my computer’ option.
  8. In the new window, click on ‘Browse…’ button.
  9. Go to folder unzipped at step 2. Select the folder where you extract the USB drivers. Click Next.
    • Make sure to tick the subfolder box too.
  10. Now, the Windows installer will search for Nexus 5 drivers. Click Install when asked for permission.
  11. Wait for the process to complete and then check the Device Manager list to confirm that the installation was successful.

Source: Download and Install Google Nexus 5 USB Drivers (ADB / Fastboot)

How to update PATH variable permanently from Windows command line?

For reference purpose, for anyone searching how to change the path via code, I am quoting a useful post by a Delphi programmer from this web page: http://www.tek-tips.com/viewthread.cfm?qid=686382

TonHu (Programmer) 22 Oct 03 17:57 I found where I read the original posting, it's here: http://news.jrsoftware.org/news/innosetup.isx/msg02129....

The excerpt of what you would need is this:

You must specify the string "Environment" in LParam. In Delphi you'd do it this way:

 SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));

It was suggested by Jordan Russell, http://www.jrsoftware.org, the author of (a.o.) InnoSetup, ("Inno Setup is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability.") (I just would like more people to use InnoSetup )

HTH

How to prevent a double-click using jQuery?

This is my first ever post & I'm very inexperienced so please go easy on me, but I feel I've got a valid contribution that may be helpful to someone...

Sometimes you need a very big time window between repeat clicks (eg a mailto link where it takes a couple of secs for the email app to open and you don't want it re-triggered), yet you don't want to slow the user down elsewhere. My solution is to use class names for the links depending on event type, while retaining double-click functionality elsewhere...

var controlspeed = 0;

$(document).on('click','a',function (event) {
    eventtype = this.className;
    controlspeed ++;
    if (eventtype == "eg-class01") {
        speedlimit = 3000;
    } else if (eventtype == "eg-class02") { 
        speedlimit = 500; 
    } else { 
        speedlimit = 0; 
    } 
    setTimeout(function() {
        controlspeed = 0;
    },speedlimit);
    if (controlspeed > 1) {
        event.preventDefault();
        return;
    } else {

        (usual onclick code goes here)

    }
});

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

How to make an input type=button act like a hyperlink and redirect using a get request?

You can make <button> tag to do action like this:

<a href="http://www.google.com/">
   <button>Visit Google</button>
</a>

or:

<a href="http://www.google.com/">
   <input type="button" value="Visit Google" />
</a>

It's simple and no javascript required!


NOTE:

This approach is not valid from HTML structure. But, it works on many modern browser. See following reference :

python pandas dataframe to dictionary

mydict = dict(zip(df.id, df.value))

Logical XOR operator in C++?

There was some good code posted that solved the problem better than !a != !b

Note that I had to add the BOOL_DETAIL_OPEN/CLOSE so it would work on MSVC 2010

/* From: http://groups.google.com/group/comp.std.c++/msg/2ff60fa87e8b6aeb

   Proposed code    left-to-right?  sequence point?  bool args?  bool result?  ICE result?  Singular 'b'?
   --------------   --------------  ---------------  ---------- ------------  -----------  -------------
   a ^ b                  no              no             no          no           yes          yes
   a != b                 no              no             no          no           yes          yes
   (!a)!=(!b)             no              no             no          no           yes          yes
   my_xor_func(a,b)       no              no             yes         yes          no           yes
   a ? !b : b             yes             yes            no          no           yes          no
   a ? !b : !!b           yes             yes            no          no           yes          no
   [* see below]          yes             yes            yes         yes          yes          no
   (( a bool_xor b ))     yes             yes            yes         yes          yes          yes

   [* = a ? !static_cast<bool>(b) : static_cast<bool>(b)]

   But what is this funny "(( a bool_xor b ))"? Well, you can create some
   macros that allow you such a strange syntax. Note that the
   double-brackets are part of the syntax and cannot be removed! The set of
   three macros (plus two internal helper macros) also provides bool_and
   and bool_or. That given, what is it good for? We have && and || already,
   why do we need such a stupid syntax? Well, && and || can't guarantee
   that the arguments are converted to bool and that you get a bool result.
     Think "operator overloads". Here's how the macros look like:

   Note: BOOL_DETAIL_OPEN/CLOSE added to make it work on MSVC 2010
  */

#define BOOL_DETAIL_AND_HELPER(x) static_cast<bool>(x):false
#define BOOL_DETAIL_XOR_HELPER(x) !static_cast<bool>(x):static_cast<bool>(x)

#define BOOL_DETAIL_OPEN (
#define BOOL_DETAIL_CLOSE )

#define bool_and BOOL_DETAIL_CLOSE ? BOOL_DETAIL_AND_HELPER BOOL_DETAIL_OPEN
#define bool_or BOOL_DETAIL_CLOSE ? true:static_cast<bool> BOOL_DETAIL_OPEN
#define bool_xor BOOL_DETAIL_CLOSE ? BOOL_DETAIL_XOR_HELPER BOOL_DETAIL_OPEN

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

CSS Image size, how to fill, but not stretch?

I think it's quite late for this answer. Anyway hope this will help somebody in the future. I faced the problem positioning the cards in angular. There are cards displayed for array of events. If image width of the event is big for card, the image should be shown by cropping from two sides and height of 100 %. If image height is long, images' bottom part is cropped and width is 100 %. Here is my pure css solution for this:

enter image description here

HTML:

 <span class="block clear img-card b-b b-light text-center" [ngStyle]="{'background-image' : 'url('+event.image+')'}"></span>

CSS

.img-card {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
width: 100%;
overflow: hidden;
}

Equivalent of shell 'cd' command to change the working directory?

import os

abs_path = 'C://a/b/c'
rel_path = './folder'

os.chdir(abs_path)
os.chdir(rel_path)

You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.

How can I convert string to double in C++?

Most simple way is to use boost::lexical_cast:

double value;
try
{
    value = boost::lexical_cast<double>(my_string);
}
catch (boost::bad_lexical_cast const&)
{
    value = 0;
}

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

How to access pandas groupby dataframe by key

Rather than

gb.get_group('foo')

I prefer using gb.groups

df.loc[gb.groups['foo']]

Because in this way you can choose multiple columns as well. for example:

df.loc[gb.groups['foo'],('A','B')]

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Importing PNG files into Numpy?

If you are loading images, you are likely going to be working with one or both of matplotlib and opencv to manipulate and view the images.

For this reason, I tend to use their image readers and append those to lists, from which I make a NumPy array.

import os
import matplotlib.pyplot as plt
import cv2
import numpy as np

# Get the file paths
im_files = os.listdir('path/to/files/')

# imagine we only want to load PNG files (or JPEG or whatever...)
EXTENSION = '.png'

# Load using matplotlib
images_plt = [plt.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, H, W, C)
images = np.array(images_plt)

# Load using opencv
images_cv = [cv2.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, C, H, W)
images = np.array(images_cv)

The only difference to be aware of is the following:

  • opencv loads channels first
  • matplotlib loads channels last.

So a single image that is 256*256 in size would produce matrices of size (3, 256, 256) with opencv and (256, 256, 3) using matplotlib.

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

Biggest differences of Thrift vs Protocol Buffers?

There are some excellent points here and I'm going to add another one in case someones' path crosses here.

Thrift gives you an option to choose between thrift-binary and thrift-compact (de)serializer, thrift-binary will have an excellent performance but bigger packet size, while thrift-compact will give you good compression but needs more processing power. This is handy because you can always switch between these two modes as easily as changing a line of code (heck, even make it configurable). So if you are not sure how much your application should be optimized for packet size or in processing power, thrift can be an interesting choice.

PS: See this excellent benchmark project by thekvs which compares many serializers including thrift-binary, thrift-compact, and protobuf: https://github.com/thekvs/cpp-serializers

PS: There is another serializer named YAS which gives this option too but it is schema-less see the link above.

Default nginx client_max_body_size

You can increase body size in nginx configuration file as

sudo nano /etc/nginx/nginx.conf

client_max_body_size 100M;

Restart nginx to apply the changes.

sudo service nginx restart

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

In jQuery, how do I select an element by its name attribute?

If you want a true/false value, use this:

  $("input:radio[name=theme]").is(":checked")

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.

from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

Sqlite primary key on multiple columns

According to the documentation, it's

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

How to execute raw queries with Laravel 5.1?

    DB::statement("your query")

I used it for add index to column in migration

Is there a way to disable initial sorting for jquery DataTables?

In datatable options put this:

$(document).ready( function() {
  $('#example').dataTable({
    "aaSorting": [[ 2, 'asc' ]], 
    //More options ...

   });
})

Here is the solution: "aaSorting": [[ 2, 'asc' ]],

2 means table will be sorted by third column,
asc in ascending order.

Is there a php echo/print equivalent in javascript

You can use document.write or even console.write (this is good for debugging).

But your best bet and it gives you more control is to use DOM to update the page.

How does the "final" keyword in Java work? (I can still modify an object.)

final is a reserved keyword in Java to restrict the user and it can be applied to member variables, methods, class and local variables. Final variables are often declared with the static keyword in Java and are treated as constants. For example:

public static final String hello = "Hello";

When we use the final keyword with a variable declaration, the value stored inside that variable cannot be changed latter.

For example:

public class ClassDemo {
  private final int var1 = 3;
  public ClassDemo() {
    ...
  }
}

Note: A class declared as final cannot be extended or inherited (i.e, there cannot be a subclass of the super class). It is also good to note that methods declared as final cannot be overridden by subclasses.

Benefits of using the final keyword are addressed in this thread.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

write multiple lines in a file in python

You're confusing the braces. Do it like this:

target.write("%s \n %s \n %s \n" % (line1, line2, line3))

Or even better, use writelines:

target.writelines([line1, line2, line3])

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Set value for particular cell in pandas DataFrame with iloc

For mixed position and index, use .ix. BUT you need to make sure that your index is not of integer, otherwise it will cause confusions.

df.ix[0, 'COL_NAME'] = x

Update:

Alternatively, try

df.iloc[0, df.columns.get_loc('COL_NAME')] = x

Example:

import pandas as pd
import numpy as np

# your data
# ========================
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 2), columns=['col1', 'col2'], index=np.random.randint(1,100,10)).sort_index()

print(df)


      col1    col2
10  1.7641  0.4002
24  0.1440  1.4543
29  0.3131 -0.8541
32  0.9501 -0.1514
33  1.8676 -0.9773
36  0.7610  0.1217
56  1.4941 -0.2052
58  0.9787  2.2409
75 -0.1032  0.4106
76  0.4439  0.3337

# .iloc with get_loc
# ===================================
df.iloc[0, df.columns.get_loc('col2')] = 100

df

      col1      col2
10  1.7641  100.0000
24  0.1440    1.4543
29  0.3131   -0.8541
32  0.9501   -0.1514
33  1.8676   -0.9773
36  0.7610    0.1217
56  1.4941   -0.2052
58  0.9787    2.2409
75 -0.1032    0.4106
76  0.4439    0.3337

Safely override C++ virtual functions

Make the function abstract, so that derived classes have no other choice than to override it.

@Ray Your code is invalid.

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

Abstract functions cannot have bodies defined inline. It must be modified to become

class parent {
public:
  virtual void handle_event(int something) const = 0;
};

void parent::handle_event( int something ) { /* do w/e you want here. */ }

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

giving permision 400 makes the key private and not accessible by someone unknown. It makes the key as a protected one.

chmod 400 /Users/tudouya/.ssh/vm/vm_id_rsa.pub

Java serialization - java.io.InvalidClassException local class incompatible

This worked for me:

If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.

So, write the necessary objects to file again if a class is modified and recompiled.

PS: This is NOT a solution; was meant to be a workaround.

assign value using linq

It can be done this way as well

foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                {
                    //do your stuff here
                    company.Id= 2;
                    company.Name= "Sample"
                }

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

What is the most efficient/elegant way to parse a flat table into a tree?

This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.

It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)

This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.

public class Node {

    private Node parent = null;

    private List<Node> children;

    private String name;

    private int id = -1;

    public Node(Node parent, int id, String name) {
        this.parent = parent;
        this.children = new ArrayList<Node>();
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public List<Node> getChildren() {
        return children;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", parent=" + parent;
    }
}

public class NodeBuilder {

    public static Node build(List<Map<String, String>> input) {

        // maps id of a node to it's Node object
        Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();

        // maps id of a node to the id of it's parent
        Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();

        // create special 'root' Node with id=0
        Node root = new Node(null, 0, "root");
        nodeMap.put(root.getId(), root);

        // iterate thru the input
        for (Map<String, String> map : input) {

            // expect each Map to have keys for "id", "name", "parent" ... a
            // real implementation would read from a SQL object or resultset
            int id = Integer.parseInt(map.get("id"));
            String name = map.get("name");
            int parent = Integer.parseInt(map.get("parent"));

            Node node = new Node(null, id, name);
            nodeMap.put(id, node);

            childParentMap.put(id, parent);
        }

        // now that each Node is created, setup the child-parent relationships
        for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
            int nodeId = entry.getKey();
            int parentId = entry.getValue();

            Node child = nodeMap.get(nodeId);
            Node parent = nodeMap.get(parentId);
            parent.addChild(child);
        }

        return root;
    }
}

public class NodePrinter {

    static void printRootNode(Node root) {
        printNodes(root, 0);
    }

    static void printNodes(Node node, int indentLevel) {

        printNode(node, indentLevel);
        // recurse
        for (Node child : node.getChildren()) {
            printNodes(child, indentLevel + 1);
        }
    }

    static void printNode(Node node, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("\t");
        }
        sb.append(node);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        // setup dummy data
        List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
        resultSet.add(newMap("1", "Node 1", "0"));
        resultSet.add(newMap("2", "Node 1.1", "1"));
        resultSet.add(newMap("3", "Node 2", "0"));
        resultSet.add(newMap("4", "Node 1.1.1", "2"));
        resultSet.add(newMap("5", "Node 2.1", "3"));
        resultSet.add(newMap("6", "Node 1.2", "1"));

        Node root = NodeBuilder.build(resultSet);
        printRootNode(root);

    }

    //convenience method for creating our dummy data
    private static Map<String, String> newMap(String id, String name, String parentId) {
        Map<String, String> row = new HashMap<String, String>();
        row.put("id", id);
        row.put("name", name);
        row.put("parent", parentId);
        return row;
    }
}

Set color of TextView span in Android

Set Color on Text by passing String and color:

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

Set text on TextView / Button / EditText etc by calling below code:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView);

Get Colored String:

String name = getColoredSpanned("Hiren", "#800000");

Set Text on TextView:

txtView.setText(Html.fromHtml(name));

Done

Convert blob URL to normal URL

another way to create a data url from blob url may be using canvas.

var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)

as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)

Eclipse Build Path Nesting Errors

Make two folders: final/src/ to store the source java code, and final/WebRoot/.

You cannot put the source and the webroot together. I think you may misunderstand your teacher.

SQL server stored procedure return a table

You can use an out parameter instead of the return value if you want both a result set and a return value

CREATE PROCEDURE proc_name 
@param int out
AS
BEGIN
    SET @param = value
SELECT ... FROM [Table] WHERE Condition
END
GO

What is a classpath and how do I set it?

The classpath in this context is exactly what it is in the general context: anywhere the VM knows it can find classes to be loaded, and resources as well (such as output.vm in your case).

I'd understand Velocity expects to find a file named output.vm anywhere in "no package". This can be a JAR, regular folder, ... The root of any of the locations in the application's classpath.

How a thread should close itself in Java?

If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.

The reason you need to use Thread.currentThread() in order to call interrupt() is that interrupt() is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.

How to run Tensorflow on CPU

You could use tf.config.set_visible_devices. One possible function that allows you to set if and which GPUs to use is:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

Suppose you are on a system with 4 GPUs and you want to use only two GPUs, the one with id = 0 and the one with id = 2, then the first command of your code, immediately after importing the libraries, would be:

set_gpu([0, 2])

In your case, to use only the CPU, you can invoke the function with an empty list:

set_gpu([])

For completeness, if you want to avoid that the runtime initialization will allocate all memory on the device, you can use tf.config.experimental.set_memory_growth. Finally, the function to manage which devices to use, occupying the GPUs memory dynamically, becomes:

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            for gpu in gpus_used:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

Check if all values in list are greater than a certain number

You could do the following:

def Lists():

    my_list1 = [30,34,56]
    my_list2 = [29,500,43]

    for element in my_list1:
        print(element >= 30)

    for element in my_list2:
        print(element >= 30)

Lists()

This will return the values that are greater than 30 as True, and the values that are smaller as false.

Can we call the function written in one JavaScript in another JS file?

Well, I came across another sweet solution.

window['functioName'](params);

How can I display an image from a file in Jupyter Notebook?

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Search for one value in any column of any table inside a database

I expanded the code, because it's not told me the 'record number', and I must to refind it.

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)

CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    ,@TableShortName nvarchar(256)
    ,@TableKeys nvarchar(512)
    ,@SQL nvarchar(3830)

SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''

    -- Scan Tables
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
    Set @TableShortName=PARSENAME(@TableName, 1)
    -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***

        -- LOOK Key Fields, Set Key Columns
        SET @TableKeys=''
        SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
         FROM syscolumns 
         WHERE [id] IN (
            SELECT [id] 
             FROM sysobjects 
             WHERE [name] = @TableShortName)
           AND colid IN (
            SELECT SIK.colid 
             FROM sysindexkeys SIK 
             JOIN sysobjects SO ON 
                SIK.[id] = SO.[id]  
             WHERE 
                SIK.indid = 1
                AND SO.[name] = @TableShortName)
        If @TableKeys<>''
            SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
        -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***

    -- Search in Columns
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        ) -- Set ColumnName

        IF @ColumnName IS NOT NULL
        BEGIN
            SET @SQL='
                SELECT 
                    ''' + @TableName + '''
                    ,'+@TableKeys+'
                    ,''' + @ColumnName + '''
                ,LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            --Print @SQL -- *** DEBUG LINE ***
            INSERT INTO #Results
                Exec (@SQL)
        END -- IF ColumnName
    END -- While Table and Column
END --While Table

SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
END

How to scroll to an element in jQuery?

For my problem this code worked, I had to navigate to an anchor tag on page load :

$(window).scrollTop($('a#captchaAnchor').position().top);

For that matter you can use this on any element, not just an anchor tag.

jQuery and AJAX response header

If this is a CORS request, you may see all headers in debug tools (such as Chrome->Inspect Element->Network), but the xHR object will only retrieve the header (via xhr.getResponseHeader('Header')) if such a header is a simple response header:

  • Content-Type
  • Last-modified
  • Content-Language
  • Cache-Control
  • Expires
  • Pragma

If it is not in this set, it must be present in the Access-Control-Expose-Headers header returned by the server.

About the case in question, if it is a CORS request, one will only be able to retrieve the Location header through the XMLHttpRequest object if, and only if, the header below is also present:

Access-Control-Expose-Headers: Location

If its not a CORS request, XMLHttpRequest will have no problem retrieving it.

Read data from SqlDataReader

I would argue against using SqlDataReader here; ADO.NET has lots of edge cases and complications, and in my experience most manually written ADO.NET code is broken in at least one way (usually subtle and contextual).

Tools exist to avoid this. For example, in the case here you want to read a column of strings. Dapper makes that completely painless:

var region = ... // some filter
var vals = connection.Query<string>(
    "select Name from Table where Region=@region", // query
    new { region } // parameters
).AsList();

Dapper here is dealing with all the parameterization, execution, and row processing - and a lot of other grungy details of ADO.NET. The <string> can be replaced with <SomeType> to materialize entire rows into objects.

In Android EditText, how to force writing uppercase?

A Java 1-liner of the proposed solution could be:

editText.setFilters(Lists.asList(new InputFilter.AllCaps(), editText.getFilters())
    .toArray(new InputFilter[editText.getFilters().length + 1]));

Note it needs com.google.common.collect.Lists.

CSS smooth bounce animation

The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration to suit your needs.

_x000D_
_x000D_
.animated {_x000D_
  -webkit-animation-duration: .5s;_x000D_
  animation-duration: .5s;_x000D_
  -webkit-animation-fill-mode: both;_x000D_
  animation-fill-mode: both;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  0%, 100% {_x000D_
    -webkit-transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    -webkit-transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
@keyframes bounce {_x000D_
  0%, 100% {_x000D_
    transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
.bounce {_x000D_
  -webkit-animation-name: bounce;_x000D_
  animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background-color: red;_x000D_
  position: relative;_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
  position: relative;_x000D_
  top: 92px;_x000D_
  left: -300px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
_x000D_
_x000D_


Here is how your original keyframe settings would be interpreted by the browser:

  • At 0% (that is, at 0s or start of animation) - translate by 0px in Y axis.
  • At 20% (that is, at 0.5s of animation) - translate by 0px in Y axis.
  • At 40% (that is, at 1s of animation) - translate by 0px in Y axis.
  • At 50% (that is, at 1.25s of animation) - translate by 5px in Y axis. This results in a gradual upward movement.
  • At 60% (that is, at 1.5s of animation) - translate by 0px in Y axis. This results in a gradual downward movement.
  • At 80% (that is, at 2s of animation) - translate by 0px in Y axis.
  • At 100% (that is, at 2.5s or end of animation) - translate by 0px in Y axis.

How to get the first non-null value in Java?

With Guava you can do:

Optional.fromNullable(a).or(b);

which doesn't throw NPE if both a and b are null.

EDIT: I was wrong, it does throw NPE. The correct way as commented by Michal Cizmazia is:

Optional.fromNullable(a).or(Optional.fromNullable(b)).orNull();

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

Can't ping a local VM from the host

Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1

How do I check whether a file exists without exceptions?

Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:

import pathlib
p = pathlib.Path('path/to/file')
if p.is_file():  # or p.is_dir() to see if it is a directory
    # do stuff

You can (and usually should) still use a try/except block when opening files:

try:
    with p.open() as f:
        # do awesome stuff
except OSError:
    print('Well darn.')

The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:

# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2

Then import it as follows:

# Older Python versions
import pathlib2 as pathlib

How to apply a function to two columns of Pandas dataframe

The method you are looking for is Series.combine. However, it seems some care has to be taken around datatypes. In your example, you would (as I did when testing the answer) naively call

df['col_3'] = df.col_1.combine(df.col_2, func=get_sublist)

However, this throws the error:

ValueError: setting an array element with a sequence.

My best guess is that it seems to expect the result to be of the same type as the series calling the method (df.col_1 here). However, the following works:

df['col_3'] = df.col_1.astype(object).combine(df.col_2, func=get_sublist)

df

   ID   col_1   col_2   col_3
0   1   0   1   [a, b]
1   2   2   4   [c, d, e]
2   3   3   5   [d, e, f]

phpmailer - The following SMTP Error: Data not accepted

We send email via the Gmail SMTP servers, and we get this exact error from PHPMailer sometimes when we hit our Gmail send limits.

You can check if it's the same thing happening to you by going into Gmail and trying to manually send an email. In our case that displays the more helpful error message about sending limits.

https://support.google.com/a/answer/166852?hl=en

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

How to implement an STL-style iterator and avoid common pitfalls?

Thomas Becker wrote a useful article on the subject here.

There was also this (perhaps simpler) approach that appeared previously on SO: How to correctly implement custom iterators and const_iterators?

can we use xpath with BeautifulSoup?

I've searched through their docs and it seems there is not xpath option. Also, as you can see here on a similar question on SO, the OP is asking for a translation from xpath to BeautifulSoup, so my conclusion would be - no, there is no xpath parsing available.

Add a CSS class to <%= f.submit %>

Solution When Using form_with helper

<%= f.submit, "Submit", class: 'btn btn-primary' %>

Don't forget the comma after the f.submit method!

HTH!

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use

How to validate a date?

Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(

My proposition is to use improved version of this function:

//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
        var bits = input.split('-');
        var d = new Date(bits[0], bits[1] - 1, bits[2]);
        return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}

How to change node.js's console font color?

I don't want any dependency for this and only these worked for me on OS X. All other samples from answers here gave me Octal literal errors.

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

source: https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

How to calculate md5 hash of a file using javascript

You need to to use FileAPI. It is available in the latest FF & Chrome, but not IE9. Grab any md5 JS implementation suggested above. I've tried this and abandoned it because JS was too slow (minutes on large image files). Might revisit it if someone rewrites MD5 using typed arrays.

Code would look something like this:

HTML:     
<input type="file" id="file-dialog" multiple="true" accept="image/*">

JS (w JQuery)

$("#file-dialog").change(function() {
  handleFiles(this.files);
});

function handleFiles(files) {
    for (var i=0; i<files.length; i++) {
        var reader = new FileReader();
        reader.onload = function() {
        var md5 = binl_md5(reader.result, reader.result.length);
            console.log("MD5 is " + md5);
        };
        reader.onerror = function() {
            console.error("Could not read the file");
        };
        reader.readAsBinaryString(files.item(i));
     }
 }

How to copy a map?

I'd use recursion just in case so you can deep copy the map and avoid bad surprises in case you were to change a map element that is a map itself.

Here's an example in a utils.go:

package utils

func CopyMap(m map[string]interface{}) map[string]interface{} {
    cp := make(map[string]interface{})
    for k, v := range m {
        vm, ok := v.(map[string]interface{})
        if ok {
            cp[k] = CopyMap(vm)
        } else {
            cp[k] = v
        }
    }

    return cp
}

And its test file (i.e. utils_test.go):

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }

    m2 := CopyMap(m1)

    m1["a"] = "zzz"
    delete(m1, "b")

    require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }, m2)
}

It should easy enough to adapt if you need the map key to be something else instead of a string.

How to increase Bootstrap Modal Width?

If you want to keep the modal responsive use % of width instead of pixels. You can do it in-line (see below) or with CSS.

<div class="modal fade" id="phpModal" role="dialog">
            <div class="modal-dialog modal-lg" style="width:80%;">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">HERE YOU TITLE</h4>
                    </div>
                    <div class="modal-body helpModal phpModal">
                        HERE YOUR CONTENT
                    </div>
                </div>
            </div>
        </div>

If you use CSS, you can even do different % for modal-sm and modal-lg.

What does yield mean in PHP?

None of the answers above show a concrete example using massive arrays populated by non-numeric members. Here is an example using an array generated by explode() on a large .txt file (262MB in my use case):

<?php

ini_set('memory_limit','1000M');

echo "Starting memory usage: " . memory_get_usage() . "<br>";

$path = './file.txt';
$content = file_get_contents($path);

foreach(explode("\n", $content) as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output was:

Starting memory usage: 415160
Final memory usage: 270948256

Now compare that to a similar script, using the yield keyword:

<?php

ini_set('memory_limit','1000M');

echo "Starting memory usage: " . memory_get_usage() . "<br>";

function x() {
    $path = './file.txt';
    $content = file_get_contents($path);
    foreach(explode("\n", $content) as $x) {
        yield $x;
    }
}

foreach(x() as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output for this script was:

Starting memory usage: 415152
Final memory usage: 415616

Clearly memory usage savings were considerable (?MemoryUsage -----> ~270.5 MB in first example, ~450B in second example).

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

How permission can be checked at runtime without throwing SecurityException?

Step 1 - add permission request

    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, 
    Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int REQUEST_CODE = 101;

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissionArrays, REQUEST_CODE );
        } else {
             // if already permition granted
            // PUT YOUR ACTION (Like Open cemara etc..)
        }
    }

Step 2 - Handle Permission result

     @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == REQUEST_CODE ) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission

            }else {
                //  user grant the permission
                // you can perfome your action 
            }
        }
    }
}

Python group by

I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set

result = pandas.DataFrame(input).groupby(1).groups

Purge or recreate a Ruby on Rails database

According to Rails guide, this one liner should be used because it would load from the schema.rb instead of reloading the migration files one by one:

rake db:reset

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

https with WCF error: "Could not find base address that matches scheme https"

Look at your base address and your endpoint address (can't see it in your sample code). most likely you missed a column or some other typo e.g. https// instead of https://

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

convert nan value to zero

Where A is your 2D array:

import numpy as np
A[np.isnan(A)] = 0

The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.

Running multiple commands with xargs

One thing I do is to add to .bashrc/.profile this function:

function each() {
    while read line; do
        for f in "$@"; do
            $f $line
        done
    done
}

then you can do things like

... | each command1 command2 "command3 has spaces"

which is less verbose than xargs or -exec. You could also modify the function to insert the value from the read at an arbitrary location in the commands to each, if you needed that behavior also.

Remove "whitespace" between div element

You may use line-height on div1 as below:

<div id="div1" style="line-height:0px;">
    <div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>

See this: http://jsfiddle.net/wCpU8/

How to select records from last 24 hours using SQL?

If the timestamp considered is a UNIX timestamp You need to first convert UNIX timestamp (e.g 1462567865) to mysql timestamp or data

SELECT * FROM `orders` WHERE FROM_UNIXTIME(order_ts) > DATE_SUB(CURDATE(), INTERVAL 1 DAY)

How to count the frequency of the elements in an unordered list?

Yet another solution with another algorithm without using collections:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count

Converting newline formatting from Mac to Windows

Just do tr delete:

tr -d "\r" <infile.txt >outfile.txt

How to store an array into mysql?

create table like this,

CommentId    UserId
---------------------
   1            usr1
   1            usr2

In this way you can check whether the user posted the comments are not.. Apart from this there should be tables for Comments and Users with respective id's

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

you can create one image for bottom border and set it to the background of your UITextField :

 yourTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourBorderedImageName"]];

or set borderStyle to none and put image of line exactly equal length to textfield!

How to use setInterval and clearInterval?

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

wampserver doesn't go green - stays orange

If you can't start Wamp anymore right after a Windows update, this is often caused because of Windows that has automatically re-turned on the World Wide Web Publishing Service.

To solve: Click on Start, type Services, click Services, find World Wide Web Publishing Service, double click it, set Startup type to Disabled and click Stop button, OK this dialog and try to restart Wamp.

Set line spacing

Yup, as everyone's saying, line-height is the thing. Any font you are using, a mid-height character (such as a or ¦, not going through the upper or lower) should go with the same height-length at line-height: 0.6 to 0.65.

_x000D_
_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div style="line-height: 0.6; font-family: 'Fira Code', monospace, sans-serif">_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
<strong>BUT</strong>_x000D_
<br>_x000D_
<br>_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
ddd<br>_x000D_
ƒƒƒ<br>_x000D_
ggg_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a hyperlink in telegram without using bots?

As of Telegram Desktop 1.3 you can format your messages and add links.

[Ctrl+K] = create link (https://my.website)

Other useful hotkeys are:

[Ctrl+B] = bold
[Ctrl+I] = italic
[Ctrl+Shift+M] = monospace
[Ctrl+Shift+N] = clear formatting

Docker error response from daemon: "Conflict ... already in use by container"

I got this error quite a lot, so now I do a batch removal of all unused containers at once:

docker container prune 

add -f to force removal without prompt.

To list all unused containers (without removal):

docker container ls -a --filter status=exited --filter status=created 

See here more examples how to prune other objects (networks, volumes, etc.).

File to byte[] in Java

Try this :

import sun.misc.IOUtils;
import java.io.IOException;

try {
    String path="";
    InputStream inputStream=new FileInputStream(path);
    byte[] data=IOUtils.readFully(inputStream,-1,false);
}
catch (IOException e) {
    System.out.println(e);
}

C++ vector of char array

You can directly define a char type vector as below.

vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};

How to get the difference between two arrays of objects in JavaScript

If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.

_.difference([1,2,3,4,5][1,4,10])

==>[2,3,5]

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Specify the name of columns in the CSV in the load data infile statement.

The code is like this:

LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);

Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.

The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.

Thank you.

How to change font size in a textbox in html

For a <input type='text'> element:

input { font-size: 18px; }

or for a <textarea>:

textarea { font-size: 18px; }

or for a <select>:

select { font-size: 18px; }

you get the drift.

H2 in-memory database. Table not found

I know this was not your case but I had the same problem because H2 was creating the tables with UPPERCASE names then behaving case-sensitive, even though in all scripts (including in the creation ones) i used lowercase.

Solved by adding ;DATABASE_TO_UPPER=false to the connection URL.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.

  • varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.

Get list of a class' instance methods

You actually want TestClass.instance_methods, unless you're interested in what TestClass itself can do.

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]

Or you can call methods (not instance_methods) on the object:

test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

How to turn off page breaks in Google Docs?

The only way to remove the dotted line (to my knowledge) is with css hacking using plugin.

  • Install the User CSS (or User JS & CSS) plugin, which allows adding CSS rules per site.

  • Once on Google Docs, click the plugins icon, toggle the OFF to ON button, and add the following css code:

.

.kix-page-compact::before{
    border-top: none;
}

enter image description here

Should work like a charm.

Understanding Python super() with __init__() methods

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer. The standard docs also refer to a guide to using super() which is quite explanatory.

How to create the most compact mapping n ? isprime(n) up to a limit N?

I have got a prime function which works until (2^61)-1 Here:

from math import sqrt
def isprime(num): num > 1 and return all(num % x for x in range(2, int(sqrt(num)+1)))

Explanation:

The all() function can be redefined to this:

def all(variables):
    for element in variables:
        if not element: return False
    return True

The all() function just goes through a series of bools / numbers and returns False if it sees 0 or False.

The sqrt() function is just doing the square root of a number.

For example:

>>> from math import sqrt
>>> sqrt(9)
>>> 3
>>> sqrt(100)
>>> 10

The num % x part returns the remainder of num / x.

Finally, range(2, int(sqrt(num))) means that it will create a list that starts at 2 and ends at int(sqrt(num)+1)

For more information about range, have a look at this website!

The num > 1 part is just checking if the variable num is larger than 1, becuase 1 and 0 are not considered prime numbers.

I hope this helped :)

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

python 2 instead of python 3 as the (temporary) default python?

Use python command to launch scripts, not shell directly. E.g.

  python2 /usr/bin/command

AFAIK this is the recommended method to workaround scripts with bad env interpreter line.

How can I access Oracle from Python?

In addition to cx_Oracle, you need to have the Oracle client library installed and the paths set correctly in order for cx_Oracle to find it - try opening the cx_Oracle DLL in "Dependency Walker" (http://www.dependencywalker.com/) to see what the missing DLL is.

How do I plot list of tuples in Python?

With gnuplot using gplot.py

from gplot import *

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

gplot.log('y')
gplot(*zip(*l))

enter image description here

Split data frame string column into multiple columns

Notice that sapply with "[" can be used to extract either the first or second items in those lists so:

before$type_1 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 1)
before$type_2 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 2)
before$type <- NULL

And here's a gsub method:

before$type_1 <- gsub("_and_.+$", "", before$type)
before$type_2 <- gsub("^.+_and_", "", before$type)
before$type <- NULL

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to write multiple line string using Bash with variables?

The heredoc solutions are certainly the most common way to do this. Other common solutions are:

echo 'line 1, '"${kernel}"'
line 2,
line 3, '"${distro}"'
line 4' > /etc/myconfig.conf

and

exec 3>&1 # Save current stdout
exec > /etc/myconfig.conf
echo line 1, ${kernel}
echo line 2, 
echo line 3, ${distro}
...
exec 1>&3  # Restore stdout

Git merge two local branches

If I understood your question, you want to merge branchB into branchA. To do so, first checkout branchA like below,

git checkout branchA

Then execute the below command to merge branchB into branchA:

git merge branchB

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

On Windows machine you can temporarily set Java version.
For example, to change the version to Java 8, run this command on cmd:

set JAVA_HOME=C:\\...\jdk1.8.0_65

Difference between a virtual function and a pure virtual function

A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:

 Derived d;
 Base& rb = d;
 // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
 rb.f();  

A pure virtual function is a virtual function whose declaration ends in =0:

class Base {
  // ...
  virtual void f() = 0;
  // ...

A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.

An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)


Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;

See this question and this one for more info on this use of delete and default.

How to redirect page after click on Ok button on sweet alert?

function confirmDetete(ctl, event) {

    debugger;
    event.preventDefault();
    var defaultAction = $(ctl).prop("href");
    swal({
        title: "Are you sure?",
        text: "You will  be able to add it back again!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "Cancel",
        closeOnConfirm: false,
        closeOnCancel: false
    },
        function (isConfirm) {
            if (isConfirm) {
                $.get(ctl);
                swal({
                    title: "success",
                    text: "Deleted",
                    confirmButtonText: "ok",
                    allowOutsideClick: "true"
                }, function () { window.location.href = ctl })

     // $("#signupform").submit();
            } else {
                swal("Cancelled", "Is safe :)", "success");

            }
        });
}

A potentially dangerous Request.Path value was detected from the client (*)

Try to set web project's server propery as Local IIS if it is IIS Express. Be sure if project url is right and create virual directory.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

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

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

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

This code works to insert both header and footer on the first page with header center aligned and footer left aligned

\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
  % for the first page
  \def\ps@IEEEtitlepagestyle{%
    \old@ps@IEEEtitlepagestyle%
    \def\@oddhead{\strut\hfill#1\hfill\strut}%
    \def\@evenhead{\strut\hfill#1\hfill\strut}%
 \def\@oddfoot{\mycopyrightnotice}
  \def\@evenfoot{}
  }%
  \ps@headings%
}
\makeatother

\confheader{%
  5$^{th}$  IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}

\def\mycopyrightnotice{
  {\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
  \gdef\mycopyrightnotice{}

}

\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}


\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```

Can't install gems on OS X "El Capitan"

As it have been said, the issue comes from a security function of Mac OSX since "El Capitan".

Using the default system Ruby, the install process happens in the /Library/Ruby/Gems/2.0.0 directory which is not available to the user and gives the error.

You can have a look to your Ruby environments parameters with the command

$ gem env

There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use --user-install parameter instead as using sudo which is never a recommanded way of doing.

$ gem install myGemName --user-install

There should not be any rights issue anymore in the process. The gems are then installed in the user directory : ~/.gem/Ruby/2.0.0/bin

But to make the installed gems available, this directory should be available in your path. According to the Ruby’s faq, you can add the following line to your ~/.bash_profile or ~/.bashrc

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

Then close and reload your terminal or reload your .bash_profile or .bashrc (. ~/.bash_profile)

R - argument is of length zero in if statement

You can use isTRUE for such cases. isTRUE is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }

If you use shiny there you could use isTruthy which covers the following cases:

  • FALSE

  • NULL

  • ""

  • An empty atomic vector

  • An atomic vector that contains only missing values

  • A logical vector that contains all FALSE or missing values

  • An object of class "try-error"

  • A value that represents an unclicked actionButton()

nodemon command is not recognized in terminal for node js server

  1. Install nodemon globally:

    C:\>npm install -g nodemon
    
  2. Get prefix:

    C:\>npm config get prefix
    

    You will get output like following in your console:

    C:\Users\Family\.node_modules_global
    

    Copy it.

  3. Set Path.
    Go to Advance System Settings → Environment Variable → Click New (Under User Variables) → Pop up form will be displayed → Pass the following values:

    variable name = path,
    variable value = Copy output from your console
    
  4. Now Run Nodemon:

    C:\>nodemon .
    

What's the proper value for a checked attribute of an HTML checkbox?

I think this may help:


First read all the specs from Microsoft and W3.org.
You'd see that the setting the actual element of a checkbox needs to be done on the ELEMENT PROPERTY, not the UI or attribute.
$('mycheckbox')[0].checked

Secondly, you need to be aware that the checked attribute RETURNS a string "true", "false"
Why is this important? Because you need to use the correct Type. A string, not a boolean. This also important when parsing your checkbox.
$('mycheckbox')[0].checked = "true"

if($('mycheckbox')[0].checked === "true"){ //do something }

You also need to realize that the "checked" ATTRIBUTE is for setting the value of the checkbox initially. This doesn't do much once the element is rendered to the DOM. Picture this working when the webpage loads and is initially parsed.
I'll go with IE's preference on this one: <input type="checkbox" checked="checked"/>

Lastly, the main aspect of confusion for a checkbox is that the checkbox UI element is not the same as the element's property value. They do not correlate directly. If you work in .net, you'll discover that the user "checking" a checkbox never reflects the actual bool value passed to the controller. To set the UI, I use both $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');


In short, for a checked checkbox you need:
Initial DOM: <input type="checkbox" checked="checked">
Element Property: $('mycheckbox')[0].checked = "true";
UI: $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

How do I parse command line arguments in Java?

Maybe these

  • JArgs command line option parsing suite for Java - this tiny project provides a convenient, compact, pre-packaged and comprehensively documented suite of command line option parsers for the use of Java programmers. Initially, parsing compatible with GNU-style 'getopt' is provided.

  • ritopt, The Ultimate Options Parser for Java - Although, several command line option standards have been preposed, ritopt follows the conventions prescribed in the opt package.

onchange event on input type=range is not triggering in firefox while dragging

Andrew Willem's solutions are not mobile device compatible.

Here's a modification of his second solution that works in Edge, IE, Opera, FF, Chrome, iOS Safari and mobile equivalents (that I could test):

Update 1: Removed "requestAnimationFrame" portion, as I agree it's not necessary:

var listener = function() {
  // do whatever
};

slider1.addEventListener("input", function() {
  listener();
  slider1.addEventListener("change", listener);
});
slider1.addEventListener("change", function() {
  listener();
  slider1.removeEventListener("input", listener);
}); 

Update 2: Response to Andrew's 2nd Jun 2016 updated answer:

Thanks, Andrew - that appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari).

Update 3: if ("oninput in slider) solution

The following appears to work across all the above browsers. (I cannot find the original source now.) I was using this, but it subsequently failed on IE and so I went looking for a different one, hence I ended up here.

if ("oninput" in slider1) {
    slider1.addEventListener("input", function () {
        // do whatever;
    }, false);
}

But before I checked your solution, I noticed this was working again in IE - perhaps there was some other conflict.

"Prevent saving changes that require the table to be re-created" negative effects

Yes, there are negative effects from this:

If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:

  1. Even microsoft warns that this may cause data loss (that comment is auto-generated)!
  2. for a period of time, foreign keys are not enforced.
  3. if you manually run this in ssms and the ' EXEC('INSERT INTO ' fails, and you let the following statements run (which they do by default, as they are split by 'go') then you will insert 0 rows, then drop the old table.
  4. if this is a big table, the runtime of the insert can be large, and the transaction is holding a schema modification lock, so blocks many things.

--

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/

BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
    (
    ContactID int NOT NULL IDENTITY (1, 1),
    ProfileID int NOT NULL,
    AddressType char(2) NOT NULL,
    ContactText varchar(250) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
     EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
        SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
    DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
    DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
    DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT' 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact_1 PRIMARY KEY CLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact UNIQUE NONCLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
    (
    AddressType
    ) 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_contact_profile FOREIGN KEY
    (
    ProfileID
    ) REFERENCES raw.Profile
    (
    ProfileID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_Contact_AddressType FOREIGN KEY
    (
    AddressType
    ) REFERENCES ref.ContactpointType
    (
    ContactPointTypeCode
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
    fk_phones_contact FOREIGN KEY
    (
    ProfileID,
    PhoneID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
    fk_marketingflag_contact FOREIGN KEY
    (
    ProfileID,
    ContactID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
    fk_AddressProfile FOREIGN KEY
    (
    ProfileID,
    AddressID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

setHintTextColor() in EditText

This is like default hint color, worked for me:

editText.setHintTextColor(Color.GRAY);

How to detect the physical connected state of a network cable/connector?

Somehow if you want to check if the ethernet cable plugged in linux after the commend:" ifconfig eth0 down". I find a solution: use the ethtool tool.

#ethtool -t eth0
The test result is PASS
The test extra info:
Register test  (offline)         0
Eeprom test    (offline)         0
Interrupt test (offline)         0
Loopback test  (offline)         0
Link test   (on/offline)         0

if cable is connected,link test is 0,otherwise is 1.

PHP split alternative?

Yes, I would use explode or you could use:

preg_split

Which is the advised method with PHP 6. preg_split Documentation

Set EditText cursor color

For anyone that needs to set the EditText cursor color dynamically, below you will find two ways to achieve this.


First, create your cursor drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ff000000" />

    <size android:width="1dp" />

</shape>

Set the cursor drawable resource id to the drawable you created (https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564">source)):

try {
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(yourEditText, R.drawable.cursor);
} catch (Exception ignored) {
}

To just change the color of the default cursor drawable, you can use the following method:

public static void setCursorDrawableColor(EditText editText, int color) {
    try {
        Field fCursorDrawableRes = 
            TextView.class.getDeclaredField("mCursorDrawableRes");
        fCursorDrawableRes.setAccessible(true);
        int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
        Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        Object editor = fEditor.get(editText);
        Class<?> clazz = editor.getClass();
        Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
        fCursorDrawable.setAccessible(true);

        Drawable[] drawables = new Drawable[2];
        Resources res = editText.getContext().getResources();
        drawables[0] = res.getDrawable(mCursorDrawableRes);
        drawables[1] = res.getDrawable(mCursorDrawableRes);
        drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
        drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
        fCursorDrawable.set(editor, drawables);
    } catch (final Throwable ignored) {
    }
}

POST request via RestTemplate in JSON

As specified here I guess you need to add a messageConverter for MappingJacksonHttpMessageConverter

Function inside a function.?

It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.

echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
$x=x(2);
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';

Output

y is not defined

y is defined

Simple thing you can not call function y before executed x

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

Set Response Status Code

Since PHP 5.4 you can use http_response_code.

http_response_code(404);

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.

refresh both the External data source and pivot tables together within a time schedule

Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.

With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.

Then you just modify the following code:

ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh

You can also turn off background refresh in VBA:

ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False

Recursively find files with a specific extension

My preference:

find . -name '*.jpg' -o -name '*.png' -print | grep Robert

How to get file creation & modification date/times in Python?

If following symbolic links is not important, you can also use the os.lstat builtin.

>>> os.lstat("2048.py")
posix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)
>>> os.lstat("2048.py").st_atime
1423378041.0