Programs & Examples On #Actionlistener

Java ActionListener is an invisible GUI object that gets its method called when the user performs a certain action. Common actions include pressing the push button, toggling the toggle button, checking the checkbox, selecting an item in combo box and the like.

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

How to add action listener that listens to multiple buttons

The first problem is that button1 is a local variable of the main method, so the actionPerformed method doesn't have access to it.

The second problem is that the ActionListener interface is implemented by the class calc, but no instance of this class is created in the main method.

The usual way to do what you want is to create an instance of calc and make button1 a field of the calc class.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Differences between action and actionListener

ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.

If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.

Here is a link that describes the relationship:

http://www.java-samples.com/showtutorial.php?tutorialid=605

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

How to Disable GUI Button in Java

Is there a reason you are not doing something like:

public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    public IPGUI() 
    {
        ...

        btnConvertDocuments = new JButton("1. Convert Documents");

        ...

        btnExtractImages = new JButton("2. Extract Images");

        ...

        //etc.
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled( false );
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled( false );
        }

        // etc.
    }    
}

The if statement with your disabling code won't get called unless you keep calling the IPGUI constructor.

How to delete all data from solr and hbase

If you want to clean up Solr index -

you can fire http url -

http://host:port/solr/[core name]/update?stream.body=<delete><query>*:*</query></delete>&commit=true

(replace [core name] with the name of the core you want to delete from). Or use this if posting data xml data:

<delete><query>*:*</query></delete>

Be sure you use commit=true to commit the changes

Don't have much idea with clearing hbase data though.

How do I get total physical memory size using PowerShell without WMI?

If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.

(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()

Checking for Undefined In React

You can try adding a question mark as below. This worked for me.

 componentWillReceiveProps(nextProps) {
    this.setState({
        title: nextProps?.blog?.title,
        body: nextProps?.blog?.content
     })
    }

How to add a custom Ribbon tab using VBA?

Another approach to this would be to download Jan Karel Pieterse's free Open XML class module from this page: Editing elements in an OpenXML file using VBA

With this added to your VBA project, you can unzip the Excel file, use VBA to modify the XML, then use the class to rezip the files.

Is there a typical state machine implementation pattern?

This article is a good one for the state pattern (though it is C++, not specifically C).

If you can put your hands on the book "Head First Design Patterns", the explanation and example are very clear.

Connecting to remote URL which requires authentication using Java

You can also use the following, which does not require using external packages:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Why is the Android emulator so slow? How can we speed up the Android emulator?

I noticed that the my emulator (Eclipse plugin) was significantly slowed by my Nvidia graphics card anti-aliasing settings. Removing 2x anti aliasing from the graphics menu and changing it to application controlled made it more responsive. It is still slow, but better than it used to be.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Download a single folder or directory from a GitHub repo

For a Generic git Repo:

If you want to download files, not clone the repository with history, you can do this with git-archive.

git-archive makes a compressed zip or tar archive of a git repository. Some things that make it special:

  1. You can choose which files or directories in the git repository to archive.
  2. It doesn't archive the .git/ folder, or any untracked files in the repository it's run on.
  3. You can archive a specific branch, tag, or commit. Projects managed with git often use this to generate archives of versions of the project (beta, release, 2.0, etc.) for users to download.

An example of creating an archive of the docs/usage directory from a remote repo you're connected to with ssh:

# in terminal
$ git archive --format tar --remote ssh://server.org/path/to/git HEAD docs/usage > /tmp/usage_docs.tar

More information in this blog post and the git documentation.

Note on GitHub Repos:

GitHub doesn't allow git-archive access. ??

Max length for client ip address

Take it from someone who has tried it all three ways... just use a varchar(39)

The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.

'str' object does not support item assignment in Python

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

Switch statement with returns -- code correctness

I think the *break*s are there for a purpose. It is to keep the 'ideology' of programming alive. If we are to just 'program' our code without logical coherence perhaps it would be readable to you now, but try tomorrow. Try explaining it to your boss. Try running it on Windows 3030.

Bleah, the idea is very simple:


Switch ( Algorithm )
{

 case 1:
 {
   Call_911;
   Jump;
 }**break**;
 case 2:
 {
   Call Samantha_28;
   Forget;
 }**break**;
 case 3:
 {
   Call it_a_day;
 }**break**;

Return thinkAboutIt?1:return 0;

void Samantha_28(int oBed)
{
   LONG way_from_right;
   SHORT Forget_is_my_job;
   LONG JMP_is_for_assembly;
   LONG assembly_I_work_for_cops;

   BOOL allOfTheAbove;

   int Elligence_says_anyways_thinkAboutIt_**break**_if_we_code_like_this_we_d_be_monkeys;

}
// Sometimes Programming is supposed to convey the meaning and the essence of the task at hand. It is // there to serve a purpose and to keep it alive. While you are not looking, your program is doing  // its thing. Do you trust it?
// This is how you can...
// ----------
// **Break**; Please, take a **Break**;

/* Just a minor question though. How much coffee have you had while reading the above? I.T. Breaks the system sometimes */

Java - How do I make a String array with values?

You want to initialize an array. (For more info - Tutorial)

int []ar={11,22,33};

String []stringAr={"One","Two","Three"};

From the JLS

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Check if a class `active` exist on element with jquery

$(document).ready(function()
{
  changeColor = $(.active).css("color","any color");
  if($(".classname").hasClass('active')) {
  $(this).eq(changeColor);
  }
});

Simple pthread! C++

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

The function passed to pthread_create must have a prototype of

void* name(void *arg)

RelativeLayout center vertical

Try aligning top and bottom of text view to one of the icon, this will make text view sharing same height as them, then set gravity to center_vertical to make the text inside text view center vertically.

<TextView 
        android:id="@+id/func_text" android:layout_toRightOf="@id/icon"
        android:layout_alignTop="@id/icon" android:layout_alignBottom="@id/icon"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:gravity="center_vertical" />

How to add google-play-services.jar project dependency so my project will run and present map

What i have done is that import a new project into eclipse workspace, and that path of that was be

android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib

and add as library in your project.. that it .. simple!! you might require to add support library in your project.

The first day of the current month in php using date_modify as DateTime object

using date method, we should be able to get the result. ie; date('N/D/l', mktime(0, 0, 0, month, day, year));

For Example

echo date('N', mktime(0, 0, 0, 7, 1, 2017));   // will return 6
echo date('D', mktime(0, 0, 0, 7, 1, 2017));   // will return Sat
echo date('l', mktime(0, 0, 0, 7, 1, 2017));   // will return Saturday

C/C++ line number

You could use a macro with the same behavior as printf(), except that it also includes debug information such as function name, class, and line number:

#include <cstdio>  //needed for printf
#define print(a, args...) printf("%s(%s:%d) " a,  __func__,__FILE__, __LINE__, ##args)
#define println(a, args...) print(a "\n", ##args)

These macros should behave identically to printf(), while including java stacktrace-like information. Here's an example main:

void exampleMethod() {
    println("printf() syntax: string = %s, int = %d", "foobar", 42);
}

int main(int argc, char** argv) {
    print("Before exampleMethod()...\n");
    exampleMethod();
    println("Success!");
}

Which results in the following output:

main(main.cpp:11) Before exampleMethod()...
exampleMethod(main.cpp:7) printf() syntax: string = foobar, int = 42
main(main.cpp:13) Success!

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

Make sure to close the streams at end if you use Stream Readers

private String readStream(InputStream iStream) throws IOException {
    //build a Stream Reader, it can read char by char
    InputStreamReader iStreamReader = new InputStreamReader(iStream);
    //build a buffered Reader, so that i can read whole line at once
    BufferedReader bReader = new BufferedReader(iStreamReader);
    String line = null;
    StringBuilder builder = new StringBuilder();
    while((line = bReader.readLine()) != null) {  //Read till end
        builder.append(line);
        builder.append("\n"); // append new line to preserve lines
    }
    bReader.close();         //close all opened stuff
    iStreamReader.close();
    //iStream.close(); //EDIT: Let the creator of the stream close it!
                       // some readers may auto close the inner stream
    return builder.toString();
}

EDIT: On JDK 7+, you can use try-with-resources construct.

/**
 * Reads the stream into a string
 * @param iStream the input stream
 * @return the string read from the stream
 * @throws IOException when an IO error occurs
 */
private String readStream(InputStream iStream) throws IOException {

    //Buffered reader allows us to read line by line
    try (BufferedReader bReader =
                 new BufferedReader(new InputStreamReader(iStream))){
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = bReader.readLine()) != null) {  //Read till end
            builder.append(line);
            builder.append("\n"); // append new line to preserve lines
        }
        return builder.toString();
    }
}

