Programs & Examples On #Webautomation

Deals with programatically automating web browsing activities.

How can I login to a website with Python?

For HTTP things, the current choice should be: Requests- HTTP for Humans

Automatic login script for a website on windows machine?

You can use Autohotkey, download it from: http://ahkscript.org/download/

After the installation, if you want to open Gmail website when you press Alt+g, you can do something like this:

!g::
Run www.gmail.com 
return

Further reference: Hotkeys (Mouse, Joystick and Keyboard Shortcuts)

element not interactable exception in selenium web automation

Please try selecting the password field like this.

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#Passwd")));
    passwordElement.click();
  passwordElement.clear();
     passwordElement.sendKeys("123");

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

After using pngcheck and resave all my image files to *.png, the problem still.

Finally, I found the issue is about *.9.png files. Open and check all your 9-Patch files, make sure that all files have black lines as below, if don't have, just click the white place and add it, then save it.

9-Patch

How to map an array of objects in React

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

Why is my CSS style not being applied?

Reasoning for my CSS styles not being applied, even though they were being loaded:

The media attribute on the link tag which was loading the stylesheet had an incorrect value. I had inadvertently set it to 1 instead of all. This meant the browser was ignoring those styles in that linked stylesheet.

Broken:

<link rel="stylesheet" type="text/css" href="css/style.css" media="1" />

Corrected:

<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

getActivity() returns null in Fragment function

Another good solution would be using Android's LiveData with MVVM architecture. You would define a LiveData object inside your ViewModel and observe it in your fragment, and when LiveData value is changed, it would notify your observer (fragment in this case) only if your fragment is in active state, so it would be guaranteed that you would make your UI works and access the activity only when your fragment is in active state. This is one advantage that comes with LiveData

Of course when this question was first asked, there was no LiveData. I am leaving this answer here because as I see, there is still this problem and it could be helpful to someone.

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

Error: Cannot find module 'webpack'

While working on windows, I've installed webpack locally and it fixed my problem

So, on your command prompt, go to the directory of which you want to run webpack, install webpack locally (without the -g) and enjoy...

Troubleshooting "Illegal mix of collations" error in mysql

TL;DR

Either change the collation of one (or both) of the strings so that they match, or else add a COLLATE clause to your expression.


  1. What is this "collation" stuff anyway?

    As documented under Character Sets and Collations in General:

    A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

    Suppose that we have an alphabet with four letters: “A”, “B”, “a”, “b”. We give each letter a number: “A” = 0, “B” = 1, “a” = 2, “b” = 3. The letter “A” is a symbol, the number 0 is the encoding for “A”, and the combination of all four letters and their encodings is a character set.

    Suppose that we want to compare two string values, “A” and “B”. The simplest way to do this is to look at the encodings: 0 for “A” and 1 for “B”. Because 0 is less than 1, we say “A” is less than “B”. What we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): “compare the encodings.” We call this simplest of all possible collations a binary collation.

    But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters “a” and “b” as equivalent to “A” and “B”; (2) then compare the encodings. We call this a case-insensitive collation. It is a little more complex than a binary collation.

    In real life, most character sets have many characters: not just “A” and “B” but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules, not just for whether to distinguish lettercase, but also for whether to distinguish accents (an “accent” is a mark attached to a character as in German “Ö”), and for multiple-character mappings (such as the rule that “Ö” = “OE” in one of the two German collations).

    Further examples are given under Examples of the Effect of Collation.

  2. Okay, but how does MySQL decide which collation to use for a given expression?

    As documented under Collation of Expressions:

    In the great majority of statements, it is obvious what collation MySQL uses to resolve a comparison operation. For example, in the following cases, it should be clear that the collation is the collation of column charset_name:

    SELECT x FROM T ORDER BY x;
    SELECT x FROM T WHERE x = x;
    SELECT DISTINCT x FROM T;
    

    However, with multiple operands, there can be ambiguity. For example:

    SELECT x FROM T WHERE x = 'Y';
    

    Should the comparison use the collation of the column x, or of the string literal 'Y'? Both x and 'Y' have collations, so which collation takes precedence?

    Standard SQL resolves such questions using what used to be called “coercibility” rules.

    [ deletia ]

    MySQL uses coercibility values with the following rules to resolve ambiguities:

    • Use the collation with the lowest coercibility value.

    • If both sides have the same coercibility, then:

      • If both sides are Unicode, or both sides are not Unicode, it is an error.

      • If one of the sides has a Unicode character set, and another side has a non-Unicode character set, the side with Unicode character set wins, and automatic character set conversion is applied to the non-Unicode side. For example, the following statement does not return an error:

        SELECT CONCAT(utf8_column, latin1_column) FROM t1;
        

        It returns a result that has a character set of utf8 and the same collation as utf8_column. Values of latin1_column are automatically converted to utf8 before concatenating.

      • For an operation with operands from the same character set but that mix a _bin collation and a _ci or _cs collation, the _bin collation is used. This is similar to how operations that mix nonbinary and binary strings evaluate the operands as binary strings, except that it is for collations rather than data types.

  3. So what is an "illegal mix of collations"?

    An "illegal mix of collations" occurs when an expression compares two strings of different collations but of equal coercibility and the coercibility rules cannot help to resolve the conflict. It is the situation described under the third bullet-point in the above quotation.

    The particular error given in the question, Illegal mix of collations (latin1_general_cs,IMPLICIT) and (latin1_general_ci,IMPLICIT) for operation '=', tells us that there was an equality comparison between two non-Unicode strings of equal coercibility. It furthermore tells us that the collations were not given explicitly in the statement but rather were implied from the strings' sources (such as column metadata).

  4. That's all very well, but how does one resolve such errors?

    As the manual extracts quoted above suggest, this problem can be resolved in a number of ways, of which two are sensible and to be recommended:

    • Change the collation of one (or both) of the strings so that they match and there is no longer any ambiguity.

      How this can be done depends upon from where the string has come: Literal expressions take the collation specified in the collation_connection system variable; values from tables take the collation specified in their column metadata.

    • Force one string to not be coercible.

      I omitted the following quote from the above:

      MySQL assigns coercibility values as follows:

      • An explicit COLLATE clause has a coercibility of 0. (Not coercible at all.)

      • The concatenation of two strings with different collations has a coercibility of 1.

      • The collation of a column or a stored routine parameter or local variable has a coercibility of 2.

      • A “system constant” (the string returned by functions such as USER() or VERSION()) has a coercibility of 3.

      • The collation of a literal has a coercibility of 4.

      • NULL or an expression that is derived from NULL has a coercibility of 5.

      Thus simply adding a COLLATE clause to one of the strings used in the comparison will force use of that collation.

    Whilst the others would be terribly bad practice if they were deployed merely to resolve this error:

    • Force one (or both) of the strings to have some other coercibility value so that one takes precedence.

      Use of CONCAT() or CONCAT_WS() would result in a string with a coercibility of 1; and (if in a stored routine) use of parameters/local variables would result in strings with a coercibility of 2.

    • Change the encodings of one (or both) of the strings so that one is Unicode and the other is not.

      This could be done via transcoding with CONVERT(expr USING transcoding_name); or via changing the underlying character set of the data (e.g. modifying the column, changing character_set_connection for literal values, or sending them from the client in a different encoding and changing character_set_client / adding a character set introducer). Note that changing encoding will lead to other problems if some desired characters cannot be encoded in the new character set.

    • Change the encodings of one (or both) of the strings so that they are both the same and change one string to use the relevant _bin collation.

      Methods for changing encodings and collations have been detailed above. This approach would be of little use if one actually needs to apply more advanced collation rules than are offered by the _bin collation.

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 use a PHP class from another file?

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )
    )
    .setResultTransformer(Transformers.aliasToBean(entityClazz); 
    .list();

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

jQuery DataTables: control table width

I ran into a similar issue when having a div wrapped around the table.

Adding position: relative fixed it for me.


#report_container {
 float: right;
 position: relative;
 width: 100%;
}

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

