Programs & Examples On #Hook menu

This hook enables Drupal modules to register paths in order to define how URL requests are handled.

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

Using number as "index" (JSON)

What about

Game.status[0][0] or Game.status[0]["0"] ?

Does one of these work?

PS: What you have in your question is a Javascript Object, not JSON. JSON is the 'string' version of a Javascript Object.

cleanest way to skip a foreach if array is empty

foreach((array)$items as $item) {}

How to remove .html from URL?

For those who are using Firebase hosting none of the answers will work on this page. Because you can't use .htaccess in Firebase hosting. You will have to configure the firebase.json file. Just add the line "cleanUrls": true in your file and save it. That's it.

After adding the line firebase.json will look like this :

{
  "hosting": {
    "public": "public",
    "cleanUrls": true, 
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

How do I see if Wi-Fi is connected on Android?

In new version Android

private void getWifiInfo(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network[] networks = connManager.getAllNetworks();

    if(networks == null || networks.length == 0)
        return;

    for( int i = 0; i < networks.length; i++) {
        Network ntk = networks[i];
        NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
        if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
            final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
            if (connectionInfo != null) {
                // add some code here
            }
        }

    }
}

and add premission too

How to use passive FTP mode in Windows command prompt?

This is a common problem . when we start the ftp connection only the external ip opens the port for pasv connection. but the ip behind the NAT doesn't open the connection so passive connection fails with PASV command

we need to specify that while opening the connection so open connection with

ftp -p {host}

Django Rest Framework File Upload

If you are using ModelViewSet, well actually you are done! It handles every things for you! You just need to put the field in your ModelSerializer and set content-type=multipart/form-data; in your client.

BUT as you know you can not send files in json format. (when content-type is set to application/json in your client). Unless you use Base64 format.

So you have two choices:

  • let ModelViewSet and ModelSerializer handle the job and send the request using content-type=multipart/form-data;
  • set the field in ModelSerializer as Base64ImageField (or) Base64FileField and tell your client to encode the file to Base64 and set the content-type=application/json

How do I make a splash screen?

Splash screen example :

public class MainActivity extends Activity {
    private ImageView splashImageView;
    boolean splashloading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        splashImageView = new ImageView(this);
        splashImageView.setScaleType(ScaleType.FIT_XY);
        splashImageView.setImageResource(R.drawable.ic_launcher);
        setContentView(splashImageView);
        splashloading = true;
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            public void run() {
                splashloading = false;
                setContentView(R.layout.activity_main);
            }

        }, 3000);

    }

}

SQL query: Delete all records from the table except latest N?

I know I'm resurrecting quite an old question, but I recently ran into this issue, but needed something that scales to large numbers well. There wasn't any existing performance data, and since this question has had quite a bit of attention, I thought I'd post what I found.

The solutions that actually worked were the Alex Barrett's double sub-query/NOT IN method (similar to Bill Karwin's), and Quassnoi's LEFT JOIN method.

Unfortunately both of the above methods create very large intermediate temporary tables and performance degrades quickly as the number of records not being deleted gets large.

What I settled on utilizes Alex Barrett's double sub-query (thanks!) but uses <= instead of NOT IN:

DELETE FROM `test_sandbox`
  WHERE id <= (
    SELECT id
    FROM (
      SELECT id
      FROM `test_sandbox`
      ORDER BY id DESC
      LIMIT 1 OFFSET 42 -- keep this many records
    ) foo
  )

It uses OFFSET to get the id of the Nth record and deletes that record and all previous records.

Since ordering is already an assumption of this problem (ORDER BY id DESC), <= is a perfect fit.

It is much faster, since the temporary table generated by the subquery contains just one record instead of N records.

Test case

I tested the three working methods and the new method above in two test cases.

Both test cases use 10000 existing rows, while the first test keeps 9000 (deletes the oldest 1000) and the second test keeps 50 (deletes the oldest 9950).

+-----------+------------------------+----------------------+
|           | 10000 TOTAL, KEEP 9000 | 10000 TOTAL, KEEP 50 |
+-----------+------------------------+----------------------+
| NOT IN    |         3.2542 seconds |       0.1629 seconds |
| NOT IN v2 |         4.5863 seconds |       0.1650 seconds |
| <=,OFFSET |         0.0204 seconds |       0.1076 seconds |
+-----------+------------------------+----------------------+

What's interesting is that the <= method sees better performance across the board, but actually gets better the more you keep, instead of worse.

Importing class/java files in Eclipse

I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

Recheck the naming convention of the images and the validity of the XML in your resource files- then rebuild the project after cleaning.

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

What is the difference between procedural programming and functional programming?

I've never seen this definition given elsewhere, but I think this sums up the differences given here fairly well:

Functional programming focuses on expressions

Procedural programming focuses on statements

Expressions have values. A functional program is an expression who's value is a sequence of instructions for the computer to carry out.

Statements don't have values and instead modify the state of some conceptual machine.

In a purely functional language there would be no statements, in the sense that there's no way to manipulate state (they might still have a syntactic construct named "statement", but unless it manipulates state I wouldn't call it a statement in this sense). In a purely procedural language there would be no expressions, everything would be an instruction which manipulates the state of the machine.

Haskell would be an example of a purely functional language because there is no way to manipulate state. Machine code would be an example of a purely procedural language because everything in a program is a statement which manipulates the state of the registers and memory of the machine.

The confusing part is that the vast majority of programming languages contain both expressions and statements, allowing you to mix paradigms. Languages can be classified as more functional or more procedural based on how much they encourage the use of statements vs expressions.

For example, C would be more functional than COBOL because a function call is an expression, whereas calling a sub program in COBOL is a statement (that manipulates the state of shared variables and doesn't return a value). Python would be more functional than C because it allows you to express conditional logic as an expression using short circuit evaluation (test && path1 || path2 as opposed to if statements). Scheme would be more functional than Python because everything in scheme is an expression.

You can still write in a functional style in a language which encourages the procedural paradigm and vice versa. It's just harder and/or more awkward to write in a paradigm which isn't encouraged by the language.

How to set a string's color

I created an API called JCDP, former JPrinter, which stands for Java Colored Debug Printer. For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive. For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

This library is licensed under the MIT License so feel free to use it.

Have a look at JCDP's github repository.

How do I set the visibility of a text box in SSRS using an expression?

Switch your false and true returns? I think if you put those as a function in the visibility area, then false will show it and true will not show it.

Python script to copy text to clipboard

One more answer to improve on: https://stackoverflow.com/a/4203897/2804197 and https://stackoverflow.com/a/25476462/1338797 (Tkinter).

Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

import sys

try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()

if len(sys.argv) < 2:
    data = sys.stdin.read()
else:
    data = ' '.join(sys.argv[1:])

r.clipboard_append(data)

if sys.platform != 'win32':
    if len(sys.argv) > 1:
        raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
    else:
        # stdin already read; use GUI to exit
        print('Data was copied into clipboard. Paste, then close popup to exit...')
        r.deiconify()
        r.mainloop()
else:
    r.destroy()

This showcases:

  • importing Tk across Py2 and Py3
  • raw_input and print() compatibility
  • "unhiding" Tk root window when needed
  • waiting for exit on Linux in two different ways.

What is the equivalent to getLastInsertId() in Cakephp?

CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID(). Actually these methods are identical so it really doesn't matter which method you use.

echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();

This methods can be found in cake/libs/model/model.php on line 2768

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

Using DISTINCT inner join in SQL

Is this what you mean?

SELECT DISTINCT C.valueC
FROM 
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

Eloquent - where not equal to

For where field not empty this worked for me:

->where('table_name.field_name', '<>', '')

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Actually, this is an ongoing problem. While Andy is right about the downloaded source, .val(...) and .attr('value',...) don't seem to actually modify the html. I think this is a javascript problem and not a jquery problem. If you had used firebug even you would have had the same question. While it seems that if you submit the form with the modified values it will go through, the html does not change. I ran into this issue trying to create a print preview of the modified form (doing [form].html()) it copies everything okay, including all changes except values changes. Thus, my modal print preview is somewhat useless... my workaround may have to be to 'build' a hidden form containing the values they have added, or generate the preview independently and make each modification the user makes also modify the preview. Both are inoptimal, but unless someone figures out why the value-setting behavior does not change the html (in the DOM i'm assuming) it will have to do.

