Programs & Examples On #Math mode

Math-Mode is a term used in TeX-based automatic typesetting systems. When in math-mode (as opposed to paragraph-mode or other lower-level modes), all input is interpreted as mathematical notation.

python capitalize first letter only

Only because no one else has mentioned it:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

However, this would also give

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

i.e. it doesn't just capitalize the first alphabetic character. But then .capitalize() has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob', so meh.

How to iterate through range of Dates in Java?

Here is Java 8 code. I think this code will solve your problem.Happy Coding

    LocalDate start = LocalDate.now();
    LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
    Long duration = start.until(end, ChronoUnit.DAYS);
    System.out.println(duration);
     // Do Any stuff Here there after
    IntStream.iterate(0, i -> i + 1)
             .limit(duration)
             .forEach((i) -> {});
     //old way of iteration
    for (int i = 0; i < duration; i++)
     System.out.print("" + i);// Do Any stuff Here

Web API optional parameters

Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

Android Lint contentDescription warning

ContentDescription needed for the Android accessibility. Particularly for the screen reader feature. If you don't support Android accessibility you can ignore it with setup Lint.

So just create lint.xml.

<?xml version="1.0" encoding="UTF-8"?>
<lint>

    <issue id="ContentDescription" severity="ignore" />

</lint>

And put it to the app folder.

enter image description here

How to disable the back button in the browser using JavaScript

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

Using CSS :before and :after pseudo-elements with inline CSS?

No you cant target the pseudo-classes or pseudo-elements in inline-css as David Thomas said. For more details see this answer by BoltClock about Pseudo-classes

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes are a member of the family of selectors, which don't occur in the attribute .....

We can also write use same for the pseudo-elements

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes and pseudo-elements the are a member of the family of selectors, which don't occur in the attribute so you cant style them inline.

how to find host name from IP with out login to the host

You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

$ host 192.168.0.10
server10 has address 192.168.0.10

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

How do I convert a calendar week into a date in Excel?

If you are looking for the opposite to get a date from a weeknumber i found a solution online and changed it slightly:

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
  ' get the date from a certain day in a certain week in a certain year
  fnDateFromWeek = DateSerial(iYear, 1, (iWeek * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
End Function

I took the formular from asap-utilities.com/ and changed

DateSerial(iYear, 1, ((iWeek - 1) * 7) 

to

DateSerial(iYear, 1, (iWeek * 7)

Update

It seems that at least for germany the formular works not as expected for the leap year 2016 so i changed it to this

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
' get the date from a certain day in a certain week in a certain year
  
    If isLeapYear(iYear) Then
        curDate = DateSerial(iYear, 1, ((iWeek) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    Else
        curDate = DateSerial(iYear, 1, ((iWeek - 1) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    End If
    fnDateFromWeek = curDate
End Function

Since 2016 hardcoded is not ideal you could check if a year is a leap year with this function

Function isLeapYear(iYear As Integer) As Boolean

    If (Month(DateSerial(iYear, 2, 29)) = 2) Then
        isLeapYear = True
    Else
        isLeapYear = False
    End If
    
End Function

For a non-leap-year DateSerial(iYear,2 ,29) returns 1st of march

This may still be wrong but my limited test gave the expected results:

Sub TestExample()
   Debug.Print Format(fnDateFromWeek(2014, 48, 2), "ddd dd mmm yyyy") ' mo 24 Nov 2014
   Debug.Print Format(fnDateFromWeek(2015, 11, 6), "ddd dd-mmm-yyyy") ' fr 13 Mar 2015
   Debug.Print Format(fnDateFromWeek(2016, 36, 2), "ddd dd-mmm-yyyy") ' Mo 05 Sep 2015
End Sub

Getting json body in aws Lambda via API gateway

I think there are a few things to understand when working with API Gateway integration with Lambda.

Lambda Integration vs Lambda Proxy Integration

There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.

As of September 2017, you no longer have to configure mappings to access the request body.

Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.

Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.

Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.

Words need to navigate the thinking. To get the terminologies straight.

  • Lambda Proxy Integration = Pass through
    Simply pass the HTTP request through to lambda.

  • Lambda Integration = Template transformation
    Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.

body is escaped string, not JSON

Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.

"body": "{\"foo\":\"bar\"}" 

If tested in a JSON formatter.

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

The document below is about response but it should apply to request.

The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.

For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.

The AWS documentation shows what to do.

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

How to open .mov format video in HTML video Tag?

My new answer is to use ffmpeg to transcode the .mov like ffmpeg -i sourceFile.mov destinationFile.mp4. Do same for the webm format.

OLD Answer: Here's what you do:

  1. Upload your video to Youtube.
  2. Install the "Complete YouTube Saver" plugin for Firefox
  3. Using the plugin in Firefox, download both the MP4 and WEBM formats and place them on your Web server
  4. Add the HTML5 Video element to your webpage per MDN's recommendation
<video controls>
  <source src="somevideo.webm" type="video/webm">
  <source src="somevideo.mp4" type="video/mp4">
  I'm sorry; your browser doesn't support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.
  <!-- You can embed a Flash player here, to play your mp4 video in older browsers -->
</video>
  1. Style the <video> element with CSS to suit your needs. For example Materializecss has a simple helper class to render the video nicely across device types.

What is the GAC in .NET?

Centralized DLL library.

How can I explicitly free memory in Python?

Others have posted some ways that you might be able to "coax" the Python interpreter into freeing the memory (or otherwise avoid having memory problems). Chances are you should try their ideas out first. However, I feel it important to give you a direct answer to your question.

There isn't really any way to directly tell Python to free memory. The fact of that matter is that if you want that low a level of control, you're going to have to write an extension in C or C++.

That said, there are some tools to help with this:

How to run Tensorflow on CPU

In some systems one have to specify:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"

BEFORE importing tensorflow.

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

How to create a inner border for a box in html?

  1. Use dashed border style for outline.
  2. Draw background-color with :before or :after pseudo element.

Note: This method will allow you to have maximum browser support.

Output Image:

Output Image

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
  border: 1px dashed #fff;_x000D_
  position: relative;_x000D_
  height: 160px;_x000D_
  width: 350px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
  position: absolute;_x000D_
  background: black;_x000D_
  content: '';_x000D_
  bottom: -10px;_x000D_
  right: -10px;_x000D_
  left: -10px;_x000D_
  top: -10px;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Try webfs, it's tiny and doesn't depend on having a platform like node.js or python installed.

How to ignore ansible SSH authenticity checking?

Use the parameter named as validate_certs to ignore the ssh validation

- ec2_ami:
    instance_id: i-0661fa8b45a7531a7
    wait: yes
    name: ansible
    validate_certs: false
    tags:
      Name: ansible
      Service: TestService

By doing this it ignores the ssh validation process

Simple excel find and replace for formulas

The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.

  1. In Excel, hit Control + ~ (OS X)
  2. Excel will convert all values to their formula version
  3. CMD + A (I usually do this twice) to select the entire sheet
  4. Copy all contents and paste them into Notepad++/Sublime Text 2
  5. Find / Replace your formula contents here
  6. Copy the contents and paste back into Excel, confirming any issues about cell size differences
  7. Control + ~ to switch back to values mode

How to use a FolderBrowserDialog from a WPF application

//add a reference to System.Windows.Forms.dll

public partial class MainWindow : Window, System.Windows.Forms.IWin32Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        var fbd = new FolderBrowserDialog();
        fbd.ShowDialog(this);
    }

    IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get
        {
            return ((HwndSource)PresentationSource.FromVisual(this)).Handle;
        }
    }
}

Adding a slide effect to bootstrap dropdown

I am using the code above but I have changed the delay effect by slideToggle.

It slides the dropdown on hover with animation.

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
    }, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
    });

Difference between FetchType LAZY and EAGER in Java Persistence API?

The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.

Eager fetch
 Eager fetch

Lazy fetch Lazy fetch

Javascript/Jquery Convert string to array

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]

//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2

Powershell command to hide user from exchange address lists

"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."

This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.

Python Script Uploading files via FTP

I just answered a similar question here IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp.

I have an FTP account from dotgeek.com so I am not sure if this will work for other FTP accounts.

#!/usr/bin/python

from fabric.api import run, env, sudo, put

env.user = 'username'
env.hosts = ['ftp_host_name',]     # such as ftp.google.com

def copy():
    # assuming i have wong_8066.zip in the same directory as this script
    put('wong_8066.zip', '/www/public/wong_8066.zip')

save the file as fabfile.py and run fab copy locally.

yeukhon@yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password: 
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip

Done.
Disconnecting from 1.ai... done.

Once again, if you don't want to input password all the time, just add

env.password = 'my_password'

Can I pass a JavaScript variable to another browser window?

The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain. If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).