How do I obtain crash-data from my Android application?

I've been using Crittercism for my Android and iOS apps -- heard about them on techcrunch. Pretty happy with them so far!

How to find specified name and its value in JSON-string from Java?

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.

Android: Proper Way to use onBackPressed() with Toast

additionally, you need to dissmis dialog before calling activity.super.onBackPressed(), otherwise you'll get "Activity has leaked.." error.

Example in my case with sweetalerdialog library:

 @Override
    public void onBackPressed() {
        //super.onBackPressed();
        SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
        progressDialog.setCancelable(false);
        progressDialog.setTitleText("Are you sure you want to exit?");
        progressDialog.setCancelText("No");
        progressDialog.setConfirmText("Yes");
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                MainActivity.super.onBackPressed();
            }
        });
        progressDialog.show();
    }

Heap space out of memory

If you are using a lot of memory and facing memory leaks, then you might want to check if you are using a large number of ArrayLists or HashMaps with many elements each.

An ArrayList is implemented as a dynamic array. The source code from Sun/Oracle shows that when a new element is inserted into a full ArrayList, a new array of 1.5 times the size of the original array is created, and the elements copied over. What this means is that you could be wasting up to 50% of the space in each ArrayList you use, unless you call its trimToSize method. Or better still, if you know the number of elements you are going to insert before hand, then call the constructor with the initial capacity as its argument.

I did not examine the source code for HashMap very carefully, but at a first glance it appears that the array length in each HashMap must be a power of two, making it another implementation of a dynamic array. Note that HashSet is essentially a wrapper around HashMap.

Spring Security redirect to previous page after successful login

You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.

CustomSuccessHandler class provides custom redirect functionality:

package com.mycompany.uomrmsweb.configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isStaff(roles)) {
            url = "/staff";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isStudent(roles)) {
            url = "/student";
        }else if (isUser(roles)) {
            url = "/home";
        } else {
            url="/Access_Denied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isStudent(List<String> roles) {
        if (roles.contains("ROLE_Student")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
            return true;
        }
        return false;
    }

    private boolean isStaff(List<String> roles) {
        if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
            return true;
        }
        return false;
    }
}

Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.

Registering CustomSuccessHandler using SecurityConfiguration class:

package com.mycompany.uomrmsweb.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
        .antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
        .antMatchers("/student/**").access("hasRole('Student')")  
                    .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
}

successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].

How to use multiple LEFT JOINs in SQL?

Yes it is possible. You need one ON for each join table.

LEFT JOIN ab
  ON ab.sht = cd.sht
LEFT JOIN aa
  ON aa.sht = cd.sht

Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

How to pip or easy_install tkinter on Windows

I came here looking for an answer to this same question and none of the answers above actually answer the question at all!

So after some investigation I found out: there is a package (for python 3.x at least):

pip3 install pytk

The problem is, it is only the python part of the equation and doesn't install the tkinter libraries in your OS, so the answer is that you can't install it completely via pip https://tkdocs.com/tutorial/install.html

Personally I find this very annoying as i'm packaging a python application to be installed via pip that uses tkinter and I was looking for a way to have pip ensure that tkinter is installed and the answer is I can't I have to instruct users to install it if it's not installed already, a very poor experience for end users who should not need to know or care what tkinter is to use my application.

Printing 1 to 1000 without loop or conditionals

#include <stdio.h>

void nothing(int);
void next(int);
void (*dispatch[2])(int) = {next, nothing};

void nothing(int x) { }
void next(int x)
{
    printf("%i\n", x);
    dispatch[x/1000](x+1);
}

int main()
{
    next(1);
    return 0;
}

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

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.

EDIT::

I am thinking of

int &x = y;

as almost equivalent of

int* __px = &y;
#define x (*__px)

where __px is a fresh name, and the #define x works only inside the block containing the declaration of x reference.

REST / SOAP endpoints for a WCF service

This post has already a very good answer by "Community wiki" and I also recommend to look at Rick Strahl's Web Blog, there are many good posts about WCF Rest like this.

I used both to get this kind of MyService-service... Then I can use the REST-interface from jQuery or SOAP from Java.

This is from my Web.Config:

<system.serviceModel>
 <services>
  <service name="MyService" behaviorConfiguration="MyServiceBehavior">
   <endpoint name="rest" address="" binding="webHttpBinding" contract="MyService" behaviorConfiguration="restBehavior"/>
   <endpoint name="mex" address="mex" binding="mexHttpBinding" contract="MyService"/>
   <endpoint name="soap" address="soap" binding="basicHttpBinding" contract="MyService"/>
  </service>
 </services>
 <behaviors>
  <serviceBehaviors>
   <behavior name="MyServiceBehavior">
    <serviceMetadata httpGetEnabled="true"/>
    <serviceDebug includeExceptionDetailInFaults="true" />
   </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
   <behavior name="restBehavior">
    <webHttp/>
   </behavior>
  </endpointBehaviors>
 </behaviors>
</system.serviceModel>

And this is my service-class (.svc-codebehind, no interfaces required):

    /// <summary> MyService documentation here ;) </summary>
[ServiceContract(Name = "MyService", Namespace = "http://myservice/", SessionMode = SessionMode.NotAllowed)]
//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]
[ServiceBehavior(Name = "MyService", Namespace = "http://myservice/")]
public class MyService
{
    [OperationContract(Name = "MyResource1")]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "MyXmlResource/{key}")]
    public string MyResource1(string key)
    {
        return "Test: " + key;
    }

    [OperationContract(Name = "MyResource2")]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource/{key}")]
    public string MyResource2(string key)
    {
        return "Test: " + key;
    }
}

Actually I use only Json or Xml but those both are here for a demo purpose. Those are GET-requests to get data. To insert data I would use method with attributes:

[OperationContract(Name = "MyResourceSave")]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource")]
public string MyResourceSave(string thing){
    //...

Check time difference in Javascript

Here is my rendition....

function get_time_difference(earlierDate, laterDate) 
{
    var oDiff = new Object();

    //  Calculate Differences
    //  -------------------------------------------------------------------  //
    var nTotalDiff = laterDate.getTime() - earlierDate.getTime();

    oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
    nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

    oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
    nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

    oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
    nTotalDiff -= oDiff.minutes * 1000 * 60;

    oDiff.seconds = Math.floor(nTotalDiff / 1000);
    //  -------------------------------------------------------------------  //

    //  Format Duration
    //  -------------------------------------------------------------------  //
    //  Format Hours
    var hourtext = '00';
    if (oDiff.days > 0){ hourtext = String(oDiff.days);}
    if (hourtext.length == 1){hourtext = '0' + hourtext};

    //  Format Minutes
    var mintext = '00';
    if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
    if (sectext.length == 1) { sectext = '0' + sectext };

    //  Set Duration
    var sDuration = hourtext + ':' + mintext + ':' + sectext;
    oDiff.duration = sDuration;
    //  -------------------------------------------------------------------  //

    return oDiff;
}

How to parse JSON array in jQuery?

You can use the Javascript eval() function to parse the JSON for you. See the JSON website for a better explanation, but you should be able to change your success function to...

var returnedObjects = eval(data);
var i = 0;
for (i = 0; i < returnedObjects.length; i++){
    console.log('Time: ' + returnedObjects[i].time);
}

...or something close.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData() {
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}

Is __init__.py not required for packages in Python 3.3+

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

UPD: If you want to use implicit namespace packages without __init__.py you just have to use find_namespace_packages() instead

Docs

What causes a Python segmentation fault?

I understand you've solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.

The way to do it, is operating system dependant. In linux, you can check with the command ulimit -s your current value and you can increase it with ulimit -s <new_value>

Try doubling the previous value and continue doubling if it does not work, until you find one that does or run out of memory.

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

jQuery map vs. each

var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});