Why is volatile needed in C?

There are two uses. These are specially used more often in embedded development.

  1. Compiler will not optimise the functions that uses variables that are defined with volatile keyword

  2. Volatile is used to access exact memory locations in RAM, ROM, etc... This is used more often to control memory-mapped devices, access CPU registers and locate specific memory locations.

See examples with assembly listing. Re: Usage of C "volatile" Keyword in Embedded Development

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

How to redirect all HTTP requests to HTTPS

I'd recommend with 301 redirect:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

join list of lists in python

l = []
map(l.extend, list_of_lists)

shortest!

Wi-Fi Direct and iOS Support

The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

  • Wireless Accessory Configuration (WAC)
  • HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

Ruby String to Date Conversion

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

IntelliJ: Working on multiple projects

Yes, your intuition was good. You shouldn't use three instances of intellij. You can open one Project and add other 'parts' of application as Modules. Add them via project browser, default hotkey is alt+1

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

How can I convert spaces to tabs in Vim or Linux?

Linux: with unexpand (and expand)

Here is a very good solution: https://stackoverflow.com/a/11094620/1115187, mostly because it uses *nix-utilities:

  1. unexpand — spaces -> tabs
  2. expand — tabs -> spaces

Linux: custom script

My original answer

Bash snippet for replacing 4-spaces indentation (there are two {4} in script) with tabs in all .py files in the ./app folder (recursively):

find ./app -iname '*.py' -type f \
    -exec awk -i inplace \
    '{ match($0, /^(( {4})*)(.*?)$/, arr); gsub(/ {4}/, "\t", arr[1]) }; { print arr[1] arr[3] }' {} \; 

It doesn't modify 4-spaces in the middle or at the end.

Was tested under Ubuntu 16.0x and Linux Mint 18

IntelliJ and Tomcat.. Howto..?

Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.

For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.

WindowsError: [Error 126] The specified module could not be found

I met the same problem in Win10 32bit OS. I resolved the problem by changing the DLL from debug to release version.

I think it is because the debug version DLL depends on other DLL, and the release version did not.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

In My case I had one nuget package that was installed in my project however package folder was never checked in to TFS therefore, in build machine that nuget package bin files were missing. And hence in production I was getting this error. I had to compare the bin folder over production vs my local then I found which dlls are missing and I found that those were belonging to one nuget package.

How to get current working directory in Java?

Use CodeSource#getLocation(). This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument.

How to change the author and committer name and e-mail of multiple commits in Git?

This answer uses git-filter-branch, for which the docs now give this warning:

git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.

Changing the author (or committer) would require re-writing all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The man page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the git man page.

Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):

#!/bin/sh

git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

How do I tell what type of value is in a Perl variable?

ref():

Perl provides the ref() function so that you can check the reference type before dereferencing a reference...

By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...

How to get local server host and port in Spring Boot?

I used to declare the configuration in application.properties like this (you can use you own property file)

server.host = localhost
server.port = 8081

and in application you can get it easily by @Value("${server.host}") and @Value("${server.port}") as field level annotation.

or if in your case it is dynamic than you can get from system properties

Here is the example

@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")

For a better understanding of this annotation , see this example Multiple uses of @Value annotation

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

Applying same filter in HTML with multiple columns, just example:

 variable = (array | filter : {Lookup1Id : subject.Lookup1Id, Lookup2Id : subject.Lookup2Id} : true)

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

How to get a subset of a javascript object's properties

Using Object Destructuring and Property Shorthand

_x000D_
_x000D_
const object = { a: 5, b: 6, c: 7  };_x000D_
const picked = (({ a, c }) => ({ a, c }))(object);_x000D_
_x000D_
console.log(picked); // { a: 5, c: 7 }
_x000D_
_x000D_
_x000D_


From Philipp Kewisch:

This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

_x000D_
_x000D_
let unwrap = ({a, c}) => ({a, c});_x000D_
_x000D_
let unwrap2 = function({a, c}) { return { a, c }; };_x000D_
_x000D_
let picked = unwrap({ a: 5, b: 6, c: 7 });_x000D_
_x000D_
let picked2 = unwrap2({a: 5, b: 6, c: 7})_x000D_
_x000D_
console.log(picked)_x000D_
console.log(picked2)
_x000D_
_x000D_
_x000D_

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Recommendation for compressing JPG files with ImageMagick

I added -adaptive-resize 60% to the suggested command, but with -quality 60%.

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 60% -adaptive-resize 60% img_original.jpg img_resize.jpg

These were my results

  • img_original.jpg = 13,913KB
  • img_resized.jpg = 845KB

I'm not sure if that conversion destroys my image too much, but I honestly didn't think my conversion looked like crap. It was a wide angle panorama and I didn't care for meticulous obstruction.

Why am I getting this error Premature end of file?

I resolved the issue by converting the source feed from http://www.news18.com/rss/politics.xml to https://www.news18.com/rss/politics.xml

with http below code was creating an empty file which was causing the issue down the line

    String feedUrl = "https://www.news18.com/rss/politics.xml"; 
    File feedXmlFile = null;

    try {
    feedXmlFile =new File("C://opinionpoll/newsFeed.xml");
    FileUtils.copyURLToFile(new URL(feedUrl),feedXmlFile);


          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
          Document doc = dBuilder.parse(feedXmlFile);

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

How to obfuscate Python code effectively?

I recently stumbled across this blogpost: Python Source Obfuscation using ASTs where the author talks about python source file obfuscation using the builtin AST module. The compiled binary was to be used for the HitB CTF and as such had strict obfuscation requirements.

Since you gain access to individual AST nodes, using this approach allows you to perform arbitrary modifications to the source file. Depending on what transformations you carry out, resulting binary might/might not behave exactly as the non-obfuscated source.

Remove non-ascii character in string

It can also be done with a positive assertion of removal, like this:

textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");

This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx} but also the flag 'u' must present; note the regex has flags 'gu'.

I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^" says "not" and the range \x00-\x7F says "ascii," so the two together say "not ascii."

textContent = textContent.replace(/[^\x00-\x7F]/g,"");

That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.

A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":

> textContent
""
> textContent.length
7

This prompted me to want to see what was in that string.

> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"

This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B" might be inserted by CK-Editor (CKEditor).