How to call C++ function from C?

I would do it in the following way:

(If working with MSVC, ignore the GCC compilation commands)

Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.

The C++ code of class AAA - Pure C++, I don't modify it:

aaa.h

#ifndef AAA_H
#define AAA_H

class AAA {
    public:
        AAA();
        void sayHi(const char *name);
};

#endif

aaa.cpp

#include <iostream>

#include "aaa.h"

AAA::AAA() {
}

void AAA::sayHi(const char *name) {
    std::cout << "Hi " << name << std::endl;
}

Compiling this class as regularly done for C++. This code "does not know" that it is going to be used by C code. Using the command:

g++ -fpic -shared aaa.cpp -o libaaa.so

Now, also in C++, creating a C connector. Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:

aaa_c_connector.h

#ifndef AAA_C_CONNECTOR_H 
#define AAA_C_CONNECTOR_H 

#ifdef __cplusplus
extern "C" {
#endif

void AAA_sayHi(const char *name);

#ifdef __cplusplus
}
#endif


#endif

aaa_c_connector.cpp

#include <cstdlib>

#include "aaa_c_connector.h"
#include "aaa.h"

#ifdef __cplusplus
extern "C" {
#endif

// Inside this "extern C" block, I can implement functions in C++, which will externally 
//   appear as C functions (which means that the function IDs will be their names, unlike
//   the regular C++ behavior, which allows defining multiple functions with the same name
//   (overloading) and hence uses function signature hashing to enforce unique IDs),


static AAA *AAA_instance = NULL;

void lazyAAA() {
    if (AAA_instance == NULL) {
        AAA_instance = new AAA();
    }
}

void AAA_sayHi(const char *name) {
    lazyAAA();
    AAA_instance->sayHi(name);
}

#ifdef __cplusplus
}
#endif

Compiling it, again, using a regular C++ compilation command:

g++ -fpic -shared aaa_c_connector.cpp -L. -laaa -o libaaa_c_connector.so

Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:

main.c

#include "aaa_c_connector.h"

int main() {
    AAA_sayHi("David");
    AAA_sayHi("James");

    return 0;
}

Compiling it using a C compilation command:

gcc main.c -L. -laaa_c_connector -o c_aaa

I will need to set LD_LIBRARY_PATH to contain $PWD, and if I run the executable ./c_aaa, I will get the output I expect:

Hi David
Hi James

EDIT:

On some linux distributions, -laaa and -lstdc++ may also be required for the last compilation command. Thanks to @AlaaM. for the attention

clear table jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

As @Jthorpe alluded to, ComponentClass only allows either Component or PureComponent but not a FunctionComponent.

If you attempt to pass a FunctionComponent, typescript will throw an error similar to...

Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.

However, by using ComponentType rather than ComponentClass you allow for both cases. Per the react declaration file the type is defined as...

type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>

What is the best comment in source code you have ever encountered?

#ifdef TRACE
#undef TRACE     /* All your trace are belong to us. */
#endif
#define TRACE ....

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:

#!/usr/bin/python2.7

Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.

#!/usr/bin/env python is generally the better approach, but this helps with special cases.

Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.

Add new column in Pandas DataFrame Python

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

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

Import error No module named skimage

As per the official installation page of skimage (skimage Installation) : python-skimage package depends on matplotlib, scipy, pil, numpy and six.

So install them first using

sudo apt-get install python-matplotlib python-numpy python-pil python-scipy

Apparently skimage is a part of Cython which in turn is a superset of python and hence you need to install Cython to be able to use skimage.

sudo apt-get install build-essential cython

Now install skimage package using

sudo apt-get install python-skimage

This solved the Import error for me.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

How do I localize the jQuery UI Datepicker?

For those that still have problems, you have to download the language file your want from here:

https://github.com/jquery/jquery-ui/tree/master/ui/i18n

and then include it in your page like this for example(italian language):

<script type="text/javascript" src="/scripts/jquery.ui.datepicker-it.js"></script>

then use zilverdistel's code :D

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

How to avoid 'cannot read property of undefined' errors?

You can avoid getting an error by giving a default value before getting the property

_x000D_
_x000D_
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];

for (i=0; i<test.length; i++) {
    const obj = test[i]
    // No error, just undefined, which is ok
    console.log(((obj.a || {}).b || {}).c);
}
_x000D_
_x000D_
_x000D_

This works great with arrays too:

_x000D_
_x000D_
const entries = [{id: 1, name: 'Scarllet'}]
// Giving a default name when is empty
const name = (entries.find(v => v.id === 100) || []).name || 'no-name'
console.log(name)
_x000D_
_x000D_
_x000D_

Change tab bar tint color on iOS 7

In app delegate didFinishLaunchingWithOptions:

window.tintColor = [UIColor purpleColor];

sets the tint color globally for the app.

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

PHP send mail to multiple email addresses

You can just write multiple email address to whom you want to send and pass it as the first argument. Example:-

mail("[email protected], [email protected]","Subject","Message","From: [email protected]");

Property '...' has no initializer and is not definitely assigned in the constructor

If you want to initialize an object based on an interface you can initialize it empty with following statement.

myObj: IMyObject = {} as IMyObject;

CROSS JOIN vs INNER JOIN in SQL

While writing queries using inner joins the records will fetches from both tables if the condition satisfied on both tables, i.e. exact match of the common column in both tables.

While writing query using cross join the result is like cartesian product of the no of records in both tables. example if table1 contains 2 records and table2 contains 3 records then result of the query is 2*3 = 6 records.

So dont go for cross join until you need that.

How to call two methods on button's onclick method in HTML or JavaScript?

<input type="button" onclick="functionA();functionB();" />

function functionA()
{

}

function functionB()
{

}

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

Jquery click not working with ipad

I know this was asked a long time ago but I found an answer while searching for this exact question.

There are two solutions.

You can either set an empty onlick attribute on the html element:

<div class="clickElement" onclick=""></div>

Or you can add it in css by setting the pointer cursor:

.clickElement { cursor:pointer }

The problem is that on ipad, the first click on a non-anchor element registers as a hover. This is not really a bug, because it helps with sites that have hover-menus that haven't been tablet/mobile optimised. Setting the cursor or adding an empty onclick attribute tells the browser that the element is indeed a clickable area.

(via http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working)

C# getting its own class name

Use this

Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

This will return .

s1 = "TEST.form1"