//lets use map function
$.map(intArray, function(element, index) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2,4,5. skip the number 3.
});

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Simulate string split function in Excel formula

Highlight the cell, use Dat => Text to Columns and the DELIMITER is space. Result will appear in as many columns as the split find the space.

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

This was what I did to solve my related problem

interface Map {
  [key: string]: string | undefined
}

const HUMAN_MAP: Map = {
  draft: "Draft",
}

export const human = (str: string) => HUMAN_MAP[str] || str

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Android 6.0 multiple permissions

In a Fragment

public class Homefragment extends Fragment {
    View hfrag;
   Context context;
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

//first we must check the permissions are already granted

        hfrag = inflater.inflate(R.layout.home, container, false);
        context = getActivity();
checkAndRequestPermissions();

}




}


private boolean checkAndRequestPermissions() {
        int permissionSendMessage = ContextCompat.checkSelfPermission(context,
                Manifest.permission.READ_SMS);
        int contactpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS);

        int writepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        int callpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);

        int receivepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS);
        int locationpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);

        List<String> listPermissionsNeeded = new ArrayList<>();

        if (locationpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (contactpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
        }
        if (writepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (receivepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
        }

        if (callpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }



 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) {


        if (grantResults.length > 0) {
            for (int i = 0; i < permissions.length; i++) {


                if (permissions[i].equals(Manifest.permission.GET_ACCOUNTS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "accounts granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "storage granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.CALL_PHONE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "call granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.RECEIVE_SMS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "sms granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "location granted");

                    }
                }


            }

        }


    }
}

}

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Return background color of selected cell

The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:

Range.DisplayFormat.Interior.ColorIndex

then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use

Range.Interior.ColorIndex

as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")

Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
    Dim colorVal As Variant
    colorVal = rng.DisplayFormat.Interior.Color
    Select Case UCase(formatType)
        Case "HEX"
            iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
                           Format(Hex((colorVal \ 256) Mod 256),"00") & _
                           Format(Hex((colorVal \ 65536)),"00")
        Case "RGB"
            iColor = Format((colorVal Mod 256),"00") & ", " & _
                     Format(((colorVal \ 256) Mod 256),"00") & ", " & _
                     Format((colorVal \ 65536),"00")
        Case "IDX"
            iColor = rng.Interior.ColorIndex
        Case Else
            iColor = colorVal
    End Select
End Function

'Example use of the iColor function
Sub Get_Color_Format()
    Dim rng As Range

    For Each rng In Selection.Cells
        rng.Offset(0, 1).Value = iColor(rng, "HEX")
        rng.Offset(0, 2).Value = iColor(rng, "RGB")
    Next
End Sub

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

You would need to enable https binding on server side. IISExpress in this case. Select Properties on website project in solution explorer (not double click). In the properties pane then you need to enable SSL.

Maven error :Perhaps you are running on a JRE rather than a JDK?

I had the same error and I was missing the User variable: JAVA_HOME and the value for the SDK - "C:\Program Files\Java\jdk-9.0.1" in my case

How to check if a string contains only digits in Java

According to Oracle's Java Documentation:

private static final Pattern NUMBER_PATTERN = Pattern.compile(
        "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
        "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
        "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
        "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}

How do I make a list of data frames?

The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1, d2, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.

The other answers give plenty of detail of how to assign data frames to list elements, access them, etc. We'll cover that a little here too, but the Main Point is to say don't wait until you have a bunch of a data.frames to add them to a list. Start with the list.

The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[ and [ in accessing elements of a list?.


Lists from the start

Don't ever create d1 d2 d3, ..., dn in the first place. Create a list d with n elements.

Reading multiple files into a list of data frames

This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ... in a directory. Your goal is a list of data.frames called mydata. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")), but it's probably easier to use list.files to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$"). You can use regular expressions to match the files, read more about regular expressions in other questions if you need help there. This way you can grab all CSV files even if they don't follow a nice naming scheme. Or you can use a fancier regex pattern if you need to pick certain CSV files out from a bunch of them.

At this point, most R beginners will use a for loop, and there's nothing wrong with that, it works just fine.

my_data <- list()
for (i in seq_along(my_files)) {
    my_data[[i]] <- read.csv(file = my_files[i])
}

A more R-like way to do it is with lapply, which is a shortcut for the above

my_data <- lapply(my_files, read.csv)

Of course, substitute other data import function for read.csv as appropriate. readr::read_csv or data.table::fread will be faster, or you may also need a different function for a different file type.

Either way, it's handy to name the list elements to match the files

names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")

Splitting a data frame into a list of data frames

This is super-easy, the base function split() does it for you. You can split by a column (or columns) of the data, or by anything else you want

mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl

This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars into training, test, and validation pieces.

groups = sample(c("train", "test", "validate"),
                size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!

Simulating a list of data frames

Maybe you're simulating data, something like this:

my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))

But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate and put them in a list:

sim_list = replicate(n = 10,
                     expr = {data.frame(x = rnorm(50), y = rnorm(50))},
                     simplify = F)

In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table or dplyr it's quite easy to do things "by group" to a data frame.

I didn't put my data in a list :( I will next time, but what can I do now?

If they're an odd assortment (which is unusual), you can simply assign them:

mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...

If you have data frames named in a pattern, e.g., df1, df2, df3, and you want them in a list, you can get them if you can write a regular expression to match the names. Something like

df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.

Generally, mget is used to get multiple objects and return them in a named list. Its counterpart get is used to get a single object and return it (not in a list).

Combining a list of data frames into a single data frame

A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind for a pair of them, but for a list of data frames here are three good choices:

# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)

# data table and dplyr have nice functions for this that
#  - are much faster
#  - add id columns to identify the source
#  - fill in missing values if some data frames have more columns than others
# see their help pages for details
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)

(Similarly using cbind or dplyr::bind_cols for columns.)

To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce with merge (or some other joining function) to get them together.

Why put the data in a list?

Put similar data in lists because you want to do similar things to each data frame, and functions like lapply, sapply do.call, the purrr package, and the old plyr l*ply functions make it easy to do that. Examples of people easily doing things with lists are all over SO.

Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste and access the objects with get. Easier to debug, too.

Think of scalability. If you really only need three variables, it's fine to use d1, d2, d3. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14 to d15, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv files are in your directory.

You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).

Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

Raw SQL Query without DbSet - Entity Framework Core

You can also use QueryFirst. Like Dapper, this is totally outside EF. Unlike Dapper (or EF), you don't need to maintain the POCO, you edit your sql SQL in a real environment, and it's continually revalidated against the DB. Disclaimer: I'm the author of QueryFirst.

SQL ORDER BY multiple columns

It depends on the size of your database.

SQL is based on the SET theory: there is no order inherently used when querying a table.

So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.

If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

@BalusC is completely right, but If you still encounter this exception, it means that something you have done wrong. The most important information you will find is on the SO JSTL Tag Info page.

Basically this is a summary of what you need to do to deal with this exception.

  1. Check the servlet version in web.xml: <web-app version="2.5">

  2. Check if JSTL version is supported for this servlet version: Servlet version 2.5 uses JSTL 1.2 or Servlet version 2.4 uses JSTL 1.1

  3. Your servlet container must have the appropriate library, or you must include it manually in your application. For example: JSTL 1.2 requires jstl-1.2.jar

What to do with Tomcat 5 or 6:

You need to include appropriate jar(s) into your WEB-INF/lib directory (it will work only for your application) or to the tomcat/lib (will work globally for all applications).

