Programs & Examples On #Comdlg32

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not a COM DLL and cannot be registered.

One way to confirm this for yourself is to run this command:

dumpbin /exports comdlg32.dll

You'll see that comdlg32.dll doesn't contain a DllRegisterServer method. Hence RegSvr32.exe won't work.

That's your answer.


ComDlg32.dll is a a system component. (exists in both c:\windows\system32 and c:\windows\syswow64) Trying to replace it or override any registration with an older version could corrupt the rest of Windows.


I can help more, but I need to know what MSComDlg.CommonDialog is. What does it do and how is it supposed to work? And what version of ComDlg32.dll are you trying to register (and where did you get it)?

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

#include <sys/types.h>
#include <sys/stat.h>

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

browser sessionStorage. share between tabs?

Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)

  1. In your first JSP page, onload event call a servlet (ajex call) to setup a "window.title" and event tracker in the session(just a integer variable to be set as 0 for first time)
  2. Make sure none of the other pages set a window.title
  3. All pages (including the first page) add a java script to check the window title once the page load is complete. if the title is not found then close the current page/tab(make sure to undo the "window.unload" function when this occurs)
  4. Set page window.onunload java script event(for all pages) to capture the page refresh event, if a page has been refreshed call the servlet to reset the event tracker.

1)first page JS

BODY onload="javascript:initPageLoad()"

function initPageLoad() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {                           var serverResponse = xmlhttp.responseText;
            top.document.title=serverResponse;
        }
    };
                xmlhttp.open("GET", 'data.do', true);
    xmlhttp.send();

}

2)common JS for all pages

window.onunload = function() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {             
            var serverResponse = xmlhttp.responseText;              
        }
    };

    xmlhttp.open("GET", 'data.do?reset=true', true);
    xmlhttp.send();
}

var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
    init();
    clearInterval(readyStateCheckInterval);
}}, 10);
function init(){ 
  if(document.title==""){   
  window.onunload=function() {};
  window.open('', '_self', ''); window.close();
  }
 }

3)web.xml - servlet mapping

<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>     
</servlet-mapping>  
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>

4)servlet code

public class MyAction extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Integer sessionCount = (Integer) request.getSession().getAttribute(
            "sessionCount");
    PrintWriter out = response.getWriter();
    Boolean reset = Boolean.valueOf(request.getParameter("reset"));
    if (reset)
        sessionCount = new Integer(0);
    else {
        if (sessionCount == null || sessionCount == 0) {
            out.println("hello Title");
            sessionCount = new Integer(0);
        }
                          sessionCount++;
    }
    request.getSession().setAttribute("sessionCount", sessionCount);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "private, no-store, no-cache, must-                      revalidate");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");
} 
  }

How to change Angular CLI favicon

TO RELOAD FAVICON FOR ANY WEB PROJECT:

Right click on the favicon and click 'reload'. Works every time.

How to embed fonts in HTML?

And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE. Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism. A list apart had a good discussion about this a while back.

Pointer to class data member "::*"

A realworld example of a pointer-to-member could be a more narrow aliasing constructor for std::shared_ptr:

template <typename T>
template <typename U>
shared_ptr<T>::shared_ptr(const shared_ptr<U>, T U::*member);

What that constructor would be good for

assume you have a struct foo:

struct foo {
    int ival;
    float fval;
};

If you have given a shared_ptr to a foo, you could then retrieve shared_ptr's to its members ival or fval using that constructor:

auto foo_shared = std::make_shared<foo>();
auto ival_shared = std::shared_ptr<int>(foo_shared, &foo::ival);

This would be useful if want to pass the pointer foo_shared->ival to some function which expects a shared_ptr

https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

Running Jupyter via command line on Windows

If you are using the Anaconda distribution, make sure when installing it that you check the "Change PATH" option.

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

add async in main()

and await before

follow my code

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var fsconnect = FirebaseFirestore.instance;

  myget() async {
    var d = await fsconnect.collection("students").get();
    // print(d.docs[0].data());

    for (var i in d.docs) {
      print(i.data());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Firebase Firestore App'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('send data'),
            onPressed: () {
              fsconnect.collection("students").add({
                'name': 'sarah',
                'title': 'xyz',
                'email': '[email protected]',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}

How to configure XAMPP to send mail from localhost?

just spent over an hour trying to make this work. for everybody having the same trouble with all the suggestions posted not working: you have to restart Apache in your XAMPP inrerface! just restarting XAMPP wont work!!

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

Sending and Parsing JSON Objects in Android

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

Adding POST parameters before submit

If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:

var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});

$.post("api/comment", formData, function(data) {
  // request has finished, check for errors
  // and then for example redirect to another page
});

See .serializeArray() and $.post() documentation.

Splitting words into letters in Java

"Stack Me 123 Heppa1 oeu".toCharArray() ?

How to test if a file is a directory in a batch script?

A variation of @batchman61's approach (checking the Directory attribute).

This time I use an external 'find' command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

@ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
    ECHO %1 is a directory
)

Outputs yes on:

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
  • Directories which you have no read permission on (e.g. "C:\System Volume Information")

How do I disable form resizing for users?

Use the FormBorderStyle property. Make it FixedSingle:

this.FormBorderStyle = FormBorderStyle.FixedSingle;

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

Extract a substring according to a pattern

This should do:

gsub("[A-Z][1-9]:", "", string)

gives

[1] "E001" "E002" "E003"

Mockito matcher and array of primitives

You can use Mockito.any() when arguments are arrays also. I used it like this:

verify(myMock, times(0)).setContents(any(), any());

How to remove files and directories quickly via terminal (bash shell)

rm -rf *

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

C++ program converts fahrenheit to celsius

It is the simplest one I could come up with, so wanted to share here,

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<”Enter the Temperature in Celsius”<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<”Temperature in Fahrenheit is “<<fah;
//get character
getch();
}

Source: Celsius to Fahrenheit

How do I put a border around an Android textview?

Let me summarize a few different (non-programmatic) methods.

Using a shape drawable

Save the following as an XML file in your drawable folder (for example, my_border.xml):

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

    <!-- View background color -->
    <solid
        android:color="@color/background_color" >
    </solid>

    <!-- View border color and width -->
    <stroke
        android:width="1dp"
        android:color="@color/border_color" >
    </stroke>

    <!-- The radius makes the corners rounded -->
    <corners
        android:radius="2dp"   >
    </corners>

</shape>

Then just set it as the background to your TextView:

<TextView
    android:id="@+id/textview1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_border" />

More help:

Using a 9-patch

A 9-patch is a stretchable background image. If you make an image with a border then it will give your TextView a border. All you need to do is make the image and then set it to the background in your TextView.

<TextView
    android:id="@+id/textview1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_ninepatch_image" />

Here are some links that will show how to make a 9-patch image:

What if I just want the top border?

Using a layer-list

You can use a layer list to stack two rectangles on top of each other. By making the second rectangle just a little smaller than the first rectangle, you can make a border effect. The first (lower) rectangle is the border color and the second rectangle is the background color.

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

    <!-- Lower rectangle (border color) -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/border_color" />
        </shape>
    </item>

    <!-- Upper rectangle (background color) -->
    <item android:top="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/background_color" />
        </shape>
    </item>
</layer-list>

Setting android:top="2dp" offsets the top (makes it smaller) by 2dp. This allows the first (lower) rectangle to show through, giving a border effect. You can apply this to the TextView background the same way that the shape drawable was done above.

Here are some more links about layer lists:

Using a 9-patch

You can just make a 9-patch image with a single border. Everything else is the same as discussed above.

Using a View

This is kind of a trick but it works well if you need to add a seperator between two views or a border to a single TextView.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- This adds a border between the TextViews -->
    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@android:color/black" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Here are some more links:

Early exit from function?

Apparently you can do this:

function myFunction() {myFunction:{
    console.log('i get executed');
    break myFunction;
    console.log('i do not get executed');
}}