php return 500 error but no error log

If you still have 500 error and no logs you can try to execute from command line:

php -f file.php

it will not work exactly like in a browser (from server) but if there is syntax error in your code, you will see error message in console.

jquery if div id has children

You can also check whether div has specific children or not,

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

script to map network drive

Here a JScript variant of JohnB's answer

// Below the MSDN page for MapNetworkDrive Method with link and in case if Microsoft breaks it like every now and then the path to the documentation of now.
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
// MSDN Library -> Web Development -> Scripting -> JScript and VBScript -> Windows Scripting -> Windows Script Host -> Reference (Windows Script Host) -> Methods (Windows Script Host) -> MapNetworkDrive Method

var WshNetwork = WScript.CreateObject('WScript.Network');
function localNameInUse(localName) {
    var driveIterator = WshNetwork.EnumNetworkDrives();
    for (var i=0, l=driveIterator.length; i < l; i += 2) {
        if (driveIterator.Item(i) == localName) {
            return true;
        }
    }
    return false;
}

function mount(localName, remoteName) {
    if (localNameInUse(localName)) {
        WScript.Echo('"' + localName + '" drive letter already in use.');
    } else {
        WshNetwork.MapNetworkDrive(localName, remoteName);
    }
}

function unmount(localName) {
    if (localNameInUse(localName)) {
        WshNetwork.RemoveNetworkDrive(localName);
    }
}

Enable SQL Server Broker taking too long

USE master;
GO
ALTER DATABASE Database_Name
    SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
GO
USE Database_Name;
GO

CSS background-image not working

 <span class="btn-pTool">
 <a class="btn-pToolName" href="#"></a>
 </span>

That's empty. Try adding a non breaking space to give the link and span some contents:

 <span class="btn-pTool">
 <a class="btn-pToolName" href="#">&nbsp;</a>
 </span>

It's also worth noting that the CSS spec says that you can't give a span a background image because spans are not block elements. Put the background image code in the div's class style, or use <p> instead of <span>. Some browsers might let you put a background in a span, but not all will (perhaps older versions of IE).

Killing a process using Java

AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))

You can use system-dependant commands like

 Runtime rt = Runtime.getRuntime();
  if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) 
     rt.exec("taskkill " +....);
   else
     rt.exec("kill -9 " +....);

req.body empty on posts

If you are doing with the postman, Please confirm these stuff when you are requesting API

enter image description here

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

Check if value exists in enum in TypeScript

Update:

I've found that whenever I need to check if a value exists in an enum, I don't really need an enum and that a type is a better solution. So my enum in my original answer becomes:

export type ValidColors =
  | "red"
  | "orange"
  | "yellow"
  | "green"
  | "blue"
  | "purple";

Original answer:

For clarity, I like to break the values and includes calls onto separate lines. Here's an example:

export enum ValidColors {
  Red = "red",
  Orange = "orange",
  Yellow = "yellow",
  Green = "green",
  Blue = "blue",
  Purple = "purple",
}

function isValidColor(color: string): boolean {
  const options: string[] = Object.values(ButtonColors);
  return options.includes(color);
}

Build project into a JAR automatically in Eclipse

Using Thomas Bratt's answer above, just make sure your build.xml is configured properly :

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="bin/" includes="**/*.class" />
  </target>
</project>

(Notice the double asterisk - it will tell build to look for .class files in all sub-directories.)

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

This does not directly answer your question, but have you had a look at Litmus? We tend to use it mostly for testing HTML/CSS compatibility across multiple browsers (supported by Litmus).

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

how to run two commands in sudo?

An alternative using eval so avoiding use of a subshell:

sudo -s eval 'whoami; whoami'

Note: The other answers using sudo -s fail because the quotes are being passed on to bash and run as a single command so need to strip quotes with eval. eval is better explained is this SO answer

Quoting within the commands is easier too:

$ sudo -s eval 'whoami; whoami; echo "end;"'
root
root
end;

And if the commands need to stop running if one fails use double-ampersands instead of semi-colons:

$ sudo -s eval 'whoami && whoamit && echo "end;"'
root
/bin/bash: whoamit: command not found

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

Make a UIButton programmatically in Swift

Swift 5.0

        let button = self.makeButton(title: "Login", titleColor: .blue, font: UIFont.init(name: "Arial", size: 18.0), background: .white, cornerRadius: 3.0, borderWidth: 2, borderColor: .black)
        view.addSubview(button)
        // Adding Constraints
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true
        button.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
        button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
        button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
        button.addTarget(self, action: #selector(pressed(_ :)), for: .touchUpInside)

       // Define commmon method
        func makeButton(title: String? = nil,
                           titleColor: UIColor = .black,
                           font: UIFont? = nil,
                           background: UIColor = .clear,
                           cornerRadius: CGFloat = 0,
                           borderWidth: CGFloat = 0,
                           borderColor: UIColor = .clear) -> UIButton {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(title, for: .normal)
        button.backgroundColor = background
        button.setTitleColor(titleColor, for: .normal)
        button.titleLabel?.font = font
        button.layer.cornerRadius = 6.0
        button.layer.borderWidth = 2
        button.layer.borderColor = UIColor.red.cgColor
        return button
      }
        // Button Action
         @objc func pressed(_ sender: UIButton) {
                print("Pressed")
          }

enter image description here

How can I find the location of origin/master in git, and how do I change it?

I came to this question looking for an explanation about what the message "your branch is ahead by..." means, in the general scheme of git. There was no answer to that here, but since this question currently shows up at the top of Google when you search for the phrase "Your branch is ahead of 'origin/master'", and I have since figured out what the message really means, I thought I'd post the info here.

So, being a git newbie, I can see that the answer I needed was a distinctly newbie answer. Specifically, what the "your branch is ahead by..." phrase means is that there are files you've added and committed to your local repository, but have never pushed to the origin. The intent of this message is further obfuscated by the fact that "git diff", at least for me, showed no differences. It wasn't until I ran "git diff origin/master" that I was told that there were differences between my local repository, and the remote master.

So, to be clear:


"your branch is ahead by..." => You need to push to the remote master. Run "git diff origin/master" to see what the differences are between your local repository and the remote master repository.


Hope this helps other newbies.

(Also, I recognize that there are configuration subtleties that may partially invalidate this solution, such as the fact that the master may not actually be "remote", and that "origin" is a reconfigurable name used by convention, etc. But newbies do not care about that sort of thing. We want simple, straightforward answers. We can read about the subtleties later, once we've solved the pressing problem.)

Earl

How to convert hashmap to JSON object in Java

In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:

Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
    .map(e -> "\""+ e.getKey() + "\"" + ":\"" + String.valueOf(e.getValue()) + "\"")
    .collect(Collectors.joining(", "))+"}";

Space between Column's children in Flutter

You can also use a helper function to add spacing after each child.

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

So then, the returned list may be used as a children of a column

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

I'm not sure though if it's wrong or have a performance penalty to run the children through a helper function for the same goal?

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

JSON character encoding

First, your posted data isn't valid JSON. This would be:

{"value": "aériennes"}

Note the double quotes: They are required.

The Content-Type for JSON data should be application/json. The actual JSON data (what we have above) should be encoded using UTF-8, UTF-16, or UTF-32 - I'd recommend using UTF-8.

You can use a tool like Wireshark to monitor network traffic and see how the data looks, you should see the bytes c3 89 for the é. I've never worked with Spring, but if it's doing the JSON encoding, this is probably taken care of properly, for you.

Once the JSON reaches the browser, it should good, if it is valid. However, how are you inserting the data from the JSON response into the webpage?

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

In Bash, how do I add a string after each line in a file?

  1. Pure POSIX shell and sponge:

    suffix=foobar
    while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | 
    sponge file
    
  2. xargs and printf:

    suffix=foobar
    xargs -L 1 printf "%s${suffix}\n" < file | sponge file
    
  3. Using join:

    suffix=foobar
    join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
    
  4. Shell tools using paste, yes, head & wc:

    suffix=foobar
    paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file
    

    Note that paste inserts a Tab char before $suffix.

Of course sponge can be replaced with a temp file, afterwards mv'd over the original filename, as with some other answers...

Get current clipboard content?

Following will give you the selected content as well as updating the clipboard.

Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.

document.querySelector('element').bind('copy', function(event) {
  var selectedText = window.getSelection().toString(); 
  selectedText = selectedText.replace(/\u200B/g, "");

  clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
  clipboardData.setData('text/html', selectedText);

  event.preventDefault();
});

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

How to put a List<class> into a JSONObject and then read that object?

Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.

For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):

JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();

SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);

SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);

obj.put("list", sList);

JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
  System.out.println(jArray.getJSONObject(ii).getString("value"));

Text Editor which shows \r\n?

On the Windows platform the Zeus editor has an option to display white space (i.e. View, White sapce menu).

It also has an option to display the file in hex mode (i.e. Tools, Hex Dump menu).

AngularJS For Loop with Numbers & Ranges

Hi you can achieve this using pure html using AngularJS (NO Directive is required!)

<div ng-app="myapp" ng-controller="YourCtrl" ng-init="x=[5];">
  <div ng-if="i>0" ng-repeat="i in x">
    <!-- this content will repeat for 5 times. -->
    <table class="table table-striped">
      <tr ng-repeat="person in people">
         <td>{{ person.first + ' ' + person.last }}</td>
      </tr>
    </table>
    <p ng-init="x.push(i-1)"></p>
  </div>
</div>

How to get HTTP response code for a URL in Java?

you can use java http/https url connection to get the response code from the website and other information as well here is a sample code.

 try {

            url = new URL("https://www.google.com"); // create url object for the given string  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(https_url.startsWith("https")){
                 connection = (HttpsURLConnection) url.openConnection();
            }

            ((HttpURLConnection) connection).setRequestMethod("HEAD");
            connection.setConnectTimeout(50000); //set the timeout
            connection.connect(); //connect
            String responseMessage = connection.getResponseMessage(); //here you get the response message
             responseCode = connection.getResponseCode(); //this is http response code
            System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
            connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

How to try convert a string to a Guid

use code like this:

new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")

instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value

How to restart a node.js server

Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

PHP str_replace replace spaces with underscores

For one matched character replace, use str_replace:

$string = str_replace(' ', '_', $string);

For all matched character replace, use preg_replace:

$string = preg_replace('/\s+/', '_', $string);

how to toggle (hide/show) a table onClick of <a> tag in java script

visibility property makes the element visible or invisible.

function showTable(){
    document.getElementById('table').style.visibility = "visible";
}
function hideTable(){
    document.getElementById('table').style.visibility = "hidden";
}

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')

If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:

import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
    match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings = match.group(1).split()
    result_matrix.append(map(int, values_as_strings))

how to upload a file to my server using html

You need enctype="multipart/form-data" otherwise you will load only the file name and not the data.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

this is not the recommendation solution.. But worth to share. Since my project are upgrade the DBMS from old Mysql to newest (8). But I cant change the table structure, only the DBMS config (mysql). The solution for mysql server.

test on Windows mysql 8.0.15 on mysql config search for

sql-mode="....."

uncomment it. Or in my case just type/add

sql-mode="NO_ENGINE_SUBSTITUTION"

why not recommended solution. because if you use latin1 (my case).. the data insert successly but not the content (mysql not respond with error!!) . for example you type info like this

bla \x12

it save

bla [] (box)

okay.. for my problem.. I can change the field to UTF8.. But there is small problem.. see above answer about other solution is failed because the word is not inserted because contain more than 2 bytes (cmiiw).. this solution make your insert data become box. The reasonable is to use blob.. and you can skip my answer.

Another testing related to this were.. using utf8_encode on your code before save. I use on latin1 and it was success (I'm not using sql-mode)! same as above answer using base64_encode .

My suggestion to analys your table requirement and tried to change from other format to UTF8

How do I create a file at a specific path?

The file is created wherever the root of the python interpreter was started.

Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

Find ALL tweets from a user (not just the first 3,200)

You can use twitter search page to bypass 3,200 limit. However you have to scroll down many times in the search results page. For example, I searched tweets from @beyinsiz_adam. This is the link of search results: https://twitter.com/search?q=from%3Abeyinsiz_adam&src=typd&f=realtime

Now in order to scroll down many times, you can use the following javascript code.

    var myVar=setInterval(function(){myTimer()},1000);
    function myTimer() {
        window.scrollTo(0,document.body.scrollHeight);
    }

Just run it in the FireBug console. And wait some time to load all tweets.

How to display databases in Oracle 11g using SQL*Plus

I am not clearly about it but typically one server has one database (with many users), if you create many databases mean that you create many instances, listeners, ... as well. So you can check your LISTENER to identify it.

In my testing I created 2 databases (dbtest and dbtest_1) so when I check my LISTENER status it appeared like this:

lsnrctl status

....

STATUS of the LISTENER

.....

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.20.20)(PORT=1521)))

Services Summary...

Service "dbtest" has 1 instance(s).

Instance "dbtest", status READY, has 1 handler(s) for this service...

Service "dbtest1XDB" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service...

Service "dbtest_1" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service... The command completed successfully

Syncing Android Studio project with Gradle files

I am using Android Studio 4 developing a Fluter/Dart application. There does not seem to be a Sync project with gradle button or file menu item, there is no clean or rebuild either.

I fixed the problem by removing the .idea folder. The suggestion included removing .gradle as well, but it did not exist.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Liquibase lock - reasons?

I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.

Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!

Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!

Run PostgreSQL queries from the command line

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase 
mydatabase=#

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable;

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs 
mydatabase=# ;  
ERROR:  syntax error at or near "asdfs"
LINE 1: asdfs
    ^

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

How to execute an external program from within Node.js?

From the Node.js documentation:

Node provides a tri-directional popen(3) facility through the ChildProcess class.

See http://nodejs.org/docs/v0.4.6/api/child_processes.html

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

How to delete a workspace in Perforce (using p4v)?

  1. Ctrl + 5

view workspace in p4v

  1. Delete the relevant workspace

enter image description here

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

Final keyword has a numerous way to use:

  • A final class cannot be subclassed.
  • A final method cannot be overridden by subclasses
  • A final variable can only be initialized once

Other usage:

  • When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class

A static class variable will exist from the start of the JVM, and should be initialized in the class. The error message won't appear if you do this.

How to delete session cookie in Postman?

Is the Postman Interceptor enabled? Toggling it will route all requests and responses through the Chrome browser.

Interceptor - https://www.getpostman.com/docs/capture Cookies documentation - http://blog.getpostman.com/index.php/2014/11/28/using-the-interceptor-to-read-and-write-cookies/

update one table with data from another

Try following code. It is working for me....

UPDATE TableOne 
SET 
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT  TableTwo.id 
                             FROM   TableTwo 
                             WHERE  TableOne.id = TableTwo.id) 

A monad is just a monoid in the category of endofunctors, what's the problem?

First, the extensions and libraries that we're going to use:

{-# LANGUAGE RankNTypes, TypeOperators #-}

import Control.Monad (join)

Of these, RankNTypes is the only one that's absolutely essential to the below. I once wrote an explanation of RankNTypes that some people seem to have found useful, so I'll refer to that.

Quoting Tom Crockett's excellent answer, we have:

A monad is...

  • An endofunctor, T : X -> X
  • A natural transformation, µ : T × T -> T, where × means functor composition
  • A natural transformation, ? : I -> T, where I is the identity endofunctor on X

...satisfying these laws:

  • µ(µ(T × T) × T)) = µ(T × µ(T × T))
  • µ(?(T)) = T = µ(T(?))

How do we translate this to Haskell code? Well, let's start with the notion of a natural transformation:

-- | A natural transformations between two 'Functor' instances.  Law:
--
-- > fmap f . eta g == eta g . fmap f
--
-- Neat fact: the type system actually guarantees this law.
--
newtype f :-> g =
    Natural { eta :: forall x. f x -> g x }