The last thing is a taglib in your jsp files. For JSTL 1.2 correct one is this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Why call git branch --unset-upstream to fixup?

I had this question twice, and it was always caused by the corruption of the git cache file at my local branch. I fixed it by writing the missing commit hash into that file. I got the right commit hash from the server and ran the following command locally:

cat .git/refs/remotes/origin/feature/mybranch \
echo 1edf9668426de67ab764af138a98342787dc87fe \
>> .git/refs/remotes/origin/feature/mybranch

Client to send SOAP request and receive response

I got this simple solution here:

Sending SOAP request and receiving response in .NET 4.0 C# without using the WSDL or proxy classes:

class Program
    {
        /// <summary>
        /// Execute a Soap WebService call
        /// </summary>
        public static void Execute()
        {
            HttpWebRequest request = CreateWebRequest();
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                  <soap:Body>
                    <HelloWorld xmlns=""http://tempuri.org/"" />
                  </soap:Body>
                </soap:Envelope>");

            using (Stream stream = request.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    Console.WriteLine(soapResult);
                }
            }
        }
        /// <summary>
        /// Create a soap webrequest to [Url]
        /// </summary>
        /// <returns></returns>
        public static HttpWebRequest CreateWebRequest()
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://localhost:56405/WebService1.asmx?op=HelloWorld");
            webRequest.Headers.Add(@"SOAP:Action");
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        static void Main(string[] args)
        {
            Execute();
        }
    }

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

Countdown timer using Moment js

Here's my timer for 5 minutes:

var start = moment("5:00", "m:ss");
var seconds = start.minutes() * 60;
this.interval = setInterval(() => {
    this.timerDisplay = start.subtract(1, "second").format("m:ss");
    seconds--;
    if (seconds === 0) clearInterval(this.interval);
}, 1000);

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

Finding what branch a Git commit came from

I think someone should face the same problem that can't find out the branch, although it actually exists in one branch.

You'd better pull all first:

git pull --all

Then do the branch search:

git name-rev <SHA>

or:

git branch --contains <SHA>

How do I check if a column is empty or null in MySQL?

This statement is much cleaner and more readable for me:

select * from my_table where ISNULL(NULLIF(some_col, ''));

Pandas - Get first row value of a given column

Another way of getting the first row and preserving the index:

x = df.first('d') # Returns the first day. '3d' gives first three days.

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

Class method differences in Python: bound, unbound and static

method_two won't work because you're defining a member function but not telling it what the function is a member of. If you execute the last line you'll get:

>>> a_test.method_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

If you're defining member functions for a class the first argument must always be 'self'.

How to print all key and values from HashMap in Android?

First, there are errors in your code, ie. you are missing a semicolon and a closing parenthesis in the for loop.

Then, if you are trying to append values to the view, you should use textview.appendText(), instead of .setText().

There's a similar question here: how to change text in Android TextView

Bridged networking not working in Virtualbox under Windows 10

Virtual Box gives a lot of issues when it comes to bridge adaptor. I had the same issue with Virtual Box for windows 10. I decided to create VirtualBox Host-Only Ethernet adapter. But I again got issues while creating the host-only ethernet adaptor. I decided to switch to vmware. Vmware did not give me any issues. After installing vmware (and after changing few settings in the BIOS) and installing ubuntu on it, it automatically connected to my host machine's internet. It was able to generate it's own IP address as well and could also ping the host machine (windows machine). Hence, for me virtual box created a lot of issues whereas, vmware worked smoothly for me.

Unable to copy ~/.ssh/id_rsa.pub

add by user root this command : ssh user_to_acces@hostName -X

user_to_acces = user hostName = hostname machine

RegEx for matching UK Postcodes

This is the regex Google serves on their i18napis.appspot.com domain:

GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

Remove Rows From Data Frame where a Row matches a String

You can use the dplyr package to easily remove those particular rows.

library(dplyr)
df <- filter(df, C != "Foo")

How can I get form data with JavaScript/jQuery?

I have included the answer to also give back the object required.

function getFormData(form) {
var rawJson = form.serializeArray();
var model = {};

$.map(rawJson, function (n, i) {
    model[n['name']] = n['value'];
});

return model;
}

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I needed to change by defaultConnectionFactory to be SqlConnectionFactory instead of the default

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="<My Connection String>" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

http://blogs.msdn.com/b/davidobando/archive/2012/08/14/changing-ef-s-default-provider-from-localdb-to-sql-server.aspx

wkhtmltopdf: cannot connect to X server

It is recommended to use at least 0.12.2.1.

Starting from wkhtmltopdf >= 0.12.2 it doesn't require X server or emulation anymore. You can download new version from http://wkhtmltopdf.org/downloads.html

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

How to create a GUID in Excel?

Italian version:

=CONCATENA(
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
    DECIMALE.HEX(CASUALE.TRA(0;42949);4))

How can query string parameters be forwarded through a proxy_pass with nginx?

From the proxy_pass documentation:

A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.

Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:

location /service/ {
  # Note the trailing slash on the proxy_pass.
  # It tells nginx to replace /service/ with / when passing the request.
  proxy_pass http://apache/;
}

Or if you want to use the regex location, just include the args:

location ~* ^/service/(.*) {
  proxy_pass http://apache/$1$is_args$args;
}

How to search JSON tree with jQuery

You can use DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". With which you can query XPath queries on JSON structures. Example:

var byId = function(s) {return document.getElementById(s);},
data = {
   "people": {
      "person": [
         {
            "name": "Peter",
            "age": 43,
            "sex": "male"
         },
         {
            "name": "Zara",
            "age": 65,
            "sex": "female"
         }
      ]
   }
},
res = JSON.search( data, '//person[name="Peter"]' );

byId('name').innerHTML = res[0].name;
byId('age').innerHTML = res[0].age;
byId('sex').innerHTML = res[0].sex;

Here is a working fiddle;
http://jsfiddle.net/hbi99/NhL7p/

Error inflating class android.support.design.widget.NavigationView

For me, I encountered this error many times,

Error inflating class android.support.design.widget.NavigationView #28 and #29

The solution that works for me is that you must match your support design library and your support appcompat library.

compile 'com.android.support:appcompat-v7:23.1.1'

compile 'com.android.support:design:23.1.1'

For me they must match. :) It works for me!

Do a "git export" (like "svn export")?

It appears that this is less of an issue with Git than SVN. Git only puts a .git folder in the repository root, whereas SVN puts a .svn folder in every subdirectory. So "svn export" avoids recursive command-line magic, whereas with Git recursion is not necessary.

setTimeout in React Native

import React, {Component} from 'react';
import {StyleSheet, View, Text} from 'react-native';

class App extends Component {
  componentDidMount() {
    setTimeout(() => {
      this.props.navigation.replace('LoginScreen');
    }, 2000);
  }