encodeURI()  UTF-8     Unicode  html     Meaning
-----------  --------  -------  -------  -------------------
"%E2%80%8B"  EC 80 8B  U 200B   &#8203;  zero-width-space
"%E2%80%8E"  EC 80 8E  U 200E   &#8206;  left-to-right-mark
"%E2%80%8F"  EC 80 8F  U 200F   &#8207;  right-to-left-mark

Some references on those:

http://www.fileformat.info/info/unicode/char/200B/index.htm

https://en.wikipedia.org/wiki/Left-to-right_mark

Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:

https://en.wikipedia.org/wiki/UTF-8

How do you make an element "flash" in jQuery

The following codes work for me. Define two fade-in and fade-out functions and put them in each other's callback.

var fIn = function() { $(this).fadeIn(300, fOut); };
var fOut = function() { $(this).fadeOut(300, fIn); };
$('#element').fadeOut(300, fIn);

The following controls the times of flashes:

var count = 3;
var fIn = function() { $(this).fadeIn(300, fOut); };
var fOut = function() { if (--count > 0) $(this).fadeOut(300, fIn); };
$('#element').fadeOut(300, fIn);

What is "origin" in Git?

Origin is the shortname that acts like an alias for the url of the remote repository.

Let me explain with an example.

Suppose you have a remote repository called amazing-project and then you clone that remote repository to your local machine so that you have a local repository. Then you would have something like what you can see in the diagram below:

enter image description here

Because you cloned the repository. The remote repository and the local repository are linked.

If you run the command git remote -v it will list all the remote repositories that are linked to your local repository. There you will see that in order to push or fetch code from your remote repository you will use the shortname 'origin'. enter image description here

Now, this may be a bit confusing because in GitHub (or the remote server) the project is called 'amazing-project'. So why does it seem like there are two names for the remote repository?

enter image description here

Well one of the names that we have for our repository is the name it has on GitHub or a remote server somewhere. This can be kind of thought like a project name. And in our case that is 'amazing-project'.

The other name that we have for our repository is the shortname that it has in our local repository that is related to the URL of the repository. It is the shortname we are going to use whenever we want to push or fetch code from that remote repository. And this shortname kind of acts like an alias for the url, it's a way for us to avoid having to use that entire long url in order to push or fetch code. And in our example above it is called origin.

So, what is origin?

Basically origin is the default shortname that Git uses for a remote repository when you clone that remote repository. So it's just the default.

In many cases you will have links to multiple remote repositories in your local repository and each of those will have a different shortname.

So final question, why don't we just use the same name?

I will answer that question with another example. Suppose we have a friend who forks our remote repository so they can help us on our project. And let's assume we want to be able to fetch code from their remote repository. We can use the command git remote add <shortname> <url> in order to add a link to their remote repository in our local repository.

enter image description here

In the above image you can see that I used the shortname friend to refer to my friend's remote repository. You can also see that both of the remote repositories have the same project name amazing-project and that gives us one reason why the remote repository names in the remote server and the shortnames in our local repositories should not be the same!

There is a really helpful video that explains all of this that can be found here.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

How to prevent SIGPIPEs (or handle them properly)

Handle SIGPIPE Locally

It's usually best to handle the error locally rather than in a global signal event handler since locally you will have more context as to what's going on and what recourse to take.

I have a communication layer in one of my apps that allows my app to communicate with an external accessory. When a write error occurs I throw and exception in the communication layer and let it bubble up to a try catch block to handle it there.

Code:

The code to ignore a SIGPIPE signal so that you can handle it locally is:

// We expect write failures to occur but we want to handle them where 
// the error occurs rather than in a SIGPIPE handler.
signal(SIGPIPE, SIG_IGN);

This code will prevent the SIGPIPE signal from being raised, but you will get a read / write error when trying to use the socket, so you will need to check for that.

ASP.NET MVC3 - textarea with @Html.EditorFor

Declare in your Model with

  [DataType(DataType.MultilineText)]
  public string urString { get; set; }

Then in .cshtml can make use of editor as below. you can make use of @cols and @rows for TextArea size

     @Html.EditorFor(model => model.urString, new { htmlAttributes = new { @class = "",@cols = 35, @rows = 3 } })

Thanks !

How to add a default "Select" option to this ASP.NET DropDownList control?

Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete

     If Not IsPostBack Then
     DropDownList1.Items.Insert(0, "Select")
     End If

End Sub

How can I calculate an md5 checksum of a directory?

There are two more solutions:

Create:

du -csxb /path | md5sum > file

ls -alR -I dev -I run -I sys -I tmp -I proc /path | md5sum > /tmp/file

Check:

du -csxb /path | md5sum -c file

ls -alR -I dev -I run -I sys -I tmp -I proc /path | md5sum -c /tmp/file

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Change button text from Xcode?

Yes. There is a method on UIButton -setTitle:forState: use that.

How can I set the background color of <option> in a <select> element?

I had this problem too. I found setting the appearance to none helped.

.class {
    appearance:none;
    -moz-appearance:none;
    -webkit-appearance:none;

    background-color: red;
}

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

For Java, from a command line:

java -version

will indicate whether it's 64-bit or not.

Output from the console on my Ubuntu box:

java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)

IE will indicate 64-bit versions in the About dialog, I believe.

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

Check for special characters in string

Your regexp use ^ and $ so it tries to match the entire string. And if you want only a boolean as the result, use test instead of match.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

if(format.test(string)){
  return true;
} else {
  return false;
}

C# - using List<T>.Find() with custom objects

Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

cocoapods - 'pod install' takes forever

After a half of the day of investigating why Analyzing Dependencies takes forever, I found out that I was installing the latest Firebase pod (7.1.0), which relies on GoogleAppMeasurement version 7.1.0, and there was another pod, which is an ad mediation framework, which includes Google-Mobile-Ads-SDK. This SDK was relying on a much lower version of GoogleAppMeasurement ~ 6.0. I was able to install the pods by commenting out the conflicting pod from the ad mediation. Something like this:

# Ad network framework
  pod 'SomeMediationNetwork/Core'
#  pod 'SomeMediationNetwork/GoogleMobileAds' # - the conflicting pod
  pod 'SomeMediationNetwork/Facebook'
  pod 'SomeMediationNetwork/SmartAdServer'
  pod 'SomeMediationNetwork/Mopub'

I had to contact the ad mediation library publisher to fix this issue, most probably by updating to the latest Google-Mobile-Ads-SDK pod and releasing a new version.

I hope this one helps some other folks who are banging their head

How to define Singleton in TypeScript

Another option is to use Symbols in your module. This way you can protect your class, also if the final user of your API is using normal Javascript:

let _instance = Symbol();
export default class Singleton {

    constructor(singletonToken) {
        if (singletonToken !== _instance) {
            throw new Error("Cannot instantiate directly.");
        }
        //Init your class
    }

    static get instance() {
        return this[_instance] || (this[_instance] = new Singleton(_singleton))
    }

    public myMethod():string {
        return "foo";
    }
}

Usage:

var str:string = Singleton.instance.myFoo();

If the user is using your compiled API js file, also will get an error if he try to instantiate manually your class:

// PLAIN JAVASCRIPT: 
var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

In my case, package python-pygments was missed. You can fix it by command:

sudo apt-get install python-pygments

If there is problem with pandoc. You should install pandoc and pandoc-citeproc.

sudo apt-get install pandoc pandoc-citeproc

Force decimal point instead of comma in HTML5 number input (client-side)

Have you considered using Javascript for this?

$('input').val($('input').val().replace(',', '.'));

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

Making a Sass mixin with optional arguments