for function name:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

will return

s1 = foo 

Note if you want to use this in exception use :

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}

What is the difference between MOV and LEA?

Lets understand this with a example.

mov eax, [ebx] and

lea eax, [ebx] Suppose value in ebx is 0x400000. Then mov will go to address 0x400000 and copy 4 byte of data present their to eax register.Whereas lea will copy the address 0x400000 into eax. So, after the execution of each instruction value of eax in each case will be (assuming at memory 0x400000 contain is 30).

eax = 30 (in case of mov) eax = 0x400000 (in case of lea) For definition mov copy the data from rm32 to destination (mov dest rm32) and lea(load effective address) will copy the address to destination (mov dest rm32).

How to bind to a PasswordBox in MVVM

I used an authentication check followed by a sub called by a mediator class to the View (which also implements an authentication check) to write the password to the data class.

It's not a perfect solution; however, it remedied my problem of not being able to move the password.

What does "xmlns" in XML mean?

You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.

For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns. For example, mash up friend of a friend with vCard, etc.

Importing CSV with line breaks in Excel 2007

Use Google Sheets and import the CSV file.

Then you can export that to use in Excel

Can't find SDK folder inside Android studio path, and SDK manager not opening

I had to open Android studio and go through the wizard. Android studio will install the SDK for you.

Private vs Protected - Visibility Good-Practice Concern

Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.

how to access parent window object using jquery?

or you can use another approach:

$( "#serverMsg", window.opener.document )

Java Reflection Performance

There is some overhead with reflection, but it's a lot smaller on modern VMs than it used to be.

If you're using reflection to create every simple object in your program then something is wrong. Using it occasionally, when you have good reason, shouldn't be a problem at all.

Bootstrap Dropdown menu is not working

For Bootstrap 4 you need an additional library. If you read your browser console, Bootstrap will actually print an error message telling you that you need it for drop down to work.

Error: Bootstrap dropdown require Popper.js (https://popper.js.org)

'uint32_t' does not name a type

Add the following in the base.mk file. The following 3rd line is important -include $(TOP)/defs.mk

CFLAGS=$(DEBUG) -Wall -W -Wwrite-strings 
CFLAGS_C=-Wmissing-prototypes
CFLAGS_CXX=-std=c++0x
LDFLAGS=
LIBS=

to avoid the #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

Can a variable number of arguments be passed to a function?

If I may, Skurmedel's code is for python 2; to adapt it to python 3, change iteritems to items and add parenthesis to print. That could prevent beginners like me to bump into: AttributeError: 'dict' object has no attribute 'iteritems' and search elsewhere (e.g. Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp()) why this is happening.

def myfunc(**kwargs):
for k,v in kwargs.items():
   print("%s = %s" % (k, v))

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

and:

def myfunc2(*args, **kwargs):
   for a in args:
       print(a)
   for k,v in kwargs.items():
       print("%s = %s" % (k, v))

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

REST API using POST instead of GET

If I understand the question correctly, he needs to perform a REST GET action, but wonders if it's OK to send in data via HTTP POST method.

As Scott had nicely laid out in his answer earlier, there are many good reasons to POST input data. IMHO it should be done this way, if quality of solution is the top priority.

A while back we created an REST API to authenticate users, taking username/password and returning an access token. The API is encrypted under TLS, but exposed to public internet. After evaluating different options, we chose HTTP POST for the REST method of "GET access token," because that's the only way to meet security standards.

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 can I compare two dates in PHP?

You can convert the dates into UNIX timestamps and compare the difference between them in seconds.

$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
   {
     echo "Enter a valid date";
   }

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

ng-repeat finish event

There is no need of creating a directive especially just to have a ng-repeat complete event.

ng-init does the magic for you.

  <div ng-repeat="thing in things" ng-init="$last && finished()">

the $last makes sure, that finished only gets fired, when the last element has been rendered to the DOM.

Do not forget to create $scope.finished event.

Happy Coding!!

EDIT: 23 Oct 2016

In case you also want to call the finished function when there is no item in the array then you may use the following workaround

<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>

Just add the above line on the top of the ng-repeat element. It will check if the array is not having any value and call the function accordingly.

E.g.

<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">

How to get store information in Magento?

To get information about the current store from anywhere in Magento, use:

<?php
$store = Mage::app()->getStore();

This will give you a Mage_Core_Model_Store object, which has some of the information you need:

<?php
$name = $store->getName();

As for your other question about line number, I'm not sure what you mean. If you mean that you want to know what line number in the code you are on (for error handling, for instance), try:

<?php
$line      = __LINE__;
$file      = __FILE__;
$class     = __CLASS__;
$method    = __METHOD__;
$namespace = __NAMESPACE__;

How to convert seconds to time format?

Maybe the simplest way is:

gmdate('H:i:s', $your_time_in_seconds);

How to force open links in Chrome not download them?

To open docs automatically in Chrome without them being saved;

  1. Go to the the three vertical dots on your top far right corner in Chrome.

  2. Scroll down to Settings and click.

  3. Scroll down to Show advance settings...

  4. Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.

  5. Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.

  6. When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

Equivalent of LIMIT for DB2

There are 2 solutions to paginate efficiently on a DB2 table :

1 - the technique using the function row_number() and the clause OVER which has been presented on another post ("SELECT row_number() OVER ( ORDER BY ... )"). On some big tables, I noticed sometimes a degradation of performances.

2 - the technique using a scrollable cursor. The implementation depends of the language used. That technique seems more robust on big tables.

I presented the 2 techniques implemented in PHP during a seminar next year. The slide is available on this link : http://gregphplab.com/serendipity/uploads/slides/DB2_PHP_Best_practices.pdf

Sorry but this document is only in french.

What is the difference between bottom-up and top-down?

Dynamic programming problems can be solved using either bottom-up or top-down approaches.

Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.

But you can also have bottom-up and top-down approaches using recursion as shown below.

Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.

int n = 5;
fibBottomUp(1, 1, 2, n);

private int fibBottomUp(int i, int j, int count, int n) {
    if (count > n) return 1;
    if (count == n) return i + j;
    return fibBottomUp(j, i + j, count + 1, n);
}

Top-Down: Start with the final condition and recursively get the result of its sub-problems.

int n = 5;
fibTopDown(n);

private int fibTopDown(int n) {
    if (n <= 1) return 1;
    return fibTopDown(n - 1) + fibTopDown(n - 2);
}

iPhone UILabel text soft shadow

This answer to this similar question provides code for drawing a blurred shadow behind a UILabel. The author uses CGContextSetShadow() to generate the shadow for the drawn text.

How to count lines in a document?

As others said wc -l is the best solution, but for future reference you can use Perl:

perl -lne 'END { print $. }'

$. contains line number and END block will execute at the end of script.

Getting the names of all files in a directory with PHP

Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}

How do I do base64 encoding on iOS?

