Programs & Examples On #Axwebbrowser

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)

Thanks

How to read a file into a variable in shell?

You can access 1 line at a time by for loop

#!/bin/bash -eu

#This script prints contents of /etc/passwd line by line

FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
    echo "Line number $((I++)) -->  $LN"
done

Copy the entire content to File (say line.sh ) ; Execute

chmod +x line.sh
./line.sh

Laravel 5 – Remove Public from URL

I found the most working solution to this problem.

Just edit your .htaccess in the root folder and write the following code. Nothing else required

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit -1
   php_value post_max_size 8M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php71"
   php_value upload_max_filesize 2M
   php_flag zlib.output_compression Off
</IfModule>

Calling a particular PHP function on form submit

If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form you can do that as :

<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
       display();
} 
?>
</body>
</html>

reducing number of plot ticks

If somebody still gets this page in search results:

fig, ax = plt.subplots()

plt.plot(...)

every_nth = 4
for n, label in enumerate(ax.xaxis.get_ticklabels()):
    if n % every_nth != 0:
        label.set_visible(False)

Export javascript data to CSV file without server interaction

See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

How to find if div with specific id exists in jQuery?

put the id you want to check in jquery is method.

var idcheck = $("selector").is("#id"); 

if(idcheck){ // if the selector contains particular id

// your code if particular Id is there

}
else{
// your code if particular Id is NOT there
}

Compare one String with multiple values in one expression

Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:

class A {

  final Set<String> strings = new HashSet<>() {{
    add("val1");
    add("val2");
  }};

  // ...

  if (strings.contains(str.toLowerCase())) {
  }

  // ...
}

It allows you to initialize you Set in-place.

How should you diagnose the error SEHException - External component has thrown an exception

Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.

You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

MySQL parameterized queries

The linked docs give the following example:

   cursor.execute ("""
         UPDATE animal SET name = %s
         WHERE name = %s
       """, ("snake", "turtle"))
   print "Number of rows updated: %d" % cursor.rowcount

So you just need to adapt this to your own code - example:

cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%s, %s, %s, %s, %s, %s)

        """, (var1, var2, var3, var4, var5, var6))

(If SongLength is numeric, you may need to use %d instead of %s).

How to change Navigation Bar color in iOS 7?

The behavior of tintColor for bars has changed in iOS 7.0. It no longer affects the bar's background.

From the documentation:

barTintColor Class Reference

The tint color to apply to the navigation bar background.

@property(nonatomic, retain) UIColor *barTintColor

Discussion
This color is made translucent by default unless you set the translucent property to NO.

Availability

Available in iOS 7.0 and later.

Declared In
UINavigationBar.h

Code

NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[ver objectAtIndex:0] intValue] >= 7) {
    // iOS 7.0 or later   
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationController.navigationBar.translucent = NO;
}else {
    // iOS 6.1 or earlier
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
}

We can also use this to check iOS Version as mention in iOS 7 UI Transition Guide

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        // iOS 6.1 or earlier
        self.navigationController.navigationBar.tintColor = [UIColor redColor];
    } else {
        // iOS 7.0 or later     
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        self.navigationController.navigationBar.translucent = NO;
    }

EDIT Using xib

enter image description here

Most simple code to populate JTable from ResultSet

The JTable constructor accepts two arguments 2dimension Object Array for the data, and String Array for the column names.

eg:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Test6 extends JFrame {

    public Test6(){     
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Mpanel m = new Mpanel();
        this.add(m,BorderLayout.CENTER);        
    }


    class Mpanel extends JPanel {       

        JTable mTable;
        private Object[][] cells = {{"Vivek",10.00},{"Vishal",20.00}};
        private String[] columnNames = { "Planet", "Radius" };
        JScrollPane mScroll;

        public Mpanel(){
            this.setSize(150,150);
            this.setComponent();
        }

        public void setComponent(){
            mTable = new JTable(cells,columnNames);
            mTable.setAutoCreateRowSorter(true);
            mScroll = new JScrollPane(mTable);

            this.add(mScroll);
        }
    }

    public static void main(String[] args){     
        new Test6().setVisible(true);
    }
}

Can I use Twitter Bootstrap and jQuery UI at the same time?

The data-role="none" is the key to make them work together. You can apply to the elements you want bootstrap to touch but jquery mobile to ignore. like this input type="text" class="form-control" placeholder="Search" data-role="none"

Efficient way to remove ALL whitespace from String?

My solution is to use Split and Join and it is surprisingly fast, in fact the fastest of the top answers here.

str = string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));

Timings for 10,000 loop on simple string with whitespace inc new lines and tabs

  • split/join = 60 milliseconds
  • linq chararray = 94 milliseconds
  • regex = 437 milliseconds

Improve this by wrapping it up in method to give it meaning, and also make it an extension method while we are at it ...

public static string RemoveWhitespace(this string str) {
    return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
}

Is it possible to apply CSS to half of a character?

Here an ugly implementation in canvas. I tried this solution, but the results are worse than I expected, so here it is anyway.

Canvas example

_x000D_
_x000D_
$("div").each(function() {_x000D_
  var CHARS = $(this).text().split('');_x000D_
  $(this).html("");_x000D_
  $.each(CHARS, function(index, char) {_x000D_
    var canvas = $("<canvas />")_x000D_
      .css("width", "40px")_x000D_
      .css("height", "40px")_x000D_
      .get(0);_x000D_
    $("div").append(canvas);_x000D_
    var ctx = canvas.getContext("2d");_x000D_
    var gradient = ctx.createLinearGradient(0, 0, 130, 0);_x000D_
    gradient.addColorStop("0", "blue");_x000D_
    gradient.addColorStop("0.5", "blue");_x000D_
    gradient.addColorStop("0.51", "red");_x000D_
    gradient.addColorStop("1.0", "red");_x000D_
    ctx.font = '130pt Calibri';_x000D_
    ctx.fillStyle = gradient;_x000D_
    ctx.fillText(char, 10, 130);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>Example Text</div>
_x000D_
_x000D_
_x000D_

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

ng is not recognized as an internal or external command

1- Install

$ npm install -g @angular/cli

2- Make sure where your ng.cmd is present.

enter image description here

3- Then add this path into variables.

enter image description here

Jackson - Deserialize using generic class

For class Data<>

ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructParametrizedType(Data.class, Data.class, Parameter.class);
Data<Parameter> dataParam = mapper.readValue(jsonString,type)

Detecting request type in PHP (GET, POST, PUT or DELETE)

It is valuable to additionally note, that PHP will populate all the $_GET parameters even when you send a proper request of other type.

Methods in above replies are completely correct, however if you want to additionaly check for GET parameters while handling POST, DELETE, PUT, etc. request, you need to check the size of $_GET array.

PuTTY scripting to log onto host

I'm not sure why previous answers haven't suggested that the original poster set up a shell profile (bashrc, .tcshrc, etc.) that executed their commands automatically every time they log in on the server side.

The quest that brought me to this page for help was a bit different -- I wanted multiple PuTTY shortcuts for the same host that would execute different startup commands.

I came up with two solutions, both of which worked:

(background) I have a folder with a variety of PuTTY shortcuts, each with the "target" property in the shortcut tab looking something like:

"C:\Program Files (x86)\PuTTY\putty.exe" -load host01

with each load corresponding to a PuTTY profile I'd saved (with different hosts in the "Session" tab). (Mostly they only differ in color schemes -- I like to have each group of related tasks share a color scheme in the terminal window, with critical tasks, like logging in as root on a production system, performed only in distinctly colored windows.)

The folder's Windows properties are set to very clean and stripped down -- it functions as a small console with shortcut icons for each of my frequent remote PuTTY and RDP connections.

(solution 1) As mentioned in other answers the -m switch is used to configure a script on the Windows side to run, the -t switch is used to stay connected, but I found that it was order-sensitive if I wanted to get it to run without exiting

What I finally got to work after a lot of trial and error was:

(shortcut target field):

"C:\Program Files (x86)\PuTTY\putty.exe" -t -load "SSH Proxy" -m "C:\Users\[me]\Documents\hello-world-bash.txt"

where the file being executed looked like

echo "Hello, World!"
echo ""
export PUTTYVAR=PROXY
/usr/local/bin/bash

(no semicolons needed)

This runs the scripted command (in my case just printing "Hello, world" on the terminal) and sets a variable that my remote session can interact with.

Note for debugging: when you run PuTTY it loads the -m script, if you edit the script you need to re-launch PuTTY instead of just restarting the session.

(solution 2) This method feels a lot cleaner, as the brains are on the remote Unix side instead of the local Windows side:

From Putty master session (not "edit settings" from existing session) load a saved config and in the SSH tab set remote command to:

export PUTTYVAR=GREEN; bash -l

Then, in my .bashrc, I have a section that performs different actions based on that variable:

case ${PUTTYVAR} in
  "")
    echo "" 
    ;;
  "PROXY")
    # this is the session config with all the SSH tunnels defined in it
    echo "";
    echo "Special window just for holding tunnels open." ;
    echo "";
    PROMPT_COMMAND='echo -ne "\033]0;Proxy Session @master01\$\007"'
    alias temppass="ssh keyholder.example.com makeonetimepassword"
    alias | grep temppass
    ;;
  "GREEN")
    echo "";
    echo "It's not easy being green"
    ;;
  "GRAY")
    echo ""
    echo "The gray ghost"
    ;;
  *)
    echo "";
    echo "Unknown PUTTYVAR setting ${PUTTYVAR}"
    ;;
esac

(solution 3, untried)

It should also be possible to have bash skip my .bashrc and execute a different startup script, by putting this in the PuTTY SSH command field:

bash --rcfile .bashrc_variant -l 

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

QUERY syntax using cell reference

Here is working code: =QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")

In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

The only things that work for for moving to the beginning and end of line are

?? "SEND ESC SEQ" OH - to move to the beginning of line
?? "SEND ESC SEQ" OF - to move to the end of line

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

Difference between a Seq and a List in Scala

As @daniel-c-sobral said, List extends the trait Seq and is an abstract class implemented by scala.collection.immutable.$colon$colon (or :: for short), but technicalities aside, mind that most of lists and seqs we use are initialized in the form of Seq(1, 2, 3) or List(1, 2, 3) which both return scala.collection.immutable.$colon$colon, hence one can write:

var x: scala.collection.immutable.$colon$colon[Int] = null
x = Seq(1, 2, 3).asInstanceOf[scala.collection.immutable.$colon$colon[Int]]
x = List(1, 2, 3).asInstanceOf[scala.collection.immutable.$colon$colon[Int]]

As a result, I'd argue than the only thing that matters are the methods you want to expose, for instance to prepend you can use :: from List that I find redundant with +: from Seq and I personally stick to Seq by default.

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

Same problem. List contained numbers of type numpy.int64 which throws a TypeError. Quick workaround for me was to

mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})

which converts list to str() and eval() function evaluates the String like a Python expression and returns the result as a list of integers in my case.

View stored procedure/function definition in MySQL

If you want to know the list of procedures you can run the following command -

show procedure status;

It will give you the list of procedures and their definers Then you can run the show create procedure <procedurename>;

Composer Update Laravel

this is command for composer update please try this...

composer self-update

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

If you need such large structures, perhaps you could utilize Memory Mapped Files. This article could prove helpful: http://www.codeproject.com/KB/recipes/MemoryMappedGenericArray.aspx

LP, Dejan

Printing a 2D array in C

...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
 printf("%<...>\t",var);
}
printf("\n");
}
...

considering that <...> would be d,e,f,s,c... etc datatype... X)

String to Binary in C#

Here's an extension function:

        public static string ToBinary(this string data, bool formatBits = false)
        {
            char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
            int index = 0;
            for (int i = 0; i < data.Length; i++)
            {
                string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                for (int j = 0; j < 8; j++)
                {
                    buffer[index] = binary[j];
                    index++;
                }
                if (formatBits && i < (data.Length - 1))
                {
                    buffer[index] = ' ';
                    index++;
                }
            }
            return new string(buffer);
        }

You can use it like:

Console.WriteLine("Testing".ToBinary());

and if you add 'true' as a parameter, it will automatically separate each binary sequence.

How to make a submit out of a <a href...>...</a> link?

Untested / could be better:

<form action="page-you're-submitting-to.html" method="POST">
    <a href="#" onclick="document.forms[0].submit();return false;"><img src="whatever.jpg" /></a>
</form>

Android Horizontal RecyclerView scroll Direction

This following code is enough

RecyclerView recyclerView;
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,true);

 recyclerView.setLayoutManager(layoutManager);

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

When should a class be Comparable and/or Comparator?

Difference between Comparator and Comparable interfaces

Comparable is used to compare itself by using with another object.

Comparator is used to compare two datatypes are objects.

MySQL: How to allow remote connection to mysql

For whom it needs it, check firewall port 3306 is open too, if your firewall service is running.

Jenkins Pipeline Wipe Out Workspace

Like @gotgenes pointed out with Jenkins Version. 2.74, the below works, not sure since when, maybe if some one can edit and add the version above

cleanWs()

With, Jenkins Version 2.16 and the Workspace Cleanup Plugin, that I have, I use

step([$class: 'WsCleanup'])

to delete the workspace.

You can view it by going to

JENKINS_URL/job/<any Pipeline project>/pipeline-syntax

Then selecting "step: General Build Step" from Sample step and then selecting "Delete workspace when build is done" from Build step

Maven Error: Could not find or load main class

The first thing i would suggest is to use the correct configuration for predefined descriptors.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        [...]
</project>

To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass> parameter.

Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

gradlew command not found?

Hi @Hayden Stites I faced the same issue, but after some tries I found it was happening because I was trying to create build in git bash , instead of CMD with admin access. If you create build with Command prompt run as administrator build will get create.

Pandas get the most frequent values of a column

Not Obvious, But Fast

f, u = pd.factorize(df.name.values)
counts = np.bincount(f)
u[counts == counts.max()]

array(['alex', 'helen'], dtype=object)

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

You could use a Collector:

import java.util.*;
import java.util.stream.Collectors;

public class Defensive {

  public static void main(String[] args) {
    Map<String, Column> original = new HashMap<>();
    original.put("foo", new Column());
    original.put("bar", new Column());

    Map<String, Column> copy = original.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                                  e -> new Column(e.getValue())));

    System.out.println(original);
    System.out.println(copy);
  }

  static class Column {
    public Column() {}
    public Column(Column c) {}
  }
}

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

How to change shape color dynamically?

circle.xml (drawable)

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

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

<size
    android:width="10dp"
    android:height="10dp"/>
</shape>

layout

<ImageView
      android:id="@+id/circleColor"
      android:layout_width="15dp"
       android:layout_height="15dp"
      android:textSize="12dp"
       android:layout_gravity="center"
       android:layout_marginLeft="10dp"
      android:background="@drawable/circle"/>

in activity

   circleColor = (ImageView) view.findViewById(R.id.circleColor);
   int color = Color.parseColor("#00FFFF");
   ((GradientDrawable)circleColor.getBackground()).setColor(color);

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

ReactJS lifecycle method inside a function Component

You can use react-pure-lifecycle to add lifecycle functions to functional components.

Example:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
  componentDidMount(props) {
    console.log('I mounted! Here are my props: ', props);
  }
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);

What are the differences between .gitignore and .gitkeep?

.gitignore

is a text file comprising a list of files in your directory that git will ignore or not add/update in the repository.

.gitkeep

Since Git removes or doesn't add empty directories to a repository, .gitkeep is sort of a hack (I don't think it's officially named as a part of Git) to keep empty directories in the repository.

Just do a touch /path/to/emptydirectory/.gitkeep to add the file, and Git will now be able to maintain this directory in the repository.

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

How can I hash a password in Java?

You could use Spring Security Crypto (has only 2 optional compile dependencies), which supports PBKDF2, BCrypt, SCrypt and Argon2 password encryption.

Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder();
String aCryptedPassword = argon2PasswordEncoder.encode("password");
boolean passwordIsValid = argon2PasswordEncoder.matches("password", aCryptedPassword);
SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder();
String sCryptedPassword = sCryptPasswordEncoder.encode("password");
boolean passwordIsValid = sCryptPasswordEncoder.matches("password", sCryptedPassword);
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String bCryptedPassword = bCryptPasswordEncoder.encode("password");
boolean passwordIsValid = bCryptPasswordEncoder.matches("password", bCryptedPassword);
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder();
String pbkdf2CryptedPassword = pbkdf2PasswordEncoder.encode("password");
boolean passwordIsValid = pbkdf2PasswordEncoder.matches("password", pbkdf2CryptedPassword);

Is it possible to use raw SQL within a Spring Repository

we can use createNativeQuery("Here Nagitive SQL Query ");

for Example :

Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

How to install and use "make" in Windows?

make is a GNU command so the only way you can get it on Windows is installing a Windows version like the one provided by GNUWin32. Anyway, there are several options for getting that:

  1. Using MinGW, be sure you have C:\MinGW\bin\mingw32-make.exe. Otherwise you're missing the mingw32-make additional utilities. Look for the link at MinGW's HowTo page to get it installed. Once you've got it, you have two choices:
  • 1.1 Copy the MinGW make executable to make.exe:

    copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe
    
  • 1.2 Create a link to the actual executable, in your PATH. In this case, if you update MinGW, the link is not deleted:

    mklink c:\bin\make.exe C:\MinGW\bin\mingw32-make.exe
    
  1. Other option is using Chocolatey. First you need to install this package manager. Once installed you simlpy need to install make:

    choco install make
    
  2. Last option is installing a Windows Subsystem for Linux (WSL), so you'll have a Linux distribution of your choice embedded in Windows 10 where you'll be able to install make, gccand all the tools you need to build C programs.

Passing additional variables from command line to make

it seems

command args overwrite environment variable

Makefile

send:
    echo $(MESSAGE1) $(MESSAGE2)

Run example

$ MESSAGE1=YES MESSAGE2=NG  make send MESSAGE2=OK
echo YES OK
YES OK

How do I create a Java string from the contents of a file?

If you're willing to use an external library, check out Apache Commons IO (200KB JAR). It contains an org.apache.commons.io.FileUtils.readFileToString() method that allows you to read an entire File into a String with one line of code.

Example:

import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;

public String readFile() throws IOException {
    File file = new File("data.txt");
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

The network path was not found

This is probably related to your database connection string or something like that.

I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).

I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)

Android "hello world" pushnotification example

Overview of gcm: You send a request to google server from your android phone. You receive a registration id as a response. You will then have to send this registration id to the server from where you wish to send notifications to the mobile. Using this registration id you can then send notification to the device.

Answer:

  1. To send a notification you send the data(message) with the registration id of the device to https://android.googleapis.com/gcm/send. (use curl in php).
  2. To receive notification and registration etc, thats all you will be requiring.
  3. You will have to store the registration id on the device as well as on server. If you use GCM.jar the registration id is stored in preferences. If you wish you can save it in your local database as well.

What is the best way to initialize a JavaScript Date to midnight?

I have made a couple prototypes to handle this for me.

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

Date.method('endOfDay', function () {
    var date = new Date(this);
    date.setHours(23, 59, 59, 999);
    return date;
});

Date.method('startOfDay', function () {
    var date = new Date(this);
    date.setHours(0, 0, 0, 0);
    return date;
});

if you dont want the saftey check, then you can just use

Date.prototype.startOfDay = function(){
  /*Method body here*/
};

Example usage:

var date = new Date($.now()); // $.now() requires jQuery
console.log('startOfDay: ' + date.startOfDay());
console.log('endOfDay: ' + date.endOfDay());

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

For Windows, you can check the official Intel MKL optimization for TensorFlow wheels that are compiled with AVX2. This solution speeds up my inference ~x3.

conda install tensorflow-mkl

How to create an HTTPS server in Node.js?

The minimal setup for an HTTPS server in Node.js would be something like this :

var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

https.createServer(httpsOptions, app).listen(4433);

If you also want to support http requests, you need to make just this small modification :

var http = require('http');
var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Go to Control Panel>>System and Security>>System>>Advance system settings>>Environment Variables then set variable value of ANDROID_HOME set it like this "C:\Users\username\AppData\Local\Android\sdk" set username as your pc name, then restart your android studio. after that you can create your AVD again than the error will gone than it will start the virtual device.

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

Mocking Extension Methods with Moq

I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.

I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.

Pycharm does not show plot

Just use

plt.show()

This command tells the system to draw the plot in Pycharm.

Example:

plt.imshow(img.reshape((28, 28)))
plt.show()

Exclude subpackages from Spring autowiring?

It seems you've done this through XML, but if you were working in new Spring best practice, your config would be in Java, and you could exclude them as so:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.example.tool",
  excludeFilters = {@ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE,
    value = {JPAConfiguration.class, SecurityConfig.class})
  })

How to split data into training/testing sets using sample function

I would use dplyr for this, makes it super simple. It does require an id variable in your data set, which is a good idea anyway, not only for creating sets but also for traceability during your project. Add it if doesn't contain already.

mtcars$id <- 1:nrow(mtcars)
train <- mtcars %>% dplyr::sample_frac(.75)
test  <- dplyr::anti_join(mtcars, train, by = 'id')

Can Android Studio be used to run standard Java projects?

Here's exactly what the setup looks like.

enter image description here

Edit Configurations > '+' > Application: enter image description here

Does java have a int.tryparse that doesn't throw an exception for bad data?

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

How to center text vertically with a large font-awesome icon?

I use icons next to text 99% of the time so I made the change globally:

.fa-2x {
  vertical-align: middle;
}

Add 3x, 4x, etc to the same definition as needed.

'LIKE ('%this%' OR '%that%') and something=else' not working

It would be nice if you could, but you can't use that syntax in SQL.

Try this:

(column1 LIKE '%this%' OR column1 LIKE '%that%') AND something = else

Note the use of brackets! You need them around the OR expression.
Without brackets, it will be parsed as A OR (B AND C),which won't give you the results you expect.

Displaying a message in iOS which has the same functionality as Toast in Android

This is how I have done in Swift 3.0. I created UIView extension and calling the self.view.showToast(message: "Message Here", duration: 3.0) and self.view.hideToast()

extension UIView{
var showToastTag :Int {return 999}

//Generic Show toast
func showToast(message : String, duration:TimeInterval) {

    let toastLabel = UILabel(frame: CGRect(x:0, y:0, width: (self.frame.size.width)-60, height:64))

    toastLabel.backgroundColor = UIColor.gray
    toastLabel.textColor = UIColor.black
    toastLabel.numberOfLines = 0
    toastLabel.layer.borderColor = UIColor.lightGray.cgColor
    toastLabel.layer.borderWidth = 1.0
    toastLabel.textAlignment = .center;
    toastLabel.font = UIFont(name: "HelveticaNeue", size: 17.0)
    toastLabel.text = message
    toastLabel.center = self.center
    toastLabel.isEnabled = true
    toastLabel.alpha = 0.99
    toastLabel.tag = showToastTag
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    self.addSubview(toastLabel)

    UIView.animate(withDuration: duration, delay: 0.1, options: .curveEaseOut, animations: {
        toastLabel.alpha = 0.95
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
}

//Generic Hide toast
func hideToast(){
    if let view = self.viewWithTag(self.showToastTag){
        view.removeFromSuperview()
    }
  }
}

How should strace be used?

Minimal runnable example

If a concept is not clear, there is a simpler example that you haven't seen that explains it.

In this case, that example is the Linux x86_64 assembly freestanding (no libc) hello world:

hello.S

.text
.global _start
_start:
    /* write */
    mov $1, %rax    /* syscall number */
    mov $1, %rdi    /* stdout */
    mov $msg, %rsi  /* buffer */
    mov $len, %rdx  /* buffer len */
    syscall

    /* exit */
    mov $60, %rax   /* exit status */
    mov $0, %rdi    /* syscall number */
    syscall
msg:
    .ascii "hello\n"
len = . - msg

GitHub upstream.

Assemble and run:

as -o hello.o hello.S
ld -o hello.out hello.o
./hello.out

Outputs the expected:

hello

Now let's use strace on that example:

env -i ASDF=qwer strace -o strace.log -s999 -v ./hello.out arg0 arg1
cat strace.log

We use:

strace.log now contains:

execve("./hello.out", ["./hello.out", "arg0", "arg1"], ["ASDF=qwer"]) = 0
write(1, "hello\n", 6)                  = 6
exit(0)                                 = ?
+++ exited with 0 +++

With such a minimal example, every single character of the output is self evident:

  • execve line: shows how strace executed hello.out, including CLI arguments and environment as documented at man execve

  • write line: shows the write system call that we made. 6 is the length of the string "hello\n".

    = 6 is the return value of the system call, which as documented in man 2 write is the number of bytes written.

  • exit line: shows the exit system call that we've made. There is no return value, since the program quit!

More complex examples

The application of strace is of course to see which system calls complex programs are actually doing to help debug / optimize your program.

Notably, most system calls that you are likely to encounter in Linux have glibc wrappers, many of them from POSIX.

Internally, the glibc wrappers use inline assembly more or less like this: How to invoke a system call via sysenter in inline assembly?

The next example you should study is a POSIX write hello world:

main.c

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(void) {
    char *msg = "hello\n";
    write(1, msg, 6);
    return 0;
}

Compile and run:

gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

This time, you will see that a bunch of system calls are being made by glibc before main to setup a nice environment for main.

This is because we are now not using a freestanding program, but rather a more common glibc program, which allows for libc functionality.

Then, at the every end, strace.log contains:

write(1, "hello\n", 6)                  = 6
exit_group(0)                           = ?
+++ exited with 0 +++

So we conclude that the write POSIX function uses, surprise!, the Linux write system call.

We also observe that return 0 leads to an exit_group call instead of exit. Ha, I didn't know about this one! This is why strace is so cool. man exit_group then explains:

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

And here is another example where I studied which system call dlopen uses: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710

Tested in Ubuntu 16.04, GCC 6.4.0, Linux kernel 4.4.0.

ActionBarActivity is deprecated

According to this video of Android Developers you should only make two changes

enter image description here

Use sed to replace all backslashes with forward slashes

For me, this replaces one backslash with a forward slash.

sed -e "s/\\\\/\//"  file.txt

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Include of non-modular header inside framework module

"Include of non-modular header inside framework module"

When you get this error the solution in some circumstances can be to simply to mark the file you're trying to import as "public" in the file inspector "Target Membership". The default is "Project", and when set this way it can cause this error. That was the case with me when trying to import Google Analytic's headers into a framework, for example.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

ASP.NET Setting width of DataBound column in GridView

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
   </Columns>
</asp:GridView>

Move a view up only when the keyboard covers an input field

Swift 3

@IBOutlet var scrollView: UIScrollView!
@IBOutlet var edtEmail: UITextField!
@IBOutlet var bottomTextfieldConstrain: NSLayoutConstraint! // <- this guy is the constrain that connect the bottom of textField to lower object or bottom of page!

 @IBAction func edtEmailEditingDidBegin(_ sender: Any) { 
        self.bottomTextfieldConstrain.constant = 200
        let point = CGPoint(x: 0, y: 200)
        scrollView.contentOffset = point
    }

@IBAction func edtEmailEditingDidEnd(_ sender: Any) { 
    self.bottomTextfieldConstrain.constant = 50
}

Bootstrap full-width text-input within inline-form

With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.

_x000D_
_x000D_
.prop-label {_x000D_
    margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
    margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
 <div class="col-12">_x000D_
  <div class="d-flex">_x000D_
   <label class="flex-fill prop-label">Label:</label>_x000D_
   <input type="text" class="flex-fill form-control prop-field">_x000D_
  </div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to reload apache configuration for a site without restarting apache?

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.

Source: https://httpd.apache.org/docs/2.4/stopping.html

How to implement a Keyword Search in MySQL?

I will explain the method i usally prefer:

First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.

1) Add a field (i usually call it "digest") where you store all the data from the table.

The field will look like:

"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word

I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.

2) Use the LIKE statement %keyword% on the digest field:

SELECT * FROM table WHERE digest LIKE %keyword%

you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:

SELECT * FROM table WHERE 
 digest LIKE %keyword1% AND 
 digest LIKE %keyword2% AND 
 digest LIKE %keyword3% ... 

In MySQL, can I copy one row to insert into the same table?

Update 07/07/2014 - The answer based on my answer, by Grim..., is a better solution as it improves on my solution below, so I'd suggest using that.

You can do this without listing all the columns with the following syntax:

CREATE TEMPORARY TABLE tmptable SELECT * FROM table WHERE primarykey = 1;
UPDATE tmptable SET primarykey = 2 WHERE primarykey = 1;
INSERT INTO table SELECT * FROM tmptable WHERE primarykey = 2;

You may decide to change the primary key in another way.

How to send an email from JavaScript

There is not a straight answer to your question as we can not send email only using javascript, but there are ways to use javascript to send emails for us:

1) using an api to and call the api via javascript to send the email for us, for example https://www.emailjs.com says that you can use such a code below to call their api after some setting:

var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: '[email protected]',
message: 'This is awesome!'
};

emailjs.send(service_id,template_id,template_params);

2) create a backend code to send an email for you, you can use any backend framework to do it for you.

3) using something like:

window.open('mailto:me@http://stackoverflow.com/');

which will open your email application, this might get into blocked popup in your browser.

In general, sending an email is a server task, so should be done in backend languages, but we can use javascript to collect the data which is needed and send it to the server or api, also we can use third parities application and open them via the browser using javascript as mentioned above.

How do I get the serial key for Visual Studio Express?

I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.

Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".

Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.

MySQL Update Inner Join tables query

The SET clause should come after the table specification.

UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

How to set dropdown arrow in spinner?

If you have a vector icon and not bitmap, you can set it this way.

<item>
    <layer-list>
        <item>
            <shape android:shape="rectangle">
                <gradient android:angle="270" android:centerColor="#65FFFFFF" android:centerY="0.2" android:endColor="#00FFFFFF" android:startColor="@color/light_gray" />
                <stroke android:width="1dp" android:color="@color/darkGray" />
                <corners android:radius="@dimen/edit_text_corner_radius" />
            </shape>
        </item>

        <item
            android:right="5dp"
            android:gravity="center|right"
            android:drawable="@drawable/gardify_spinner_dropdown_icon"/>

    </layer-list>
</item>

What precisely does 'Run as administrator' do?

UPDATE

"Run as Aministrator" is just a command, enabling the program to continue some operations that require the Administrator privileges, without displaying the UAC alerts.

Even if your user is a member of administrators group, some applications like yours need the Administrator privileges to continue running, because the application is considered not safe, if it is doing some special operation, like editing a system file or something else. This is the reason why Windows needs the Administrator privilege to execute the application and it notifies you with a UAC alert. Not all applications need an Amnistrator account to run, and some applications, like yours, need the Administrator privileges.

If you execute the application with 'run as administrator' command, you are notifying the system that your application is safe and doing something that requires the administrator privileges, with your confirm.

If you want to avoid this, just disable the UAC on Control Panel.

If you want to go further, read the question Difference between "Run as Administrator" and Windows 7 Administrators Group on Microsoft forum or this SuperUser question.

Vue.js - How to properly watch for nested data

Here's a way to write watchers for nested properties:

    new Vue({
        ...allYourOtherStuff,
        watch: {
            ['foo.bar'](newValue, oldValue) {
                // Do stuff here
            }
        }
    });

You can even use this syntax for asynchronous watchers:

    new Vue({
        ...allYourOtherStuff,
        watch: {
            async ['foo.bar'](newValue, oldValue) {
                // Do stuff here
            }
        }
    });

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Toggle Checkboxes on/off

The most basic example would be:

_x000D_
_x000D_
// get DOM elements_x000D_
var checkbox = document.querySelector('input'),_x000D_
    button = document.querySelector('button');_x000D_
_x000D_
// bind "cilck" event on the button_x000D_
button.addEventListener('click', toggleCheckbox);_x000D_
_x000D_
// when clicking the button, toggle the checkbox_x000D_
function toggleCheckbox(){_x000D_
  checkbox.checked = !checkbox.checked;_x000D_
};
_x000D_
<input type="checkbox">_x000D_
<button>Toggle checkbox</button>
_x000D_
_x000D_
_x000D_

Using grep and sed to find and replace a string

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

How to analyse the heap dump using jmap in java

Very late to answer this, but worth to take a quick look at. Just 2 minutes needed to understand in detail.

First create this java program

import java.util.ArrayList;
import java.util.List;

public class GarbageCollectionAnalysisExample{
    public static void main(String[] args) {
           List<String> l = new ArrayList<String>();
           for (int i = 0; i < 100000000; i++) {
                  l = new ArrayList<String>(); //Memory leak
                  System.out.println(l);
           }
           System.out.println("Done");
    }
}

Use jps to find the vmid (virtual machine id i.e. JVM id)

Go to CMD and type below commands >

C:\>jps
18588 Jps
17252 GarbageCollectionAnalysisExample
16048
2084 Main

17252 is the vmid which we need.

Now we will learn how to use jmap and jhat

Use jmap - to generate heap dump

From java docs about jmap “jmap prints shared object memory maps or heap memory details of a given process or core file or a remote debug server”

Use following command to generate heap dump >

C:\>jmap -dump:file=E:\heapDump.jmap 17252
Dumping heap to E:\heapDump.jmap ...
Heap dump file created

Where 17252 is the vmid (picked from above).

Heap dump will be generated in E:\heapDump.jmap

Now use Jhat Jhat is used for analyzing the garbage collection dump in java -

C:\>jhat E:\heapDump.jmap
Reading from E:\heapDump.jmap...
Dump file created Mon Nov 07 23:59:19 IST 2016
Snapshot read, resolving...
Resolving 241865 objects...
Chasing references, expect 48 dots................................................
Eliminating duplicate references................................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

By default, it will start http server on port 7000. Then we will go to http://localhost:7000/

Courtesy : JMAP, How to monitor and analyze the garbage collection in 10 ways

How to set a default Value of a UIPickerView

This is How to set a default Value of a UIPickerView

[self.picker selectRow:4 inComponent:0 animated:YES];

App.settings - the Angular way?

I found that using an APP_INITIALIZER for this doesn't work in situations where other service providers require the configuration to be injected. They can be instantiated before APP_INITIALIZER is run.

I've seen other solutions that use fetch to read a config.json file and provide it using an injection token in a parameter to platformBrowserDynamic() prior to bootstrapping the root module. But fetch isn't supported in all browsers and in particular WebView browsers for the mobile devices I target.

The following is a solution that works for me for both PWA and mobile devices (WebView). Note: I've only tested in Android so far; working from home means I don't have access to a Mac to build.

In main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { APP_CONFIG } from './app/lib/angular/injection-tokens';

function configListener() {
  try {
    const configuration = JSON.parse(this.responseText);

    // pass config to bootstrap process using an injection token
    platformBrowserDynamic([
      { provide: APP_CONFIG, useValue: configuration }
    ])
      .bootstrapModule(AppModule)
      .catch(err => console.error(err));

  } catch (error) {
    console.error(error);
  }
}

function configFailed(evt) {
  console.error('Error: retrieving config.json');
}

if (environment.production) {
  enableProdMode();
}

const request = new XMLHttpRequest();
request.addEventListener('load', configListener);
request.addEventListener('error', configFailed);
request.open('GET', './assets/config/config.json');
request.send();

This code:

  1. kicks off an async request for the config.json file.
  2. When the request completes, parses the JSON into a Javascript object
  3. provides the value using the APP_CONFIG injection token, prior to bootstrapping.
  4. And finally bootstraps the root module.

APP_CONFIG can then be injected into any additional providers in app-module.ts and it will be defined. For example, I can initialise the FIREBASE_OPTIONS injection token from @angular/fire with the following:

{
      provide: FIREBASE_OPTIONS,
      useFactory: (config: IConfig) => config.firebaseConfig,
      deps: [APP_CONFIG]
}

I find this whole thing a surprisingly difficult (and hacky) thing to do for a very common requirement. Hopefully in the near future there will be a better way, such as, support for async provider factories.

The rest of the code for completeness...

In app/lib/angular/injection-tokens.ts:

import { InjectionToken } from '@angular/core';
import { IConfig } from '../config/config';

export const APP_CONFIG = new InjectionToken<IConfig>('app-config');

and in app/lib/config/config.ts I define the interface for my JSON config file:

export interface IConfig {
    name: string;
    version: string;
    instance: string;
    firebaseConfig: {
        apiKey: string;
        // etc
    }
}

Config is stored in assets/config/config.json:

{
  "name": "my-app",
  "version": "#{Build.BuildNumber}#",
  "instance": "localdev",
  "firebaseConfig": {
    "apiKey": "abcd"
    ...
  }
}

Note: I use an Azure DevOps task to insert Build.BuildNumber and substitute other settings for different deployment environments as it is being deployed.

List supported SSL/TLS versions for a specific OpenSSL build

It's clumsy, but you can get this from the usage messages for s_client or s_server, which are #ifed at compile time to match the supported protocol versions. Use something like

 openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}' 
 # in older releases any unknown -option will work; in 1.1.0 must be exactly -help

Can't bind to 'ngModel' since it isn't a known property of 'input'

This is for the folks who use plain JavaScript instead of Type Script. In addition to referencing the forms script file on top of the page like below:

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

You should also tell the the module loader to load the ng.forms.FormsModule. After making the changes my imports property of NgModule method looked like below:

imports: [ng.platformBrowser.BrowserModule, ng.forms.FormsModule],

Printing to the console in Google Apps Script?

Even though Logger.log() is technically the correct way to output something to the console, it has a few annoyances:

  1. The output can be an unstructured mess and hard to quickly digest.
  2. You have to first run the script, then click View / Logs, which is two extra clicks (one if you remember the Ctrl+Enter keyboard shortcut).
  3. You have to insert Logger.log(playerArray), and then after debugging you'd probably want to remove Logger.log(playerArray), hence an additional 1-2 more steps.
  4. You have to click on OK to close the overlay (yet another extra click).

Instead, whenever I want to debug something I add breakpoints (click on line number) and press the Debug button (bug icon). Breakpoints work well when you are assigning something to a variable, but not so well when you are initiating a variable and want to peek inside of it at a later point, which is similar to what the op is trying to do. In this case, I would force a break condition by entering "x" (x marks the spot!) to throw a run-time error:

enter image description here

Compare with viewing Logs:

enter image description here

The Debug console contains more information and is a lot easier to read than the Logs overlay. One minor benefit with this method is that you never have to worry about polluting your code with a bunch of logging commands if keeping clean code is your thing. Even if you enter "x", you are forced to remember to remove it as part of the debugging process or else your code won't run (built-in cleanup measure, yay).

How to print Unicode character in Python?

Print a unicode character in Python:

Print a unicode character directly from python interpreter:

el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
?

Unicode character u'\u2713' is a checkmark. The interpreter prints the checkmark on the screen.

Print a unicode character from a python script:

Put this in test.py:

#!/usr/bin/python
print("here is your checkmark: " + u'\u2713');

Run it like this:

el@apollo:~$ python test.py
here is your checkmark: ?

If it doesn't show a checkmark for you, then the problem could be elsewhere, like the terminal settings or something you are doing with stream redirection.

Store unicode characters in a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

How to take column-slices of dataframe in pandas

if Data frame look like that:

group         name      count
fruit         apple     90
fruit         banana    150
fruit         orange    130
vegetable     broccoli  80
vegetable     kale      70
vegetable     lettuce   125

and OUTPUT could be like

   group    name  count
0  fruit   apple     90
1  fruit  banana    150
2  fruit  orange    130

if you use logical operator np.logical_not

df[np.logical_not(df['group'] == 'vegetable')]

more about

https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.logic.html

other logical operators

  1. logical_and(x1, x2, /[, out, where, ...]) Compute the truth value of x1 AND x2 element-wise.

  2. logical_or(x1, x2, /[, out, where, casting, ...]) Compute the truth value of x1 OR x2 element-wise.

  3. logical_not(x, /[, out, where, casting, ...]) Compute the truth value of NOT x element-wise.
  4. logical_xor(x1, x2, /[, out, where, ..]) Compute the truth value of x1 XOR x2, element-wise.

Capture Video of Android's Screen

If you developing video-camera applications, then it will be good to know the API to use for video capturing:

http://developer.android.com/training/camera/videobasics.html

(the above link only show how the video recording can be done via Intent submission, not how the actual recording is done)

https://www.linux.com/learn/tutorials/729988-android-app-development-how-to-capture-video

and if you want to write the "screenrecord" adb application yourself:

https://android.googlesource.com/platform/frameworks/av/+/android-cts-4.4_r1/cmds/screenrecord/screenrecord.cpp

And the key recording action is done here:

static status_t recordScreen(const char* fileName) {
    status_t err;

<...>

    // Configure, but do not start, muxer.
    sp<MediaMuxer> muxer = new MediaMuxer(fileName,
            MediaMuxer::OUTPUT_FORMAT_MPEG_4);
    if (gRotate) {
        muxer->setOrientationHint(90);
    }

    // Main encoder loop.
    err = runEncoder(encoder, muxer);
    if (err != NO_ERROR) {
        encoder->release();
        encoder.clear();

        return err;
    }

For Samsung phone there is additional settings ('cam_mode' hack):

CamcorderProfile.QUALITY_HIGH resolution produces green flickering video

More useful links:

How can I capture a video recording on Android?

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Can JavaScript connect with MySQL?

You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.

Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.

Dealing with float precision in Javascript

From this post: How to deal with floating point number precision in JavaScript?

You have a few options:

  • Use a special datatype for decimals, like decimal.js
  • Format your result to some fixed number of significant digits, like this: (Math.floor(y/x) * x).toFixed(2)
  • Convert all your numbers to integers

how to define variable in jquery

In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.

SQL Insert Query Using C#

static SqlConnection myConnection;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myConnection = new SqlConnection("server=localhost;" +
                                                      "Trusted_Connection=true;" +
             "database=zxc; " +
                                                      "connection timeout=30");
        try
        {

            myConnection.Open();
            label1.Text = "connect successful";

        }
        catch (SqlException ex)
        {
            label1.Text = "connect fail";
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("insert successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Incrementing a variable inside a Bash loop

minimalist

counter=0
((counter++))
echo $counter

Zabbix server is not running: the information displayed may not be current

Edit this file: sudo nano /etc/default/zabbix-server

Adjust the START property to yes:

START=yes

Then try to run Zabbix again: sudo service zabbix-server start

Getting value of selected item in list box as string

To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:

foreach(object element in listbox.SelectedItems) {
    DataRowView row = (DataRowView)element;
    MessageBox.Show(row[0]);
}

How to set Java environment path in Ubuntu

Open file /etc/environment with a text editor Add the line JAVA_HOME="[path to your java]" Save and close then run source /etc/environment

How to get TimeZone from android mobile?

All the answers here seem to suggest setting the daylite parameter to false. This is incorrect for many timezones which change abbreviated names depending on the time of the year (e.g. EST vs EDT).

The solution below will give you the correct abbreviation according to the current date for the timezone.

val tz = TimeZone.getDefault()
val isDaylite = tz.inDaylightTime(Date())
val timezone = tz.getDisplayName(isDaylite, TimeZone.SHORT)

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

    [HttpPost]
    public JsonResult ContactAdd(ContactViewModel contactViewModel)
    {
        if (ModelState.IsValid)
        {
            var job = new Job { Contact = new Contact() };

            Mapper.Map(contactViewModel, job);
            Mapper.Map(contactViewModel, job.Contact);

            _db.Jobs.Add(job);

            _db.SaveChanges();

            //you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
            //Response.StatusCode = (int)HttpStatusCode.OK;

            return Json(new { jobId = job.JobId });
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { jobId = -1 });
        }
    }

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

Copy tables from one database to another in SQL Server

If there is existing table and we wants to copy only data, we can try this query.

insert into Destination_Existing_Tbl select col1,col2 FROM Source_Tbl

Is it possible to clone html element objects in JavaScript / JQuery?

Using your code you can do something like this in plain JavaScript using the cloneNode() method:

// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );

// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );

// Append the newly created element on element p 
document.querySelector('p').appendChild( clone );

Or using jQuery clone() method (not the most efficient):

$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Are the decimal places in a CSS width respected?

Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.

This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.

This can be seen in this runnable code snippet:

_x000D_
_x000D_
body {_x000D_
  color:            white;_x000D_
  font-family:      sans-serif;_x000D_
  font-weight:      bold;_x000D_
  background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
  height:           10px;_x000D_
  background-color: orange;_x000D_
  display:          inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
  width:            0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
  width:            200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
  <p>0.5px div x 400</p>_x000D_
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
  <p>200px div x 1</p>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the request parameters in Symfony 2?

Try this, it works

$this->request = $this->container->get('request_stack')->getCurrentRequest();

Regards

How do you list the primary key of a SQL Server table?

Give this a try:

SELECT
    CONSTRAINT_CATALOG AS DataBaseName,
    CONSTRAINT_SCHEMA AS SchemaName,
    TABLE_NAME AS TableName,
    CONSTRAINT_Name AS PrimaryKey
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
WHERE CONSTRAINT_TYPE = 'Primary Key' and Table_Name = 'YourTable'

Cannot perform runtime binding on a null reference, But it is NOT a null reference

My solution to this error was that a copy and paste from another project that had a reference to @Model.Id. This particular page didn't have a model but the error line was so far off from the actual error I about never found it!

Convert Pandas Series to DateTime in a DataFrame

Some handy script:

hour = df['assess_time'].dt.hour.values[0]

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

Not this exact problem, but this is the top result when googling for almost the exact same error:

If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames registry key

  1. In regedit, locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
  2. Right-click MSV1_0, point to New, and then click Multi-String Value.
  3. In the Name column, type BackConnectionHostNames, and then press ENTER.
  4. Right-click BackConnectionHostNames, and then click Modify. In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
    • Type each host name on a separate line.

See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.

Python unexpected EOF while parsing

Check the version of your Compiler.

  1. if you are dealing with Python2 then use -

n= raw_input("Enter your Input: ")

  1. if you are dealing with python3 use -

n= input("Enter your Input: ")

Escaping double quotes in JavaScript onClick event handler

You may also want to try two backslashes (\\") to escape the escape character.

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

Array slices in C#

Arrays are enumerable, so your foo already is an IEnumerable<byte> itself. Simply use LINQ sequence methods like Take() to get what you want out of it (don't forget to include the Linq namespace with using System.Linq;):

byte[] foo = new byte[4096];

var bar = foo.Take(41);

If you really need an array from any IEnumerable<byte> value, you could use the ToArray() method for that. That does not seem to be the case here.

duplicate 'row.names' are not allowed error

This related question points out a part of the ?read.table documentation that explains your problem:

If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered.

Your header row likely has 1 fewer column than the rest of the file and so read.table assumes that the first column is the row.names (which must all be unique), not a column (which can contain duplicated values). You can fix this by using one of the following two Solutions:

  1. adding a delimiter (ie \t or ,) to the front or end of your header row in the source file, or,
  2. removing any trailing delimiters in your data

The choice will depend on the structure of your data.

Example:
Here the header row is interpreted as having one fewer column than the data because the delimiters don't match:

v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

This is how it is interpreted by default:

   v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

The first column (with no header) values are interpreted as row.names: a1 and b1. If this column contains duplicates, which is entirely possible, then you get the duplicate 'row.names' are not allowed error.

If you set row.names = FALSE, the shift doesn't happen, but you still have a mismatching number of items in the header and in the data because the delimiters don't match.

Solution 1 Add trailing delimiter to header:

v1,v2,v3,  # 4 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

Solution 2 Remove excess trailing delimiter from non-header rows:

v1,v2,v3   # 3 items
a1,a2,a3   # 3 items!!
b1,b2,b3   # 3 items!!

C# Get a control's position on a form

Oddly enough, PointToClient and PointToScreen weren't ideal for my situation. Particularly because I'm working with offscreen controls that aren't associated with any form. I found sahin's solution the most helpful, but took out recursion and eliminated the Form termination. The solution below works for any of my controls visible or not, Form-contained or not, IContainered or not. Thanks Sahim.

private static Point FindLocation(Control ctrl)
{
    Point p;
    for (p = ctrl.Location; ctrl.Parent != null; ctrl = ctrl.Parent)
        p.Offset(ctrl.Parent.Location);
    return p;
}

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.

This is illustrated best with an example:

<div my-customer name="Customer XYZ"></div>

and the directive definition:

angular.module('myModule', [])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerName: '@name'
    },
    controllerAs: 'vm',
    bindToController: true,
    controller: ['$http', function($http) {
      var vm = this;

      vm.doStuff = function(pane) {
        console.log(vm.customerName);
      };
    }],
    link: function(scope, element, attrs) {
      console.log(scope.customerName);
    }
  };
});

When the scope property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.

In very simple terms, the meaning of the binding symbols is:

someObject: '=' (two-way data binding)

someString: '@' (passed directly or through interpolation with double curly braces notation {{}})

someExpression: '&' (e.g. hideDialog())

This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.

The symbol > is not part of the syntax.

However, < does exist as part of the AngularJS component bindings and means one way binding.

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

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.

Why should I use a pointer rather than the object itself?

But I can't figure out why should we use it like this?

I will compare how it works inside the function body if you use:

Object myObject;

Inside the function, your myObject will get destroyed once this function returns. So this is useful if you don't need your object outside your function. This object will be put on current thread stack.

If you write inside function body:

 Object *myObject = new Object;

then Object class instance pointed by myObject will not get destroyed once the function ends, and allocation is on the heap.

Now if you are Java programmer, then the second example is closer to how object allocation works under java. This line: Object *myObject = new Object; is equivalent to java: Object myObject = new Object();. The difference is that under java myObject will get garbage collected, while under c++ it will not get freed, you must somewhere explicitly call `delete myObject;' otherwise you will introduce memory leaks.

Since c++11 you can use safe ways of dynamic allocations: new Object, by storing values in shared_ptr/unique_ptr.

std::shared_ptr<std::string> safe_str = make_shared<std::string>("make_shared");

// since c++14
std::unique_ptr<std::string> safe_str = make_unique<std::string>("make_shared"); 

also, objects are very often stored in containers, like map-s or vector-s, they will automatically manage a lifetime of your objects.

Parse (split) a string in C++ using string delimiter (standard C++)

You can use next function to split string:

vector<string> split(const string& str, const string& delim)
{
    vector<string> tokens;
    size_t prev = 0, pos = 0;
    do
    {
        pos = str.find(delim, prev);
        if (pos == string::npos) pos = str.length();
        string token = str.substr(prev, pos-prev);
        if (!token.empty()) tokens.push_back(token);
        prev = pos + delim.length();
    }
    while (pos < str.length() && prev < str.length());
    return tokens;
}

Get SSID when WIFI is connected

For me it only worked when I set the permission on the phone itself (settings -> app permissions -> location always on).

Simple Pivot Table to Count Unique Values

Siddharth's answer is terrific.

However, this technique can hit trouble when working with a large set of data (my computer froze up on 50,000 rows). Some less processor-intensive methods:

Single uniqueness check

  1. Sort by the two columns (A, B in this example)
  2. Use a formula that looks at less data

    =IF(SUMPRODUCT(($A2:$A3=A2)*($B2:$B3=B2))>1,0,1) 
    

Multiple uniqueness checks

If you need to check uniqueness in different columns, you can't rely on two sorts.

Instead,

  1. Sort single column (A)
  2. Add formula covering the maximum number of records for each grouping. If ABC might have 50 rows, the formula will be

    =IF(SUMPRODUCT(($A2:$A49=A2)*($B2:$B49=B2))>1,0,1)
    

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

Setting onSubmit in React.js

I'd also suggest moving the event handler outside render.

var OnSubmitTest = React.createClass({

  submit: function(e){
    e.preventDefault();
    alert('it works!');
  }

  render: function() {
    return (
      <form onSubmit={this.submit}>
        <button>Click me</button>
      </form>
    );
  }
});

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

How can I close a browser window without receiving the "Do you want to close this window" prompt?

This will work :

<script type="text/javascript">
function closeWindowNoPrompt()
{
window.open('', '_parent', '');
window.close();
}
</script>

Only allow specific characters in textbox

You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.

You can set the Handled property of the event args to stop handling the event.

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Refresh Excel VBA Function Results

The Application.Volatile doesn't work for recalculating a formula with my own function inside. I use the following function: Application.CalculateFull

How can I convert ArrayList<Object> to ArrayList<String>?

You can use wildcard to do this as following

ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I got some errors that the software was unavailable from the update server when trying

xcode-select --install

What fixed it for me was going here https://developer.apple.com/download/more/ and downloading Command Line Tools (macOS 10.14) for Xcode 10 and then installing it manually.

After that, the errors should be gone when you open up a new terminal.

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

Capturing image from webcam in java?

I have used JMF on a videoconference application and it worked well on two laptops: one with integrated webcam and another with an old USB webcam. It requires JMF being installed and configured before-hand, but once you're done you can access the hardware via Java code fairly easily.

What is the difference between resource and endpoint?

According https://apiblueprint.org/documentation/examples/13-named-endpoints.html is a resource a "general" place of storage of the given entity - e.g. /customers/30654/orders, whereas an endpoint is the concrete action (HTTP Method) over the given resource. So one resource can have multiple endpoints.

Git pull command from different user

Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.

Posting this answer here since I think this is the intended question

So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.

How to pull from the repo without using the credentials of the old user ?

You edit the .git/config file of your repo.

and change

url = https://<old-username>@github.com/abc/repo.git/

to

url = https://<new-username>@github.com/abc/repo.git/

After saving the changes, from now onwards git pull will pull data while using credentials of the new user.

I hope this helps anyone with a similar problem

Creating a div element in jQuery

Create an in-memory DIV

$("<div/>");

Add click handlers, styles etc - and finally insert into DOM into a target element selector:

_x000D_
_x000D_
$("<div/>", {_x000D_
_x000D_
  // PROPERTIES HERE_x000D_
  _x000D_
  text: "Click me",_x000D_
  id: "example",_x000D_
  "class": "myDiv",      // ('class' is still better in quotes)_x000D_
  css: {           _x000D_
    color: "red",_x000D_
    fontSize: "3em",_x000D_
    cursor: "pointer"_x000D_
  },_x000D_
  on: {_x000D_
    mouseenter: function() {_x000D_
      console.log("PLEASE... "+ $(this).text());_x000D_
    },_x000D_
    click: function() {_x000D_
      console.log("Hy! My ID is: "+ this.id);_x000D_
    }_x000D_
  },_x000D_
  append: "<i>!!</i>",_x000D_
  appendTo: "body"      // Finally, append to any selector_x000D_
  _x000D_
}); // << no need to do anything here as we defined the properties internally.
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.

How is a JavaScript hash map implemented?

I was running into the problem where i had the json with some common keys. I wanted to group all the values having the same key. After some surfing I found hashmap package. Which is really helpful.

To group the element with the same key, I used multi(key:*, value:*, key2:*, value2:*, ...).

This package is somewhat similar to Java Hashmap collection, but not as powerful as Java Hashmap.

Get the full URL in PHP

    public static function getCurrentUrl($withQuery = true)
    {
        $protocol = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        or (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
        or (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
        or (isset($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443) ? 'https' : 'http';

        $uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        return $withQuery ? $uri : str_replace('?' . $_SERVER['QUERY_STRING'], '', $uri);
    }

How do I create and access the global variables in Groovy?

def iamnotglobal=100 // This will not be accessible inside the function

iamglobal=200 // this is global and will be even available inside the 

def func()
{
    log.info "My value is 200. Here you see " + iamglobal
    iamglobal=400
    //log.info "if you uncomment me you will get error. Since iamnotglobal cant be printed here " + iamnotglobal
}
def func2()
{
   log.info "My value was changed inside func to 400 . Here it is = " + iamglobal
}
func()
func2()

here iamglobal variable is a global variable used by func and then again available to func2

if you declare variable with def it will be local, if you don't use def its global

Convert a python dict to a string and back

If you care about the speed use ujson (UltraJSON), which has the same API as json:

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

Making TextView scrollable on Android

Use it like this

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:maxLines = "AN_INTEGER"
    android:scrollbars = "vertical"
/>

How to write character & in android strings.xml

For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0

Clicking HTML 5 Video element to play, pause video, breaks play button

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

When to use reinterpret_cast?

Here is a variant of Avi Ginsburg's program which clearly illustrates the property of reinterpret_cast mentioned by Chris Luengo, flodin, and cmdLP: that the compiler treats the pointed-to memory location as if it were an object of the new type:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

class A
{
public:
    int i;
};

class B : public A
{
public:
    virtual void f() {}
};

int main()
{
    string s;
    B b;
    b.i = 0;
    A* as = static_cast<A*>(&b);
    A* ar = reinterpret_cast<A*>(&b);
    B* c = reinterpret_cast<B*>(ar);
    
    cout << "as->i = " << hex << setfill('0')  << as->i << "\n";
    cout << "ar->i = " << ar->i << "\n";
    cout << "b.i   = " << b.i << "\n";
    cout << "c->i  = " << c->i << "\n";
    cout << "\n";
    cout << "&(as->i) = " << &(as->i) << "\n";
    cout << "&(ar->i) = " << &(ar->i) << "\n";
    cout << "&(b.i) = " << &(b.i) << "\n";
    cout << "&(c->i) = " << &(c->i) << "\n";
    cout << "\n";
    cout << "&b = " << &b << "\n";
    cout << "as = " << as << "\n";
    cout << "ar = " << ar << "\n";
    cout << "c  = " << c  << "\n";
    
    cout << "Press ENTER to exit.\n";
    getline(cin,s);
}

Which results in output like this:

as->i = 0
ar->i = 50ee64
b.i   = 0
c->i  = 0

&(as->i) = 00EFF978
&(ar->i) = 00EFF974
&(b.i)   = 00EFF978
&(c->i)  = 00EFF978

&b = 00EFF974
as = 00EFF978
ar = 00EFF974
c  = 00EFF974
Press ENTER to exit.

It can be seen that the B object is built in memory as B-specific data first, followed by the embedded A object. The static_cast correctly returns the address of the embedded A object, and the pointer created by static_cast correctly gives the value of the data field. The pointer generated by reinterpret_cast treats b's memory location as if it were a plain A object, and so when the pointer tries to get the data field it returns some B-specific data as if it were the contents of this field.

One use of reinterpret_cast is to convert a pointer to an unsigned integer (when pointers and unsigned integers are the same size):

int i; unsigned int u = reinterpret_cast<unsigned int>(&i);

How to copy a dictionary and only edit the copy

When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copy

dict2 = copy.deepcopy(dict1)

Taking multiple inputs from user in python

Split function will split the input data according to whitespace.

data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))

name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

pass parameter by link_to ruby on rails

Maybe try this:

<%= link_to "Add to cart", 
            :controller => "car", 
            :action => "add_to_cart", 
            :car => car.attributes %>

But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

Why use $_SERVER['PHP_SELF'] instead of ""

There is no difference. The $_SERVER['PHP_SELF'] just makes the execution time slower by like 0.000001 second.

PHP: If internet explorer 6, 7, 8 , or 9

A version that will continue to work with both IE10 and IE11:

preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
  preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}

if (count($matches)>1){
  //Then we're using IE
  $version = $matches[1];

  switch(true){
    case ($version<=8):
      //IE 8 or under!
      break;

    case ($version==9 || $version==10):
      //IE9 & IE10!
      break;

    case ($version==11):
      //Version 11!
      break;

    default:
      //You get the idea
  }
}

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

How to sort strings in JavaScript

since strings can be compared directly in javascript, this will do the job

list.sort(function (a, b) {
    return a.attr > b.attr ? 1: -1;
})

the subtraction in a sort function is used only when non alphabetical (numerical) sort is desired and of course it does not work with strings

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Validating parameters to a Bash script

The sh solution by Brian Campbell, while noble and well executed, has a few problems, so I thought I'd provide my own bash solution.

The problems with the sh one:

  • The tilde in ~/foo doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read statement or quoted in the rm statement. Which means you'll get No such file or directory errors.
  • Forking off grep and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.
  • I also noticed a few quoting issues, for instance around a parameter expansion in his echo.
  • While rare, the solution cannot cope with filenames that contain newlines. (Almost no solution in sh can cope with them - which is why I almost always prefer bash, it's far more bulletproof & harder to exploit when used well).

While, yes, using /bin/sh for your hashbang means you must avoid bashisms at all costs, you can use all the bashisms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash at the top.

So, here's a bash solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.

[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
  1. Notice the quotes around $1 in the rm statement!
  2. The -d check will also fail if $1 is empty, so that's two checks in one.
  3. I avoided regular expressions for a reason. If you must use =~ in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

Py_Initialize fails - unable to load the file system codec

In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH, they all work fine

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

Magento - How to add/remove links on my account navigation?

Most of the above work, but for me, this was the easiest.

Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.

http://www.magentocommerce.com/magento-connect/frontend-links-manager.html

Unable to establish SSL connection, how do I fix my SSL cert?

The problem I faced was in client server environment. The client was trying to connect over http port 80 but wanted the server proxy to redirect the request to some other port and data was https. So basically asking secure information over http. So server should have http port 80 as well as the port client is requesting, let's say urla:1111\subB.

The issue was server was hosting this on some other port e,g urla:2222\subB; so the client was trying to access over 1111 was receiving the error. Correcting the port number should fix this issue. In this case to port number 1111.

Split Strings into words with multiple word boundary delimiters

I like pprzemek's solution because it does not assume that the delimiters are single characters and it doesn't try to leverage a regex (which would not work well if the number of separators got to be crazy long).

Here's a more readable version of the above solution for clarity:

def split_string_on_multiple_separators(input_string, separators):
    buffer = [input_string]
    for sep in separators:
        strings = buffer
        buffer = []  # reset the buffer
        for s in strings:
            buffer = buffer + s.split(sep)

    return buffer

How to create a JavaScript callback for knowing when an image is loaded?

If the goal is to style the img after browser has rendered image, you should:

const img = new Image();
img.src = 'path/to/img.jpg';

img.decode().then(() => {
/* set styles */
/* add img to DOM */ 
});

because the browser first loads the compressed version of image, then decodes it, finally paints it. since there is no event for paint you should run your logic after browser has decoded the img tag.

When to favor ng-if vs. ng-show/ng-hide?

From my experience:

1) If your page has a toggle that uses ng-if/ng-show to show/hide something, ng-if causes more of a browser delay (slower). For example: if you have a button used to toggle between two views, ng-show seems to be faster.

2) ng-if will create/destroy scope when it evaluates to true/false. If you have a controller attached to the ng-if, that controller code will get executed every time the ng-if evaluates to true. If you are using ng-show, the controller code only gets executed once. So if you have a button that toggles between multiple views, using ng-if and ng-show would make a huge difference in how you write your controller code.

How to use a Bootstrap 3 glyphicon in an html select

To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.

<select class="form-control glyphicon">
    <option value="">&#x2212; &#x2212; &#x2212; Hello</option>
    <option value="glyphicon-list-alt">&#xe032; Text</option>
</select>

Here's a list of the icons with their unicode:

http://glyphicons.bootstrapcheatsheets.com/

How to know Hive and Hadoop versions from command prompt?

another way is to make a REST call, if you have WebHCat (part of Hive project) installed, is

curl -i http://172.22.123.63:50111/templeton/v1/version/hive?user.name=foo

which will come back with JSON like

{"module":"hive","version":"1.2.1.2.3.0.0-2458"}

WebHCat docs has some details

SQL use CASE statement in WHERE IN clause

 select  * from Tran_LibraryBooksTrans LBT  left join
 Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN' AND
 LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
 LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 ELSE 0 END`enter code here`select  * from Tran_LibraryBooksTrans LBT 
 left join Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
 LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
 1 ELSE 0 END

How can I refresh a page with jQuery?

You can use JavaScript location.reload() method. This method accepts a boolean parameter. true or false. If the parameter is true; the page always reloaded from the server. If it is false; which is the default or with empty parameter browser reload the page from it's cache.

With true parameter

<button type="button" onclick="location.reload(true);">Reload page</button>

With default/ false parameter

 <button type="button" onclick="location.reload();">Reload page</button>

Using jquery

<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
    $('#Reloadpage').click(function() {
        location.reload();
    }); 
</script>

Django: How can I call a view function from template?

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">
</form>

inside view.py:

import mypythoncode

def request_page(request):
  if(request.GET.get('mybtn')):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2