See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

I can't see any downsides yet. But it doesn't seem like a common use.

Derived this answer: JavaScript equivalent of PHP’s die

Get integer value from string in swift

8:1 Odds(*)

var stringNumb: String = "1357"
var someNumb = Int(stringNumb)

or

var stringNumb: String = "1357"
var someNumb:Int? = Int(stringNumb)

Int(String) returns an optional Int?, not an Int.


Safe use: do not explicitly unwrap

let unwrapped:Int = Int(stringNumb) ?? 0

or

if let stringNumb:Int = stringNumb { ... }

(*) None of the answers actually addressed why var someNumb: Int = Int(stringNumb) was not working.

How to access List elements

I'd start by not calling it list, since that's the name of the constructor for Python's built in list type.

But once you've renamed it to cities or something, you'd do:

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

How do change the color of the text of an <option> within a <select>?

_x000D_
_x000D_
<select id="select">_x000D_
    <optgroup label="select one option">_x000D_
        <option>one</option>  _x000D_
        <option>two</option>  _x000D_
        <option>three</option>  _x000D_
        <option>four</option>  _x000D_
        <option>five</option>_x000D_
    </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

It all sounded like a lot of hard work to me, when optgroup gives you what you need - at least I think it does.

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

I have the same problem in eclipse IDE, my solution was: Right click in My project > Properties

enter image description here

Click in Maven and write: jar in the Active Maven Project

enter image description here

Finally, Apply and Close

Is it a bad practice to use an if-statement without curly braces?

One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:

if(one)
    if(two)
        foo();
    else
        bar();

From this:

if(one)
    if(two)
        foo();
else
    bar();

Why is Event.target not Element in Typescript?

Using typescript, I use a custom interface that only applies to my function. Example use case.

  handleChange(event: { target: HTMLInputElement; }) {
    this.setState({ value: event.target.value });
  }

In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.

Later in my code I can use

<input type='text' value={this.state.value} onChange={this.handleChange} />

A cleaner approach would be to put the interface to a separate file.

interface HandleNameChangeInterface {
  target: HTMLInputElement;
}

then later use the following function definition:

  handleChange(event: HandleNameChangeInterface) {
    this.setState({ value: event.target.value });
  }

In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.

Python wildcard search in string

You could try the fnmatch module, it's got a shell-like wildcard syntax

or can use regular expressions

import re

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

If you want to rule out any problems with the else part, try removing the else and place the command on a new line. Like this:

IF EXIST D:\RPS_BACKUP\backups_temp\ goto tempexists
goto tempexistscontinue  

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

Is there any kind of hash code function in JavaScript?

My solution introduces a static function for the global Object object.

(function() {
    var lastStorageId = 0;

    this.Object.hash = function(object) {
        var hash = object.__id;

        if (!hash)
             hash = object.__id = lastStorageId++;

        return '#' + hash;
    };
}());

I think this is more convenient with other object manipulating functions in JavaScript.

What's the fastest way to convert String to Number in JavaScript?

The fastest way is using -0:

const num = "12.34" - 0;

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

I had a similar issue and tried the other suggestions.

Utilizing the PdaNet driver in the download from http://www.junefabrics.com/android/download.php is what finally did the job and allowed me to finally connect via ADB. Prior to installing the driver from here I was unable to recognize my Nexus in order to sideload the new Android 4.2 on my device.

I am running Windows 7 64 bit with my Nexus 7.

How to import Maven dependency in Android Studio/IntelliJ?

As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:

dependencies {

    // Remote binary dependency
    compile 'net.schmizz:sshj:0.10.0'

}

You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.

enter image description here

Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

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

Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:

function GetProcedureById(procedureId)
{
    var includeMaster = true;
    pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: pString,
        datatype: "json",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
        success: function(msg)
        {
            LoadProcedure(msg);
        },
        failure: function(msg)
        {
            // $("#sometextplace").text("Procedure did not load");
        }
    });
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
    if (jdata.length < 10)
    {
        $("select#cptIcdProcedureSelect").attr('size', jdata.length);
    }
    else
    {
        $("select#cptIcdProcedureSelect").attr('size', '10');
    };
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
    };
    $("select#cptIcdProcedureSelect").html(options);
};

How to insert special characters into a database?

$var = mysql_real_escape_string("data & the base");
$result = mysql_query('SELECT * FROM php_bugs WHERE php_bugs_category like  "%' .$var.'%"');

How do I undo the most recent local commits in Git?

"Reset the working tree to the last commit"

git reset --hard HEAD^ 

"Clean unknown files from the working tree"

git clean    

see - Git Quick Reference

NOTE: This command will delete your previous commit, so use with caution! git reset --hard is safer.

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

Method to Add new or update existing item in Dictionary

Functionally, they are equivalent.

Performance-wise map[key] = value would be quicker, as you are only making single lookup instead of two.

Style-wise, the shorter the better :)

The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.

socket.emit() vs. socket.send()

With socket.emit you can register custom event like that:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

Socket.send does the same, but you don't register to 'news' but to message:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.send('hi');
});

client:

var socket = io.connect('http://localhost');
socket.on('message', function (message) {
  console.log(message);
});

How to connect to LocalDB in Visual Studio Server Explorer?

The fastest way in Visual Studio 2017 is to go to Tools -> SQL Server -> New query.. Choose from Local databases and choose the desired Database name at the bottom.

Alternative way

Visual Studio 2017 Server name is:

(localdb)\MSSQLLocalDB

Add the new connection using menu Tools -> Connect to Database...

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Scenario 1

In client application (application is not web application, e.g may be swing app)

private static ApplicationContext context = new  ClassPathXmlApplicationContext("test-client.xml");

context.getBean(name);

No need of web.xml. ApplicationContext as container for getting bean service. No need for web server container. In test-client.xml there can be Simple bean with no remoting, bean with remoting.

Conclusion: In Scenario 1 applicationContext and DispatcherServlet are not related.

Scenario 2

In a server application (application deployed in server e.g Tomcat). Accessed service via remoting from client program (e.g Swing app)

Define listener in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

At server startup ContextLoaderListener instantiates beans defined in applicationContext.xml.

Assuming you have defined the following in applicationContext.xml:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml.

Conclusion: In Scenario 2 applicationContext and DispatcherServlet are not related.

Scenario 3

In a web application with spring MVC.

In web.xml define:

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

When Tomcat starts, beans defined in springweb-servlet.xml are instantiated. DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for springweb . In our case springweb is FrameworkServlet.

Conclusion: In Scenario 3 applicationContext and DispatcherServlet are not related.

Scenario 4

In web application with spring MVC. springweb-servlet.xml for servlet and applicationContext.xml for accessing the business service within the server program or for accessing DB service in another server program.

In web.xml the following are defined:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

At server startup, ContextLoaderListener instantiates beans defined in applicationContext.xml; assuming you have declared herein:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationContext.xml, beans defined in springweb-servlet.xml are instantiated.

So the instantiation order is: the root (application context), then FrameworkServlet.

Now it should be clear why they are important in which scenario.

Wait for shell command to complete

what you proposed with a change at the parenthesis at the Run command worked fine with VBA for me

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

How do I fire an event when a iframe has finished loading in jQuery?

Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:

    window.onload = function () {


    //creating an iframe element
    var ifr = document.createElement('iframe');
    document.body.appendChild(ifr);

    // making the iframe fill the viewport
    ifr.width  = '100%';
    ifr.height = window.innerHeight;

    // continuously checking to see if the pdf file has been loaded
     self.interval = setInterval(function () {
        if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
            clearInterval(self.interval);

            console.log("loaded");
            //You can do print here: ifr.contentWindow.print();
        }
    }, 100); 

    ifr.src = src;
}

How do you create a yes/no boolean field in SQL server?

You can use the data type bit