As per your requirement i have created a sample demo using Swift 4 in which you can encode/decode string and image as per your requirement.

  • I have also added sample methods of relevant operations.

    //
    //  Base64VC.swift
    //  SOF_SortArrayOfCustomObject
    //
    //  Created by Test User on 09/01/18.
    //  Copyright © 2018 Test User. All rights reserved.
    //
    
    import UIKit
    import Foundation
    
    class Base64VC: NSObject {
    
        //----------------------------------------------------------------
        // MARK:-
        // MARK:- String to Base64 Encode Methods
        //----------------------------------------------------------------
    
        func sampleStringEncodingAndDecoding() {
            if let base64String = self.base64Encode(string: "TestString") {
                print("Base64 Encoded String: \n\(base64String)")
                if let originalString = self.base64Decode(base64String: base64String) {
                    print("Base64 Decoded String: \n\(originalString)")
                }
            }
        }
    
    
        //----------------------------------------------------------------
    
        func base64Encode(string: String) -> String? {
            if let stringData = string.data(using: .utf8) {
                return stringData.base64EncodedString()
            }
            return nil
        }
    
        //----------------------------------------------------------------
    
        func base64Decode(base64String: String) -> String? {
            if let base64Data = Data(base64Encoded: base64String) {
                return String(data: base64Data, encoding: .utf8)
            }
            return nil
        }
    
    
        //----------------------------------------------------------------
        // MARK:-
        // MARK:- Image to Base64 Encode  Methods
        //----------------------------------------------------------------
    
        func sampleImageEncodingAndDecoding() {
            if let base64ImageString = self.base64Encode(image: UIImage.init(named: "yourImageName")!) {
                print("Base64 Encoded Image: \n\(base64ImageString)")
                if let originaImage = self.base64Decode(base64ImageString: base64ImageString) {
                    print("originalImageData \n\(originaImage)")
                }
            }
        }
    
        //----------------------------------------------------------------
    
        func base64Encode(image: UIImage) -> String? {
            if let imageData = UIImagePNGRepresentation(image) {
                return imageData.base64EncodedString()
            }
            return nil
        }
    
        //----------------------------------------------------------------
    
        func base64Decode(base64ImageString: String) -> UIImage? {
            if let base64Data = Data(base64Encoded: base64ImageString) {
                return UIImage(data: base64Data)!
            }
            return nil
        }
    
    
    }
    

enable cors in .htaccess

This is what worked for me:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

How to remove line breaks from a file in Java?

Linebreaks are not the same under windows/linux/mac. You should use System.getProperties with the attribute line.separator.

Java LinkedHashMap get first or last entry

right, you have to manually enumerate keyset till the end of the linkedlist, then retrieve the entry by key and return this entry.

iterrows pandas get next rows value

Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.

A version of your first idea that would work would be:

row_iterator = df.iterrows()
_, last = row_iterator.next()  # take first item from row_iterator
for i, row in row_iterator:
    print(row['value'])
    print(last['value'])
    last = row

The second method could do something similar, to save one index into the dataframe:

last = df.irow(0)
for i in range(1, df.shape[0]):
    print(last)
    print(df.irow(i))
    last = df.irow(i)

When speed is critical you can always try both and time the code.

Add item to Listview control

Add items:

arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);

Retrieve items:

productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;

source code

How do you allow spaces to be entered using scanf?

People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).

Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.

Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Maximum name size + 1. */

#define MAX_NAME_SZ 256

int main(int argC, char *argV[]) {
    /* Allocate memory and check if okay. */

    char *name = malloc(MAX_NAME_SZ);
    if (name == NULL) {
        printf("No memory\n");
        return 1;
    }

    /* Ask user for name. */

    printf("What is your name? ");

    /* Get the name, with size limit. */

    fgets(name, MAX_NAME_SZ, stdin);

    /* Remove trailing newline, if there. */

    if ((strlen(name) > 0) && (name[strlen (name) - 1] == '\n'))
        name[strlen (name) - 1] = '\0';

    /* Say hello. */

    printf("Hello %s. Nice to meet you.\n", name);

    /* Free memory and exit. */

    free (name);
    return 0;
}

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

What is the color code for transparency in CSS?

In the CSS write:

.exampleclass {
    background:#000000;
    opacity: 10; /* you can always adjust this */
}

Trigger back-button functionality on button click in Android

You should use finish() when the user clicks on the button in order to go to the previous activity.

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    finish();
  }
});

Alternatively, if you really need to, you can try to trigger your own back key press:

this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

Execute both of these.

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How do I debug "Error: spawn ENOENT" on node.js?

In my case, I was getting this error thrown due to the necessary dependent system resources not being installed.

More specifically, I have a NodeJS app that is utilizing ImageMagick. Despite having the npm package installed, the core Linux ImageMagick was not installed. I did an apt-get to install ImageMagick and after that all worked great!

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

How do I create a folder in VB if it doesn't exist?

You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.

What is Type-safe?

Many answers here conflate type-safety with static-typing and dynamic-typing. A dynamically typed language (like smalltalk) can be type-safe as well.

A short answer: a language is considered type-safe if no operation leads to undefined behavior. Many consider the requirement of explicit type conversions necessary for a language to be strictly typed, as automatic conversions can sometimes leads to well defined but unexpected/unintuitive behaviors.

What is the easiest way to encrypt a password when I save it to the registry?

If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.

Otherwise use hashes SHA1 or MD5 like others have said here.

File to import not found or unreadable: compass

Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.

Before you can do @import 'compass';, you should:

Install Compass as a Ruby gem:

gem install compass

After that, you should use Compass's own command line tool to compile your SASS code:

cd path/to/your/project/
compass compile

Note that Compass reqiures a configuration file called config.rb. You should create it for Compass to work.

The minimal config.rb can be as simple as this:

css_dir =   "css"
sass_dir =  "sass"

And your SASS code should reside in sass/.

Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name> and then copy your SASS code inside it.

Note that if you want to use Compass extensions, you will have to:

  1. require them from the config.rb;
  2. import them from your SASS file.

More info here: http://compass-style.org/help/

What generates the "text file busy" message in Unix?

One of my experience:

I always change the default keyboard shortcut of Chrome through reverse engineering. After modification, I forgot to close Chrome and ran the following:

sudo cp chrome /opt/google/chrome/chrome
cp: cannot create regular file '/opt/google/chrome/chrome': Text file busy

Using strace, you can find the more details:

sudo strace cp ./chrome /opt/google/chrome/chrome 2>&1 |grep 'Text file busy'
open("/opt/google/chrome/chrome", O_WRONLY|O_TRUNC) = -1 ETXTBSY (Text file busy)

Vertically centering a div inside another div

This works for me. Width and hight of the outer div can be defined.