A type of the form f :-> g is analogous to a function type, but instead of thinking of it as a function between two types (of kind *), think of it as a morphism between two functors (each of kind * -> *). Examples:

listToMaybe :: [] :-> Maybe
listToMaybe = Natural go
    where go [] = Nothing
          go (x:_) = Just x

maybeToList :: Maybe :-> []
maybeToList = Natural go
    where go Nothing = []
          go (Just x) = [x]

reverse' :: [] :-> []
reverse' = Natural reverse

Basically, in Haskell, natural transformations are functions from some type f x to another type g x such that the x type variable is "inaccessible" to the caller. So for example, sort :: Ord a => [a] -> [a] cannot be made into a natural transformation, because it's "picky" about which types we may instantiate for a. One intuitive way I often use to think of this is the following:

  • A functor is a way of operating on the content of something without touching the structure.
  • A natural transformation is a way of operating on the structure of something without touching or looking at the content.

Now, with that out of the way, let's tackle the clauses of the definition.

The first clause is "an endofunctor, T : X -> X." Well, every Functor in Haskell is an endofunctor in what people call "the Hask category," whose objects are Haskell types (of kind *) and whose morphisms are Haskell functions. This sounds like a complicated statement, but it's actually a very trivial one. All it means is that that a Functor f :: * -> * gives you the means of constructing a type f a :: * for any a :: * and a function fmap f :: f a -> f b out of any f :: a -> b, and that these obey the functor laws.

Second clause: the Identity functor in Haskell (which comes with the Platform, so you can just import it) is defined this way:

newtype Identity a = Identity { runIdentity :: a }

instance Functor Identity where
    fmap f (Identity a) = Identity (f a)

So the natural transformation ? : I -> T from Tom Crockett's definition can be written this way for any Monad instance t:

return' :: Monad t => Identity :-> t
return' = Natural (return . runIdentity)

Third clause: The composition of two functors in Haskell can be defined this way (which also comes with the Platform):

newtype Compose f g a = Compose { getCompose :: f (g a) }

-- | The composition of two 'Functor's is also a 'Functor'.
instance (Functor f, Functor g) => Functor (Compose f g) where
    fmap f (Compose fga) = Compose (fmap (fmap f) fga)

So the natural transformation µ : T × T -> T from Tom Crockett's definition can be written like this:

join' :: Monad t => Compose t t :-> t
join' = Natural (join . getCompose)

The statement that this is a monoid in the category of endofunctors then means that Compose (partially applied to just its first two parameters) is associative, and that Identity is its identity element. I.e., that the following isomorphisms hold:

  • Compose f (Compose g h) ~= Compose (Compose f g) h
  • Compose f Identity ~= f
  • Compose Identity g ~= g

These are very easy to prove because Compose and Identity are both defined as newtype, and the Haskell Reports define the semantics of newtype as an isomorphism between the type being defined and the type of the argument to the newtype's data constructor. So for example, let's prove Compose f Identity ~= f:

Compose f Identity a
    ~= f (Identity a)                 -- newtype Compose f g a = Compose (f (g a))
    ~= f a                            -- newtype Identity a = Identity a
Q.E.D.

401 Unauthorized: Access is denied due to invalid credentials

I faced this error when I created an empty project with the MVC folders and then deployed the application to the server. My issue was that I didn't define the authentication in Web.config, so all I had to do was add this line to a system.web tag.

<system.web>
    <authentication mode="None"/>
</system.web>

Read and overwrite a file in Python

Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.

How to clear textarea on click?

You can use the placeholder attribute introduced in HTML5:

<textarea placeholder="Please describe why"></textarea>

This will place your filler text in grey that will disappear automatically when a user clicks on the text field. Additionally, it will reappear if it loses focus and the text area is blank.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

XAMPP - Port 80 in use by “Unable to open process” with PID 4! 12

run the comment in cmd tasklist

and find which the PID and process name related to this now open window task manager

you can also open window task manager by using CTRL+ALT+DEL

now click on the process tab and find the name which using PID and right click on that and end process

now again restart the xampp

How can I disable selected attribute from select2() dropdown Jquery?

In selec2 site you can see options. There is "disabled" option for api. You can use like :

$('#foo').select2({
    disabled: true
});

Transition color fade on hover?

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

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

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x, it is not guaranteed at all:

>>> False = 5
>>> 0 == False
False

So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.

In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.

How could I put a border on my grid control in WPF?

This is my solution, wish useful for you:

public class Sheet : Grid
{
    public static readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register(nameof(BorderBrush), typeof(Brush), typeof(Sheet), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderBrushChanged));

    public static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register(nameof(BorderThickness), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(1D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderThicknessChanged, CoerceBorderThickness));
    public static readonly DependencyProperty CellSpacingProperty = DependencyProperty.Register(nameof(CellSpacing), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(0D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnCellSpacingChanged, CoerceCellSpacing));

    public Brush BorderBrush
    {
        get => this.GetValue(BorderBrushProperty) as Brush;
        set => this.SetValue(BorderBrushProperty, value);
    }

    public double BorderThickness
    {
        get => (double)this.GetValue(BorderThicknessProperty);
        set => this.SetValue(BorderThicknessProperty, value);
    }

    public double CellSpacing
    {
        get => (double)this.GetValue(CellSpacingProperty);
        set => this.SetValue(CellSpacingProperty, value);
    }

    protected override Size ArrangeOverride(Size arrangeSize)
    {
        Size size = base.ArrangeOverride(arrangeSize);
        double border = this.BorderThickness;
        double doubleBorder = border * 2D;
        double spacing = this.CellSpacing;
        double halfSpacing = spacing * 0.5D;
        if (border > 0D || spacing > 0D)
        {
            foreach (UIElement child in this.InternalChildren)
            {
                this.GetChildBounds(child, out double left, out double top, out double width, out double height);

                left += halfSpacing + border;
                top += halfSpacing + border;
                height -= spacing + doubleBorder;
                width -= spacing + doubleBorder;

                if (width < 0D)
                {
                    width = 0D;
                }

                if (height < 0D)
                {
                    height = 0D;
                }

                left -= left % 0.5D;
                top -= top % 0.5D;
                width -= width % 0.5D;
                height -= height % 0.5D;

                child.Arrange(new Rect(left, top, width, height));
            }

            if (border > 0D && this.BorderBrush != null)
            {
                this.InvalidateVisual();
            }
        }

        return size;
    }
    
    protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);

        if (this.BorderThickness > 0D && this.BorderBrush != null)
        {
            if (this.CellSpacing == 0D)
            {
                this.DrawCollapsedBorder(dc);
            }
            else
            {
                this.DrawSeperatedBorder(dc);
            }
        }
    }

    private void DrawSeperatedBorder(DrawingContext dc)
    {
        double spacing = this.CellSpacing;
        double halfSpacing = spacing * 0.5D;


        #region draw border
        Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
        UIElementCollection children = this.InternalChildren;
        foreach (UIElement child in children)
        {
            this.GetChildBounds(child, out double left, out double top, out double width, out double height);
            left += halfSpacing;
            top += halfSpacing;
            width -= spacing;
            height -= spacing;

            dc.DrawRectangle(null, pen, new Rect(left, top, width, height));
        }
        #endregion
    }

    private void DrawCollapsedBorder(DrawingContext dc)
    {
        RowDefinitionCollection rows = this.RowDefinitions;
        ColumnDefinitionCollection columns = this.ColumnDefinitions;
        int rowCount = rows.Count;
        int columnCount = columns.Count;
        const byte BORDER_LEFT = 0x08;
        const byte BORDER_TOP = 0x04;
        const byte BORDER_RIGHT = 0x02;
        const byte BORDER_BOTTOM = 0x01;
        byte[,] borderState = new byte[rowCount, columnCount];
        int column = columnCount - 1;
        int columnSpan;
        int row = rowCount - 1;
        int rowSpan;
        #region generate main border data
        for (int i = 0; i < rowCount; i++)
        {
            borderState[i, 0] = BORDER_LEFT;
            borderState[i, column] = BORDER_RIGHT;
        }

        for (int i = 0; i < columnCount; i++)
        {
            borderState[0, i] |= BORDER_TOP;
            borderState[row, i] |= BORDER_BOTTOM;
        }
        #endregion

        #region generate child border data
        UIElementCollection children = this.InternalChildren;
        foreach (UIElement child in children)
        {
            this.GetChildLayout(child, out row, out rowSpan, out column, out columnSpan);
            for (int i = 0; i < rowSpan; i++)
            {
                borderState[row + i, column] |= BORDER_LEFT;
                borderState[row + i, column + columnSpan - 1] |= BORDER_RIGHT;
            }
            for (int i = 0; i < columnSpan; i++)
            {
                borderState[row, column + i] |= BORDER_TOP;
                borderState[row + rowSpan - 1, column + i] |= BORDER_BOTTOM;
            }
        }
        #endregion

        #region draw border
        Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
        double left;
        double top;
        double width, height;


        for (int r = 0; r < rowCount; r++)
        {
            RowDefinition v = rows[r];
            top = v.Offset;
            height = v.ActualHeight;
            for (int c = 0; c < columnCount; c++)
            {
                byte state = borderState[r, c];

                ColumnDefinition h = columns[c];
                left = h.Offset;
                width = h.ActualWidth;
                if ((state & BORDER_LEFT) == BORDER_LEFT)
                {
                    dc.DrawLine(pen, new Point(left, top), new Point(left, top + height));
                }
                if ((state & BORDER_TOP) == BORDER_TOP)
                {
                    dc.DrawLine(pen, new Point(left, top), new Point(left + width, top));
                }
                if ((state & BORDER_RIGHT) == BORDER_RIGHT && (c + 1 >= columnCount || (borderState[r, c + 1] & BORDER_LEFT) == 0))
                {
                    dc.DrawLine(pen, new Point(left + width, top), new Point(left + width, top + height));
                }
                if ((state & BORDER_BOTTOM) == BORDER_BOTTOM && (r + 1 >= rowCount || (borderState[r + 1, c] & BORDER_TOP) == 0))
                {
                    dc.DrawLine(pen, new Point(left, top + height), new Point(left + width, top + height));
                }
            }

        }
        #endregion
    }

    private void GetChildBounds(UIElement child, out double left, out double top, out double width, out double height)
    {
        ColumnDefinitionCollection columns = this.ColumnDefinitions;
        RowDefinitionCollection rows = this.RowDefinitions;
        int rowCount = rows.Count;

        int row = (int)child.GetValue(Grid.RowProperty);
        if (row >= rowCount)
        {
            row = rowCount - 1;
        }

        int rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
        if (row + rowSpan > rowCount)
        {
            rowSpan = rowCount - row;
        }
        int columnCount = columns.Count;

        int column = (int)child.GetValue(Grid.ColumnProperty);
        if (column >= columnCount)
        {
            column = columnCount - 1;
        }

        int columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
        if (column + columnSpan > columnCount)
        {
            columnSpan = columnCount - column;
        }

        left = columns[column].Offset;
        top = rows[row].Offset;
        ColumnDefinition right = columns[column + columnSpan - 1];
        width = right.Offset + right.ActualWidth - left;
        RowDefinition bottom = rows[row + rowSpan - 1];
        height = bottom.Offset + bottom.ActualHeight - top;
        if (width < 0D)
        {
            width = 0D;
        }

        if (height < 0D)
        {
            height = 0D;
        }

    }
    private void GetChildLayout(UIElement child, out int row, out int rowSpan, out int column, out int columnSpan)
    {
        int rowCount = this.RowDefinitions.Count;

        row = (int)child.GetValue(Grid.RowProperty);
        if (row >= rowCount)
        {
            row = rowCount - 1;
        }

        rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
        if (row + rowSpan > rowCount)
        {
            rowSpan = rowCount - row;
        }
        int columnCount = this.ColumnDefinitions.Count;

        column = (int)child.GetValue(Grid.ColumnProperty);
        if (column >= columnCount)
        {
            column = columnCount - 1;
        }

        columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
        if (column + columnSpan > columnCount)
        {
            columnSpan = columnCount - column;
        }
    }

    private static void OnBorderBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateVisual();
        }
    }

    private static void OnBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateArrange();
        }
    }

    private static void OnCellSpacingChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (d is UIElement element)
        {
            element.InvalidateArrange();
        }
    }

    private static object CoerceBorderThickness(DependencyObject d, object baseValue)
    {
        if (baseValue is double value)
        {
            return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
        }

        return 0D;
    }
    private static object CoerceCellSpacing(DependencyObject d, object baseValue)
    {
        if (baseValue is double value)
        {
            return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
        }

        return 0D;
    }
}

a demo: demo of a table with collapsed border

How do I generate a random integer between min and max in Java?

This generates a random integer of size psize

public static Integer getRandom(Integer pSize) {

    if(pSize<=0) {
        return null;
    }
    Double min_d = Math.pow(10, pSize.doubleValue()-1D);
    Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
    int min = min_d.intValue();
    int max = max_d.intValue();
    return RAND.nextInt(max-min) + min;
}

javascript regular expression to not match a word

This is what you are looking for:

^((?!(abc|def)).)*$

the explanation is here: Regular expression to match a line that doesn't contain a word?

Add URL link in CSS Background Image?

Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:

<div class="wrapWithBackgroundImage">
    <a href="#" class="invisibleLink"></a>
</div>

.wrapWithBackgroundImage {
    background-image: url(...);
}
.invisibleLink {
    display: block;
    left: 55px; top: 55px;
    position: absolute;
    height: 55px width: 55px;
}

Print line numbers starting at zero using awk

Another option besides awk is nl which allows for options -v for setting starting value and -n <lf,rf,rz> for left, right and right with leading zeros justified. You can also include -s for a field separator such as -s "," for comma separation between line numbers and your data.

In a Unix environment, this can be done as

cat <infile> | ...other stuff... | nl -v 0 -n rz

or simply

nl -v 0 -n rz <infile>

Example:

echo "Here 
are
some 
words" > words.txt

cat words.txt | nl -v 0 -n rz

Out:

000000      Here
000001      are
000002      some
000003      words

jquery how to use multiple ajax calls one after the end of the other

Haven't tried it yet but this is the best way I can think of if there umpteen number of ajax calls.

Method1:

let ajax1= $.ajax({url:'', type:'', . . .});
let ajax2= $.ajax({url:'', type:'', . . .});
.
.
.
let ajaxList = [ajax1, ajax2, . . .]

let count = 0;
let executeAjax = (i) => {
   $.when(ajaxList[i]).done((data) => {
      //  dataOperations goes here
      return i++
   })
}
while (count< ajaxList.length) {
   count = executeAjax(count)
}

If there are only a handful you can always nest them like this.

Method2:

$.when(ajax1).done((data1) => {
      //  dataOperations goes here on data1
      $.when(ajax2).done((data2) => {
         //  Here you can utilize data1 and data 2 simultaneously 
         . . . and so on
      })
   })

Note: If it is repetitive task go for method1, And if each data is to be treated differently, nesting in method2 makes more sense.

Regular expression for a hexadecimal number?

If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

This answer was taken from:http://ult-tex.net/info/perl/

Add a border outside of a UIView (instead of inside)

With the above accepted best answer i made experiences with such not nice results and unsightly edges:

border without bezier path

So i will share my UIView Swift extension with you, that uses a UIBezierPath instead as border outline – without unsightly edges (inspired by @Fattie):

border with bezier path

//  UIView+BezierPathBorder.swift

import UIKit

extension UIView {

    fileprivate var bezierPathIdentifier:String { return "bezierPathBorderLayer" }

    fileprivate var bezierPathBorder:CAShapeLayer? {
        return (self.layer.sublayers?.filter({ (layer) -> Bool in
            return layer.name == self.bezierPathIdentifier && (layer as? CAShapeLayer) != nil
        }) as? [CAShapeLayer])?.first
    }