Values inserted which are greater than 0 will be stored as '1'

Values inserted which are less than 0 will be stored as '1'

Values inserted as '0' will be stored as '0'

This holds true for MS SQL Server 2012 Express

SSH to Vagrant box in Windows?

I also met the same problem before.

  1. In the homestead folder, use bash init.sh.

  2. If you don't have .ssh folder in D:/Users/your username/, you need to get a pair of ssh keys, ssh-keygen -t rsa -C "you@homestead".

  3. Edit Homestead.yaml(homestead/), authoriza: ~/.ssh/id_rsa.pub.

  4. keys: - ~/.ssh/id_rsa

5.

folders:
    - map: (share directory path in the host computer) 
      to: /home/vagrant/Code

sites:
    - map: homestead.app
      to: /home/vagrant/Code
  1. You need to use git bash desktop app.

  2. Open git bash desktop app. vagrant up

  3. vagrant ssh

Make a link use POST instead of GET

This is an old question, but none of the answers satisfy the request in-full. So I'm adding another answer.

The requested code, as I understand, should make only one change to the way normal hyperlinks work: the POST method should be used instead of GET. The immediate implications would be:

  1. When the link is clicked we should reload the tab to the url of the href
  2. As the method is POST, we should have no query string in the URL of the target page we load
  3. That page should receive the data in parameters (names and value) by POST

I am using jquery here, but this could be done with native apis (harder and longer of course).

<html>
<head>
    <script src="path/to/jquery.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            $("a.post").click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                var href = this.href;
                var parts = href.split('?');
                var url = parts[0];
                var params = parts[1].split('&');
                var pp, inputs = '';
                for(var i = 0, n = params.length; i < n; i++) {
                    pp = params[i].split('=');
                    inputs += '<input type="hidden" name="' + pp[0] + '" value="' + pp[1] + '" />';
                }
                $("body").append('<form action="'+url+'" method="post" id="poster">'+inputs+'</form>');
                $("#poster").submit();
            });
        });
    </script>
</head>
<body>
    <a class="post" href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Post it!</a><br/>
    <a href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Normal link</a>
</body>
</html>

And to see the result, save the following as reflector.php in the same directory you have the above saved.

<h2>Get</h2>
<pre>
<?php print_r($_GET); ?>
</pre>

<h2>Post</h2>
<pre>
<?php print_r($_POST); ?>
</pre>

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure

How to drop column with constraint?

The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.

ALTER TABLE MyTable
    DROP CONSTRAINT FK_MyColumn
    CONSTRAINT DK_MyColumn
    -- etc...
    COLUMN MyColumn
GO

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

How do I get a human-readable file size in bytes abbreviation using .NET?

My 2 cents:

  • The prefix for kilobyte is kB (lowercase K)
  • Since these functions are for presentation purposes, one should supply a culture, for example: string.Format(CultureInfo.CurrentCulture, "{0:0.##} {1}", fileSize, unit);
  • Depending on the context a kilobyte can be either 1000 or 1024 bytes. The same goes for MB, GB, etc.

How to write a Unit Test?

Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x

Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

How do you make an array of structs in C?

move

struct body bodies[n];

to after

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

Rest all looks fine.

PHP get dropdown value and text

You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...

<option value="2|Dog">Dog</option>

Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.

The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.

SSL InsecurePlatform error when using Requests package

I just had a similar issue on a CentOS 5 server where I installed python 2.7.12 in /usr/local on top of a much older version of python2.7. Upgrading to CentOS 6 or 7 isn't an option on this server right now.

Some of the python 2.7 modules were still existing from the older version of python, but pip was failing to upgrade because the newer cryptography package is not supported by the CentOS 5 packages.

Specifically, 'pip install requests[security]' was failing because the openssl version on the CentOS 5 was 0.9.8e which is no longer supported by cryptography > 1.4.0.

To solve the OPs original issue I did:

1) pip install 'cryptography<1.3.5,>1.3.0'.  

This installed cryptography 1.3.4 which works with openssl-0.9.8e. cryptograpy 1.3.4 is also sufficient to satisfy the requirement for the following command.

2) pip install 'requests[security]'

This command now installs because it doesn't try to install cryptography > 1.4.0.

Note that on Centos 5 I also needed to:

yum install openssl-devel

To allow cryptography to build

How to check if a float value is a whole number

>>> def is_near_integer(n, precision=8, get_integer=False):
...     if get_integer:
...         return int(round(n, precision))
...     else:
...         return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
...     print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>

Make column fixed position in bootstrap

Use this, works for me and solve problems with small screen.

<div class="row">
    <!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
    <div class="col-lg-3 device-lg visible-lg">
       <div class="affix">
           fixed position 
        </div>
    </div>
    <div class="col-lg-9">
    <!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
    <div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
       <div>
           NO fixed position
        </div>
    </div>
       Normal data enter code here
    </div>
</div>

Passing a 2D array to a C++ function

In the case you want to pass a dynamic sized 2-d array to a function, using some pointers could work for you.

void func1(int *arr, int n, int m){
    ...
    int i_j_the_element = arr[i * m + j];  // use the idiom of i * m + j for arr[i][j] 
    ...
}

void func2(){
    ...
    int arr[n][m];
    ...
    func1(&(arr[0][0]), n, m);
}

SQLAlchemy IN clause

With the expression API, which based on the comments is what this question is asking for, you can use the in_ method of the relevant column.

To query

SELECT id, name FROM user WHERE id in (123,456)

use

myList = [123, 456]
select = sqlalchemy.sql.select([user_table.c.id, user_table.c.name], user_table.c.id.in_(myList))
result = conn.execute(select)
for row in result:
    process(row)

This assumes that user_table and conn have been defined appropriately.

How to set a radio button in Android

For radioButton use

radio1.setChecked(true);

It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through

radio2.setChecked(false); ...

If your setting is just on/off use CheckBox.

How does lock work exactly?

The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

To resolve the issues make sure you are using build tools version "23.0.0 rc2" with the following tools build gradle dependency:

classpath 'com.android.tools.build:gradle:1.3.0-beta2'

Reading a simple text file

This is how I do it:

public static String readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));

    // do reading, usually loop until end of file reading  
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        sb.append(mLine); // process line
        mLine = reader.readLine();
    }
    reader.close();
    return sb.toString();
}

use it as follows:

readFromAssets(context,"test.txt")

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

ExecuteNonQuery: Connection property has not been initialized.

A couple of things wrong here.

  1. Do you really want to open and close the connection for every single log entry?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

I highly recommend a C# / SQL Server tutorial.

Declaring variables in Excel Cells

The lingo in excel is different, you don't "declare variables", you "name" cells or arrays.

A good overview of how you do that is below: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010342417.aspx

How can I do a BEFORE UPDATED trigger with sql server?

The updated or deleted values are stored in DELETED. we can get it by the below method in trigger

Full example,

CREATE TRIGGER PRODUCT_UPDATE ON PRODUCTS
FOR UPDATE 
AS
BEGIN
DECLARE @PRODUCT_NAME_OLD VARCHAR(100)
DECLARE @PRODUCT_NAME_NEW VARCHAR(100)

SELECT @PRODUCT_NAME_OLD = product_name from DELETED
SELECT @PRODUCT_NAME_NEW = product_name from INSERTED

END

What does O(log n) mean exactly?

Overview

Others have given good diagram examples, such as the tree diagrams. I did not see any simple code examples. So in addition to my explanation, I'll provide some algorithms with simple print statements to illustrate the complexity of different algorithm categories.

First, you'll want to have a general idea of Logarithm, which you can get from https://en.wikipedia.org/wiki/Logarithm . Natural science use e and the natural log. Engineering disciples will use log_10 (log base 10) and computer scientists will use log_2 (log base 2) a lot, since computers are binary based. Sometimes you'll see abbreviations of natural log as ln(), engineers normally leave the _10 off and just use log() and log_2 is abbreviated as lg(). All of the types of logarithms grow in a similar fashion, that is why they share the same category of log(n).