I know its not exactly the answer you were searching for but you could pass "null" as last argument when @include box-shadow mixin, like this @include box-shadow(12px, 14px, 2px, green, null); Now, if that argument is only one in that property than that property (and its (default) value) won't get compiled. If there are two or more args on that "line" only ones that you nulled won't get compiled (your case).

CSS output is exactly as you wanted it, but you have to write your nulls :)

  @include box-shadow(12px, 14px, 2px, green, null);

  // compiles to ...

  -webkit-box-shadow: 12px 14px 2px green;  
  -moz-box-shadow: 12px 14px 2px green;  
  box-shadow: 12px 14px 2px green;

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

While creating the matrix X and Y vector use values.

X=dataset.iloc[:,4].values
Y=dataset.iloc[:,0:4].values

It will definitely solve your problem.

Google Text-To-Speech API

I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World

And requested with python library..however I'm getting HTTP 403 FORBIDDEN

In the end I had to mock the User-Agent header with the browser's one to succeed.

jQuery datepicker, onSelect won't work

It should be "datepicker", not "datePicker" if you are using the jQuery UI DatePicker plugin. Perhaps, you have a different but similar plugin that doesn't support the select handler.

Rails: How to reference images in CSS within Rails 4

In Rails 4, simply use

.hero { background-image: url("picture.jpg"); }

in your style.css file as long as the background image is tucked in app/assets/images.

Get an object's class name at runtime

If you already know what types to expect (for example, when a method returns a union type), then you can use type guards.

For example, for primitive types you can use a typeof guard:

if (typeof thing === "number") {
  // Do stuff
}

For complex types you can use an instanceof guard:

if (thing instanceof Array) {
  // Do stuff
}

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]> which means a list of Object tables and not a list of Employee.

Object[0] refers an Employee entity 
Object[1] refers a Departement entity 

When you use fetch, there is just one select and the result is the list of Employee List<Employee> containing the list of departements. It overrides the lazy declaration of the entity.

How do I change the language of moment.js?

I had to import also the language:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

Then use moment like you normally would

alert(moment(date).fromNow())

"Could not find a part of the path" error message

There's something wrong. You have written:

string source_dir = @"E:\\Debug\\VipBat\\{0}";

and the error was

Could not find a part of the path E\Debug\VCCSBat

This is not the same directory.

In your code there's a problem, you have to use:

string source_dir = @"E:\Debug\VipBat"; // remove {0} and the \\ if using @

or

string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the @ if using \\

To check if string contains particular word

Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}

Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}

Now in Solution-2 it wll return false because no independent cent word exist.

Additional: You can add or remove space on either side in 2nd solution according to your requirements.

ContractFilter mismatch at the EndpointDispatcher exception

I spent days looking for the answer and I found it, but not in this thread. I am very new to WCF and C#, so to some the answer might be obvious.

In my situation I had a client tool that was originally developed for ASMX service, and for me it was returning that same error message.

After trying all sorts of recommendations I found this site:

http://myshittycode.com/2013/10/01/the-message-with-action-cannot-be-processed-at-the-receiver-due-to-a-contractfilter-mismatch-at-the-endpointdispatcher/

It put me on the right path. Specifically "soap:operation" - WCF was appending ServiceName to the Namespace:

client expected Http://TEST.COM/Login, but WCF sent Http://TEST.COM/IService1/Login. Solution is to add setting to [OperationContract] like this:

[OperationContract(Action = "http://TEST.COM/Login", ReplyAction = "http://TEST.COM/Login")] (Ignore blank spaces in Http)

How do I query using fields inside the new PostgreSQL JSON datatype?

With Postgres 9.3+, just use the -> operator. For example,

SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;

see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.

How do I crop an image in Java?

File fileToWrite = new File(filePath, "url");

BufferedImage bufferedImage = cropImage(fileToWrite, x, y, w, h);

private BufferedImage cropImage(File filePath, int x, int y, int w, int h){

    try {
        BufferedImage originalImgage = ImageIO.read(filePath);

        BufferedImage subImgage = originalImgage.getSubimage(x, y, w, h);



        return subImgage;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Where are the Android icon drawables within the SDK?

i found mine here:

~/android-sdks/platforms/android-23/data/res/drawable...

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

"Edit and Continue", when enabled, will only allow you to edit code when it is in break-mode: e.g. by having the execution paused by an exception or by hitting a breakpoint.

This implies you can't edit the code when the execution isn't paused! When it comes to debugging (ASP.NET) web projects, this is very unintuitive, as you would often want to make changes between requests. At this time, the code your (probably) debugging isn't running, but it isn't paused either!
To solve this, you can click "Break all" (or press Ctrl+Alt+Break). Alternatively, set a breakpoint somewhere (e.g. in your Page_Load event), then reload the page so the execution pauses when it hits the breakpoint, and now you can edit code. Even code in .cs files.

How to select option in drop down using Capybara

In Capybara you can use only find with xpath

find(:xpath, "//*[@id='organizationSelect']/option[2]").click

and method click

"Debug certificate expired" error in Eclipse Android plugins

If a certificate expires in the middle of project debugging, you must do a manual uninstall:

Please execute adb uninstall <package_name> in a shell.

How to get number of entries in a Lua table?

The easiest way that I know of to get the number of entries in a table is with '#'. #tableName gets the number of entries as long as they are numbered:

tbl={
    [1]
    [2]
    [3]
    [4]
    [5]
}
print(#tbl)--prints the highest number in the table: 5

Sadly, if they are not numbered, it won't work.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Laravel 5 PDOException Could Not Find Driver

It will depend of your php version. Check it running:

php -version

Now, according to your current version, run:

sudo apt-get install php7.2-mysql

Displaying all table names in php from MySQL database

The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.

It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Php $_POST method to get textarea value

it is very simply. Just write your php value code between textarea tag.

<textarea id="contact_list"> <?php echo isset($_POST['contact_list']) ? $_POST['contact_list'] : '' ; ?> </textarea>

How to efficiently use try...catch blocks in PHP

There is no reason against using a single block for multiple operations, since any thrown exception will prevent the execution of further operations after the failed one. At least as long as you can conclude which operation failed from the exception caught. That is as long as it is fine if some operations are not processed.

However I'd say that returning the exception makes only limited sense. A return value of a function should be the expected result of some action, not the exception. If you need to react on the exception in the calling scope then either do not catch the exception here inside your function, but in the calling scope or re-throw the exception for later processing after having done some debug logging and the like.

Swift - iOS - Dates and times in different format

let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
            //usDateFormat now contains an optional string "MM/dd/yyyy"

let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
            //gbDateFormat now contains an optional string "dd/MM/yyyy"

let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
            //geDateFormat now contains an optional string "dd.MM.yyyy"

You can use it in following way to get the current format from device:

let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)

Send Email to multiple Recipients with MailMessage?

According to the Documentation :

MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message

Here MailAddressCollection has a in built method called

   public void Add(string addresses)

   1. Summary:
          Add a list of email addresses to the collection.

   2. Parameters:
          addresses: 
                *The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
                *email addresses must be separated with a comma character (",").     

Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma

In your case :

simply replace all the ; with ,

Msg.To.Add(toEmail.replace(";", ","));

For reference :

  1. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8
  2. https://www.geeksforgeeks.org/c-sharp-replace-method/

How can I run an EXE program from a Windows Service using C#?

i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.

I am adding necessary explanation to this scenario

You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager. enter image description here

But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.

In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot. enter image description here

Important codes

// obtain the process id of the winlogon process that 
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
    if ((uint)p.SessionId == dwSessionId)
    {
        winlogonPid = (uint)p.Id;
    }
}

// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
    CloseHandle(hProcess);
    return false;
}