  render() {
    return (
      <View style={styles.MainView}>
        <Text>React Native</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainView: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

Typing the Enter/Return key using Python and Selenium

It could be achieved using Action interface as well. In case of WebDriver -

WebElement username = driver.findElement(By.name("q"));
username.sendKeys(searchKey);
Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);
action.perform();

JPA Hibernate One-to-One relationship

I have a better way of doing this:

@Entity
public class Person {

    @OneToOne(cascade={javax.persistence.CascadeType.ALL})
    @JoinColumn(name = "`Id_OtherInfo`")
    public OtherInfo getOtherInfo() {
      return otherInfo;
    }

}

That's all

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Using Xcode 4.2 on Snow Leopard, I used the following settings to build an app that worked on both armv6 (Iphone 3G and lower) AND armv7 (everything newer than 3G including 3GS).

architectures: armv6 and armv7 (removed $(ARCHS_STANDARD_32_BIT))
build active architecture only: no
required device capabilities: armv6

do not put armv7 in required device capabilities if you want the app to run on 3G and lower as well.

Trying to start a service on boot on Android

As an additional info: BOOT_COMPLETE is sent to applications before external storage is mounted. So if application is installed to external storage it won't receive BOOT_COMPLETE broadcast message.

More details here in section Broadcast Receivers listening for "boot completed"

How can I write variables inside the tasks file in ansible

NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.

Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.


ORIGINAL ANSWER

Use set_fact before your task to set facts which seem interchangeable with variables:

- name: Set Apache URL
  set_fact:
    apache_url: 'http://example.com/apache'

- name: Download Apache
  shell: wget {{ apache_url }}

See http://docs.ansible.com/set_fact_module.html for the official word.

Is there a way to create multiline comments in Python?

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__

Count number of tables in Oracle

Select count(*) FROM all_tables where owner='schema_name'

How to flush output after each `echo` call?

what you want is the flush method. example:

echo "log to client";
 flush();

Jackson - Deserialize using generic class

public class Data<T> extends JsonDeserializer implements ContextualDeserializer {
    private Class<T> cls;
    public JsonDeserializer createContextual(DeserializationContext ctx, BeanProperty prop) throws JsonMappingException {
        cls = (Class<T>) ctx.getContextualType().getRawClass();
        return this;
    }
    ...
 }

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

How do I get the directory from a file's full path?

You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.

If you're doing other things with the path, the FileInfo class may have advantages.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

Extracting extension from filename in Python

# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs

import os.path

class LinkChecker:

    @staticmethod
    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
        else:
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
            else:
                return ""

How to measure elapsed time in Python?

In addition to %timeit in ipython you can also use %%timeit for multi-line code snippets:

In [1]: %%timeit
   ...: complex_func()
   ...: 2 + 2 == 5
   ...:
   ...:

1 s ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Also it can be used in jupyter notebook the same way, just put magic %%timeit at the beginning of cell.

How do you connect to multiple MySQL databases on a single webpage?

Try below code:

    $conn = mysql_connect("hostname","username","password");
    mysql_select_db("db1",$conn);
    mysql_select_db("db2",$conn);

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;
}

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;
}

print_r($data1);
print_r($data2);

How do I send a POST request with PHP?

Here is using just one command without cURL. Super simple.

echo file_get_contents('https://www.server.com', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'content' => http_build_query([
            'key1' => 'Hello world!', 'key2' => 'second value'
        ])
    ]
]));

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Simply just append your fields and their values to the elements:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);

is there any PHP function for open page in new tab

Use the target attribute on your anchor tag with the _blank value.

Example:

<a href="http://google.com" target="_blank">Click Me!</a>

How to both read and write a file in C#

This thread seems to answer your question : simultaneous-read-write-a-file

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

How to give your program more memory when running from Eclipse

Go to Run / Run Configurations. Select the run configuration for your program. Click on the tab "Arguments". In the "Program arguments" area, add a -Xmx argument, for example -Xmx2048m to give your program a max. of 2048 MB (2 GB) memory.

How to prevent this memory problem

Re-write your program in such a way that it does not need to store so much data in memory. I haven't looked at your code in detail, but it looks like you're storing a lot of data in a HashMap; more than fits in memory when you have a lot of records.

Convert JSON format to CSV format for MS Excel

You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361

Write variable to a file in Ansible

Based on Ramon's answer I run into an error. The problem where spaces in the JSON I tried to write I got it fixed by changing the task in the playbook to look like:

- copy:
    content: "{{ your_json_feed }}"
    dest: "/path/to/destination/file"

As of now I am not sure why this was needed. My best guess is that it had something to do with how variables are replaced in Ansible and the resulting file is parsed.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I have the same error only on the production build. In development was all right, no warning.

The problem was a comment line

ERROR

return ( // comment
  <div>foo</div>
)

OK

// comment
return (
  <div>foo</div>
)

Foreign keys in mongo?

The purpose of ForeignKey is to prevent the creation of data if the field value does not match its ForeignKey. To accomplish this in MongoDB, we use Schema middlewares that ensure the data consistency.

Please have a look at the documentation. https://mongoosejs.com/docs/middleware.html#pre

force css grid container to fill full screen of device

If you take advantage of width: 100vw; and height: 100vh;, the object with these styles applied will stretch to the full width and height of the device.

Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a * global no padding and margins so you can see the difference. Keep this in mind.

_x000D_
_x000D_
*{_x000D_
  box-sizing: border-box;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Couldn't connect to server 127.0.0.1:27017

I have mongo version 3.2.1 and had to delete the lock file from /data/db/ and after this, ran mongod and it started successfully.

>rm /data/db/mongod.lock
>mongod

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

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

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

How to create a release signed apk file using Gradle?

It is 2019 and I need to sign APK with V1 (jar signature) or V2 (full APK signature). I googled "generate signed apk gradle" and it brought me here. So I am adding my original solution here.

signingConfigs {
    release {
        ...
        v1SigningEnabled true
        v2SigningEnabled true
    }
}

My original question: How to use V1 (Jar signature) or V2 (Full APK signature) from build.gradle file

Entity Framework vs LINQ to SQL

I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables:

Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing.

How do you get total amount of RAM the computer has?

All the answers here, including the accepted one, will give you the total amount of RAM available for use. And that may have been what OP wanted.

But if you are interested in getting the amount of installed RAM, then you'll want to make a call to the GetPhysicallyInstalledSystemMemory function.

From the link, in the Remarks section:

The GetPhysicallyInstalledSystemMemory function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications.

Sample code:

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);

static void Main()
{
    long memKb;
    GetPhysicallyInstalledSystemMemory(out memKb);
    Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
}

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

Copy a table from one database to another in Postgres

If the both DBs(from & to) are password protected, in that scenario terminal won't ask for the password for both the DBs, password prompt will appear only once. So, to fix this, pass the password along with the commands.

PGPASSWORD=<password> pg_dump -h <hostIpAddress> -U <hostDbUserName> -t <hostTable> > <hostDatabase> | PGPASSWORD=<pwd> psql -h <toHostIpAddress> -d <toDatabase> -U <toDbUser>

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

How do I style a <select> dropdown with only CSS?

A native solution

Check this fiddle, and forgive me the overstyling: https://jsfiddle.net/dkellner/7ac9us70/

  • You already know all the elements
  • You can style them the usual way
  • Very little JS involved.

The trick behind: as soon as the <select> tag gets a property called "size", it will behave as a fixed-height list, and, suddenly, for some reason, allows you to style the hell out of it. Now strictly speaking, the fixed list is a side effect - but it just helps us more because we use it for the "dropped-down look".

A minimal example:

<style>

    .stylish span   {position:relative;}
    .stylish select {position:absolute;left:0px;display:none}

</style>
...
<div class="stylish">
    <label> Choose your superhero: </label>
    <span>
        <input onclick="$(this).closest('div').find('select').slideToggle(110)"><br>
        <select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">

            <optgroup label="Fantasy"></optgroup>
            <option value="1">  Gandalf        </option>
            <option value="2">  Harry Potter   </option>
            <option value="3">  Jon Snow       </option>

            <!-- ... and so on -->

        </select>
    </span>
</div>

(to keep it simple I did it with jQuery - but you can do the same without it)

Side notes

  • This solution gives you more than just a select: the value is also manually editable. Use the readonly property if you prefer the default select-restricted way.

  • To maximize styling possibilities, <optgroup> tags are not around their children, they're moved before them. It's intentional, it's visually clearer, and they're happy to work like this, don't worry.

  • Javascripts: yes I know the OP said "no Javascript" but I understood it as please don't bother with plugins, which is fine. You don't need any libraries for this one. Not even jQuery, as I said, it's only for the clarity of the example.