    func bezierPathBorder(_ color:UIColor = .white, width:CGFloat = 1) {

        var border = self.bezierPathBorder
        let path = UIBezierPath(roundedRect: self.bounds, cornerRadius:self.layer.cornerRadius)
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask

        if (border == nil) {
            border = CAShapeLayer()
            border!.name = self.bezierPathIdentifier
            self.layer.addSublayer(border!)
        }

        border!.frame = self.bounds
        let pathUsingCorrectInsetIfAny =
            UIBezierPath(roundedRect: border!.bounds, cornerRadius:self.layer.cornerRadius)

        border!.path = pathUsingCorrectInsetIfAny.cgPath
        border!.fillColor = UIColor.clear.cgColor
        border!.strokeColor = color.cgColor
        border!.lineWidth = width * 2
    }

    func removeBezierPathBorder() {
        self.layer.mask = nil
        self.bezierPathBorder?.removeFromSuperlayer()
    }

}

Example:

let view = UIView(frame: CGRect(x: 20, y: 20, width: 100, height: 100))
view.layer.cornerRadius = view.frame.width / 2
view.backgroundColor = .red

//add white 2 pixel border outline
view.bezierPathBorder(.white, width: 2)

//remove border outline (optional)
view.removeBezierPathBorder()

Setting equal heights for div's with jQuery

function setEqualHeight(columns) {
  var tallestColumn = 0;

  columns.each(function(){
    var currentHeight = $(this).height();

    if(currentHeight > tallestColumn){
      tallestColumn  = currentHeight;
    }
  });

  columns.height(tallestColumn);
}

=> setEqualHeight($('.column'));

Converting integer to binary in python

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'

How to track down access violation "at address 00000000"

It's probably because you are directly or indirectly through a library call accessing a NULL pointer. In this particular case, it looks like you've jumped to a NULL address, which is a b bit hairier.

In my experience, the easiest way to track these down are to run it with a debugger, and dump a stack trace.

Alternatively, you can do it "by hand" and add lots of logging until you can track down exactly which function (and possibly LOC) this violation occurred in.

Take a look at Stack Tracer, which might help you improve your debugging.

Java error: Implicit super constructor is undefined for default constructor

You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:

public ACSubClass() {
    super();
}

However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super(); because there is not a no-argument constructor in BaseClass.

This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.

The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.

grep using a character vector with multiple patterns

Based on Brian Digg's post, here are two helpful functions for filtering lists:

#Returns all items in a list that are not contained in toMatch
#toMatch can be a single item or a list of items
exclude <- function (theList, toMatch){
  return(setdiff(theList,include(theList,toMatch)))
}

#Returns all items in a list that ARE contained in toMatch
#toMatch can be a single item or a list of items
include <- function (theList, toMatch){
  matches <- unique (grep(paste(toMatch,collapse="|"), 
                          theList, value=TRUE))
  return(matches)
}

Change the row color in DataGridView based on the quantity of a cell value

Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    Dim drv As DataRowView
    If e.RowIndex >= 0 Then
        If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
            drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
            Dim c As Color
            If drv.Item("Quantity").Value < 5  Then
                c = Color.LightBlue
            Else
                c = Color.Pink
            End If
            e.CellStyle.BackColor = c
        End If
    End If
End Sub

Convert Iterable to Stream using Java 8 JDK

If you can use Guava library, since version 21, you can use

Streams.stream(iterable)

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

Php header location redirect not working

Be very careful with whitespace and other stuff that may affect the "output" already done. I certainly know this but still suffered from the same problem. My whole "Admin.php"-file had some spaces after the closing php-tag ?> down the bottom on the last row :)

Easily discovered by adding...

error_reporting(E_ALL);

...which told me which line of code that generated the output.

gitignore all files of extension in directory

It would appear that the ** syntax is supported by git as of version 1.8.2.1 according to the documentation.

Two consecutive asterisks ("**") in patterns matched against full pathname may have special meaning:

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

  • A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.

  • A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.

  • Other consecutive asterisks are considered invalid.

Gson - convert from Json to a typed ArrayList<T>

You have a string like this.

"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"

Then you can covert it to ArrayList via Gson like

var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()

Your HotelInfo class should like this.

import com.squareup.moshi.Json

data class HotelInfo(

    @Json(name="cityName")
    val cityName: String? = null,

    @Json(name="id")
    val id: Int? = null,

    @Json(name="hotelId")
    val hotelId: String? = null,

    @Json(name="hotelName")
    val hotelName: String? = null
)

Invoking Java main method with parameters from Eclipse

If have spaces within your string argument, do the following:

Run > Run Configurations > Java Application > Arguments > Program arguments

  1. Enclose your string argument with quotes
  2. Separate each argument by space or new line

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

MemoryStream - Cannot access a closed Stream

In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):

PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);

The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Hide div by default and show it on click with bootstrap

Try this one:

<button class="button" onclick="$('#target').toggle();">
    Show/Hide
</button>
<div id="target" style="display: none">
    Hide show.....
</div>

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I faced this issue when I was tring to link a locally created repo with a blank repo on github. Initially I was trying git remote set-url but I had to do git remote add instead.

git remote add origin https://github.com/VijayNew/NewExample.git

Check if object exists in JavaScript

zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.

if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

AngularJS. How to call controller function from outside of controller component

It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.

But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.

Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)

python: iterate a specific range in a list

By using iter builtin:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)

Adding images to an HTML document with javascript

With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).

<head>
    <script type="text/javascript">
        function insert(){
            var src = document.getElementById("gamediv");
            var img = document.createElement("img");
            img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
            src.appendChild(img);
        }
     </script>
 </head>
 <body>
     <div id="gamediv">
         <script type="text/javascript">
             insert();
         </script>
     </div>
 </body>

How to get date, month, year in jQuery UI datepicker?

$("#date").datepicker('getDate').getMonth() + 1; 

The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.

Using Linq select list inside list

If you want to filter the models by applicationname and the remaining models by surname:

List<Model> newList = list.Where(m => m.application == "applicationname")
    .Select(m => new Model { 
        application = m.application, 
        users = m.users.Where(u => u.surname == "surname").ToList() 
    }).ToList();

As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.

If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any:

List<Model> newList = list
    .Where(m => m.application == "applicationname"
            &&  m.users.Any(u => u.surname == "surname"))
    .ToList();

How to show the text on a ImageButton?

Here is the solution

<LinearLayout
    android:id="@+id/buttons_line1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageButton
        android:id="@+id/btn_mute"
        android:src="@drawable/btn_mute"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
    <ImageButton
        android:id="@+id/btn_keypad"
        android:layout_marginLeft="50dp"
        android:src="@drawable/btn_dialpad"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
    <ImageButton
        android:id="@+id/btn_speaker"
        android:layout_marginLeft="50dp"
        android:src="@drawable/btn_speaker"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
</LinearLayout>
<LinearLayout
    android:layout_below="@+id/buttons_line1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:text="mute"
        android:clickable="false"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:text="keypad"
        android:clickable="false"
        android:layout_marginLeft="50dp"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:text="speaker"
        android:clickable="false"
        android:layout_marginLeft="50dp"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
</LinearLayout>

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

In addition to David Sacks answer, you may also need to go to the Build tab of the Project Properties and set Platform Target to x86 for the project that is giving you these warnings. Though you might expect it to be, this setting does not seem to be perfectly synchronized with the setting in the configuration manager.

How do I pause my shell script for a second before continuing?

In Python (question was originally tagged Python) you need to import the time module

import time
time.sleep(1)

or

from time import sleep
sleep(1)

For shell script is is just

sleep 1

Which executes the sleep command. eg. /bin/sleep

Java says FileNotFoundException but file exists

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

Use this line and see where the path is:

System.out.println(new File(".").getAbsoluteFile());

How do I exit from a function?

I'd suggest trying to avoid using return/exit if you don't have to. Some people will devoutly tell you to NEVER do it, but sometimes it just makes sense. However if you can structure you checks so that you don't have to enter into them, I think it makes it easier for people to follow your code later.

How to write an ArrayList of Strings into a text file?

I think you can also use BufferedWriter :

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));

String stuffToWrite = info;

writer.write(stuffToWrite);

writer.close();

and before that remember too add

import java.io.BufferedWriter;

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

How to set session attribute in java?

I am try to catch your point.I hope it is helpful.....