// Security attibute structure used in DuplicateTokenEx and   CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just 
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and   therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);

// copy the access token of the winlogon process; 
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, 
    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, 
    (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
    {
      CloseHandle(hProcess);
      CloseHandle(hPToken);
      return false;
    }

 STARTUPINFO si = new STARTUPINFO();
 si.cb = (int)Marshal.SizeOf(si);

// interactive window station parameter; basically this indicates 
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";

// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;

// create a new process in the current User's logon session
 bool result = CreateProcessAsUser(hUserTokenDup,  // client's access token
                            null,             // file to execute
                            applicationName,  // command line
                            ref sa,           // pointer to process    SECURITY_ATTRIBUTES
                            ref sa,           // pointer to thread SECURITY_ATTRIBUTES
                            false,            // handles are not inheritable
                            dwCreationFlags,  // creation flags
                            IntPtr.Zero,      // pointer to new environment block 
                            null,             // name of current directory 
                            ref si,           // pointer to STARTUPINFO structure
                            out procInfo      // receives information about new process
                            );

Find length (size) of an array in jquery

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

How to get current CPU and RAM usage in Python?

I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the service (on a Windows box) may be started without the database being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the "startup" command.

Fill formula down till last row in column

Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.

I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.

--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.

 ' **row** **Column1**        **Column2**
 '    1     Title1         Data 1 for title 1
 '    2                    Data 2 for title 1
 '    3                    Data 3 for title 1
 '    4     Title2         Data 1 for title 2
 '    5                    Data 2 for title 2
 '    6                    Data 3 for title 2
 '    7   Title 3          Data 1 for title 3

----- CopyDown code ----------

Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.   
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Set strtCell = ActiveCell
    FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
    Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
'   MsgBox Lastrow
    Range(Lastrow).Formula = strtCell.Formula

    Range(Lastrow).End(xlDown).Select
 End Sub

Javascript Date: next month

ah, the beauty of ternaries:

const now = new Date();
const expiry = now.getMonth() == 11 ? new Date(now.getFullYear()+1, 0 , 1) : new Date(now.getFullYear(), now.getMonth() + 1, 1);

just a simpler version of the solution provided by @paxdiablo and @Tom

How to ignore a property in class if null, using json.net

var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
//you can add multiple settings and then use it
var bodyAsJson = JsonConvert.SerializeObject(body, Formatting.Indented, settings);

.trim() in JavaScript not working in IE

I have written some code to implement the trim functionality.

LTRIM (trim left):

function ltrim(s)
{
    var l=0;
    while(l < s.length && s[l] == ' ')
    {   l++; }
    return s.substring(l, s.length);
} 

RTRIM (trim right):

function rtrim(s)
{
    var r=s.length -1;
    while(r > 0 && s[r] == ' ')
    {   r-=1;   }
    return s.substring(0, r+1);
 }

TRIM (trim both sides):

function trim(s)
{
    return rtrim(ltrim(s));
}

OR

Regular expression is also available which we can use.

function trimStr(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

Useful Explanation

PreparedStatement with Statement.RETURN_GENERATED_KEYS

Not having a compiler by me right now, I'll answer by asking a question:

Have you tried this? Does it work?

long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
    key = rs.getLong(1);
}

Disclaimer: Obviously, I haven't compiled this, but you get the idea.

PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.

Difference between $.ajax() and $.get() and $.load()

Very basic but

  • $.load(): Load a piece of html into a container DOM.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

Is a view faster than a simple query?

In SQL Server at least, Query plans are stored in the plan cache for both views and ordinary SQL queries, based on query/view parameters. For both, they are dropped from the cache when they have been unused for a long enough period and the space is needed for some other newly submitted query. After which, if the same query is issued, it is recompiled and the plan is put back into the cache. So no, there is no difference, given that you are reusing the same SQL query and the same view with the same frequency.

Obviously, in general, a view, by it's very nature (That someone thought it was to be used often enough to make it into a view) is generally more likely to be "reused" than any arbitrary SQL statement.

Image style height and width not taken in outlook mails

make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.

in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).

example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

jQuery same click event for multiple elements

If you have or want to keep your elements as variables (jQuery objects), you can also loop over them:

var $class1 = $('.class1');
var $class2 = $('.class2');

$([$class1,$class2]).each(function() {
    $(this).on('click', function(e) {
        some_function();
    });
});

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Using Selenium Web Driver to retrieve value of a HTML input

This is kind of hacky, but it works.

I used JavascriptExecutor and added a div to the HTML, and changed the text in the div to $('#prettyTime').val() I then used Selenium to retrieve the div and grab its value. After testing the correctness of the value, I removed the div that was just created.

get specific row from spark dataframe

This Works for me in PySpark

df.select("column").collect()[0][0]

Dynamically updating css in Angular 2

In Html:

<div [style.maxHeight]="maxHeightForScrollContainer + 'px'">
</div>

In Ts

this.maxHeightForScrollContainer = 200 //your custom maxheight

How to convert datetime format to date format in crystal report using C#?

Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.

Ascending and Descending Number Order in java

Just sort the array in ascending order and print it backwards.

Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
    //print arr[i]
}

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

How to print to console using swift playground?

for displaying variables only in playground, just mention the variable name without anything

let stat = 100

stat // this outputs the value of stat on playground right window

Convert a JSON String to a HashMap

Here is Vikas's code ported to JSR 353:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;