When you look at the code examples below, I recommend looking at O(1), then O(n), then O(n^2). After you are good with those, then look at the others. I've included clean examples as well as variations to demonstrate how subtle changes can still result in the same categorization.

You can think of O(1), O(n), O(logn), etc as classes or categories of growth. Some categories will take more time to do than others. These categories help give us a way of ordering the algorithm performance. Some grown faster as the input n grows. The following table demonstrates said growth numerically. In the table below think of log(n) as the ceiling of log_2.

enter image description here

Simple Code Examples Of Various Big O Categories:

O(1) - Constant Time Examples:

  • Algorithm 1:

Algorithm 1 prints hello once and it doesn't depend on n, so it will always run in constant time, so it is O(1).

print "hello";
  • Algorithm 2:

Algorithm 2 prints hello 3 times, however it does not depend on an input size. Even as n grows, this algorithm will always only print hello 3 times. That being said 3, is a constant, so this algorithm is also O(1).

print "hello";
print "hello";
print "hello";

O(log(n)) - Logarithmic Examples:

  • Algorithm 3 - This acts like "log_2"

Algorithm 3 demonstrates an algorithm that runs in log_2(n). Notice the post operation of the for loop multiples the current value of i by 2, so i goes from 1 to 2 to 4 to 8 to 16 to 32 ...

for(int i = 1; i <= n; i = i * 2)
  print "hello";
  • Algorithm 4 - This acts like "log_3"

Algorithm 4 demonstrates log_3. Notice i goes from 1 to 3 to 9 to 27...

for(int i = 1; i <= n; i = i * 3)
  print "hello";
  • Algorithm 5 - This acts like "log_1.02"

Algorithm 5 is important, as it helps show that as long as the number is greater than 1 and the result is repeatedly multiplied against itself, that you are looking at a logarithmic algorithm.

for(double i = 1; i < n; i = i * 1.02)
  print "hello";

O(n) - Linear Time Examples:

  • Algorithm 6

This algorithm is simple, which prints hello n times.

for(int i = 0; i < n; i++)
  print "hello";
  • Algorithm 7

This algorithm shows a variation, where it will print hello n/2 times. n/2 = 1/2 * n. We ignore the 1/2 constant and see that this algorithm is O(n).

for(int i = 0; i < n; i = i + 2)
  print "hello";

O(n*log(n)) - nlog(n) Examples:

  • Algorithm 8

Think of this as a combination of O(log(n)) and O(n). The nesting of the for loops help us obtain the O(n*log(n))

for(int i = 0; i < n; i++)
  for(int j = 1; j < n; j = j * 2)
    print "hello";
  • Algorithm 9

Algorithm 9 is like algorithm 8, but each of the loops has allowed variations, which still result in the final result being O(n*log(n))

for(int i = 0; i < n; i = i + 2)
  for(int j = 1; j < n; j = j * 3)
    print "hello";

O(n^2) - n squared Examples:

  • Algorithm 10

O(n^2) is obtained easily by nesting standard for loops.

for(int i = 0; i < n; i++)
  for(int j = 0; j < n; j++)
    print "hello";
  • Algorithm 11

Like algorithm 10, but with some variations.

for(int i = 0; i < n; i++)
  for(int j = 0; j < n; j = j + 2)
    print "hello";

O(n^3) - n cubed Examples:

  • Algorithm 12

This is like algorithm 10, but with 3 loops instead of 2.

for(int i = 0; i < n; i++)
  for(int j = 0; j < n; j++)
    for(int k = 0; k < n; k++)
      print "hello";
  • Algorithm 13

Like algorithm 12, but with some variations that still yield O(n^3).

for(int i = 0; i < n; i++)
  for(int j = 0; j < n + 5; j = j + 2)
    for(int k = 0; k < n; k = k + 3)
      print "hello";

Summary

The above give several straight forward examples, and variations to help demonstrate what subtle changes can be introduced that really don't change the analysis. Hopefully it gives you enough insight.

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

HashSet vs LinkedHashSet

The answer lies in which constructors the LinkedHashSet uses to construct the base class:

public LinkedHashSet(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor, true);      // <-- boolean dummy argument
}

...

public LinkedHashSet(int initialCapacity) {
    super(initialCapacity, .75f, true);            // <-- boolean dummy argument
}

...

public LinkedHashSet() {
    super(16, .75f, true);                         // <-- boolean dummy argument
}

...

public LinkedHashSet(Collection<? extends E> c) {
    super(Math.max(2*c.size(), 11), .75f, true);   // <-- boolean dummy argument
    addAll(c);
}

And (one example of) a HashSet constructor that takes a boolean argument is described, and looks like this:

/**
 * Constructs a new, empty linked hash set.  (This package private
 * constructor is only used by LinkedHashSet.) The backing
 * HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this
 *             constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}

C++ vector of char array

You need

char test[] = "abcde";  // This will add a terminating \0 character to the array
std::vector<std::string> v;
v.push_back(test);

Of if you meant to make a vector of character instead of a vector of strings,

std::vector<char> v(test, test + sizeof(test)/sizeof(*test));

The expression sizeof(test)/sizeof(*test) is for calculating the number of elements in the array test.

How can I print a quotation mark in C?

In C programming language, \ is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below

\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound

How to completely uninstall Android Studio from windows(v10)?

To Completely Remove Android Studio from Windows:

Step 1: Run the Android Studio uninstaller

The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.

Step 2: Remove the Android Studio files

To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%), and delete .android, .AndroidStudio and any analogous directories with versions on the end, i.e. .AndroidStudio1.2, as well as .gradle and .m2 if they exist.

Then go to %APPDATA% and delete the JetBrains directory.

Finally, go to C:\Program Files and delete the Android directory.

Step 3: Remove SDK

To delete any remains of the SDK, go to %LOCALAPPDATA% and delete the Android directory.

Step 4: Delete Android Studio projects

Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects, which you may want to delete.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Select distinct values from a table field

Say your model is 'Shop'

class Shop(models.Model):
    street = models.CharField(max_length=150)
    city = models.CharField(max_length=150)

    # some of your models may have explicit ordering
    class Meta:
        ordering = ('city')

Since you may have the Meta class ordering attribute set, you can use order_by() without parameters to clear any ordering when using distinct(). See the documentation under order_by()

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.

and distinct() in the note where it discusses issues with using distinct() with ordering.

To query your DB, you just have to call:

models.Shop.objects.order_by().values('city').distinct()

It returns a dictionnary

or

models.Shop.objects.order_by().values_list('city').distinct()

This one returns a ValuesListQuerySet which you can cast to a list. You can also add flat=True to values_list to flatten the results.

See also: Get distinct values of Queryset by field

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

Lua - Current time in milliseconds

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

How to delete the top 1000 rows from a table using Sql Server 2008?

It is fast. Try it:

DELETE FROM YourTABLE
FROM (SELECT TOP XX PK FROM YourTABLE) tbl
WHERE YourTABLE.PK = tbl.PK

Replace YourTABLE by table name, XX by a number, for example 1000, pk is the name of the primary key field of your table.

c++ Read from .csv file

You can follow this answer to see many different ways to process CSV in C++.

In your case, the last call to getline is actually putting the last field of the first line and then all of the remaining lines into the variable genero. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:

    getline(file, genero, file.widen('\n'));

or more succinctly:

    getline(file, genero);

In addition, your check for file.good() is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline() call for ID. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while test to be based on the getline() call for ID itself (assuming each line is well formed).

while (getline(file, ID, ',')) {
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero);
    cout << "Sexo: " <<  genero<< " "  ;
}

For better error checking, you should check the result of each call to getline().

How can I add 1 day to current date?

If you want add a day (24 hours) to current datetime you can add milliseconds like this:

new Date(Date.now() + ( 3600 * 1000 * 24))

How to get the current logged in user Id in ASP.NET Core

User.Identity.GetUserId();

does not exist in asp.net identity core 2.0. in this regard, i have managed in different way. i have created a common class for use whole application, because of getting user information.

create a common class PCommon & interface IPCommon adding reference using System.Security.Claims

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Common.Web.Helper
{
    public class PCommon: IPCommon
    {
        private readonly IHttpContextAccessor _context;
        public PayraCommon(IHttpContextAccessor context)
        {
            _context = context;
        }
        public int GetUserId()
        {
            return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
        }
        public string GetUserName()
        {
            return _context.HttpContext.User.Identity.Name;
        }

    }
    public interface IPCommon
    {
        int GetUserId();
        string GetUserName();        
    }    
}

Here the implementation of common class

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Pay.DataManager.Concreate;
using Pay.DataManager.Helper;
using Pay.DataManager.Models;
using Pay.Web.Helper;
using Pay.Web.Models.GeneralViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pay.Controllers
{

    [Authorize]
    public class BankController : Controller
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger _logger;
        private readonly IPCommon _iPCommon;


        public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)
        {
            _unitOfWork = unitOfWork;
            _iPCommon = IPCommon;
            if (logger != null) { _logger = logger; }
        }


        public ActionResult Create()
        {
            BankViewModel _bank = new BankViewModel();
            CountryLoad(_bank);
            return View();
        }

        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert(BankViewModel bankVM)
        {

            if (!ModelState.IsValid)
            {
                CountryLoad(bankVM);
                //TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);
                return View(bankVM);
            }


            try
            {
                bankVM.EntryBy = _iPCommon.GetUserId();
                var userName = _iPCommon.GetUserName()();
                //_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));
                //_unitOfWork.Save();
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);
            }
            catch (Exception ex)
            {
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);
            }
            return RedirectToAction(nameof(Index));
        }



    }
}

get userId and name in insert action

_iPCommon.GetUserId();

Thanks, Maksud

How to Replace Multiple Characters in SQL?

One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.

The general idea of char replacement can be demonstrated with a simple character map table approach:

create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')


create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')

select 
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar

Then you can bring in the tally table approach to do the lookup on each character position in the string.

create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
    insert tally values (@i)
    set @i = @i + 1
end

create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')

select
    i,
    SUBSTRING(testString, i, 1) as srcChar,
    coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
    left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)

std::cin input with spaces?

It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

Use std::getline:

int main()
{
   std::string name, title;

   std::cout << "Enter your name: ";
   std::getline(std::cin, name);

   std::cout << "Enter your favourite movie: ";
   std::getline(std::cin, title);

   std::cout << name << "'s favourite movie is " << title;
}

Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

Update

Your edited question bears little resemblance to the original.

You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.

Trust Anchor not found for Android SSL Connection

The Trust anchor error can happen for a lot of reasons. For me it was simply that I was trying to access https://example.com/ instead of https://www.example.com/.

So you might want to double-check your URLs before starting to build your own Trust Manager (like I did).

Mutex lock threads

Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)

Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.

Both processes should basically do the same thing when accessing the mutex.
lock() If the lock succeeds, then { access sharedResource unlock() }

Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ

How to change btn color in Bootstrap

Adding a step-by-step guide to @Codeply-er's answer above for SASS/SCSS newbies like me.

  1. Save btnCustom.scss.
/* import the necessary Bootstrap files */
@import 'bootstrap';

/* Define color */
$mynewcolor:#77cccc;

.btn-custom {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}

.btn-outline-custom {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}
  1. Download a SASS compiler such as Koala so that SCSS file above can be compiled to CSS.
  2. Clone the Bootstrap github repo because the compiler needs the button-variant mixins somewhere.
  3. Explicitly import bootstrap functions by creating a _bootstrap.scss file as below. This will allow the compiler to access the Bootstrap functions and variables.
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/tables";
@import "bootstrap/scss/forms";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/utilities";
  1. Compile btnCustom.scss with the previously downloaded compiler to css.

default select option as blank

<select required>
  <option value="" disabled selected>None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You can avoid custom validation in this case.

Load different application.yml in SpringBoot Test

Spring-boot framework allows us to provide YAML files as a replacement for the .properties file and it is convenient.The keys in property files can be provided in YAML format in application.yml file in the resource folder and spring-boot will automatically take it up.Keep in mind that the yaml format has to keep the spaces correct for the value to be read correctly.

You can use the @Value("${property}") to inject the values from the YAML files. Also Spring.active.profiles can be given to differentiate between different YAML for different environments for convenient deployment.

For testing purposes, the test YAML file can be named like application-test.yml and placed in the resource folder of the test directory.

If you are specifying the application-test.yml and provide the spring test profile in the .yml, then you can use the @ActiveProfiles('test') annotation to direct spring to take the configurations from the application-test.yml that you have specified.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
@ActiveProfiles("test")
public class MyTest {
 ...
}

If you are using JUnit 5 then no need for other annotations as @SpringBootTest already include the springrunner annotation. Keeping a separate main ApplicationTest.class enables us to provide separate configuration classes for tests and we can prevent the default configuration beans from loading by excluding them from a component scan in the test main class. You can also provide the profile to be loaded there.

@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ApplicationTest {
 
    public static void main(String[] args) {
        SpringApplication.run(ApplicationTest.class, args);
    }
}

Here is the link for Spring documentation regarding the use of YAML instead of .properties file(s): https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to create a Multidimensional ArrayList in Java?

ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();

Depending on your requirements, you might use a Generic class like the one below to make access easier:

import java.util.ArrayList;

class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
    public void addToInnerArray(int index, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }
        this.get(index).add(element);
    }

    public void addToInnerArray(int index, int index2, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }

        ArrayList<T> inner = this.get(index);
        while (index2 >= inner.size()) {
            inner.add(null);
        }

        inner.set(index2, element);
    }
}

Rails: call another controller action from a controller

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.

How to get current date in jquery?

The jQuery plugin page is down. So manually:

function strpad00(s)
{
    s = s + '';
    if (s.length === 1) s = '0'+s;
    return s;
}

var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );

Can I have a video with transparent background using HTML5 video tag?

Update: Webm with an alpha channel is now supported in Chrome and Firefox.

For other browers, there are workarounds, but they involve re-rendering the video using Canvas and it is kind of a hack. seeThru is one example. It works pretty well on HTML5 desktop browsers (even IE9) but it doesn't seem to work very well on mobile. I couldn't get it to work at all on Chrome for Android. It did work on Firefox for Android but with a pretty lousy framerate. I think you might be out of luck for mobile, although I'd love to be proven wrong.

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Greedy means it will consume your pattern until there are none of them left and it can look no further.

Lazy will stop as soon as it will encounter the first pattern you requested.

One common example that I often encounter is \s*-\s*? of a regex ([0-9]{2}\s*-\s*?[0-9]{7})

The first \s* is classified as greedy because of * and will look as many white spaces as possible after the digits are encountered and then look for a dash character "-". Where as the second \s*? is lazy because of the present of *? which means that it will look the first white space character and stop right there.

How to get a URL parameter in Express?

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Query parameter

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5

How to create custom button in Android using XML Styles

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

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

   <size 
       android:width="@dimen/shape_circle_width"
        android:height="@dimen/shape_circle_height"/>
</shape>

1.add this in your drawable

2.set as background to your button

How to write to an existing excel file without overwriting data (using pandas)?

writer = pd.ExcelWriter('prueba1.xlsx'engine='openpyxl',keep_date_col=True)

The "keep_date_col" hope help you

How to display the first few characters of a string in Python?

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

To get the first 4 letters:

first_four_letters = a_string[:4]
>>> 'This'

Or the last 5:

last_five_letters = a_string[-5:]
>>> 'string'

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

How can one check to see if a remote file exists using PHP?