if (session.isNew()){
     title = "Welcome to my website";
     session.setAttribute(userIDKey, userID);

Edit and Continue: "Changes are not allowed when..."

I'm adding my answer because the thing that solved it for me isn't clearly mentioned yet. Actually what helped me was this article:

http://www.rubencanton.com/blog/2012/02/how-to-fix-error-changes-are-not-allowed-while-code-is-running-in-net.html

and here is a short description of the solution:

  1. Stop running your app.
  2. Go to Tools > Options > Debugging > Edit and Continue
  3. Disable “Enable Edit and Continue”

Note how counter-intuitive this is: I had to disable (uncheck) "Enable Edit and Continue".

This will then allow you to change code in your editor without getting that message "Changes are not allowed while code is running".

Note however that the code changes you make will NOT be reflected in your running program - for that you need to stop and restart your program (off the top of my head I think that template/ASPX changes do get reflected, but not VB/C# changes, i.e. "code behind" code).

How to remove gaps between subplots in matplotlib?

Another method is to use the pad keyword from plt.subplots_adjust(), which also accepts negative values:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(pad=-5.0)

Additionally, to remove the white at the outer fringe of all subplots (i.e. the canvas), always save with plt.savefig(fname, bbox_inches="tight").

Difference between arguments and parameters in Java

They are not. They're exactly the same.

However, some people say that parameters are placeholders in method signatures:

public void doMethod(String s, int i) {
  ..
}

String s and int i are sometimes said to be parameters. The arguments are the actual values/references:

myClassReference.doMethod("someString", 25);

"someString" and 25 are sometimes said to be the arguments.

Create Local SQL Server database

For anyone still looking to do this in 2020. So long as you are purely using it for development purposes you can download a full featured version of SQL Server directly from Microsoft at https://www.microsoft.com/en-us/sql-server/sql-server-downloads.

Android getting value from selected radiobutton

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

How to tell if tensorflow is using gpu acceleration from inside python shell?

I prefer to use nvidia-smi to monitor GPU usage. if it goes up significantly when you start you program, it's a strong sign that your tensorflow is using GPU.

Mac install and open mysql using terminal

If you have your MySQL server up and running, then you just need a client to connect to it and start practicing. One is the mysql-client, which is a command-line tool, or you can use phpMyAdmin, which is a web-based tool.

Best way to script remote SSH commands in Batch (Windows)

You can also use Bash on Ubuntu on Windows directly. E.g.,

bash -c "ssh -t user@computer 'cd /; sudo my-command'"

Per Martin Prikryl's comment below:

The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.

How should we manage jdk8 stream for null values

Although the answers are 100% correct, a small suggestion to improve null case handling of the list itself with Optional:

 List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList) will allow you to handle nicely the case when listOfStuff is null and return an emptyList instead of failing with NullPointerException.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

PDO does support this (as of 2020). Just do a query() call on a PDO object as usual, separating queries by ; and then nextRowset() to step to the next SELECT result, if you have multiple. Resultsets will be in the same order as the queries. Obviously think about the security implications - so don't accept user supplied queries, use parameters, etc. I use it with queries generated by code for example.

$statement = $connection->query($query);
do {
  $data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());

How to study design patterns?

Practice, practice, practice.

You can read about playing the cello for years, and still not be able to put a bow to instrument and make anything that sounds like music.

Design patterns are best recognized as a high-level issue; one that is only relevant if you have the experience necessary to recognize them as useful. It's good that you recognize that they're useful, but unless you've seen situations where they would apply, or have applied, it's almost impossible to understand their true value.

Where they become useful is when you recognize design patterns in others' code, or recognize a problem in the design phase that fits well with a pattern; and then examine the formal pattern, and examine the problem, and determine what the delta is between them, and what that says about both the pattern and the problem.

It's really the same as coding; K&R may be the "bible" for C, but reading it cover-to-cover several times just doesn't give one practical experience; there's no replacement for experience.

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Splitting String with delimiter

dependencies {
   compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
     ['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
       def (g, m) = i.tokenize( ':' )
       dep.exclude group: g  , module: m
     }
   }
}

Python threading.timer - repeat function every 'n' seconds

I have come up with another solution with SingleTon class. Please tell me if any memory leakage is here.

import time,threading

class Singleton:
  __instance = None
  sleepTime = 1
  executeThread = False

  def __init__(self):
     if Singleton.__instance != None:
        raise Exception("This class is a singleton!")
     else:
        Singleton.__instance = self

  @staticmethod
  def getInstance():
     if Singleton.__instance == None:
        Singleton()
     return Singleton.__instance


  def startThread(self):
     self.executeThread = True
     self.threadNew = threading.Thread(target=self.foo_target)
     self.threadNew.start()
     print('doing other things...')


  def stopThread(self):
     print("Killing Thread ")
     self.executeThread = False
     self.threadNew.join()
     print(self.threadNew)


  def foo(self):
     print("Hello in " + str(self.sleepTime) + " seconds")


  def foo_target(self):
     while self.executeThread:
        self.foo()
        print(self.threadNew)
        time.sleep(self.sleepTime)

        if not self.executeThread:
           break


sClass = Singleton()
sClass.startThread()
time.sleep(5)
sClass.getInstance().stopThread()

sClass.getInstance().sleepTime = 2
sClass.startThread()

CASCADE DELETE just once

No. To do it just once you would simply write the delete statement for the table you want to cascade.

DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Why can't I have abstract static methods in C#?

Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.

Assume you could, for a moment, inherit static methods. Imagine this scenario:

public static class Base
{
    public static virtual int GetNumber() { return 5; }
}

public static class Child1 : Base
{
    public static override int GetNumber() { return 1; }
}

public static class Child2 : Base
{
    public static override int GetNumber() { return 2; }
}

If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.

How can I inspect element in chrome when right click is disabled?

Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)

What is Java EE?

Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements.

In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.

notifyDataSetChange not working from custom adapter

class StudentAdapter extends BaseAdapter {
    ArrayList<LichHocDTO> studentList;

    private void capNhatDuLieu(ArrayList<LichHocDTO> list){
        this.studentList.clear();
        this.studentList.addAll(list);
        this.notifyDataSetChanged();
    }
}

You can try. It work for me

Could pandas use column as index?

You can change the index as explained already using set_index. You don't need to manually swap rows with columns, there is a transpose (data.T) method in pandas that does it for you:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000

then you can fetch the dataframe column values and transform them to a list:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

Add space between <li> elements

add:

margin: 0 0 3px 0;

to your #access li and move

background: #0f84e8; /* Show a solid color for older browsers */

to the #access a and take out the border-bottom. Then it will work

Here: http://jsfiddle.net/bpmKW/4/

Can we rely on String.isEmpty for checking null condition on a String in Java?

You can't use String.isEmpty() if it is null. Best is to have your own method to check null or empty.

public static boolean isBlankOrNull(String str) {
    return (str == null || "".equals(str.trim()));
}

Html5 Full screen video

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

Why does this iterative list-growing code give IndexError: list assignment index out of range?

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

WAMP server, localhost is not working

First stop IIS from startmenu by typing IIS manager, Edit c:/wamp/wampmanager.tpl file so the WAMP menu points to localhost:80. Find http://localhost and change it to htttp://localhost:80 also, if you think something else has already grabbed port 80, that is why its not working..,then, Run

wampmanager->Apache->Service->Test port 80

This will launch a command window and tell you what is using port 80. Whatever it is, will need to be re-configured to use another port or for example if its IIS and you dont use IIS it should be un-installed. Further you can use 'net stop' command to stop desired service.

Array or List in Java. Which is faster?

List is the preferred way in java 1.5 and beyond as it can use generics. Arrays cannot have generics. Also Arrays have a pre defined length, which cannot grow dynamically. Initializing an array with a large size is not a good idea. ArrayList is the the way to declare an array with generics and it can dynamically grow. But if delete and insert is used more frequently, then linked list is the fastest data structure to be used.

Add timestamp column with default NOW() for new rows only

For example, I will create a table called users as below and give a column named date a default value NOW()

create table users_parent (
    user_id     varchar(50),
    full_name   varchar(240),
    login_id_1  varchar(50),
    date        timestamp NOT NULL DEFAULT NOW()
);

Thanks

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Using CSS3 you don't need to make your own image with the transparency.