public class JsonUtils {
    public static Map<String, Object> jsonToMap(JsonObject json) {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JsonObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JsonObject object) throws JsonException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keySet().iterator();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JsonArray) {
                value = toList((JsonArray) value);
            }

            else if(value instanceof JsonObject) {
                value = toMap((JsonObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

    public static List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if(value instanceof JsonArray) {
                value = toList((JsonArray) value);
            }

            else if(value instanceof JsonObject) {
                value = toMap((JsonObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

Why does my favicon not show up?

Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.

Web-servers such as lighthttpd must be configured manually to set the mime type correctly.

Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.

On POSIX based systems you can base64 encode a file with the base64 command.

To create a base64 encoded ico line use the command:

$ base64 favicon.ico --wrap 0

And insert the output into the line:

<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />

Replacing the word HERE like so:

<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA////AERpOgA5cCcA7vDtAF6jSABllFcAuuCvAK2trQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFjMzMzMzNxARYzMzMzVBEEERYzMzNhERZxRGMzZxQEA2FER3cRSAgTNxgEEREIQBMzFIARERFEEzNhERARFAATMzYREBEAhBMzMzEYEBFEEzMzNhEQQRQDMzMzcRgEAAMzMzNhERgIEzMzMyERgEQDMzMzMRAEgEMzMzMxERAEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon" />

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Try to use it

LayoutInflater inflater = (LayoutInflater).getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflate.from(YourActivity.this).inflate(R.layout.yourLayout, null);

Limiting number of displayed results when using ngRepeat

here is anaother way to limit your filter on html, for example I want to display 3 list at time than i will use limitTo:3

  <li ng-repeat="phone in phones | limitTo:3">
    <p>Phone Name: {{phone.name}}</p>
  </li>

Deep cloning objects

The reason not to use ICloneable is not because it doesn't have a generic interface. The reason not to use it is because it's vague. It doesn't make clear whether you're getting a shallow or a deep copy; that's up to the implementer.

Yes, MemberwiseClone makes a shallow copy, but the opposite of MemberwiseClone isn't Clone; it would be, perhaps, DeepClone, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.)

What I usually do is simply make a Copy method that does exactly what I want.

Get selected option text with JavaScript

 <select class="cS" onChange="fSel2(this.value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select><br>

 <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <script type="text/javascript"> "use strict";
   const s=document.querySelector(".cS");

 // options[this.selectedIndex].value
 let fSel = (sIdx) => console.log(sIdx,
     s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);

 let fSel2= (sIdx) => { // this.value
     console.log(sIdx, s.options[sIdx].text,
         s.options[sIdx].textContent, s.options[sIdx].label);
 }

 // options[this.selectedIndex].text
 // options[this.selectedIndex].textContent
 // options[this.selectedIndex].label
 // options[this.selectedIndex].innerHTML
 let fSel3= (sIdx) => {
     console.log(sIdx);
 }
 </script> // fSel

But :

 <script type="text/javascript"> "use strict";
    const x=document.querySelector(".cS"),
          o=x.options, i=x.selectedIndex;
    console.log(o[i].value,
                o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
 </script> // .cS"

And also this :

 <select id="iSel" size="3">
     <option value="one">Un</option>
     <option value="two">Deux</option>
     <option value="three">Trois</option>
 </select>


 <script type="text/javascript"> "use strict";
    const i=document.getElementById("iSel");
    for(let k=0;k<i.length;k++) {
        if(k == i.selectedIndex) console.log("Selected ".repeat(3));
        console.log(`${Object.entries(i.options)[k][1].value}`+
                    ` => ` +
                    `${Object.entries(i.options)[k][1].innerHTML}`);
        console.log(Object.values(i.options)[k].value ,
                    " => ",
                    Object.values(i.options)[k].innerHTML);
        console.log("=".repeat(25));
    }
 </script>

How should I remove all the leading spaces from a string? - swift

Swift 3 version of BadmintonCat's answer

extension String {
    func replace(_ string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(" ", replacement: "")
    }
}

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

Best /Fastest way to read an Excel Sheet into a DataTable?

public DataTable ImportExceltoDatatable(string filepath)
{
    // string sqlquery= "Select * From [SheetName$] Where YourCondition";
    string sqlquery = "Select * From [SheetName$] Where Id='ID_007'";
    DataSet ds = new DataSet();
    string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
    OleDbConnection con = new OleDbConnection(constring + "");
    OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, con);
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    return dt;
}

How to disable HTML links

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

View more than one project/solution in Visual Studio

This is the way Visual Studio is designed: One solution, one Visual Studio (VS) instance.

Besides switching between solutions in one VS instance, you can also open another VS instance and open your other solution with that one. Next to solutions there are as you said "projects". You can have multiple projects within one solution and therefore view many projects at the same time.

How to parse an RSS feed using JavaScript?

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

How do you copy and paste into Git Bash

The way I do this is to hold Alt then press Space, then E and finally P.

On Windows Alt jumps to the window menu, Space opens it, E selects Edit and P executes the Paste command.

Get these correct in succession and you can paste a snippet in under 2 seconds.

Using str_replace so that it only acts on the first match?

To expand on zombat's answer (which I believe to be the best answer), I created a recursive version of his function that takes in a $limit parameter to specify how many occurrences you want to replace.

function str_replace_limit($haystack, $needle, $replace, $limit, $start_pos = 0) {
    if ($limit <= 0) {
        return $haystack;
    } else {
        $pos = strpos($haystack,$needle,$start_pos);
        if ($pos !== false) {
            $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
            return str_replace_limit($newstring, $needle, $replace, $limit-1, $pos+strlen($replace));
        } else {
            return $haystack;
        }
    }
}

How to get number of rows using SqlDataReader in C#

If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
      {
        sqlCon.Open();

        var com = sqlCon.CreateCommand();
        com.CommandText = "select * from BigTable";
        using (var reader = com.ExecuteReader())
        {
            //here you retrieve what you need
        }

        com.CommandText = "select @@ROWCOUNT";
        var totalRow = com.ExecuteScalar();

        sqlCon.Close();
      }

You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...

How to move the layout up when the soft keyboard is shown android

Accoding to this guide, the correct way to achieve this is by declaring in your manifest:

<activity name="EditContactActivity"
        android:windowSoftInputMode="stateVisible|adjustResize">

    </activity>

How to scroll to specific item using jQuery?

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');

Order by in Inner Join

SQL doesn't return any ordering by default because it's faster this way. It doesn't have to go through your data first and then decide what to do.

You need to add an order by clause, and probably order by which ever ID you expect. (There's a duplicate of names, thus I'd assume you want One.ID)

select * From one
inner join two
ON one.one_name = two.one_name
ORDER BY one.ID

Bootstrap table striped: How do I change the stripe background colour?

You have two options, either you override the styles with a custom stylesheet, or you edit the main bootstrap css file. I prefer the former.

Your custom styles should be linked after bootstrap.

<link rel="stylesheet" src="bootstrap.css">
<link rel="stylesheet" src="custom.css">

In custom.css

.table-striped>tr:nth-child(odd){
   background-color:red;
}

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

I had the same issue with a VM running CentOS7 and Oracle 11GR2 accesible from Windows 7, the solution were weird, at my local machine the tnsnames pointing to the DB had a space before the service name, I just deleted the space and then I was able to connect.

A quick example.

Wrong tnsnames.

[this is a empty space]XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) )

EXTPROC_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) ) (CONNECT_DATA = (SID = PLSExtProc) (PRESENTATION = RO) ) )

Right tnsnames.

XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) )

EXTPROC_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) ) (CONNECT_DATA = (SID = PLSExtProc) (PRESENTATION = RO) ) )

single line comment in HTML

from http://htmlhelp.com/reference/wilbur/misc/comment.html

Since HTML is officially an SGML application, the comment syntax used in HTML documents is actually the SGML comment syntax. Unfortunately this syntax is a bit unclear at first.

The definition of an SGML comment is basically as follows:

A comment declaration starts with <!, followed by zero or more comments, followed by >. A comment starts and ends with "--", and does not contain any occurrence of "--".
This means that the following are all legal SGML comments:
  1. <!-- Hello -->
  2. <!-- Hello -- -- Hello-->
  3. <!---->
  4. <!------ Hello -->
  5. <!>
Note that an "empty" comment tag, with just "--" characters, should always have a multiple of four "-" characters to be legal. (And yes, <!> is also a legal comment - it's the empty comment).

Not all HTML parsers get this right. For example, "<!------> hello-->" is a legal comment, as you can verify with the rule above. It is a comment tag with two comments; the first is empty and the second one contains "> hello". If you try it in a browser, you will find that the text is displayed on screen.

There are two possible reasons for this:

  1. The browser sees the ">" character and thinks the comment ends there.
  2. The browser sees the "-->" text and thinks the comment ends there.
There is also the problem with the "--" sequence. Some people have a habit of using things like "<!-------------->" as separators in their source. Unfortunately, in most cases, the number of "-" characters is not a multiple of four. This means that a browser who tries to get it right will actually get it wrong here and actually hide the rest of the document.

For this reason, use the following simple rule to compose valid and accepted comments:

An HTML comment begins with "<!--", ends with "-->" and does not contain "--" or ">" anywhere in the comment.

Plotting with C#

See Samples Environment for Microsoft Chart Controls:

The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.

Seems to be more business oriented, but may be of some value to science students and scientists.

Moment js get first and last day of current month

I ran into some issues because I wasn't aware that moment().endOf() mutates the input date, so I used this work around.

_x000D_
_x000D_
let thisMoment = moment();
let endOfMonth = moment(thisMoment).endOf('month');
let startOfMonth = moment(thisMoment).startOf('month');
_x000D_
_x000D_
_x000D_

Execute Insert command and return inserted Id in Sql

The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this

FOR SQL SERVER 2005 and above

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified =(int)cmd.ExecuteScalar();

        if (con.State == System.Data.ConnectionState.Open) 
            con.Close();

        return modified;
    }
}