Here the code:

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  text-align: center;_x000D_
  width: 100%;_x000D_
  height: 150px; // Any height is allowed, also in %._x000D_
  background: gray;_x000D_
}_x000D_
_x000D_
.outer > div:first-child {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 100%;_x000D_
  -webkit-transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
  transform: translate(-50%, -50%);_x000D_
  background: red;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    Put here your text or div content!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to get element from HashMap by its position?

I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

public Object getElementAt(LinkedHashMap map, int index) {
    for (Map.Entry entry : map.entrySet()) {
        if (index-- == 0) {
            return entry.value();
        }
    }
    return null;
}

Saving to CSV in Excel loses regional date format

You need to do a lot more work than 1. click export 2. Open file.

I think that when the Excel CSV documentation talks about OS and regional settings being interpreted, that means that Excel will do that when it opens the file (which is in their "special" csv format). See this article, "Excel formatting and features are not transferred to other file formats"

Also, Excel is actually storing a number, and converting to a date string only for display. When it exports to CSV, it is converting it to a different date string. If you want that date string to be non-default, you will need to convert your Excel cells to strings before performing your export.

Alternately, you could convert your dates to the number value that Excel is saving. Since that is a time code, it actually will obey OS and regional settings, assuming you import it properly. Notepad will only show you the 10-digit number, though.

Convert hex string to int

This is the right answer:

myPassedColor = "#ffff8c85" int colorInt = Color.parseColor(myPassedColor)

jQuery select element in parent window

Use the context-parameter

$("#testdiv",parent.document)

But if you really use a popup, you need to access opener instead of parent

$("#testdiv",opener.document)

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

resource error in android studio after update: No Resource Found

if you have :

/Users/james/Development/AndroidProjects/myapp/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.0/res/values-v23/values-v23.xml
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.

error , you must change your appcompat , buildtools , sdk to 23 but , if you don't like to change it and must be in 22 do this :

  • compile 23
  • target 22

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

I also had this error, but could only fix it through the suggestion here.

To summarize, use:

127.0.0.1

Instead of:

localhost

The reason is that "localhost" is a special name for the MySQL driver making it use the UNIX socket to connect to MySQL instead of the a TCP socket.

What's the meaning of System.out.println in Java?

It is quite simple to understand the question, but to answer it we need to dig deeper in to Java native code.

  • System is static class and cannot be instantiated
  • out is a reference variable defined in System
  • println() is the method used to print on standard output.

A brief and nice explanation is always welcome on this as we can learn much from this single line of statement itself!

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

Tab space instead of multiple non-breaking spaces ("nbsp")?

I have used a span with in line styling. I have had to do this as I as processing a string of plain text and need to replace the \t with 4 spaces (appx). I couldn't use &nbsp; as further on in the process they were being interpreted so that the final mark up had non-content spaces.

HTML:

<span style="padding: 0 40px">&nbsp;</span>

I used it in a php function like this:

$message = preg_replace('/\t/', '<span style="padding: 0 40px">&nbsp;</span>', $message);

Node.js: printing to console without a trailing newline?

util.print can be used also. Read: http://nodejs.org/api/util.html#util_util_print

util.print([...])# A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

An example:

// get total length
var len = parseInt(response.headers['content-length'], 10);
var cur = 0;

// handle the response
response.on('data', function(chunk) {
  cur += chunk.length;
  util.print("Downloading " + (100.0 * cur / len).toFixed(2) + "% " + cur + " bytes\r");
});

How can I control Chromedriver open window size?

Ruby version:

caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args"=> ["--window-size=1280,960"]})

url = "http://localhost:9515"  # if you are using local chrome or url = Browserstack/ saucelabs hub url if you are using cloud service providers.

 Selenium::WebDriver.for(:remote, :url => url, :desired_capabilities => caps)

resize chrome is buggy in latest chromedrivers , it fails intermittanly with this failure message.

                        unknown error: cannot get automation extension
from timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -65.294
  (Session info: chrome=56.0.2924.76)
  (Driver info: chromedriver=2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)

And resizeTo via javascript also not supported for chrome started via selenium webdriver. So the last option was using command line switches.

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

Create JSON object dynamically via JavaScript (Without concate strings)

JavaScript

var myObj = {
   id: "c001",
   name: "Hello Test"
}

Result(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}

How to search a specific value in all tables (PostgreSQL)?

And if someone think it could help. Here is @Daniel Vérité's function, with another param that accept names of columns that can be used in search. This way it decrease the time of processing. At least in my test it reduced a lot.

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_columns name[] default '{}',
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{public}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND (c.column_name=ANY(haystack_columns) OR haystack_columns='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
    ) INTO rowctid;
    IF rowctid is not null THEN
      RETURN NEXT;
    END IF;
 END LOOP;
END;
$$ language plpgsql;

Bellow is an example of usage of the search_function created above.

SELECT * FROM search_columns('86192700'
    , array(SELECT DISTINCT a.column_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public'
    )

    , array(SELECT b.table_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public')
);

how to set font size based on container size?

If you want to set the font-size as a percentage of the viewport width, use the vwunit:

#mydiv { font-size: 5vw; }

The other alternative is to use SVG embedded in the HTML. It will just be a few lines. The font-size attribute to the text element will be interpreted as "user units", for instance those the viewport is defined in terms of. So if you define viewport as 0 0 100 100, then a font-size of 1 will be one one-hundredth of the size of the svg element.

And no, there is no way to do this in CSS using calculations. The problem is that percentages used for font-size, including percentages inside a calculation, are interpreted in terms of the inherited font size, not the size of the container. CSS could use a unit called bw (box-width) for this purpose, so you could say div { font-size: 5bw; }, but I've never heard this proposed.

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

How to run SQL script in MySQL?

Very likely, you just need to change the slash/blackslash: from

 \home\sivakumar\Desktop\test.sql

to

 /home/sivakumar/Desktop/test.sql

So the command would be:

source /home/sivakumar/Desktop/test.sql

What is the equivalent of the C# 'var' keyword in Java?

In general you can use Object class for any type, but you have do type casting later!

eg:-

Object object = 12;
    Object object1 = "Aditya";
    Object object2 = 12.12;

    System.out.println(Integer.parseInt(object.toString()) + 2);

    System.out.println(object1.toString() + " Kumar");
    System.out.println(Double.parseDouble(object2.toString()) + 2.12);

Executing <script> injected by innerHTML after AJAX call

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

#define macro for debug printing in C?

According to http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html, there should be a ## before __VA_ARGS__.

Otherwise, a macro #define dbg_print(format, ...) printf(format, __VA_ARGS__) will not compile the following example: dbg_print("hello world");.

Show two digits after decimal point in c++

cout << fixed << setprecision(2) << total;

setprecision specifies the minimum precision. So

cout << setprecision (2) << 1.2; 

will print 1.2

fixed says that there will be a fixed number of decimal digits after the decimal point

cout << setprecision (2) << fixed << 1.2;

will print 1.20

Get element of JS object with an index

I know it's a late answer, but I think this is what OP asked for.

myobj[Object.keys(myobj)[0]];

If input value is blank, assign a value of "empty" with Javascript

This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

How can I put CSS and HTML code in the same file?

<html>
<head>
    <style type="text/css">
    .title {
        color: blue;
        text-decoration: bold;
        text-size: 1em;
    }

    .author {
        color: gray;
    }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

On a side note, it would have been much easier to just do this.

Is there a way to create multiline comments in Python?

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

Getting mouse position in c#

If you need to get current position in form's area(got experimentally), try:

Console.WriteLine("Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

Although, 8 and 30 integers were found by experimenting.

Would be awesome if someone could explain why exactly these numbers ^.


Also, there's another variant(considering code is in Form's CodeBehind):

Point cp = PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

For Angular developer:

When I need to use agm-direction package, the console shows that "you have to have a credential key first, please go to here", but I already have one so I can view the google map.

Aftet a while, I found the only thing you need to do is go to Direction API and enable it, then wait for about 10s, you are good to go. The whole thing sums up that the console log didn't tell what API is needed exactly.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Install opencv for Python 3.3

I know this is an old thread, but just in case anyone is looking, here is how I got it working on El Capitan:

brew install opencv3 --with-python3

and wait a while for it to finish.

Then run the following as necessary:

brew unlink opencv

Then run the following as the final step:

brew ln opencv3 --force

Now you should be able to run import cv2 no problem in a python 3.x script.

When to use self over $this?

self refers current class(in which it is called),

$this refers current object. You can use static instead of self. See the example:

    class ParentClass {
            function test() {
                    self::which();  // output 'parent'
                    $this->which(); // output 'child'
            }

            function which() {
                    echo 'parent';
            }
    }

    class ChildClass extends ParentClass {
            function which() {
                    echo 'child';
            }
    }

    $obj = new ChildClass();
    $obj->test();

Output: parent child

Android, How to read QR code in my application?

Easy QR Code Library

A simple Android Easy QR Code Library. It is very easy to use, to use this library follow these steps.

For Gradle:

Step 1. Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency:

dependencies {
        compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}

For Maven:

Step 1. Add the JitPack repository to your build file:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Step 2. Add the dependency:

<dependency>
    <groupId>com.github.mrasif</groupId>
    <artifactId>easyqrlibrary</artifactId>
    <version>v1.0.0</version>
</dependency>

For SBT:

Step 1. Add the JitPack repository to your build.sbt file:

resolvers += "jitpack" at "https://jitpack.io"

Step 2. Add the dependency:

libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"

For Leiningen:

Step 1. Add it in your project.clj at the end of repositories:

:repositories [["jitpack" "https://jitpack.io"]]

Step 2. Add the dependency:

:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]

Add this in your layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="No QR Data"/>
    <Button
        android:id="@+id/btnQRScan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="QR Scan"/>

</LinearLayout>

Add this in your activity java files:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView tvData;
    Button btnQRScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvData=findViewById(R.id.tvData);
        btnQRScan=findViewById(R.id.btnQRScan);

        btnQRScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btnQRScan: {
                Intent intent=new Intent(MainActivity.this, QRScanner.class);
                startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
            } break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case EasyQR.QR_SCANNER_REQUEST: {
                if (resultCode==RESULT_OK){
                    tvData.setText(data.getStringExtra(EasyQR.DATA));
                }
            } break;
        }
    }
}