Just have a div with the following

position:absolute;
left:0;
background: rgba(255,255,255,.5);

The last parameter in background (.5) is the level of transparency (a higher number is more opaque).

Example Fiddle

Getting the first and last day of a month, using a given DateTime object

"Last day of month" is actually "First day of *next* month, minus 1". So here's what I use, no need for "DaysInMonth" method:

public static DateTime FirstDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, 1);
}

public static DateTime LastDayOfMonth(this DateTime value)
{
    return value.FirstDayOfMonth()
        .AddMonths(1)
        .AddMinutes(-1);
}

NOTE: The reason I use AddMinutes(-1), not AddDays(-1) here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59 so your report works correctly - including all the data from last day of month.

I.e. you actually get the "last moment of the month" here. Not Last day.

OK, I'm going to shut up now.

static files with express.js

res.sendFile & express.static both will work for this

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where public is the folder in which the client side code is

As suggested by @ATOzTOA and clarified by @Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

How to check for an active Internet connection on iOS or macOS?

Very simple.... Try these steps:

Step 1: Add the SystemConfiguration framework into your project.


Step 2: Import the following code into your header file.

#import <SystemConfiguration/SystemConfiguration.h>

Step 3: Use the following method

  • Type 1:

    - (BOOL) currentNetworkStatus {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        BOOL connected;
        BOOL isConnected;
        const char *host = "www.apple.com";
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
        SCNetworkReachabilityFlags flags;
        connected = SCNetworkReachabilityGetFlags(reachability, &flags);
        isConnected = NO;
        isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
        return isConnected;
    }
    

  • Type 2:

    Import header : #import "Reachability.h"

    - (BOOL)currentNetworkStatus
    {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
        return networkStatus != NotReachable;
    }
    

Step 4: How to use:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}

Why would $_FILES be empty when uploading files to PHP?

I had similar problem and the issue was in wrong value in htaccess as shamittomar mentioned.

Change php_value post_max_size 10MB to php_value post_max_size 10M

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

How to test which port MySQL is running on and whether it can be connected to?

I agree with @bortunac's solution. my.conf is mysql specific while netstat will provide you with all the listening ports.

Perhaps use both, one to confirm which is port set for mysql and the other to check that the system is listening through that port.

My client uses CentOS 6.6 and I have found the my.conf file under /etc/, so I used:

grep port /etc/my.conf (CentOS 6.6)

How to read a string one letter at a time in python

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

MySQL Insert into multiple tables? (Database normalization?)

For PDO You may do this

$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')"; 
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";

$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);

BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;

Could not load file or assembly 'System.Data.SQLite'

I came up with 2 quick solutions. Either work for me. I think the problem is because of permissions.

1) Instead of using the Elmah.dll file from the net-2.0 directory, I used Elmah.dll from net-1.1 .

2) Instead of keeping Elmah.dll in the project bin directory. I make a dll directory to put it in.

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

How to select an item from a dropdown list using Selenium WebDriver with java?

Use -

new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");

Of course, you need to import org.openqa.selenium.support.ui.Select;

How to open a web page from my application?

System.Diagnostics.Process.Start("http://www.webpage.com");

One of many ways.

Image resolution for new iPhone 6 and 6+, @3x support added?

I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior). But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.

**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :

Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.

Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.

Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

seeing how the rules are fairly complicated, I'd suggest the following:

/^[a-z](\w*)[a-z0-9]$/i

match the whole string and capture intermediate characters. Then either with the string functions or the following regex:

/__/

check if the captured part has two underscores in a row. For example in Python it would look like this:

>>> import re
>>> def valid(s):
    match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
    if match is not None:
        return match.group(1).count('__') == 0
    return False

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

smooth scroll to top

I just customized BootPc Deutschland's answer

You can simply use

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('body,html').animate({
            scrollTop: 0
        }, 800);
    $('#btn-go-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 800);
        return false;
    });
}); 
</script>

this will help you to smoothly scroll to the top of the page.

and for styling

#btn-go-to-top {
opacity: .5;
width:4%;
height:8%;
display: none;
position: fixed;
bottom: 5%;
right: 3%;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 10px;
 border-radius: 50%;
}

#btn-go-to-top:hover {
opacity: 1;
}
.top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
}

this styling makes the button arrive at the bottom-right of the page.

and in your page you can add the button to go to top like this

<div id="btn-go-to-top" class="text-center top">
<img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
</div>

hope this help you.if you have any doubts you are always free to ask me

.htaccess file to allow access to images folder to view pictures?

Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:

Options -Indexes

Or try:

Options All -Indexes

Best way to store passwords in MYSQL database

Passwords in the database should be stored encrypted. One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt DELETED: MD5 or SHA1. (those are older, vulnerable

In addition to that you can use additional per-user generated random string - 'salt':

$salt = MD5($this->createSalt());

$Password = SHA2($postData['Password'] . $salt);

createSalt() in this case is a function that generates a string from random characters.

EDIT: or if you want more security, you can even add 2 salts: $salt1 . $pass . $salt2

Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say). It should minimize success of brute force attacks.

NameError: global name 'xrange' is not defined in Python 3

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

What is the "hasClass" function with plain JavaScript?

The attribute that stores the classes in use is className.

So you can say:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}

If you want a location that shows you how jQuery does everything, I would suggest:

http://code.jquery.com/jquery-1.5.js

angular.js ng-repeat li items with html content

It goes like ng-bind-html-unsafe="opt.text":

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

http://jsfiddle.net/gFFBa/3/

Or you can define a function in scope:

 $scope.getContent = function(obj){
     return obj.value + " " + obj.text;
 }

And use it this way:

<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
     {{ opt.value }}
</li>

http://jsfiddle.net/gFFBa/4/

Note that you can not do it with an option tag: Can I use HTML tags in the options for select elements?

What is JavaScript's highest integer value that a number can go to without losing precision?

I write it like this:

var max_int = 0x20000000000000;
var min_int = -0x20000000000000;
(max_int + 1) === 0x20000000000000;  //true
(max_int - 1) < 0x20000000000000;    //true

Same for int32

var max_int32 =  0x80000000;
var min_int32 = -0x80000000;

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

How to get hex color value rather than RGB value?

Here is my solution, also does touppercase by the use of an argument and checks for other possible white-spaces and capitalisation in the supplied string.

var a = "rgb(10, 128, 255)";
var b = "rgb( 10, 128, 255)";
var c = "rgb(10, 128, 255 )";
var d = "rgb ( 10, 128, 255 )";
var e = "RGB ( 10, 128, 255 )";
var f = "rgb(10,128,255)";
var g = "rgb(10, 128,)";

var rgbToHex = (function () {
    var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;

    function pad(num) {
        if (num.length === 1) {
            num = "0" + num;
        }

        return num;
    }

    return function (rgb, uppercase) {
        var rxArray = rgb.match(rx),
            hex;

        if (rxArray !== null) {
            hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));

            if (uppercase === true) {
                hex = hex.toUpperCase();
            }

            return hex;
        }

        return;
    };
}());

console.log(rgbToHex(a));
console.log(rgbToHex(b, true));
console.log(rgbToHex(c));
console.log(rgbToHex(d));
console.log(rgbToHex(e));
console.log(rgbToHex(f));
console.log(rgbToHex(g));

On jsfiddle

Speed comparison on jsperf

A further improvement could be to trim() the rgb string

var rxArray = rgb.trim().match(rx),

Fade In Fade Out Android Animation in Java

Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.

// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha",  1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeIn).after(fadeOut);

mAnimationSet.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        mAnimationSet.start();
    }
});
mAnimationSet.start();

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

How to change the locale in chrome browser

Open chrome, go to chrome://settings/languages

On the left, you should see a list of languages. Use mouse to drag the language you want to the top, that will change the order for the values in Accept-language of requests.

If you still don't see the language you prefer, it may be cookies. Go to cookies and clean it up you should be good.

Get unique values from arraylist in java

If you have an array of a some kind of object (bean) you can do this:

List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);

like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.

Remove IE10's "clear field" X button on certain inputs?

To hide arrows and cross in a "time" input :

#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
    -webkit-appearance: none;
    margin: 0;
}