To check for the existence of images, exif_imagetype should be preferred over getimagesize, as it is much faster.

To suppress the E_NOTICE, just prepend the error control operator (@).

if (@exif_imagetype($filename)) {
  // Image exist
}

As a bonus, with the returned value (IMAGETYPE_XXX) from exif_imagetype we could also get the mime-type or file-extension with image_type_to_mime_type / image_type_to_extension.

Changing the row height of a datagridview

Try

datagridview.RowTemplate.MinimumHeight = 25;//25 is height.

I did that and it worked fine!

How to add a browser tab icon (favicon) for a website?

I'd recommend you to try http://faviconer.com to convert your .PNG or .GIF to a .ICO file.

You can create both 16x16 and 32x32 (for new retina display) in one .ICO file.

No issues with IE and Firefox

How to create an array of 20 random bytes?

Try the Random.nextBytes method:

byte[] b = new byte[20];
new Random().nextBytes(b);

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

0xC0000005: Access violation reading location 0x00000000

"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0 and so you try to read from the memory address 0x0, which the operating system detects and prevents you from doing.

Check and make sure that the array invaders[] is what you think it should be.

Also, you don't seem to be updating i ever - meaning that you keep placing the same Invader object into location 0 of invaders[] at every loop iteration.

Get random integer in range (x, y]?

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

How do I execute code AFTER a form has loaded?

You can close your form after some execution..

//YourForm.ActiveForm.Close();

    LoadingForm.ActiveForm.Close();

How to create Password Field in Model Django

You should create a ModelForm (docs), which has a field that uses the PasswordInput widget from the forms library.

It would look like this:

models.py

from django import models
class User(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=50)

forms.py (not views.py)

from django import forms
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        widgets = {
        'password': forms.PasswordInput(),
    }

For more about using forms in a view, see this section of the docs.

Using port number in Windows host file

Using netsh with connectaddress=127.0.0.1 did not work for me.

Despite looking everywhere on the internet I could not find the solution which solved this for me, which was to use connectaddress=127.x.x.x (i.e. any 127. ipv4 address, just not 127.0.0.1) as this appears to link back to localhost just the same but without the restriction, so that the loopback works in netsh.

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

Get $_POST from multiple checkboxes

Edit To reflect what @Marc said in the comment below.

You can do a loop through all the posted values.

HTML:

<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />

PHP:

foreach($_POST['check_list'] as $item){
  // query to delete where item = $item
}

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Replace all whitespace with a line break/paragraph mark to make a word list

You could use POSIX [[:blank:]] to match a horizontal white-space character.

sed 's/[[:blank:]]\+/\n/g' file

or you may use [[:space:]] instead of [[:blank:]] also.

Example:

$ echo 'this  is a sentence' | sed 's/[[:blank:]]\+/\n/g'
this
is
a
sentence

Can anonymous class implement interface?

Anonymous types can implement interfaces via a dynamic proxy.

I wrote an extension method on GitHub and a blog post http://wblo.gs/feE to support this scenario.

The method can be used like this:

class Program
{
    static void Main(string[] args)
    {
        var developer = new { Name = "Jason Bowers" };

        PrintDeveloperName(developer.DuckCast<IDeveloper>());

        Console.ReadKey();
    }

    private static void PrintDeveloperName(IDeveloper developer)
    {
        Console.WriteLine(developer.Name);
    }
}

public interface IDeveloper
{
    string Name { get; }
}

How to make a WPF window be on top of all other windows of my app (not system wide)?

How about htis:

Private Sub ArrangeWindows(Order As Window())
    For I As Integer = 1 To Order.Length -1
        Order(I).Owner = Order(I - 1)
    Next
End Sub

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

The solution is to add your variable to /etc/profile. Then everything works as expected! Of course you MUST do it as a root user with sudo nano /etc/profile. If you edit it with any other way the system will complain with a damaged /etc/profile, even if you change the permissions to root.

How to get page content using cURL?

For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)

  $url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

Alter table add multiple columns ms sql

Can with defaulth value (T-SQL)

ALTER TABLE
    Regions
ADD
    HasPhotoInReadyStorage BIT NULL, --this column is nullable
    HasPhotoInWorkStorage BIT NOT NULL, --this column is not nullable
    HasPhotoInMaterialStorage BIT NOT NULL DEFAULT(0) --this column default value is false
GO

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

Checking for directory and file write permissions in .NET

according to this link: http://www.authorcode.com/how-to-check-file-permission-to-write-in-c/

it's easier to use existing class SecurityManager

string FileLocation = @"C:\test.txt";
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, FileLocation);
if (SecurityManager.IsGranted(writePermission))
{
  // you have permission
}
else
{
 // permission is required!
}

but it seems it's been obsoleted, it is suggested to use PermissionSet instead.

[Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework.  Please use the PermissionSet property of either AppDomain or Assembly instead.")]

check android application is in foreground or not?

Below is updated solution for the latest Android SDK.

String PackageName = context.getPackageName();
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ComponentName componentInfo;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            List<ActivityManager.AppTask> tasks = manager.getAppTasks();
            componentInfo = tasks.get(0).getTaskInfo().topActivity;
        }
        else
        {
            List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(1);
            componentInfo = tasks.get(0).topActivity;
        }

        if (componentInfo.getPackageName().equals(PackageName))
            return true;
        return false;

Hope this helps, thanks.

Variables as commands in bash scripts

Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.

It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.

With perl, as my example, I'd be able to do something like:

@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );

The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)

Incrementing in C++ - When to use x++ or ++x?

Postfix form of ++,-- operator follows the rule use-then-change ,

Prefix form (++x,--x) follows the rule change-then-use.

Example 1:

When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)

 cout<< ++val<<" "<< val++<<" "<< val;

will result into

12    10    10 

Example 2:

In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,

int a=10,b;
b=a++ + ++a + ++a + a;
cout<<b<<a<<endl;

It's output in Turbo C++ will be

48 13

Whereas it's output in modern day compiler will be (because they follow the rules strictly)

45 13
  • Note: Multiple use of increment/decrement operators on same variable in one expression is not recommended. The handling/results of such
    expressions vary from compiler to compiler.

Mvn install or Mvn package

From the Lifecycle reference, install will run the project's integration tests, package won't.

If you really need to not install the generated artifacts, use at least verify.

Visual Studio C# IntelliSense not automatically displaying

Steps to fix are:

      Tools
      Import and Export Settings
      Reset all settings
      Back up your config
      Select your environment settings and finish

Why do I need to configure the SQL dialect of a data source?

Dialect means "the variant of a language". Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Box shadow in IE7 and IE8

use this for fixing issue with shadow box

filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='2', OffY='2', Color='#F13434', Positive='true');

INSERT VALUES WHERE NOT EXISTS

You could do this using an IF statement:

IF NOT EXISTS 
    (   SELECT  1
        FROM    tblSoftwareTitles 
        WHERE   Softwarename = @SoftwareName 
        AND     SoftwareSystemType = @Softwaretype
    )
    BEGIN
        INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
        VALUES (@SoftwareName, @SoftwareType) 
    END;

You could do it without IF using SELECT

INSERT  tblSoftwareTitles (SoftwareName, SoftwareSystemType) 
SELECT  @SoftwareName,@SoftwareType
WHERE   NOT EXISTS 
        (   SELECT  1
            FROM    tblSoftwareTitles 
            WHERE   Softwarename = @SoftwareName 
            AND     SoftwareSystemType = @Softwaretype
        );

Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:

CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
    ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);

Example on SQL-Fiddle


ADDENDUM

In SQL Server 2008 or later you can use MERGE with HOLDLOCK to remove the chance of a race condition (which is still not a substitute for a unique constraint).

MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType) 
    ON s.Softwarename = t.SoftwareName 
    AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (SoftwareName, SoftwareSystemType) 
    VALUES (s.SoftwareName, s.SoftwareSystemType);