FOR previous versions

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ)  VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified = Convert.ToInt32(cmd.ExecuteScalar());

        if (con.State == System.Data.ConnectionState.Open) con.Close();
            return modified;
    }
}

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Which version of SQL Server?

For SQL Server 2005 and later, you can obtain the SQL script used to create the view like this:

select definition
from sys.objects     o
join sys.sql_modules m on m.object_id = o.object_id
where o.object_id = object_id( 'dbo.MyView')
  and o.type      = 'V'

This returns a single row containing the script used to create/alter the view.

Other columns in the table tell about about options in place at the time the view was compiled.

Caveats

  • If the view was last modified with ALTER VIEW, then the script will be an ALTER VIEW statement rather than a CREATE VIEW statement.

  • The script reflects the name as it was created. The only time it gets updated is if you execute ALTER VIEW, or drop and recreate the view with CREATE VIEW. If the view has been renamed (e.g., via sp_rename) or ownership has been transferred to a different schema, the script you get back will reflect the original CREATE/ALTER VIEW statement: it will not reflect the objects current name.

  • Some tools truncate the output. For example, the MS-SQL command line tool sqlcmd.exe truncates the data at 255 chars. You can pass the parameter -y N to get the result with N chars.

How can JavaScript save to a local file?

It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.

Bootstrap 3 Horizontal Divider (not in a dropdown)

Yes there is, you can simply put <hr> in your code where you want it, I already use it in one of my admin panel side bar.

How to get the nth occurrence in a string?

Working off of kennebec's answer, I created a prototype function which will return -1 if the nth occurence is not found rather than 0.

String.prototype.nthIndexOf = function(pattern, n) {
    var i = -1;

    while (n-- && i++ < this.length) {
        i = this.indexOf(pattern, i);
        if (i < 0) break;
    }

    return i;
}

How to add values in a variable in Unix shell scripting?

 echo "$x"
    x=10
    echo "$y"`enter code here`
    y=10
    echo $[$x+$y]

Answer: 20

React Router Pass Param to Component

I used this to access the ID in my component:

<Route path="/details/:id" component={DetailsPage}/>

And in the detail component:

export default class DetailsPage extends Component {
  render() {
    return(
      <div>
        <h2>{this.props.match.params.id}</h2>
      </div>
    )
  }
}

This will render any ID inside an h2, hope that helps someone.

Convert a list of objects to an array of one of the object's properties

This should also work:

AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())

Extracting an attribute value with beautifulsoup

Here is an example for how to extract the href attrbiutes of all a tags:

import requests as rq 
from bs4 import BeautifulSoup as bs

url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')

hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
    # print(href.get("href"))
    links = href.get("href")
    all_hrefs.append(links)

print(all_hrefs)

Change size of axes title and labels in ggplot2

I think a better way to do this is to change the base_size argument. It will increase the text sizes consistently.

g + theme_grey(base_size = 22)

As seen here.

Reading a plain text file in Java

Here is a simple solution:

String content;

content = new String(Files.readAllBytes(Paths.get("sample.txt")));

How can I exclude a directory from Visual Studio Code "Explore" tab?

There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension

It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.


enter image description here

How can I limit possible inputs in a HTML5 "number" element?

I know there's an answer already, but if you want your input to behave exactly like the maxlength attribute or as close as you can, use the following code:

(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page. 
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();

How to install and run Typescript locally in npm?

You can now use ts-node, which makes your life as simple as

npm install -D ts-node
npm install -D typescript

ts-node script.ts

Convert Date format into DD/MMM/YYYY format in SQL Server

Try this :

select replace ( convert(varchar,getdate(),106),' ','/')

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

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

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

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

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

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

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

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

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

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

BEGIN {
    require 't.pl';
}

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


C:\Temp> s
something

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

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

How to output loop.counter in python jinja template?

change this {% if loop.counter == 1 %} to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}

and this from {{ user }} {{loop.counter}} to {{ user }} {{forloop.counter}}

How to get a list of column names

Easiest way to get the column names of the most recently executed SELECT is to use the cursor's description property. A Python example:

print_me = "("
for description in cursor.description:
    print_me += description[0] + ", "
print(print_me[0:-2] + ')')
# Example output: (inp, output, reason, cond_cnt, loop_likely)

How to get length of a list of lists in python

The method len() returns the number of elements in the list.

 list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
    print "First list length : ", len(list1)
    print "Second list length : ", len(list2)

When we run above program, it produces the following result -

First list length : 3 Second list length : 2

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Java - sending HTTP parameters via POST method easily

Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

So the minimum required code is:

    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
    connection.connect();
    connection.getOutputStream().close(); 

You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

You can also use NameValuePair apparently.

php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case this error caused by wrong /etc/nsswitch.conf configuration on debian.

I've been replaced string

hosts:          files myhostname mdns4_minimal [NOTFOUND=return] dns

with

hosts:          files dns

and everything works right now.

How to clear all input fields in a specific div with jQuery?

inspired from https://stackoverflow.com/a/10892768/2087666 but I use the selector instead of a class and prefer if over switch:

function clearAllInputs(selector) {
  $(selector).find(':input').each(function() {
    if(this.type == 'submit'){
          //do nothing
      }
      else if(this.type == 'checkbox' || this.type == 'radio') {
        this.checked = false;
      }
      else if(this.type == 'file'){
        var control = $(this);
        control.replaceWith( control = control.clone( true ) );
      }else{
        $(this).val('');
      }
   });
}

this should take care of almost all input inside any selector.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.

$(".seconddropdown option" ).each(function() {
    if(($(this).attr('value')==$(".firstdropdown  option:selected").attr('value') )){
        $(this).hide();
        $(this).siblings().show();
    }
});

Using sudo with Python script

I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for moreinformation.

#!/usr/bin/env python
import subprocess

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()

cmd1 = subprocess.Popen(['echo',sudoPassword], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = cmd2.stdout.read.decode()

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

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

Is it acceptable and safe to run pip install under sudo?

Is it acceptable & safe to run pip install under sudo?

It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'? To install Python package in your home directory you don't need root privileges. See description of --user option to pip.

Checking for a null object in C++

As everyone said, references can't be null. That is because, a reference refers to an object. In your code:

// this compiles, but doesn't work, and does this even mean anything?
if (&str == NULL)

you are taking the address of the object str. By definition, str exists, so it has an address. So, it cannot be NULL. So, syntactically, the above is correct, but logically, the if condition is always going to be false.

About your questions: it depends upon what you want to do. Do you want the function to be able to modify the argument? If yes, pass a reference. If not, don't (or pass reference to const). See this C++ FAQ for some good details.

In general, in C++, passing by reference is preferred by most people over passing a pointer. One of the reasons is exactly what you discovered: a reference can't be NULL, thus avoiding you the headache of checking for it in the function.

Find object in list that has attribute equal to some value (that meets any condition)

For below code, xGen is an anonomous generator expression, yFilt is a filter object. Note that for xGen the additional None parameter is returned rather than throwing StopIteration when the list is exhausted.

arr =((10,0), (11,1), (12,2), (13,2), (14,3))

value = 2
xGen = (x for x in arr if x[1] == value)
yFilt = filter(lambda x: x[1] == value, arr)
print(type(xGen))
print(type(yFilt))

for i in range(1,4):
    print('xGen: pass=',i,' result=',next(xGen,None))
    print('yFilt: pass=',i,' result=',next(yFilt))

Output:

<class 'generator'>
<class 'filter'>
xGen: pass= 1  result= (12, 2)
yFilt: pass= 1  result= (12, 2)
xGen: pass= 2  result= (13, 2)
yFilt: pass= 2  result= (13, 2)
xGen: pass= 3  result= None
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print('yFilt: pass=',i,' result=',next(yFilt))
StopIteration

Double precision - decimal places

An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG in <cfloat>). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15) because of that.