How to add row of data to Jtable from values received from jtextfield and comboboxes

Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

  • Set the table column headers
    1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
    2. Click on the ... button to the right of the property model. A dialog should appear.
    3. Set rows to 0, set the number of columns you want, and their names.
  • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

    1. Right-click on the button and select Events -> Action -> actionPerformed
    2. You should see code like the following auto-generated

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
      
  • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

    private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
        String data1 = something1.getSomething();
        String data2 = something2.getSomething();
        String data3 = something3.getSomething();
        String data4 = something4.getSomething();
    
        Object[] row = { data1, data2, data3, data4 };
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        model.addRow(row);
    
        // clear the entries.
    }
    

So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

How to get the first 2 letters of a string in Python?

In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

Learn about python's slice notation at the official tutorial

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Efficient way to iterate your ArrayList followed by this link. This type will improve the performance of looping during iteration

int size = list.size();

for(int j = 0; j < size; j++) {
    System.out.println(list.get(i));
}

How to hash a string into 8 digits?

Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

How to get the process ID to kill a nohup process?

If your application always uses the same port, you can kill all the processes in that port like this.

kill -9 $(lsof -t -i:8080)

Get full path of a file with FileUpload Control

It's currently true that "when you upload a file the browser will only send the source filename and not the full path" - it makes perfect sense that the server has no business knowing whether the file was in "C:\WINDOWS\" or "F:\SOMEDIR\OTHERDIR\PERSONALINFO\". The filename is always sent, and is useful both to help the user 'recognise' the content and possibly to interrogate the file extension to help determine the file type.

However I know from experience that Internet Explorer definitely used to (in older versions) send the entire path. It's difficult to find an authoritative confirmation (except this apache fileupload control doco)

Internet Explorer provides the entire path to the uploaded file and not just the base file name

Regardless, you should not use nor expect the full path to be sent by any 'modern' browser.

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

Getting time span between two times in C#?

You could use the TimeSpan constructor which takes a long for Ticks:

 TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);

Open directory dialog

You could use smth like this in WPF. I've created example method. Check below.

public string getFolderPath()
{
           // Create OpenFileDialog 
           Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

           OpenFileDialog openFileDialog = new OpenFileDialog();
           openFileDialog.Multiselect = false;

           openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
           if (openFileDialog.ShowDialog() == true)
           {
               System.IO.FileInfo fInfo = new System.IO.FileInfo(openFileDialog.FileName);
               return fInfo.DirectoryName;
           }
           return null;           
       }

How to sign in kubernetes dashboard?

Combining two answers: 49992698 and 47761914 :

# Create service account
kubectl create serviceaccount -n kube-system cluster-admin-dashboard-sa

# Bind ClusterAdmin role to the service account
kubectl create clusterrolebinding -n kube-system cluster-admin-dashboard-sa \
  --clusterrole=cluster-admin \
  --serviceaccount=kube-system:cluster-admin-dashboard-sa

# Parse the token
TOKEN=$(kubectl describe secret -n kube-system $(kubectl get secret -n kube-system | awk '/^cluster-admin-dashboard-sa-token-/{print $1}') | awk '$1=="token:"{print $2}')

Chmod 777 to a folder and all contents

If by all permissions you mean 777

Navigate to folder and

chmod -R 777 .

How to remove element from an array in JavaScript?

There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).

1) SHIFT() - Remove First Element from Original Array and Return the First Element

See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index

See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.

See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

How to make an anchor tag refer to nothing?

Make sure all your links that you want to stop have href="#!" (or anything you want, really), and then use this:

jq('body').on('click.stop_link', 'a[href="#!"]',
function(event) {
     event.preventDefault();
});

How do I get the coordinate position after using jQuery drag and drop?

I would start with something like this. Then update that to use the position plugin and that should get you where you want to be.

remove space between paragraph and unordered list

I ended up using a definition list with an unordered list inside it. It solves the issue of the unwanted space above the list without needing to change every paragraph tag.

<dl><dt>Text</dt>
<dd><ul><li>First item</li>
<li>Second item</li></ul></dd></dl>

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

CSS @font-face not working in ie

Change as per below

@font-face {
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
    src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */  
}

body nav {
     font-family: "Futura";
    font-size:1.2em;
    height: 40px;
}

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

How can I convert a zero-terminated byte array to string?

The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.

Find the location of the first zero-byte using a binary search, then slice.

You can find the zero-byte like this:

package main

import "fmt"

func FirstZero(b []byte) int {
    min, max := 0, len(b)
    for {
        if min + 1 == max { return max }
        mid := (min + max) / 2
        if b[mid] == '\000' {
            max = mid
        } else {
            min = mid
        }
    }
    return len(b)
}
func main() {
    b := []byte{1, 2, 3, 0, 0, 0}
    fmt.Println(FirstZero(b))
}

It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

How do I set response headers in Flask?

You can do this pretty easily:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Look at flask.Response and flask.make_response()

But something tells me you have another problem, because the after_request should have handled it correctly too.

EDIT
I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are:

curl -i http://127.0.0.1:5000/your/endpoint

You should see

> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT

Noting the Access-Control-Allow-Origin header.

EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem.

For example:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined

How to convert SecureString to System.String?

If you use a StringBuilder instead of a string, you can overwrite the actual value in memory when you are done. That way the password won't hang around in memory until garbage collection picks it up.

StringBuilder.Append(plainTextPassword);
StringBuilder.Clear();
// overwrite with reasonably random characters
StringBuilder.Append(New Guid().ToString());

how do I strip white space when grabbing text with jQuery?

Javascript has built in trim:

str.trim()

It doesn't work in IE8. If you have to support older browsers, use Tuxmentat's or Paul's answer.

Returning IEnumerable<T> vs. IQueryable<T>

We can use both for the same way, and they are only different in the performance.

IQueryable only executes against the database in an efficient way. It means that it creates an entire select query and only gets the related records.

For example, we want to take the top 10 customers whose name start with ‘Nimal’. In this case the select query will be generated as select top 10 * from Customer where name like ‘Nimal%’.

But if we used IEnumerable, the query would be like select * from Customer where name like ‘Nimal%’ and the top ten will be filtered at the C# coding level (it gets all the customer records from the database and passes them into C#).

Pytorch tensor to numpy array

You can use this syntax if some grads are attached with your variables.

y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

+---------------------+
| local time          |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

Oracle - How to create a materialized view with FAST REFRESH and JOINS

You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.

Boolean.parseBoolean("1") = false...?

Java is strongly typed. 0 and 1 are numbers, which is a different type than a boolean. A number will never be equal to a boolean.

How to watch for array changes?

Not sure if this covers absolutely everything, but I use something like this (especially when debugging) to detect when an array has an element added:

var array = [1,2,3,4];
array = new Proxy(array, {
    set: function(target, key, value) {
        if (Number.isInteger(Number(key)) || key === 'length') {
            debugger; //or other code
        }
        target[key] = value;
        return true;
    }
});

CSS align images and text on same line

A H4 elemental is a block display type element. You could force the H4 to have a inline display type, or simply use an inline element like P instead and style it however you require.

For reference: http://www.w3.org/TR/CSS21/visuren.html#propdef-display

So you'd change the display type of the H4 like:

<html>
<head>
   <title>test</title>
   <style type='text/css'>
     h4 { display: inline }
   </style>
  </head>
  <body>
  <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/><h4 class='liketext'>$likes</h4>
  <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/><h4 class='liketext'>$dislikes</h4>
</body>
</html>

How to check if a text field is empty or not in swift

Okay, this might be late, but in Xcode 8 I have a solution:

if(textbox.stringValue.isEmpty) {
    // some code
} else {
    //some code
}

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Swift alert view with OK and Cancel: which button tapped?

If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.

Here is an example of how to use it:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)

As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/

Swift 3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
    print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
    print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5.3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>