Example of Merge on SQL Fiddle

jQuery.inArray(), how to use it right?

The inArray function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.

When inArray returns 0 it is indicating that the first argument was found at the first position of the supplied array.

To use inArray within an if statement use:

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}

inArray returns -1 when the first argument passed to the function is not found in the array passed as the second argument.

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

Concept behind putting wait(),notify() methods in Object class

For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example: Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.

Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.

Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.

Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.

However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.

Giving my function access to outside variable

By default, when you are inside a function, you do not have access to the outer variables.


If you want your function to have access to an outer variable, you have to declare it as global, inside the function :

function someFuntion(){
    global $myArr;
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

For more informations, see Variable scope.

But note that using global variables is not a good practice : with this, your function is not independant anymore.


A better idea would be to make your function return the result :

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

And call the function like this :

$result = someFunction();


Your function could also take parameters, and even work on a parameter passed by reference :

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

Then, call the function like this :

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

With this :

  • Your function received the external array as a parameter
  • And can modify it, as it's passed by reference.
  • And it's better practice than using a global variable : your function is a unit, independant of any external code.


For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :

How to send email to multiple recipients with addresses stored in Excel?

ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
int main()
{
    int a,b,i,c,j;
    printf("\n Enter the two no. in between you want to check:");
    scanf("%d%d",&a,&c);
    printf("%d-%d\n",a,c);
    for(j=a;j<=c;j++)
    {
        b=0;
        for(i=1;i<=c;i++)
        {
            if(j%i==0)
            {
                 b++;
            }
        }
        if(b==2)
        {
            printf("\nPrime number:%d\n",j);
        }
        else
        {
            printf("\n\tNot prime:%d\n",j);
        }
    }
}

Download multiple files with a single action

This works in all browsers (IE11, firefox, Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.

//user clicks a download button to download all selected documents
$('#downloadDocumentsButton').click(function () {
    var interval = 1000;
    //select elements have class name of "document"
    $('.document').each(function (index, element) {
        var doc = $(element).val();
        if (doc) {
            setTimeout(function () {
                window.location = doc;
            }, interval * (index + 1));
        }
    });
});

This is a solution that uses promises:

 function downloadDocs(docs) {
        docs[0].then(function (result) {
            if (result.web) {
                window.open(result.doc);
            }
            else {
                window.location = result.doc;
            }
            if (docs.length > 1) {
                setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
            }
        });
    }

 $('#downloadDocumentsButton').click(function () {
        var files = [];
        $('.document').each(function (index, element) {
            var doc = $(element).val();
            var ext = doc.split('.')[doc.split('.').length - 1];

            if (doc && $.inArray(ext, docTypes) > -1) {
                files.unshift(Promise.resolve({ doc: doc, web: false }));
            }
            else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
                files.push(Promise.resolve({ doc: doc, web: true }));
            }
        });

        downloadDocs(files);
    });

RunAs A different user when debugging in Visual Studio

This works (I feel so idiotic):

C:\Windows\System32\cmd.exe /C runas /savecred /user:OtherUser DebugTarget.Exe

The above command will ask for your password everytime, so for less frustration, you can use /savecred. You get asked only once. (but works only for Home Edition and Starter, I think)

How can I make an "are you sure" prompt in a Windows batchfile?

try the CHOICE command, e.g.

CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."

Loading .sql files from within PHP

The easiest and fastest way to load & parse phpmyadmin dump or mysql dump file..

$ mysql -u username -p -h localhost dbname < dumpfile.sql 

Excel formula to get ranking position

The way I've done this, which is a bit convoluted, is as follows:

  1. Sort rows by the points in descending order
  2. Create an additional column (D) starting at D2 with numbers 1,2,3,... total number of positions
  3. In the cell for the actual positions (D2) use the formula if(C2=C1), D2, C1). This checks if the points in this row are the same as the points in the previous row. If it is it gives you the position of the previous row, otherwise it uses the value from column D and thus handle people with equal positions.
  4. Copy this formula down the entire column
  5. Copy the positions column(C), then paste special >> values to overwrite the formula with positions
  6. Resort the rows to their original order

That's worked for me! If there's a better way I'd love to know it!

How to use KeyListener

The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);
    

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

How to increment an iterator by 2?

If you don't know wether you have enough next elements in your container or not, you need to check against the end of your container between each increment. Neither ++ nor std::advance will do it for you.

if( ++iter == collection.end())
  ... // stop

if( ++iter == collection.end())
  ... // stop

You may even roll your own bound-secure advance function.

If you are sure that you will not go past the end, then std::advance( iter, 2 ) is the best solution.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

How to get access to HTTP header information in Spring MVC REST controller?

My solution in Header parameters with example is user="test" is:

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}

How to call a JavaScript function, declared in <head>, in the body when I want to call it

You can call it like that:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            var person = { name: 'Joe Blow' };
            function myfunction() {
               document.write(person.name);
            }
        </script>
    </head>
    <body>
        <script type="text/javascript">
            myfunction();
        </script>
    </body>
</html>

The result should be page with the only content: Joe Blow

Look here: http://jsfiddle.net/HWreP/

Best regards!

Why is exception.printStackTrace() considered bad practice?

Printing the exception's stack trace in itself doesn't constitute bad practice, but only printing the stace trace when an exception occurs is probably the issue here -- often times, just printing a stack trace is not enough.

Also, there's a tendency to suspect that proper exception handling is not being performed if all that is being performed in a catch block is a e.printStackTrace. Improper handling could mean at best an problem is being ignored, and at worst a program that continues executing in an undefined or unexpected state.

Example

Let's consider the following example:

try {
  initializeState();

} catch (TheSkyIsFallingEndOfTheWorldException e) {
  e.printStackTrace();
}

continueProcessingAssumingThatTheStateIsCorrect();

Here, we want to do some initialization processing before we continue on to some processing that requires that the initialization had taken place.

In the above code, the exception should have been caught and properly handled to prevent the program from proceeding to the continueProcessingAssumingThatTheStateIsCorrect method which we could assume would cause problems.

In many instances, e.printStackTrace() is an indication that some exception is being swallowed and processing is allowed to proceed as if no problem every occurred.

Why has this become a problem?

Probably one of the biggest reason that poor exception handling has become more prevalent is due to how IDEs such as Eclipse will auto-generate code that will perform a e.printStackTrace for the exception handling:

try {
  Thread.sleep(1000);
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

(The above is an actual try-catch auto-generated by Eclipse to handle an InterruptedException thrown by Thread.sleep.)

For most applications, just printing the stack trace to standard error is probably not going to be sufficient. Improper exception handling could in many instances lead to an application running in a state that is unexpected and could be leading to unexpected and undefined behavior.

I need an unordered list without any bullets

I tried and observed:

header ul {
   margin: 0;
   padding: 0;
}

How to enable CORS on Firefox?

just type in your browser CORS add in firefox Then download this and install on browser finally you found top right side one Core spell to toggle that green for enable and red for not enable

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

Yes, you can add a UNIQUE constraint after the fact. However, if you have non-unique entries in your table Postgres will complain about it until you correct them.

How to get the nth element of a python list or a default if not available

Combining @Joachim's with the above, you could use

next(iter(my_list[index:index+1]), default)

Examples:

next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:index + 1] else default

Programmatically scroll a UIScrollView

[Scrollview setContentOffset:CGPointMake(x, y) animated:YES];

How to get child element by index in Jquery?

$('.second').find('div:first')

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

How are parameters sent in an HTTP POST request?

The content is put after the HTTP headers. The format of an HTTP POST is to have the HTTP headers, followed by a blank line, followed by the request body. The POST variables are stored as key-value pairs in the body.

You can see this in the raw content of an HTTP Post, shown below:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

You can see this using a tool like Fiddler, which you can use to watch the raw HTTP request and response payloads being sent across the wire.

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