For customized scanner screen just add these lines when you start the scanner Activity.

Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);

You are done. Ref. Link: https://mrasif.github.io/easyqrlibrary

How to change checkbox's border style in CSS?

Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/

Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/

I have tested this on the following browsers:

  • FireFox (41.0.2) (42)
  • Google Chrome (46.0.2490.80 m)
  • Opera (33.0.1990.43)
  • Internet Explorer (11.0.10240.16431 [Update Versions: 11.0.22])
  • Microsoft Edge (20.10240.16384.0)
  • Safari Mobile iPhone iOS9 (601.1.46)

_x000D_
_x000D_
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
 _x000D_
label *,_x000D_
label *_x000D_
{_x000D_
    cursor: pointer;_x000D_
}_x000D_
 _x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
    opacity: 0;_x000D_
    position: absolute;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
    font: normal 11px/14px Arial, Sans-serif;_x000D_
    color: #333;_x000D_
}_x000D_
 _x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
    -moz-box-shadow: 0 0 2px #ccc;_x000D_
    -webkit-box-shadow: 0 0 2px #ccc;_x000D_
    box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
 _x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
    color: #000;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    content: "";_x000D_
    width: 12px;_x000D_
    height: 12px;_x000D_
    margin: 0 4px 0 0;_x000D_
    border: solid 1px #a8a8a8;_x000D_
    line-height: 14px;_x000D_
    text-align: center;_x000D_
     _x000D_
    -moz-border-radius: 100%;_x000D_
    -webkit-border-radius: 100%;_x000D_
    border-radius: 100%;_x000D_
     _x000D_
    background: #f6f6f6;_x000D_
    background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    color: #666;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
    cursor: default;_x000D_
     _x000D_
    -moz-opacity: .4;_x000D_
    -webkit-opacity: .4;_x000D_
    opacity: .4;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    -moz-border-radius: 2px;_x000D_
    -webkit-border-radius: 2px;_x000D_
    border-radius: 2px;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
    content: "\2022";_x000D_
    font-size: 30px;_x000D_
    margin-top: -1px;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    content: "\2714";_x000D_
    font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
    border: solid 1px blue;_x000D_
    background: #B2DBFF;_x000D_
    background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
    color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
    border: solid 1px red;_x000D_
    background: #FF9593;_x000D_
    background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
    color: darkred;_x000D_
}
_x000D_
 <label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-02"  class="blue" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-03"  class="red" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
_x000D_
_x000D_

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

How to use a variable for a key in a JavaScript object literal?

ES5 implementation to assign keys is below:

var obj = Object.create(null),
    objArgs = (
      (objArgs = {}),
      (objArgs.someKey = {
        value: 'someValue'
      }), objArgs);

Object.defineProperties(obj, objArgs);

I've attached a snippet I used to convert to bare object.

_x000D_
_x000D_
var obj = {_x000D_
  'key1': 'value1',_x000D_
  'key2': 'value2',_x000D_
  'key3': [_x000D_
    'value3',_x000D_
    'value4',_x000D_
  ],_x000D_
  'key4': {_x000D_
    'key5': 'value5'_x000D_
  }_x000D_
}_x000D_
_x000D_
var bareObj = function(obj) {_x000D_
_x000D_
  var objArgs,_x000D_
    bareObj = Object.create(null);_x000D_
_x000D_
  Object.entries(obj).forEach(function([key, value]) {_x000D_
_x000D_
    var objArgs = (_x000D_
      (objArgs = {}),_x000D_
      (objArgs[key] = {_x000D_
        value: value_x000D_
      }), objArgs);_x000D_
_x000D_
    Object.defineProperties(bareObj, objArgs);_x000D_
_x000D_
  });_x000D_
_x000D_
  return {_x000D_
    input: obj,_x000D_
    output: bareObj_x000D_
  };_x000D_
_x000D_
}(obj);_x000D_
_x000D_
if (!Object.entries) {_x000D_
  Object.entries = function(obj){_x000D_
    var arr = [];_x000D_
    Object.keys(obj).forEach(function(key){_x000D_
      arr.push([key, obj[key]]);_x000D_
    });_x000D_
    return arr;_x000D_
  }_x000D_
}_x000D_
_x000D_
console(bareObj);
_x000D_
_x000D_
_x000D_

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

Find records with a date field in the last 24 hours

SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);

sorting a List of Map<String, String>

You should implement a Comparator<Map<String, String>> which basically extracts the "name" value from the two maps it's passed, and compares them.

Then use Collections.sort(list, comparator).

Are you sure a Map<String, String> is really the best element type for your list though? Perhaps you should have another class which contains a Map<String, String> but also has a getName() method?

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

Multiple Java versions running concurrently under Windows

Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like

java ...

This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable JAVA6HOME with the value C:\java\java6 (if Java 6 is installed in this directory) and change the batch file calling

%JAVA6HOME%\bin\java ...

How to setup Main class in manifest file in jar produced by NetBeans project

The real problem is how Netbeans JARs its projects. The "Class-Path:" in the Manifest file is unnecessary when actually publishing your program for others to use. If you have an external Library added in Netbeans it acts as a package. I suggest you use a program like WINRAR to view the files within the jar and add your libraries as packages directly into the jar file.

How the inside of the jar file should look:

MyProject.jar

    Manifest.MF
         Main-Class: mainClassFolder.Mainclass

    mainClassFolder
         Mainclass.class

    packageFolder
         IamUselessWithoutMain.class

How to move or copy files listed by 'find' command in unix?

This is the best way for me:

cat filename.tsv  |
    while read FILENAME
    do
    sudo find /PATH_FROM/  -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
    done

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

C++ pass an array by reference

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

automatically execute an Excel macro on a cell change

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub

Hope this helps...

Update Eclipse with Android development tools v. 23

Download the ADT v23 plugin from Google and install it as local archive from the downloaded zip file in Eclipse.

http://developer.android.com/sdk/installing/installing-adt.html#Download

Leading zeros for Int in Swift

Unlike the other answers that use a formatter, you can also just add an "0" text in front of each number inside of the loop, like this:

for myInt in 1...3 {
    println("0" + "\(myInt)")
}

But formatter is often better when you have to add suppose a designated amount of 0s for each seperate number. If you only need to add one 0, though, then it's really just your pick.