Only resolves the @Autowired and @Qualifer annotations, that's all, it about the Dependency Injection, There are other annotations that do the same job, I think how @Inject, but all about to resolve DI through annotations.

Be aware, even when you have declared the <context:annotation-config> element, you must declare your class how a Bean anyway, remember we have three available options

  • XML: <bean>
  • @Annotations: @Component, @Service, @Repository, @Controller
  • JavaConfig: @Configuration, @Bean

Now with

<context:component-scan>

It does two things:

  • It scans all the classes annotated with @Component, @Service, @Repository, @Controller and @Configuration and create a Bean
  • It does the same job how <context:annotation-config> does.

Therefore if you declare <context:component-scan>, is not necessary anymore declare <context:annotation-config> too.

Thats all

A common scenario was for example declare only a bean through XML and resolve the DI through annotations, for example

<bean id="serviceBeanA" class="com.something.CarServiceImpl" />
<bean id="serviceBeanB" class="com.something.PersonServiceImpl" />
<bean id="repositoryBeanA" class="com.something.CarRepository" />
<bean id="repositoryBeanB" class="com.something.PersonRepository" />

We have only declared the beans, nothing about <constructor-arg> and <property>, the DI is configured in their own classes through @Autowired. It means the Services use @Autowired for their Repositories components and the Repositories use @Autowired for the JdbcTemplate, DataSource etc..components

Textarea Auto height

This using Pure JavaScript Code.

_x000D_
_x000D_
function auto_grow(element) {_x000D_
    element.style.height = "5px";_x000D_
    element.style.height = (element.scrollHeight)+"px";_x000D_
}
_x000D_
textarea {_x000D_
    resize: none;_x000D_
    overflow: hidden;_x000D_
    min-height: 50px;_x000D_
    max-height: 100px;_x000D_
}
_x000D_
<textarea oninput="auto_grow(this)"></textarea>
_x000D_
_x000D_
_x000D_

Change an image with onclick()

To change image onclik with javascript you need to have image with id:

<p>
        <img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png" 
            style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"  />
</p>

Then you could call javascript function when image is clicked:

<script language="javascript">
    function changeImage() {

        if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png") 
        {
            document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
        }
        else 
        {
            document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
        }
    }
</script>

This code will set image to maximize.png if current img.src is set to minimize.png and vice versa. For more details visit: Change image onclick with javascript link

MySQL user DB does not have password columns - Installing MySQL on OSX

It only worked with me when I "flushed" after the commands mentioned here. Here's the full list of commands I used:

Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:

1- Click on the wamp icon > mysql > mysql console

2- write following commands, one by one

use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit

Git adding files to repo

git add puts pending files to the so called git 'index' which is local.

After that you use git commit to commit (apply) things in the index.

Then use git push [remotename] [localbranch][:remotebranch] to actually push them to a remote repository.

Anaconda / Python: Change Anaconda Prompt User Path

In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:

  • Anaconda Prompt
  • Unpin from taskbar (if pinned)
  • Close window

Right-click on "Anaconda Prompt" again.

Click "Properties"

Add the path you want your anaconda prompt to open up into in the "Start In:" section.

Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated" If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated"

Escaping single quote in PHP when inserting into MySQL

You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().

http://us3.php.net/mysql-real-escape-string

The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").

Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().

regular expression for finding 'href' value of a <a> link

Try this regex:

"href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))"

You will get more help from discussions over:

Regular expression to extract URL from an HTML link

and

Regex to get the link in href. [asp.net]

Hope its helpful.

How to add a new object (key-value pair) to an array in javascript?

New solution with ES6

Default object

object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];

Another object

object =  {'id': 5};

Object assign ES6

resultObject = {...obj, ...newobj};

Result

[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];

How do I get the last character of a string?

public char LastChar(String a){
    return a.charAt(a.length() - 1);
}

JavaScript override methods

Not unless you make all variables "public", i.e. make them members of the Function either directly or through the prototype property.

var C = function( ) {
    this.x = 10 , this.y = 20 ;
    this.modify = function( ) {
        this.x = 30 , this.y = 40 ;
        console.log("(!) C >> " + (this.x + this.y) ) ;
    } ;
} ;

var A = function( ) {
    this.modify = function( ) {
       this.x = 300 , this.y = 400 ;
       console.log("(!) A >> " + (this.x + this.y) ) ;
    } ;
} ;
    A.prototype = new C ;

var B = function( ) {
    this.modify = function( ) {
       this.x = 3000 , this.y = 4000 ;
       console.log("(!) B >> " + (this.x + this.y) ) ;
    } ;
} ;


new C( ).modify( ) ;
new A( ).modify( ) ;
new B( ).modify( ) ; 

You will notice a few changes.

Most importantly the call to the supposed "super-classes" constructor is now implicit within this line:

<name>.prototype = new C ;

Both A and B will now have individually modifiable members x and y which would not be the case if we would have written ... = C instead.

Then, x, y and modify are all "public" members so that assigning a different Function to them

 <name>.prototype.modify = function( ) { /* ... */ }

will "override" the original Function by that name.

Lastly, the call to modify cannot be done in the Function declaration because the implicit call to the "super-class" would then be executed again when we set the supposed "super-class" to the prototype property of the supposed "sub-classes".

But well, this is more or less how you would do this kind of thing in JavaScript.

HTH,

FK

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

Fixed position but relative to container

The magic is to take the screen width minus the container width and divide it by 2:

//1400px is according to container max-width (left can be also right)
.fixed {
  position: fixed;
  right: calc((100vw - 1400px)/2);
}

Note: css calc() function is almost, but not 100% supported. For most use-cases it is definitely supported enough. Click here for more details