Determine if char is a num or letter

C99 standard on c >= '0' && c <= '9'

c >= '0' && c <= '9' (mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

ASCII is not guaranteed however.

Why aren't programs written in Assembly more often?

$$$

A company hires a developer to help turn code into $$$. The faster that useful code can be produced, the faster the company can turn that code into $$$.

Higher level languages are generally better at churning out larger volumes of useful code. This is not to say that assembly does not have its place, for there are times and places where nothing else will do.

PHP Multidimensional Array Searching (Find key by specific value)

Try this

function recursive_array_search($needle,$haystack) {
        foreach($haystack as $key=>$value) {
            $current_key=$key;
            if($needle==$value['uid'] OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

Multiple returns from a function

<?php
function foo(){
  $you = 5;
  $me = 10;
  return $you;
  return $me;
}

echo foo();
//output is just 5 alone so we cant get second one it only retuns first one so better go with array


function goo(){
  $you = 5;
  $me = 10;
  return $you_and_me =  array($you,$me);
}

var_dump(goo()); // var_dump result is array(2) { [0]=> int(5) [1]=> int(10) } i think thats fine enough

?>

UILabel with text of two different colors

In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder

enter image description here

Hope this may help someone else..!

Given a URL to a text file, what is the simplest way to read the contents of the text file?

requests package works really well for simple ui as @Andrew Mao suggested

import requests
response = requests.get('http://lib.stat.cmu.edu/datasets/boston')
data = response.text
for i, line in enumerate(data.split('\n')):
    print(f'{i}   {line}')

o/p:

0    The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic
1    prices and the demand for clean air', J. Environ. Economics & Management,
2    vol.5, 81-102, 1978.   Used in Belsley, Kuh & Welsch, 'Regression diagnostics
3    ...', Wiley, 1980.   N.B. Various transformations are used in the table on
4    pages 244-261 of the latter.
5   
6    Variables in order:

Checkout kaggle notebook on how to extract dataset/dataframe from URL

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

"implements Runnable" vs "extends Thread" in Java

Since this is a very popular topic and the good answers are spread all over and dealt with in great depth, I felt it is justifiable to compile the good answers from the others into a more concise form, so newcomers have an easy overview upfront:

  1. You usually extend a class to add or modify functionality. So, if you don't want to overwrite any Thread behavior, then use Runnable.

  2. In the same light, if you don't need to inherit thread methods, you can do without that overhead by using Runnable.

  3. Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.

  4. It is good design to separate domain logic from technical means, in that sense it is better to have a Runnable task isolating your task from your runner.

  5. You can execute the same Runnable object multiple times, a Thread object, however, can only be started once. (Maybe the reason, why Executors do accept Runnables, but not Threads.)

  6. If you develop your task as Runnable, you have all flexibility how to use it now and in the future. You can have it run concurrently via Executors but also via Thread. And you still could also use/call it non-concurrently within the same thread just as any other ordinary type/object.

  7. This makes it also easier to separate task-logic and concurrency aspects in your unit tests.

  8. If you are interested in this question, you might be also interested in the difference between Callable and Runnable.

Refresh image with a new one at the same url

<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>

Then below in some javascript

<script language='javascript'>
 function imageRefresh(img, timeout) {
    setTimeout(function() {
     var d = new Date;
     var http = img.src;
     if (http.indexOf("&d=") != -1) { http = http.split("&d=")[0]; } 

     img.src = http + '&d=' + d.getTime();
    }, timeout);
  }
</script>

And so what this does is, when the image loads, schedules it to be reloaded in 1 second. I'm using this on a page with home security cameras of varying type.

How to remove pip package after deleting it manually

packages installed using pip can be uninstalled completely using

pip uninstall <package>

refrence link

pip uninstall is likely to fail if the package is installed using python setup.py install as they do not leave behind metadata to determine what files were installed.

packages still show up in pip list if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

'git' is not recognized as an internal or external command

Just check whether the Bit Locker has enabled!. I faced a similar issue where my GIT in the cmd was working fine. But after a quick restart, it didn't work and I got the error as mentioned above.

So I had to unlock the Bit locker since I have installed GIT in the Hard drive volume (:E) which was encrypted by Bit Locker.

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

This also can happen just by having multiple supported frameworks defined in the app.config file and, forcing the app to run in a different .NET framework other than the one mentioned first in the app.config file.

And also this fires when you have both of the mentioned frameworks available in your system.

As a workaround, bring up the target framework you are going to use for the debugging up in the app.config

ex: if you trying to run in .NET 4, config file should have something similar to this,

<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>

Serializing and submitting a form with jQuery and PHP

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

Location of the android sdk has not been setup in the preferences in mac os?

I got this message after updating eclipse platform-tools and tools from the SDK Manager and then it was impossible to update the SDK path because I had an old version of ADT plugin.

Whenever you get this error message in a prompt right after eclipse loaded, you should do the following:

  1. Go to Help - Install new software
  2. Click on Available software sites
  3. Delete the link http://dl-ssl.google.com/android/eclipse/
  4. Reboot eclipse
  5. Go to Help - Install new software
  6. In the box "Work with" add http://dl-ssl.google.com/android/eclipse/ again
  7. Install ADT and accept whatever that prompts.

This is how my problem with this message got solved.

Setting the correct encoding when piping stdout in Python

First, regarding this solution:

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.

A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

Angular 2 change event on every keypress

The (keyup) event is your best bet.

Let's see why:

  1. (change) like you mentioned triggers only when the input loses focus, hence is of limited use.
  2. (keypress) triggers on key presses but doesn't trigger on certain keystrokes like the backspace.
  3. (keydown) triggers every time a key is pushed down. Hence always lags by 1 character; as it gets the element state before the keystroke was registered.
  4. (keyup) is your best bet as it triggers every time a key push event has completed, hence this also includes the most recent character.

So (keyup) is the safest to go with because it...

  • registers an event on every keystroke unlike (change) event
  • includes the keys that (keypress) ignores
  • has no lag unlike the (keydown) event

Sorting Directory.GetFiles()

A more succinct VB.Net version...is very nice. Thank you. To traverse the list in reverse order, add the reverse method...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

ValidateRequest="false" doesn't work in Asp.Net 4

I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod with [ValidateInput(false)] and just switch off request validation for a single ActionMethod, which is handy. And you don't need to make any changes to the web.config file, so you can still use the .NET 4 request validation everywhere else.

e.g.

[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
    // Do your own checking of value since it could contain XSS stuff!
    return View();
}

Load image from url

add Internet permission in manifest

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

than create methode as below,

 public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src", src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap", "returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception", e.getMessage());
        return null;
    }
}

now add this in your onCreate method,

 ImageView img_add = (ImageView) findViewById(R.id.img_add);


img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));

this is works for me.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

Query an XDocument for elements by name at any depth

We know the above is true. Jon is never wrong; real life wishes can go a little further.

<ota:OTA_AirAvailRQ
    xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
    <ota:OriginDestinationInformation>
        <ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
    </ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>

For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.

  1. You can find them by accessing with the namespace and the name like below

     doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
    
  2. You can find it by the attribute content value, like this one.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

While loop in batch

It was very useful for me i have used in the following way to add user in active directory:

:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "

cls

:while1

if %x% leq %lent% (

    dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
    echo User %Uname%%x% with DC %DcName% is created
    set /a "x = x + 1"
    goto :while1
)

endlocal

HTML table with fixed headers and a fixed column?

Not quite perfect, but it got me closer than some of the top answers here.

Two different tables, one with the header, and the other, wrapped with a div with the content

<table>
  <thead>
    <tr><th>Stuff</th><th>Second Stuff</th></tr>
  </thead>
</table>
<div style="height: 600px; overflow: auto;">
  <table>
    <tbody>
      //Table
    </tbody>
  </table>
</div>

When and why to 'return false' in JavaScript?

You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.