How to convert an array into an object using stdClass()

To convert array to object using stdClass just add (object) to array u declare.

EX:

echo $array['value'];
echo $object->value;

to convert object to array

$obj = (object)$array;

to convert array to object

$arr = (array)$object

with these methods you can swap between array and object very easily.


Another method is to use json

$object = json_decode(json_encode($array), FALSE);

But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

How can I determine the URL that a local Git repository was originally cloned from?

With Git 2.7 (release January 5th, 2015), you have a more coherent solution using git remote:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015):

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured URLs.

get-url:

Retrieves the URLs for a remote.
Configurations for insteadOf and pushInsteadOf are expanded here.
By default, only the first URL is listed.

  • With '--push', push URLs are queried rather than fetch URLs.
  • With '--all', all URLs for the remote will be listed.

Before git 2.7, you had:

 git config --get remote.[REMOTE].url
 git ls-remote --get-url [REMOTE]
 git remote show [REMOTE]

What are metaclasses in Python?

Python 3 update

There are (at this point) two key methods in a metaclass:

  • __prepare__, and
  • __new__

__prepare__ lets you supply a custom mapping (such as an OrderedDict) to be used as the namespace while the class is being created. You must return an instance of whatever namespace you choose. If you don't implement __prepare__ a normal dict is used.

__new__ is responsible for the actual creation/modification of the final class.

A bare-bones, do-nothing-extra metaclass would like:

class Meta(type):

    def __prepare__(metaclass, cls, bases):
        return dict()

    def __new__(metacls, cls, bases, clsdict):
        return super().__new__(metacls, cls, bases, clsdict)

A simple example:

Say you want some simple validation code to run on your attributes -- like it must always be an int or a str. Without a metaclass, your class would look something like:

class Person:
    weight = ValidateType('weight', int)
    age = ValidateType('age', int)
    name = ValidateType('name', str)

As you can see, you have to repeat the name of the attribute twice. This makes typos possible along with irritating bugs.

A simple metaclass can address that problem:

class Person(metaclass=Validator):
    weight = ValidateType(int)
    age = ValidateType(int)
    name = ValidateType(str)

This is what the metaclass would look like (not using __prepare__ since it is not needed):

class Validator(type):
    def __new__(metacls, cls, bases, clsdict):
        # search clsdict looking for ValidateType descriptors
        for name, attr in clsdict.items():
            if isinstance(attr, ValidateType):
                attr.name = name
                attr.attr = '_' + name
        # create final class and return it
        return super().__new__(metacls, cls, bases, clsdict)

A sample run of:

p = Person()
p.weight = 9
print(p.weight)
p.weight = '9'

produces:

9
Traceback (most recent call last):
  File "simple_meta.py", line 36, in <module>
    p.weight = '9'
  File "simple_meta.py", line 24, in __set__
    (self.name, self.type, value))
TypeError: weight must be of type(s) <class 'int'> (got '9')

Note: This example is simple enough it could have also been accomplished with a class decorator, but presumably an actual metaclass would be doing much more.

The 'ValidateType' class for reference:

class ValidateType:
    def __init__(self, type):
        self.name = None  # will be set by metaclass
        self.attr = None  # will be set by metaclass
        self.type = type
    def __get__(self, inst, cls):
        if inst is None:
            return self
        else:
            return inst.__dict__[self.attr]
    def __set__(self, inst, value):
        if not isinstance(value, self.type):
            raise TypeError('%s must be of type(s) %s (got %r)' %
                    (self.name, self.type, value))
        else:
            inst.__dict__[self.attr] = value

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

How to do something to each file in a directory with a batch script

Another way:

for %f in (*.mp4) do call ffmpeg -i "%~f" -vcodec copy -acodec copy "%~nf.avi"

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

Bootstrap4 adding scrollbar to div

Yes, It is possible, Just add a class like anyclass and give some CSS style. Live

.anyClass {
  height:150px;
  overflow-y: scroll;
}

_x000D_
_x000D_
.anyClass {_x000D_
  height:150px;_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
  <ul class="nav nav-pills nav-stacked anyClass">_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link active" href="#">Active</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link disabled" href="#">Disabled</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript getElementById based on a partial string

querySelectorAll with modern enumeration

polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);

function callback(element, iterator) {
    console.log(iterator, element.id);
}

The first line selects all elements which id starts with the string poll-. The second line evokes the enumeration and a callback function.

Correct use of transactions in SQL Server

Easy approach:

CREATE TABLE T
(
    C [nvarchar](100) NOT NULL UNIQUE,
);

SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
    INSERT INTO T VALUES ('A');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;

Responsive font size in CSS

Here is something that worked for me. I only tested it on an iPhone.

Whether you have h1, h2, or p tags put this around your text:

<h1><font size="5">The Text you want to make responsive</font></h1>

This renders a 22pt text on a desktop and it is still readable on the iPhone.

<font size="5"></font>

Apply formula to the entire column

Just so I don't lose my answer that works:

  1. Select the cell to copy
  2. Select the final cell in the column
  3. Press CTRL+D

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

Getting a list item by index

you can use index to access list elements

List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list

Android: I am unable to have ViewPager WRAP_CONTENT

Another solution is to update ViewPager height according to the current page height in its PagerAdapter. Assuming that your are creating your ViewPager pages this way:

@Override
public Object instantiateItem(ViewGroup container, int position) {
  PageInfo item = mPages.get(position);
  item.mImageView = new CustomImageView(container.getContext());
  item.mImageView.setImageDrawable(item.mDrawable);
  container.addView(item.mImageView, 0);
  return item;
}

Where mPages is internal list of PageInfo structures dynamically added to the PagerAdapter and CustomImageView is just regular ImageView with overriden onMeasure() method that sets its height according to specified width and keeps image aspect ratio.

You can force ViewPager height in setPrimaryItem() method:

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
  super.setPrimaryItem(container, position, object);

  PageInfo item = (PageInfo) object;
  ViewPager pager = (ViewPager) container;
  int width = item.mImageView.getMeasuredWidth();
  int height = item.mImageView.getMeasuredHeight();
  pager.setLayoutParams(new FrameLayout.LayoutParams(width, Math.max(height, 1)));
}

Note the Math.max(height, 1). That fixes annoying bug that ViewPager does not update displayed page (shows it blank), when previous page has zero height (i. e. null drawable in the CustomImageView), each odd swipe back and forth between two pages.

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

C# looping through an array

This should work:

//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
    var a = theData[i];
    var b = theData[i + 1];
    var c = theData[i + 2];
}

I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.

How to convert FileInputStream to InputStream?

InputStream is;