The nextafter() function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.

This program:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

gives me this output on my system:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288

(You can replace %.17g by, say, %.64g to see more digits, none of which are significant.)

As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0 (5) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6, not 5. Replacing 1.0/7.0 by 1.0/3.0 gives this output:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337

which shows about 16 decimal digits of precision, as you'd expect.

C string append

man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.

char * my_strcat(const char * str1, const char * str2)
{
   char * ret = malloc(strlen(str1)+strlen(str2));

   if(ret!=NULL)
   {
     sprintf(ret, "%s%s", str1, str2);
     return ret;
   }
   return NULL;    
}

Hope this solves your purpose

Multiple axis line chart in excel

An alternative is to normalize the data. Below are three sets of data with widely varying ranges. In the top chart you can see the variation in one series clearly, in another not so clearly, and the third not at all.

In the second range, I have adjusted the series names to include the data range, using this formula in cell C15 and copying it to D15:E15

=C2&" ("&MIN(C3:C9)&" to "&MAX(C3:C9)&")"

I have normalized the values in the data range using this formula in C15 and copying it to the entire range C16:E22

=100*(C3-MIN(C$3:C$9))/(MAX(C$3:C$9)-MIN(C$3:C$9))

In the second chart, you can see a pattern: all series have a low in January, rising to a high in March, and dropping to medium-low value in June or July.

You can modify the normalizing formula however you need:

=100*C3/MAX(C$3:C$9)

=C3/MAX(C$3:C$9)

=(C3-AVERAGE(C$3:C$9))/STDEV(C$3:C$9)

etc.

Normalizing Data

How to play a sound in C#, .NET

For Windows Forms one way is to use the SoundPlayer

private void Button_Click(object sender, EventArgs e)
{
    using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav")) {
        soundPlayer.Play(); // can also use soundPlayer.PlaySync()
    }
}

MSDN page

This will also work with WPF, but you have other options like using MediaPlayer MSDN page

git-upload-pack: command not found, when cloning remote Git repo

I have been having issues connecting to a Gitolite repo using SSH from Windows and it turned out that my problem was PLINK! It kept asking me for a password, but the ssh gitolite@[host] would return the repo list fine.

Check your environment variable: GIT_SSH. If it is set to Plink, then try it without any value ("set GIT_SSH=") and see if that works.

Show Hide div if, if statement is true

This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
    $fvisit = mysql_fetch_array($result3);
    $showDivFlag=true;
 }else {

 }

?>

later in html

  <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>

Convert int to a bit array in .NET

To convert the int 'x'

int x = 3;

One way, by manipulation on the int :

string s = Convert.ToString(x, 2); //Convert to binary in a string

int[] bits= s.PadLeft(8, '0') // Add 0's from left
             .Select(c => int.Parse(c.ToString())) // convert each char to int
             .ToArray(); // Convert IEnumerable from select to Array

Alternatively, by using the BitArray class-

BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();

Regular expression to find two strings anywhere in input

If you absolutely need to only use one regex then

/(?=.*?(string1))(?=.*?(string2))/is

i modifier = case-insensitive

.*? Lazy evaluation for any character (matches as few as possible)

?= for Positive LookAhead it has to match somewhere

s modifier = .(period) also accepts line breaks

How to get the path of current worksheet in VBA?

Use Application.ActiveWorkbook.Path for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName for the path with the workbook name.

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Convert seconds to HH-MM-SS with JavaScript?

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Adding quotes to a string in VBScript

The traditional way to specify quotes is to use Chr(34). This is error resistant and is not an abomination.

Chr(34) & "string" & Chr(34)

Detect Android phone via Javascript / jQuery

;(function() {
    var redirect = false
    if (navigator.userAgent.match(/iPhone/i)) {
        redirect = true
    }
    if (navigator.userAgent.match(/iPod/i)) {
        redirect = true
    }
    var isAndroid = /(android)/i.test(navigator.userAgent)
    var isMobile = /(mobile)/i.test(navigator.userAgent)
    if (isAndroid && isMobile) {
        redirect = true
    }
    if (redirect) {
        window.location.replace('jQueryMobileSite')
    }
})()

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

How to upgrade Git on Windows to the latest version?

Update (26SEP2016): It is no longer needed to uninstall your previous version of git to upgraded it to the latest; the installer package found at git win download site takes care of all. Just follow the prompts. For additional information follow instructions at installing and upgrading git.

Fast ceiling of an integer division in C / C++

How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)

q = (x > 0)? 1 + (x - 1)/y: (x / y);

I reduced y/y to one, eliminating the term x + y - 1 and with it any chance of overflow.

I avoid x - 1 wrapping around when x is an unsigned type and contains zero.

For signed x, negative and zero still combine into a single case.

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

Cannot read property 'length' of null (javascript)

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

Bash function to find newest file matching pattern

Use the find command.

Assuming you're using Bash 4.2+, use -printf '%T+ %p\n' for file timestamp value.

find $DIR -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

Example:

find ~/Downloads -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

For a more useful script, see the find-latest script here: https://github.com/l3x/helpers

How to make space between LinearLayout children?

The sample below just does what you need programatically. I have used a fixed size of (140,398).

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(140, 398);
        layoutParams.setMargins(24, 0, 24, 0);
        layout.addView(button,layoutParams);

How to display alt text for an image in chrome

Use title attribute instead of alt

<img
  height="90"
  width="90"
  src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg12.gif"
  title="Image Not Found"
/>

In Windows cmd, how do I prompt for user input and use the result in another command?

Just added the

set /p NetworkLocation= Enter name for network?

echo %NetworkLocation% >> netlist.txt

sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.

SSL Error: CERT_UNTRUSTED while using npm command

Reinstall node, then update npm.

First I removed node

apt-get purge node

Then install node according to the distibution. Docs here .

Then

npm install npm@latest -g

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

get all keys set in memcached

Found a way, thanks to the link here (with the original google group discussion here)

First, Telnet to your server:

telnet 127.0.0.1 11211

Next, list the items to get the slab ids:

stats items
STAT items:3:number 1
STAT items:3:age 498
STAT items:22:number 1
STAT items:22:age 498
END

The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:

stats cachedump 3 100
ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s]
END

stats cachedump 22 100
ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s]
END

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

NPM global install "cannot find module"

For Mac User's It's Best use the manual installation:

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, it will be a hidden directory on your home folder.

  1. Back-up your computer before you start.

  2. Make a directory for global installations:

    mkdir ~/.npm-global

  3. Configure npm to use the new directory path:

    npm config set prefix '~/.npm-global'

  4. Open or create a ~/.profile file and add this line:

    export PATH=~/.npm-global/bin:$PATH

  5. Back on the command line, update your system variables:

    source ~/.profile

  6. Test: Download a package globally without using sudo.

    npm install -g jshint

Instead of steps 2-4, you can use the corresponding ENV variable (e.g. if you don't want to modify ~/.profile):

NPM_CONFIG_PREFIX=~/.npm-global

Reference : https://docs.npmjs.com/getting-started/fixing-npm-permissions