Snippet (with a 300px container just to fit this website's widget):

_x000D_
_x000D_
.container {
  max-width: 300px;
  margin-left: auto;
  margin-right: auto;
}


.fixed {
  position: fixed;
  right: calc((100vw - 300px)/2);
}


@media screen and (max-width: 300px) {
  right: 0px;
}
_x000D_
<div style="height: 3000px">
    <div class="container">
        <button class="fixed">
            FIXED CONTENT
        </button>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum, eum? Animi quidem accusamus minima vel, dolorem suscipit quia accusantium minus harum modi commodi distinctio! Iste voluptatum earum quam voluptate culpa ad, ipsum dolorum recusandae quis atque eligendi necessitatibus magnam nisi dolores beatae qui? Perspiciatis natus cum nostrum in quod odio sapiente doloremque rerum quo dolore tenetur facere, quisquam atque accusamus fugiat eligendi, deleniti nisi minus recusandae distinctio dignissimos! Dicta quos ipsum qui pariatur at vel veritatis veniam quisquam minus modi et voluptas aliquam laborum, cumque in quo magnam sapiente. Expedita ut dolore laboriosam tempora reprehenderit vero eaque blanditiis, cumque voluptatibus, velit nemo, veniam tenetur quisquam numquam adipisci quae odio repellendus neque incidunt! Cum odio corporis soluta voluptate nesciunt, quasi nobis deleniti neque porro expedita fugiat placeat alias autem pariatur animi error, dicta veritatis atque perspiciatis inventore tempora dolor ad! Mollitia in dolorem ipsam eos porro magni perspiciatis possimus maiores, itaque facere ut. Eos culpa eum error quia incidunt repellendus quam possimus, asperiores earum ipsum molestias dicta sint fugit atque veniam dolorum illo? Officia harum sint incidunt totam, reiciendis illum eos maxime sequi neque repellat quis, expedita eum, corporis quaerat nemo qui soluta aspernatur animi. Sint ad rem numquam omnis sit.
    </div>
 </div>
_x000D_
_x000D_
_x000D_

Check for special characters (/*-+_@&$#%) in a string?

The easiest way it to use a regular expression:

Regular Expression for alphanumeric and underscores

Using regular expressions in .net:

http://www.regular-expressions.info/dotnet.html

MSDN Regular Expression

Regex.IsMatch

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

if(regexItem.IsMatch(YOUR_STRING)){..}

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How print out the contents of a HashMap<String, String> in ascending order based on its values?

the simplest and shortest code i think is this:

public void listPrinter(LinkedHashMap<String, String> caseList) {

    for(Entry entry:caseList.entrySet()) {
        System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
    }
}

What port is a given program using?

If your prefer a GUI interface CurrPorts is free and works with all versions of windows. Shows ports and what process has them open.

PHP write file from input to txt

use fwrite() instead of file_put_contents()

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

EISDIR stands for "Error, Is Directory". This means that NPM is trying to do something to a file but it is a directory. In your case, NPM is trying to "read" a file which is a directory (Line: 4). Since the operation cannot be done the error is thrown.

Three things to make sure here.

  1. Make sure the file exists. If it does not, you need to create it. (If NPM depends on any specific information in the file, you will need to have that information there).
  2. Make sure it is in fact a file and not a directory.
  3. It has the right permissions. You can change the file to have all permissions with "sudo chmod 777 FILE_NAME". (Careful: You are giving Read, Write and Execute permissions to every one on that file)

Using continue in a switch statement

It's fine, the continue statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):

while (something = get_something()) {
    if (something == A || something == B)
        do_something();
}

But if you expect break to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.

For example:

do {
    something = get_something();
} while (!(something == A || something == B));
do_something();

No Spring WebApplicationInitializer types detected on classpath

INFO: No Spring WebApplicationInitializer types detected on classpath.

Can also show up if you're using Maven with Eclipse and deploying your WAR using;

(Eclipse, Kepler, with M2)

(right-click on your project) -> Run As -> Run on Server

It's down to the generation and deletion of the m2e-wtp folder and contents.

Make sure, Maven Archive generated files under the build directory is checked.

Under: "Window -> preferences -> Maven -> Java EE Integration"

Then:

Use M2, to do your build, i.e. the usual Clean -> package or Install etc...

If "Project -> Build Automatically" is not selected. You can force the "m2e-wtp folder and contents" generation by doing;

"(right-click on your project) -> Maven -> Update Project..."

Note: make sure the "Clean Projects" option is un-selected. Otherwise the contents of target/classes will be deleted and you're back to square one.

Also,when;

"Project -> Build Automatically" is selected the "m2e-wtp folder and contents" is generated

or "Project -> Build All"

or "(right-click on project) -> Build Project"

How to read html from a url in python 3

For python 2

import urllib
some_url = 'https://docs.python.org/2/library/urllib.html'
filehandle = urllib.urlopen(some_url)
print filehandle.read()

Loop through a date range with JavaScript

var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}

Bash Templating: How to build configuration files from templates with Bash?

Taking the answer from ZyX using pure bash but with new style regex matching and indirect parameter substitution it becomes:

#!/bin/bash
regex='\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}'
while read line; do
    while [[ "$line" =~ $regex ]]; do
        param="${BASH_REMATCH[1]}"
        line=${line//${BASH_REMATCH[0]}/${!param}}
    done
    echo $line
done

Docker CE on RHEL - Requires: container-selinux >= 2.9

Installing the Selinux from the Centos repository worked for me:
1. Go to http://mirror.centos.org/centos/7/extras/x86_64/Packages/
2. Find the latest version for container-selinux i.e. container-selinux-2.21-1.el7.noarch.rpm
3. Run the following command on your terminal: $ sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/**Add_current_container-selinux_package_here**
4. The command should looks like the following $ sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.21-1.el7.noarch.rpm
Note: the container version is constantly being updated, that is why you should look for the latest version in the Centos' repository

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.

That's why each element has six DOM properties for your convenience: offsetWidth, offsetHeight, clientWidth, clientHeight, scrollWidth and scrollHeight. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).

Let's go through them in detail:

  • offsetWidth, offsetHeight: The size of the visual box incuding all borders. Can be calculated by adding width/height and paddings and borders, if the element has display: block
  • clientWidth, clientHeight: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.
  • scrollWidth, scrollHeight: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.

CSS2 Box Model

Try it out: jsFiddle


Since offsetWidth takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula

scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth

Unfortunately, we may get rounding errors, since offsetWidth and clientWidth are always integers, while the actual sizes may be fractional with zoom levels other than 1.

Note that this

scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth

does not work reliably in Chrome, since Chrome returns width with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)

Rebase array keys after unsetting elements

Just an additive.

I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."

First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.

Here's my simple, working example:

$array = array(1,2,3,4,5);

for ($i = 0; $i < count($array); $i++) {
    if($array[$i] == 1 || $array[$i] == 2) {
        array_splice($array, $i, 1);
        $i--;
    }
}

Will output:

array(3) {
    [0]=> int(3)
    [1]=> int(4)
    [2]=> int(5)
}

This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:

$files = array(
    array(
        'name' => 'example.zip',
        'size' => '100000000',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '10726556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '110726556',
        'type' => 'application/x-zip-compressed',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example2.zip',
        'size' => '12356556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
        'deleteUrl' => 'server/php/?file=example2.zip',
        'deleteType' => 'DELETE'
    )
);

for ($i = 0; $i < count($files); $i++) {
    if ($i > 0) {
        if (is_array($files[$i-1])) {
            if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
                if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
                $i--;
                array_splice($files, $i, 1);
            }
        }
    }
}

Will output:

array(1) {
    [0]=> array(6) {
            ["name"]=> string(11) "example.zip"
            ["size"]=> string(9) "110726556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
        }
    [1]=> array(6) {
            ["name"]=> string(11) "example2.zip"
            ["size"]=> string(9) "12356556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
        }
}

As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.

How to create RecyclerView with multiple view type?

if anyone is interested to see the super simple solution written in Kotlin, check the blogpost I just created. The example in the blogpost is based on creating Sectioned RecyclerView:

https://brona.blog/2020/06/sectioned-recyclerview-in-three-steps/

Launching an application (.EXE) from C#?

System.Diagnostics.Process.Start("PathToExe.exe");

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

Finding partial text in range, return an index

This formula will do the job:

=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)

you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1.

Replacement for deprecated sizeWithFont: in iOS 7?

- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
    if ([self respondsToSelector:@selector(sizeWithAttributes:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
        return ([self sizeWithAttributes:attribs]);
    }
    return ([self sizeWithFont:fontToUse]);
}

A project with an Output Type of Class Library cannot be started directly

The strange part is that I don't see a main function anywhere.

That is exactly your problem. The project merely creates a DLL. It has no executable to run.

You will need to add a second project, which is an executable which references the other project, and calls something in it.

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

How to Detect Browser Back Button event - Cross Browser

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2)
{
    //Do your code here
}

How to pass the values from one jsp page to another jsp without submit button?

You could do it in either of this ways , triggering an onclick on a form button like this,

<form id="myform" name="myform" method="post" action="demo2.jsp">
    <input type="text"  name="usnername" />
    <input type="text" name="password"/>        
    <input type="button" value="go" onclick="submitForm" />
</form>

And using javascript,

        function submitForm() {                
            document.forms[0].submit();
            return true;
        }

or you could also try Ajax to post your page

here is the link jQueryAjax

And also nice startup examples using Ajax and here

Hope this helps !!

Error 5 : Access Denied when starting windows service

check windows event log for detailed error message. I resolved the same after checking event log.

DataGridView - how to set column width?

I you dont want to do it programmatically, you can manipulate to the Column width property, which is located inside the Columns property.Once you open the column edit property you can choose which column you want to edit, scroll down to layout section of the bound column properties and change the width.

How do I install an R package from source?

From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection:

library(devtools)
install_github("twitter/AnomalyDetection")

does the trick.

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services