try {
    is = new FileInputStream("c://filename");

    is.close(); 
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return is;

PHP - define constant inside a class

This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR . PHP_EOL;
echo Foo::BAZ . PHP_EOL;
?>

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

More info here

Tensorflow import error: No module named 'tensorflow'

The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.

create a new separate environment in Anaconda dedicated to TensorFlow as follows:

conda create -n newenvt anaconda python=python_version

replace python_version by your python version

activate the new environment as follows:

activate newenvt

Then install tensorflow into the new environment (newenvt) as follows:

conda install tensorflow

Now you can check it by issuing the following python code and it will work fine.

import tensorflow

Android - How to achieve setOnClickListener in Kotlin?

You use like that onclickListener in kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {  
...
}

open failed: EACCES (Permission denied)

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

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

ImportError: DLL load failed: The specified module could not be found

Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.

What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.

ImportError: numpy.core.multiarray failed to import

uninstall existing numpy and install opencv-python will resolve the issue

How can I create a two dimensional array in JavaScript?

How to create an empty two dimensional array (one-line)

Array.from(Array(2), () => new Array(4))

2 and 4 being first and second dimensions respectively.

We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.

Array.from(arrayLike[, mapFn[, thisArg]])

_x000D_
_x000D_
var arr = Array.from(Array(2), () => new Array(4));_x000D_
arr[0][0] = 'foo';_x000D_
console.info(arr);
_x000D_
_x000D_
_x000D_

The same trick can be used to Create a JavaScript array containing 1...N


Alternatively (but more inefficient 12% with n = 10,000)

Array(2).fill(null).map(() => Array(4))

The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.

_x000D_
_x000D_
var arr = Array(2).fill(null).map(() => Array(4));_x000D_
arr[0][0] = 'foo';_x000D_
console.info(arr);
_x000D_
_x000D_
_x000D_


Follow up

Here's a method that appears correct, but has issues.

 Array(2).fill(Array(4)); // BAD! Rows are copied by reference

While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.

_x000D_
_x000D_
var arr = Array(2).fill(Array(4));_x000D_
arr[0][0] = 'foo';_x000D_
console.info(arr);_x000D_
console.info(arr[0][0], arr[1][0]);
_x000D_
_x000D_
_x000D_

Get JSF managed bean by name in any Servlet related class

You can get the managed bean by passing the name:

public static Object getBean(String beanName){
    Object bean = null;
    FacesContext fc = FacesContext.getCurrentInstance();
    if(fc!=null){
         ELContext elContext = fc.getELContext();
         bean = elContext.getELResolver().getValue(elContext, null, beanName);
    }

    return bean;
}

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

How to select the row with the maximum value in each group

A dplyr solution:

library(dplyr)
ID <- c(1,1,1,2,2,2,2,3,3)
Value <- c(2,3,5,2,5,8,17,3,5)
Event <- c(1,1,2,1,2,1,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)

group %>%
    group_by(Subject) %>%
    summarize(max.pt = max(pt))

This yields the following data frame:

  Subject max.pt
1       1      5
2       2     17
3       3      5

How to set javascript variables using MVC4 with Razor

You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side and client-side. Try this:

@{
    int proID = 123; 
    int nonProID = 456;
}

<script>

    var nonID = @nonProID;
    var proID = @proID;
    window.nonID = @nonProID;
    window.proID = @proID;

</script>

The output should be like this:

enter image description here

Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.

White spaces are required between publicId and systemId

I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:

String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);

and Java threw:

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.

Turns out that the URL string used to construct the service was missing the "?wsdl" at the end. For instance:

Bad:

http://www.host.org/service/Customer

Good:

http://www.host.org/service/Customer?wsdl

Entity Framework Code First - two Foreign Keys from same table

You can try this too:

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

In my case, this simple modification solve the problem.

How can I get the baseurl of site?

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]

Clear contents of cells in VBA using column reference

The issue is not with the with statement, it is on the Range function, it doesn't accept the absolute cell value.. it should be like Range("A4:B100").. you can refer the following thread for reference..

following code should work.. Convert cells(1,1) into "A1" and vice versa

LastColData = Sheets(WSNAME).Range("A4").End(xlToRight).Column
            LastRowData = Sheets(WSNAME).Range("A4").End(xlDown).Row
            Rng = "A4:" & Sheets(WSNAME).Cells(LastRowData, LastColData).Address(RowAbsolute:=False, ColumnAbsolute:=False)

 Worksheets(WSNAME).Range(Rng).ClearContents

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Docker has a default entrypoint which is /bin/sh -c but does not have a default command.

When you run docker like this: docker run -i -t ubuntu bash the entrypoint is the default /bin/sh -c, the image is ubuntu and the command is bash.

The command is run via the entrypoint. i.e., the actual thing that gets executed is /bin/sh -c bash. This allowed Docker to implement RUN quickly by relying on the shell's parser.

Later on, people asked to be able to customize this, so ENTRYPOINT and --entrypoint were introduced.

Everything after ubuntu in the example above is the command and is passed to the entrypoint. When using the CMD instruction, it is exactly as if you were doing docker run -i -t ubuntu <cmd>. <cmd> will be the parameter of the entrypoint.

You will also get the same result if you instead type this command docker run -i -t ubuntu. You will still start a bash shell in the container because of the ubuntu Dockerfile specified a default CMD: CMD ["bash"]

As everything is passed to the entrypoint, you can have a very nice behavior from your images. @Jiri example is good, it shows how to use an image as a "binary". When using ["/bin/cat"] as entrypoint and then doing docker run img /etc/passwd, you get it, /etc/passwd is the command and is passed to the entrypoint so the end result execution is simply /bin/cat /etc/passwd.

Another example would be to have any cli as entrypoint. For instance, if you have a redis image, instead of running docker run redisimg redis -H something -u toto get key, you can simply have ENTRYPOINT ["redis", "-H", "something", "-u", "toto"] and then run like this for the same result: docker run redisimg get key.

Using SSH keys inside docker container

Late to the party admittedly, how about this which will make your host operating system keys available to root inside the container, on the fly:

docker run -v ~/.ssh:/mnt -it my_image /bin/bash -c "ln -s /mnt /root/.ssh; ssh [email protected]"

I'm not in favour of using Dockerfile to install keys since iterations of your container may leave private keys behind.

Scroll event listener javascript

Is there a js listener for when a user scrolls in a certain textbox that can be used?

DOM L3 UI Events spec gave the initial definition but is considered obsolete.

To add a single handler you can do:

  let isTicking;
  const debounce = (callback, evt) => {
    if (isTicking) return;
    requestAnimationFrame(() => {
      callback(evt);
      isTicking = false;
    });
    isTicking = true;
  };
  const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
  document.defaultView.onscroll = evt => debounce(handleScroll, evt);

For multiple handlers or, if preferable for style reasons, you may use addEventListener as opposed to assigning your handler to onscroll as shown above.

If using something like _.debounce from lodash you could probably get away with:

const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));

Review browser compatibility and be sure to test on some actual devices before calling it done.

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Restart intelliJ and import project as maven if it is a maven project

How to get setuptools and easy_install?

For linux versions(ubuntu/linux mint), you can always type this in the command prompt:

sudo apt-get install python-setuptools

this will automatically install eas-_install

How to get the employees with their managers

This is a classic self-join, try the following:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno

And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno(+)

Or in ANSI SQL syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e
    LEFT OUTER JOIN emp m
        ON e.mgr = m.empno

Event binding on dynamically created elements?

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)

How do I write to the console from a Laravel Controller?

I haven't tried this myself, but a quick dig through the library suggests you can do this:

$output = new Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln("<info>my message</info>");

I couldn't find a shortcut for this, so you would probably want to create a facade to avoid duplication.

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

Preventing twitter bootstrap carousel from auto sliding on page load

I think maybe you should go to check the official instruction about carousel, for me, i have not found answer above, because of multiple versions of bootstrap, I'm using b4-alpha and i want the autoplay effect stop.

$(document).ready({
    pause:true,
    interval:false
});

this script does not make any effect while mouse leave that page, exactly carousel area. go to official definition and find those :

enter image description here

So you will find why.if carousel page onmouseover event triggered, page will pause, while mouse out of that page, it'll resume again.

So, if you want a page stop forever and rotate manually, you can just set data-interval='false'.

Truncate to three decimals in Python

I suggest next solution:

def my_floor(num, precision):
   return f'{num:.{precision+1}f}'[:-1]

my_floor(1.026456,2) # 1.02

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)