Programs & Examples On #Login page

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

How do I enable logging for Spring Security?

By default Spring Security redirects user to the URL that he originally requested (/Load.do in your case) after login.

You can set always-use-default-target to true to disable this behavior:

 <security:http auto-config="true">

    <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
    <security:form-login login-page="/Load.do"
        default-target-url="/Admin.do?m=loadAdminMain"
        authentication-failure-url="/Load.do?error=true"
        always-use-default-target = "true"
        username-parameter="j_username"
        password-parameter="j_password"
        login-processing-url="/j_spring_security_check"/>
    <security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

There is a typo error in define arguments, change DB_HOST into DB_SERVER and DB_USER into DB_USERNAME:

<?php

    define("DB_SERVER", "localhost");
    define("DB_USERNAME", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "databasename");
    $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

?>

Using $window or $location to Redirect in AngularJS

It seems that for full page reload $window.location.href is the preferred way.

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

https://docs.angularjs.org/guide/$location

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

It looks like the CSRF (Cross Site Request Forgery) protection in your Spring application is enabled. Actually it is enabled by default.

According to spring.io:

When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

So to disable it:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

If you want though to keep CSRF protection enabled then you have to include in your form the csrftoken. You can do it like this:

<form .... >
  ....other fields here....
  <input type="hidden"  name="${_csrf.parameterName}"   value="${_csrf.token}"/>
</form>

You can even include the CSRF token in the form's action:

<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">

An Authentication object was not found in the SecurityContext - Spring 3.2.2

The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

try {
    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
    ctx.setAuthentication(event.getAuthentication());

    //Do what ever you want to do

} finally {
    SecurityContextHolder.clearContext();
}

Update:

Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

My Application Could not open ServletContext resource

The file name u used spring-dispatcher-servlet.xml
kindly check in web.xml
servlet name as spring-dispatcher at both tag  <servlet> and <servlet-mapping>
in your case it should be

<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class></servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

In my case, this was caused by custom manifest entries added by the maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>

FAIL - Application at context path /Hello could not be started

1st Reason could be the ending tag of your application's web.xml file which could not have been closed properly.

web.xml might be ending with <web-app>, but must end with </web-app>

2nd Reason which worked in my case could be the lib folder of your tomcat must contain the supporting jar file of your database.

ojdbc on case of Oracle or sqljdbc in case of SqlServer

How do I make jQuery wait for an Ajax call to finish before it returns?

It should wait until get request completed. After that I'll return get request body from where function is called.

function foo() {
    var jqXHR = $.ajax({
        url: url,
        type: 'GET',
        async: false,
    });
    return JSON.parse(jqXHR.responseText);  
}

Regular expression for checking if capital letters are found consecutively in a string?

If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.

SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';

How to set border on jPanel?

Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:

public GoBoard(){
    this.linien = 9;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

public GoBoard(int pLinien){
    this.linien = pLinien;

}

If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:

// default constructor
public GoBoard(){
    this(9);  // calls other constructor
}

public GoBoard(int pLinien){
    this.linien = pLinien;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,

class GoTest {
   private static final int JB_WIDTH = 400;
   private static final int JB_HEIGHT = JB_WIDTH;

   private static void initGui() {
      JFrame frame = new JFrame("GoBoard");
      GoBoard jboard = new GoBoard();
      jboard.setLayout(new BorderLayout(10, 10));

      JPanel holdingPanel = new JPanel(new BorderLayout());
      int eb = 20;
      holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
      holdingPanel.add(jboard, BorderLayout.CENTER);
      frame.add(holdingPanel, BorderLayout.CENTER);
      jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //!! frame.setSize(400, 400);
      frame.pack();
      frame.setVisible(true);
   }

// .... etc....

C++ string to double conversion

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

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999 (which is double, whitespace was automatically stripped)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double

As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long

Python 3 print without parenthesis

Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.

However, print without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:

Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: var = 'Hello world'

In [2]: /print var
Hello world

And if you turn on autocall, you won't even need to type the slash:

In [3]: %autocall
Automatic calling is: Smart

In [4]: print var
------> print(var)
Hello world

Using grep to search for hex strings in a file

This seems to work for me:

LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>

short form:

LANG=C grep -obUaP "<\x-hex pattern>" <file>

Example:

LANG=C grep -obUaP "\x01\x02" /bin/grep

Output (cygwin binary):

153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>

So you can grep this again to extract offsets. But don't forget to use binary mode again.

Note: LANG=C is needed to avoid utf8 encoding issues.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

When a search engine spider finds 301 status code in the response header of a webpage, it understands that this webpage no longer exists, it searches for location header in response pick the new URL and replace the indexed URL with the new one and also transfer pagerank.

So search engine refreshes all indexed URL that no longer exist (301 found) with the new URL, this will retain your old webpage traffic, pagerank and divert it to the new one (you will not lose you traffic of old webpage).

Browser: if a browser finds 301 status code then it caches the mapping of the old URL with the new URL, the client/browser will not attempt to request the original location but use the new location from now on unless the cache is cleared.

enter image description here

When a search engine spider finds 302 status for a webpage, it will only redirect temporarily to the new location and crawl both of the pages. The old webpage URL still exists in the search engine database and it always attempts to request the old location and crawl it. The client/browser will still attempt to request the original location.

enter image description here

Read more about how to implement it in asp.net c# and what is the impact on search engines - http://www.dotnetbull.com/2013/08/301-permanent-vs-302-temporary-status-code-aspnet-csharp-Implementation.html

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Windows 10:

Android Studio -> File -> Other Settings -> Default Project Structure... -> JDK location:

copy string shown, such as:

C:\Program Files\Android\Android Studio\jre

In file locator directory window, right-click on "This PC" ->

Properties -> Advanced System Settings -> Environment Variables... -> System Variables

click on the New... button under System Variables, then type and paste respectively:

.......Variable name: JAVA_HOME

.......Variable value: C:\Program Files\Android\Android Studio\jre

and hit OK buttons to close out.

Some installations may require JRE_HOME to be set as well, the same way.

To check, open a NEW black console window, then type echo %JAVA_HOME% . You should get back the full path you typed into the system variable. Windows 10 seems to support spaces in the filename paths for system variables very well, and does not seem to need ~tilde eliding.

What does the "On Error Resume Next" statement do?

On Error Resume Next means that On Error, It will resume to the next line to resume.

e.g. if you try the Try block, That will stop the script if a error occurred

Unable to add window -- token null is not valid; is your activity running?

You should not put the windowManager.addView in onCreate

Try to call the windowManager.addView after onWindowFocusChanged and the status of hasFoucus is true.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    //code here
    //that you can add a flag that you can call windowManager.addView now.
}

Typescript - multidimensional array initialization

If you want to do it typed:

class Something {

  areas: Area[][];

  constructor() {
    this.areas = new Array<Array<Area>>();
    for (let y = 0; y <= 100; y++) {
      let row:Area[]  = new Array<Area>();      
      for (let x = 0; x <=100; x++){
        row.push(new Area(x, y));
      }
      this.areas.push(row);
    }
  }
}

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Replacing .NET WebBrowser control with a better browser, like Chrome?

I've been testing alternatives to C# Web browser component for few days now and here is my list:

1. Using newer IE versions 8,9:

Web Browser component is IE7 not IE8? How to change this?

Pros:

  • Not much work required to get it running
  • some HTML5/CSS3 support if IE9, full if IE10

Cons:

  • Target machine must have target IE version installed, IE10 is still in preview on Win7

This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.

2. OpenWebKitSharp

OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari

Pros:

  • Actively developed
  • HTML5/CSS3 support

Cons:

  • Many features not implemented
  • Doesn't support x64 (App must be built for x86)

OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..

I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.

3. GeckoFX

Pros:

  • Works on mono
  • Actively developed
  • HTML5/CSS3 support

Cons:

  • D?o?e?s?n?'?t? ?s?u?p?p?o?r?t? ?x?6?4? ?(?A?p?p? ?m?u?s?t? ?b?e? ?b?u?i?l?t? ?f?o?r? ?x?8?6?)? - see comments below

GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.

I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:

  1. Download GeckoFx-Windows-16.0-0.2, here you can check if newer is available GeckoFX
  2. Add references to two downloaded dll's
  3. Since GeckoFX is wrapper you need XulRunner, go to Version List to see which one you need
  4. Now that we know which version of XulRunner we need, we go to Mozilla XulRunner releases, go to version folder -> runtimes -> xulrunner-(your_version).en-US.win32.zip, in our case xulrunner-16.0.en-US.win32.zip
  5. Unzip everything and copy all files to your bin\Debug (or release if your project is set to release)
  6. Go to visual studio designer of your form, go to toolbox, right click inside -> Choose items -> Browse -> Find downloaded GeckoFX winforms dll file -> OK
  7. Now you should have new control GeckoWebBrowser

If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.

Update some specific field of an entity in android Room

As of Room 2.2.0 released October 2019, you can specify a Target Entity for updates. Then if the update parameter is different, Room will only update the partial entity columns. An example for the OP question will show this a bit more clearly.

@Update(entity = Tour::class)
fun update(obj: TourUpdate)

@Entity
public class TourUpdate {
    @ColumnInfo(name = "id")
    public long id;
    @ColumnInfo(name = "endAddress")
    private String endAddress;
}

Notice you have to a create a new partial entity called TourUpdate, along with your real Tour entity in the question. Now when you call update with a TourUpdate object, it will update endAddress and leave the startAddress value the same. This works perfect for me for my usecase of an insertOrUpdate method in my DAO that updates the DB with new remote values from the API but leaves the local app data in the table alone.

Seeing the underlying SQL in the Spring JdbcTemplate?

I use this line for Spring Boot applications:

logging.level.org.springframework.jdbc.core = TRACE

This approach pretty universal and I usually use it for any other classes inside my application.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I just did it like this:

<a href="@Url.Action("Index","Home")#features">Features</a>

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option and log that information to a (temporary) CURLOPT_STDERR:

// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR, 
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);

$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);

You can then read it after curl has done the request:

$result = curl_exec($handle);
if ($result === FALSE) {
    printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
           htmlspecialchars(curl_error($handle)));
}

rewind($verbose);
$verboseLog = stream_get_contents($verbose);

echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";

(I originally answered similar but more extended in a related question.)

More information like metrics about the last request is available via curl_getinfo. This information can be useful for debugging curl requests, too. A usage example, I would normally wrap that into a function:

$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I've struggled a lot with this error. Tried every single answer I found on the internet.

In the end, I've connected my computer to my cell phone's hotspot and everything worked. I turned out that my company's internet was blocking the connection with MySQL.

This is not a complete solution, but maybe someone faces the same problem. It worths to check the connection.

SQL Add foreign key to existing column

Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void) is better because it explicitly says: no parameters allowed.

void foo() means you could (under some compilers) send parameters, at least if this is the declaration of your function rather than its definition.

Closing WebSocket correctly (HTML5, Javascript)

As mentioned by theoobe, some browsers do not close the websockets automatically. Don't try to handle any "close browser window" events client-side. There is currently no reliable way to do it, if you consider support of major desktop AND mobile browsers (e.g. onbeforeunload will not work in Mobile Safari). I had good experience with handling this problem server-side. E.g. if you use Java EE, take a look at javax.websocket.Endpoint, depending on the browser either the OnClose method or the OnError method will be called if you close/reload the browser window.

Creating a random string with A-Z and 0-9 in Java

Here you can use my method for generating Random String

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

The above method from my bag using to generate a salt string for login purpose.

What Does 'zoom' do in CSS?

As Joshua M pointed out, the zoom function isn't supported only in Firefox, but you can simply fix this as shown:

div.zoom {
  zoom: 2; /* all browsers */
 -moz-transform: scale(2);  /* Firefox */
}

Docker: Container keeps on restarting again on again

Try adding these params to your docker yml file

restart: "no"
  restart: always
  restart: on-failure
  restart: unless-stopped
  environment:
    POSTGRES_DB: "db_name"
    POSTGRES_HOST_AUTH_METHOD: "trust"

Final file should look something like this

postgres:
  restart: "no"
  restart: always
  restart: on-failure
  restart: unless-stopped
  image: postgres:latest
  volumes:
    - /data/postgresql:/var/lib/postgresql
  ports:
    - "5432:5432"
  environment:
    POSTGRES_DB: "db_name"
    POSTGRES_HOST_AUTH_METHOD: "trust"

How to enable scrolling of content inside a modal?

When using Bootstrap modal with skrollr, the modal will become not scrollable.

Problem fixed with stop the touch event from propagating.

$('#modalFooter').on('touchstart touchmove touchend', function(e) {
    e.stopPropagation();
});

more details at Add scroll event to the element inside #skrollr-body

How to serialize SqlAlchemy result to JSON?

def alc2json(row):
    return dict([(col, str(getattr(row,col))) for col in row.__table__.columns.keys()])

I thought I'd play a little code golf with this one.

FYI: I am using automap_base since we have a separately designed schema according to business requirements. I just started using SQLAlchemy today but the documentation states that automap_base is an extension to declarative_base which seems to be the typical paradigm in the SQLAlchemy ORM so I believe this should work.

It does not get fancy with following foreign keys per Tjorriemorrie's solution, but it simply matches columns to values and handles Python types by str()-ing the column values. Our values consist Python datetime.time and decimal.Decimal class type results so it gets the job done.

Hope this helps any passers-by!

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I think You are trying to use the normal URL of video Like this :

Copying Direct URL from YouTube

That doesn't let you display the content on other domains.To Tackle this up , You should use the Copy Embed Code feature provided by the YouTube itself .Like this :

Copy Embed Code ( YouTube )

That would free you up from any issues .

For the above Scenario :

  • Go to Youtube Video

  • Copy Embed Code

  • Paste that into your Code ( Make sure you Escape all the " ( Inverted Commas) by \" .

How to install Cmake C compiler and CXX compiler

The approach I use is to start the "Visual Studio Command Prompt" which can be found in the Start menu. E.g. my visual studio 2010 Express install has a shortcute Visual Studio Command Prompt (2010) at Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools.

This shortcut prepares an environment by calling a script vcvarsall.bat where the compiler, linker, etc. are setup from the right Visual Studio installation.

Alternatively, if you already have a prompt open, you can prepare the environment by calling a similar script:

:: For x86 (using the VS100COMNTOOLS env-var)
call "%VS100COMNTOOLS%"\..\..\VC\bin\vcvars32.bat

or

:: For amd64 (using the full path)
call C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat

However:

Your output (with the '$' prompt) suggests that you are attempting to run CMake from a MSys shell. In that case it might be better to run CMake for MSys or MinGW, by explicitly specifying a makefile generator:

cmake -G"MSYS Makefiles"
cmake -G"MinGW Makefiles"

Run cmake --help to get a list of all possible generators.

Cross-Origin Read Blocking (CORB)

Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page.

First Make sure these resources are served with a correct "Content-Type", i.e, for JSON MIME type - "text/json", "application/json", HTML MIME type - "text/html".

Second: set mode to cors i.e, mode:cors

The fetch would look something like this

 fetch("https://example.com/api/request", {
            method: 'POST',
            body: JSON.stringify(data),
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                "Accept": 'application/json',
            }
        })
    .then((data) => data.json())
    .then((resp) => console.log(resp))
    .catch((err) => console.log(err))

references: https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md

https://www.chromium.org/Home/chromium-security/corb-for-developers

Auto-increment on partial primary key with Entity Framework Core

Annotate the property like below

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():

builder.ForNpgsqlUseIdentityColumns();

This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().

postgres efcore value generation

Get month and year from a datetime in SQL Server 2005

Beginning with SQL Server 2012, you can use:

SELECT FORMAT(@date, 'yyyyMM')

Setting onSubmit in React.js

<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>

it work fine for me

How to get a user's time zone?

You can use below code for getting current time zone

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier

  }

  let currentTimeZone = getCurrentTimeZone()
   print(currentTimeZone)

Using pg_dump to only get insert statements from one table within database

if version < 8.4.0

pg_dump -D -t <table> <database>

Add -a before the -t if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.

version >= 8.4.0

pg_dump --column-inserts --data-only --table=<table> <database>

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

What is the difference between smoke testing and sanity testing?

Smoke and sanity testing

In general, smoke and sanity testing seems very similar to many tester who have just started, because in both we talk about build, we talk about functionality and we talk about the rejection of builds, if build's health is not good for the feasible testing.

After going through several projects, from start ups to product base company, I figured out the basic difference between smoke and sanity testing.

I am writing difference between smoke testing and sanity testing here to help you in answering at least one question that normally all testers get asked in interview.

Smoke testing

  • Smoke testing is done to test the health of builds.

  • It is also known as the shallow and wide testing, in that we normally include those test cases which can cover all the functionality of the product.

  • We can say that it's the first step of testing and, after this, we normally do other kind of functional and system testing, including regression testing.

  • It's normally done by a developer with the help of certain scripts or certain tools, but in some cases it can be performed by a tester too.

  • It's valid for initial stage of a build confirmation. For example, suppose we have started the development of a certain product, and we are producing a build for the first time, then smoke testing becomes a necessity for the product.

Sanity testing

  • It is sub-regression

  • Sanity is done for those builds which have gone through many regression tests and a minor change in code has happened. In this case, we normally do the intensive testing of functionalities where this change has occurred or may have influenced.

    • Due to this, it is also known as "narrow" and "deep" testing
  • It's performed by a tester

  • It's done for mature builds, like those that are just going to hit production, and have gone through multiple regression processes.

  • It can be removed from the testing process, if regression is already being performed.

  • If any build doesn't pass the sanity tests, then it is thrown to developer back for the correction of the build.

How to add property to a class dynamically?

The best way to achieve is by defining __slots__. That way your instances can't have new attributes.

ks = ['ab', 'cd']
vs = [12, 34]

class C(dict):
    __slots__ = []
    def __init__(self, ks, vs): self.update(zip(ks, vs))
    def __getattr__(self, key): return self[key]

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab

That prints 12

    c.ab = 33

That gives: AttributeError: 'C' object has no attribute 'ab'

HTML <sup /> tag affecting line height, how to make it consistent?

&sup1, &sup2 etc. might do the trick. it's an HTML trick to superscript

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

Disable output buffering

I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.

Since Python 3.3, print() supports the keyword argument "flush" (see documentation):

print('Hello World!', flush=True)

Resize image proportionally with MaxHeight and MaxWidth constraints

Working Solution :

For Resize image with size lower then 100Kb

WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;

Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;

do
{
    ScaleTransform st = new ScaleTransform();
    st.ScaleX = 0.3;
    st.ScaleY = 0.3;
    i = new WriteableBitmap(img, st);
    img.Source = i;
} while (i.Pixels.Length / 1024 > 100);

More Reference at http://net4attack.blogspot.com/

Waiting for Target Device to Come Online

Tools - Android - Sdk manager - tab Sdk tools - install emulator 25.3.1

Where does application data file actually stored on android device?

Application Private Data files are stored within <internal_storage>/data/data/<package>

Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()

When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

Python os.path.join on Windows

To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

Finding which process was killed by Linux OOM killer

Try this so you don't need to worry about where your logs are:

dmesg -T | egrep -i 'killed process'

-T - readable timestamps

New lines (\r\n) are not working in email body

You need to use <br> instead of \r\n . For this you can use built in function call nl2br So your code should be like this

 $message = nl2br("CCCC\r\nCCCC CCCC \r CCC \n CCC \r\n CCC \n\r CCCC");

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I had a case that I used DBMS where I had to fulfill a db connection form.

I put SID into the Database field and in the dropdown, next to the field, I had had 'Service Name' value instead of 'SID' value.
(normally I don't use Oracle database so I've not been aware of the difference)

That was the reason I got the error message.

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

How to iterate over a string in C?

You need a pointer to the first char to have an ANSI string.

printf("%s", source + i);

will do the job

Plus, of course you should have meant strlen(source), not sizeof(source).

Mysql 1050 Error "Table already exists" when in fact, it does not

Sounds like you have Schroedinger's table...

Seriously now, you probably have a broken table. Try:

  • DROP TABLE IF EXISTS contenttype
  • REPAIR TABLE contenttype
  • If you have sufficient permissions, delete the data files (in /mysql/data/db_name)

Sort a List of objects by multiple fields

Yes, you absolutely can do this. For example:

public class PersonComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        // Assume no nulls, and simple ordinal comparisons

        // First by campus - stop if this gives a result.
        int campusResult = p1.getCampus().compareTo(p2.getCampus());
        if (campusResult != 0)
        {
            return campusResult;
        }

        // Next by faculty
        int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
        if (facultyResult != 0)
        {
            return facultyResult;
        }

        // Finally by building
        return p1.getBuilding().compareTo(p2.getBuilding());
    }
}

Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."

How to properly use the "choices" field option in Django

You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

import calendar
tuple((m, m) for m in calendar.month_name[1:])

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

get next sequence value from database using hibernate

To get the new id, all you have to do is flush the entity manager. See getNext() method below:

@Entity
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class SequenceFetcher
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
    private long id;

    public long getId() {
        return id;
    }

    public static long getNext(EntityManager em) {
        SequenceFetcher sf = new SequenceFetcher();
        em.persist(sf);
        em.flush();
        return sf.getId();
    }
}

How can I make a CSS glass/blur effect work for an overlay?

_x000D_
_x000D_
#bg, #search-bg {_x000D_
  background-image: url('https://images.pexels.com/photos/719609/pexels-photo-719609.jpeg?w=940&h=650&auto=compress&cs=tinysrgb');_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: 1080px auto;_x000D_
}_x000D_
_x000D_
#bg {_x000D_
  background-position: center top;_x000D_
  padding: 70px 90px 120px 90px;_x000D_
}_x000D_
_x000D_
#search-container {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#search-bg {_x000D_
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  bottom: 0px;_x000D_
  left: 0px;_x000D_
  z-index: 99;_x000D_
_x000D_
  /* Pull the background 70px higher to the same place as #bg's */_x000D_
  background-position: center -70px;_x000D_
_x000D_
  -webkit-filter: blur(10px);_x000D_
  filter: url('/media/blur.svg#blur');_x000D_
  filter: blur(10px);_x000D_
}_x000D_
_x000D_
#search {_x000D_
  /* Put this on top of the blurred layer */_x000D_
  position: relative;_x000D_
  z-index: 100;_x000D_
  padding: 20px;_x000D_
  background: rgb(34,34,34); /* for IE */_x000D_
  background: rgba(34,34,34,0.75);_x000D_
}_x000D_
_x000D_
@media (max-width: 600px ) {_x000D_
  #bg { padding: 10px; }_x000D_
  #search-bg { background-position: center -10px; }_x000D_
}_x000D_
_x000D_
#search h2, #search h5, #search h5 a { text-align: center; color: #fefefe; font-weight: normal; }_x000D_
#search h2 { margin-bottom: 50px }_x000D_
#search h5 { margin-top: 70px }
_x000D_
<div id="bg">_x000D_
  <div id="search-container">_x000D_
    <div id="search-bg"></div>_x000D_
    <div id="search">_x000D_
      <h2>Awesome</h2>_x000D_
      <h5><a href="#">How it works »</a></h5>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if multiple array keys exists

One more possible solution:

if (!array_diff(['story', 'message'], array_keys($array))) {
    // OK: all the keys are in $array
} else {
   // FAIL: some keys are not
}

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Missing Authentication Token while accessing API Gateway?

If you set up an IAM role for your server that has the AmazonAPIGatewayInvokeFullAccess permission, you still need to pass headers on each request. You can do this in python with the aws-requests-auth library like so:

import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
auth = BotoAWSRequestsAuth(
    aws_host="API_ID.execute-api.us-east-1.amazonaws.com",
    aws_region="us-east-1",
    aws_service="execute-api"
)
response = requests.get("https://API_ID.execute-api.us-east-1.amazonaws.com/STAGE/RESOURCE", auth=auth)

TortoiseSVN icons overlay not showing after updating to Windows 10

I deleted all my onedrive keys, installed latest preview etc and finally realized that the icons were working all along for some explorer directory views and not others.

In other words, medium, large, extra large, and tiles, but not list or detail. Since I don't want to learn all about how that works, I am just viewing my work directories as tiles for now.

How do I use Assert.Throws to assert the type of the exception?

Since I'm disturbed by the verbosity of some of the new NUnit patterns, I use something like this to create code that is cleaner for me personally:

public void AssertBusinessRuleException(TestDelegate code, string expectedMessage)
{
    var ex = Assert.Throws<BusinessRuleException>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

public void AssertException<T>(TestDelegate code, string expectedMessage) where T:Exception
{
    var ex = Assert.Throws<T>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

The usage is then:

AssertBusinessRuleException(() => user.MakeUserActive(), "Actual exception message");

How does delete[] know it's an array?

It's up to the runtime which is responsible for the memory allocation, in the same way that you can delete an array created with malloc in standard C using free. I think each compiler implements it differently. One common way is to allocate an extra cell for the array size.

However, the runtime is not smart enough to detect whether or not it is an array or a pointer, you have to inform it, and if you are mistaken, you either don't delete correctly (E.g., ptr instead of array), or you end up taking an unrelated value for the size and cause significant damage.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>

How can I debug javascript on Android?

Android studio provide all you need to see console.log and other. In logcat just filter to "/Web Console" and you will see your js logs...

If you get any issue you can add this plugin : https://github.com/apache/cordova-plugin-console

Change Default branch in gitlab

In Gitlab CE 9.0, You can change the default branch from the Settings Tab in a repository's header.

Tools: replace not replacing in Android manifest

You can replace those in your Manifest application tag:

<application
    tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>

and will work for you.

iPhone UITextField - Change placeholder text color

Iam new to xcode and i found a way around to the same effect.

I placed a uilabel in place of place holder with the desired format and hide it in

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag)
    {
        case 0:
            lblUserName.hidden=YES;
            break;

        case 1:
            lblPassword.hidden=YES;
            break;
 
        default:
            break;
    }
}

I agree its a work around and not a real solution but the effect was same got it from this link

NOTE: Still works on iOS 7 :|

bash export command

Are you certain that the software (and not yourself, since your test actually only shows the shell used as default for your user) uses /bin/bash ?

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

Shall we always use [unowned self] inside closure in Swift

Here is brilliant quotes from Apple Developer Forums described delicious details:

unowned vs unowned(safe) vs unowned(unsafe)

unowned(safe) is a non-owning reference that asserts on access that the object is still alive. It's sort of like a weak optional reference that's implicitly unwrapped with x! every time it's accessed. unowned(unsafe) is like __unsafe_unretained in ARC—it's a non-owning reference, but there's no runtime check that the object is still alive on access, so dangling references will reach into garbage memory. unowned is always a synonym for unowned(safe) currently, but the intent is that it will be optimized to unowned(unsafe) in -Ofast builds when runtime checks are disabled.

unowned vs weak

unowned actually uses a much simpler implementation than weak. Native Swift objects carry two reference counts, and unowned references bump the unowned reference count instead of the strong reference count. The object is deinitialized when its strong reference count reaches zero, but it isn't actually deallocated until the unowned reference count also hits zero. This causes the memory to be held onto slightly longer when there are unowned references, but that isn't usually a problem when unowned is used because the related objects should have near-equal lifetimes anyway, and it's much simpler and lower-overhead than the side-table based implementation used for zeroing weak references.

Update: In modern Swift weak internally uses the same mechanism as unowned does. So this comparison is incorrect because it compares Objective-C weak with Swift unonwed.

Reasons

What is the purpose of keeping the memory alive after owning references reach 0? What happens if code attempts to do something with the object using an unowned reference after it is deinitialized?

The memory is kept alive so that its retain counts are still available. This way, when someone attempts to retain a strong reference to the unowned object, the runtime can check that the strong reference count is greater than zero in order to ensure that it is safe to retain the object.

What happens to owning or unowned references held by the object? Is their lifetime decoupled from the object when it is deinitialized or is their memory also retained until the object is deallocated after the last unowned reference is released?

All resources owned by the object are released as soon as the object's last strong reference is released, and its deinit is run. Unowned references only keep the memory alive—aside from the header with the reference counts, its contents is junk.

Excited, huh?

How to get htaccess to work on MAMP

If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

Check/Uncheck a checkbox on datagridview

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

Import multiple csv files into pandas and concatenate into one DataFrame

If you have same columns in all your csv files then you can try the code below. I have added header=0 so that after reading csv first row can be assigned as the column names.

import pandas as pd
import glob

path = r'C:\DRO\DCL_rawdata_files' # use your path
all_files = glob.glob(path + "/*.csv")

li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame = pd.concat(li, axis=0, ignore_index=True)

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

AndroidStudio gradle proxy

In Android Studio -> Preferences -> Gradle, pass the proxy details as VM options.

Gradle VM Options -Dhttp.proxyHost=www.somehost.org -Dhttp.proxyPort=8080 etc.

*In 0.8.6 Beta Gradle is under File->Settings (Ctrl+Alt+S, on Windows and Linux)

How to trigger event in JavaScript?

HTML

<a href="demoLink" id="myLink"> myLink </a>
<button onclick="fireLink(event)"> Call My Link </button>

JS

// click event listener of the link element --------------  
document.getElementById('myLink').addEventListener("click", callLink);
function callLink(e) {
    // code to fire
}

// function invoked by the button element ----------------
function fireLink(event) {                   
    document.getElementById('myLink').click();      // script calls the "click" event of the link element 
}

Windows command to get service status?

Well I'm not sure about whether you can email the results of that from a batch file. If I may make an alternate suggestion that would solve your problem vbscript. I am far from great with vbscript but you can use it to query the services running on the local machine. The script below will email you the status of all of the services running on the machine the script gets run on. You'll obviously want to replace the smtp server and the email address. If you're part of a domain and you run this script as a privileged user (they have to be an administrator on the remote machine) you can query remote machines as well by replacing localhost with the fqdn.

Dim objComputer, objMessage
Dim strEmail

' If there is an error getting the status of a service it will attempt to move on to the next one
On Error Resume Next

' Email Setup
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Service Status Report"
objMessage.From = "[email protected]"
objMessage.To = "[email protected]"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.example.net"

'Server port (typically 25)
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

Set objComputer = GetObject("WinNT://localhost")
objComputer.Filter = Array("Service")

For Each aService In objComputer
strEmail = strEmail &chr(10) & aService.Name & "=" & aService.Status
Next

objMessage.TextBody = strEmail
objMessage.Configuration.Fields.Update
objMessage.Send

Hope this helps you! Enjoy!

Edit: Ahh one more thing a service status of 4 means the service is running, a service status of 1 means it's not. I'm not sure what 2 or 3 means but I'm willing to bet they are stopping/starting.

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

Setting Spring Profile variable

as System environment Variable:

Windows: Start -> type "envi" select environment variables and add a new: Name: spring_profiles_active Value: dev (or whatever yours is)

Linux: add following line to /etc/environment under PATH:

spring_profiles_active=prod (or whatever profile is)

then also export spring_profiles_active=prod so you have it in the runtime now.

How to find topmost view controller on iOS

I think most of the answers have completely ignored UINavigationViewController, so I handled this use case with following implementation.

+ (UIViewController *)topMostController {
    UIViewController * topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topController.presentedViewController || [topController isMemberOfClass:[UINavigationController class]]) {
        if([topController isMemberOfClass:[UINavigationController class]]) {
            topController = [topController childViewControllers].lastObject;
        } else {
            topController = topController.presentedViewController;
        }
    }

    return topController;
}

Latex - Change margins of only a few pages

I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
... 
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...    
\restoregeometry     %so it does not affect the rest of the pages.
...
... 
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

CSS: Truncate table cells, but fit as much as possible

Don't know if this will help anyone, but I solved a similar problem by specifying specific width sizes in percentage for each column. Obviously, this would work best if each column has content with width that doesn't vary too widely.

error: expected class-name before ‘{’ token

I know it is a bit late to answer this question, but it is the first entry in google, so I think it is worth to answer it.

The problem is not a coding problem, it is an architecture problem.

You have created an interface class Event: public Item to define the methods which all events should implement. Then you have defined two types of events which inherits from class Event: public Item; Arrival and Landing and then, you have added a method Landing* createNewLanding(Arrival* arrival); from the landing functionality in the class Event: public Item interface. You should move this method to the class Landing: public Event class because it only has sense for a landing. class Landing: public Event and class Arrival: public Event class should know class Event: public Item but event should not know class Landing: public Event nor class Arrival: public Event.

I hope this helps, regards, Alberto

jQuery get specific option tag text

I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:

So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:

var e = $('select[title="IntenalFieldName"] option:selected').text(); 

How can I read user input from the console?

You're missing a semicolon: double b = a * Math.PI;

javascript find and remove object in array based on key value

I agree with the answers, a simple way if you want to find an object by id and remove it is simply like below code.

   var obj = JSON.parse(data);
   var newObj = obj.filter(item=>item.Id!=88);
       

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

How to assign the output of a command to a Makefile variable

In the below example, I have stored the Makefile folder path to LOCAL_PKG_DIR and then use LOCAL_PKG_DIR variable in targets.

Makefile:

LOCAL_PKG_DIR := $(shell eval pwd)

.PHONY: print
print:
    @echo $(LOCAL_PKG_DIR)

Terminal output:

$ make print
/home/amrit/folder

What is the difference between concurrency and parallelism?

concurency: multiple execution flows with the potential to share resources

Ex: two threads competing for a I/O port.

paralelism: splitting a problem in multiple similar chunks.

Ex: parsing a big file by running two processes on every half of the file.

how to access the command line for xampp on windows

In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)

enter image description here

After pressing the button, you will see the command prompt window.

enter image description here

From this window you can navigate through the different folders and start the different services available.

How to insert a blob into a database using sql server management studio

Ok... this took me way too long. The sql-management studio tool is just not up to simple things like this (which I've noticed before when looking for where to set the timeout on queries, and it was done in 4 different locations)

I downloaded some other sql editor package (sql maestro in my case). And behold it includes a blob editor where you can look at blobs, and load new blobs into these field.

thanks for the input!

Try/catch does not seem to have an effect

This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.

try {
    Set-Location "$YourPath" -ErrorAction Stop;
} catch {
    Write-Host "Exception has been caught";
}

Difference between one-to-many and many-to-one relationship

Answer to your first question is : both are similar,

Answer to your second question is: one-to-many --> a MAN(MAN table) may have more than one wife(WOMEN table) many-to-one --> more than one women have married one MAN.

Now if you want to relate this relation with two tables MAN and WOMEN, one MAN table row may have many relations with rows in the WOMEN table. hope it clear.

How to view the current heap size that an application is using?

Use this code:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory(); 

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

 // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory(); 

It was useful to me to know it.

A column-vector y was passed when a 1d array was expected

Change this line:

model = forest.fit(train_fold, train_y)

to:

model = forest.fit(train_fold, train_y.values.ravel())

Edit:

.values will give the values in an array. (shape: (n,1)

.ravel will convert that array shape to (n, )

stale element reference: element is not attached to the page document

Whenever you face this issue, just define the web element once again above the line in which you are getting an Error.

Example:

WebElement button = driver.findElement(By.xpath("xpath"));
button.click();

//here you do something like update or save 

//then you try to use the button WebElement again to click 
button.click();

Since the DOM has changed e.g. through the update action, you are receiving a StaleElementReference Error.

Solution:

WebElement button = driver.findElement(By.xpath("xpath"));
button.click();

//here you do something like update or save 

//then you define the button element again before you use it
WebElement button1 = driver.findElement(By.xpath("xpath"));
//that new element will point to the same element in the new DOM
button1.click();

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can use Rout redirecting.

protected void btnNewEntry_Click(object sender, EventArgs e)
{
    Response.RedirectToRoute("CMS_1"); 
}

which requires to define your routing logic in Global.asax file that could be like that:

routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");

where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1

How to make div occupy remaining height?

Since you know how many pixels are occupied by the previous content, you can use the calc() function:

height: calc(100% - 50px);

How to use DISTINCT and ORDER BY in same SELECT statement?

if object_id ('tempdb..#tempreport') is not null
begin  
drop table #tempreport
end 
create table #tempreport (
Category  nvarchar(510),
CreationDate smallint )
insert into #tempreport 
select distinct Category from MonitoringJob (nolock) 
select * from #tempreport  ORDER BY CreationDate DESC

Selecting a row of pandas series/dataframe by integer index

you can loop through the data frame like this .

for ad in range(1,dataframe_c.size):
    print(dataframe_c.values[ad])

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

10

What is the best way to compare 2 folder trees on windows?

SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:

SyncToy Preview screenshot (source: https://maketecheasier-2d0f.kxcdn.com/assets/uploads/2010/06/synctoy-preview.png)

You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.

Lastly, it comes with SyncToyCmd for creating and synchronizing folder pairs from the CLI or a Scheduled Task.

How do you implement a circular buffer in C?

A simple implementation could consist of:

  • A buffer, implemented as an array of size n, of whatever type you need
  • A read pointer or index (whichever is more efficient for your processor)
  • A write pointer or index
  • A counter indicating how much data is in the buffer (derivable from the read and write pointers, but faster to track it separately)

Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.

You can't write if counter = n. You can't read if counter = 0.

Changing SVG image color with javascript

Given some SVG:

<div id="main">
  <svg id="octocat" xmlns="http://www.w3.org/2000/svg" width="400px" height="400px" viewBox="-60 0 420 330" style="fill:#fff;stroke: #000; stroke-opacity: 0.1">
    <path id="puddle" d="m296.94 295.43c0 20.533-47.56 37.176-106.22 37.176-58.67 0-106.23-16.643-106.23-37.176s47.558-37.18 106.23-37.18c58.66 0 106.22 16.65 106.22 37.18z"/>
    <path class="shadow-legs" d="m161.85 331.22v-26.5c0-3.422-.619-6.284-1.653-8.701 6.853 5.322 7.316 18.695 7.316 18.695v17.004c6.166.481 12.534.773 19.053.861l-.172-16.92c-.944-23.13-20.769-25.961-20.769-25.961-7.245-1.645-7.137 1.991-6.409 4.34-7.108-12.122-26.158-10.556-26.158-10.556-6.611 2.357-.475 6.607-.475 6.607 10.387 3.775 11.33 15.105 11.33 15.105v23.622c5.72.98 11.71 1.79 17.94 2.4z"/>
    <path class="shadow-legs" d="m245.4 283.48s-19.053-1.566-26.16 10.559c.728-2.35.839-5.989-6.408-4.343 0 0-19.824 2.832-20.768 25.961l-.174 16.946c6.509-.025 12.876-.254 19.054-.671v-17.219s.465-13.373 7.316-18.695c-1.034 2.417-1.653 5.278-1.653 8.701v26.775c6.214-.544 12.211-1.279 17.937-2.188v-24.113s.944-11.33 11.33-15.105c0-.01 6.13-4.26-.48-6.62z"/>
    <path id="cat" d="m378.18 141.32l.28-1.389c-31.162-6.231-63.141-6.294-82.487-5.49 3.178-11.451 4.134-24.627 4.134-39.32 0-21.073-7.917-37.931-20.77-50.759 2.246-7.25 5.246-23.351-2.996-43.963 0 0-14.541-4.617-47.431 17.396-12.884-3.22-26.596-4.81-40.328-4.81-15.109 0-30.376 1.924-44.615 5.83-33.94-23.154-48.923-18.411-48.923-18.411-9.78 24.457-3.733 42.566-1.896 47.063-11.495 12.406-18.513 28.243-18.513 47.659 0 14.658 1.669 27.808 5.745 39.237-19.511-.71-50.323-.437-80.373 5.572l.276 1.389c30.231-6.046 61.237-6.256 80.629-5.522.898 2.366 1.899 4.661 3.021 6.879-19.177.618-51.922 3.062-83.303 11.915l.387 1.36c31.629-8.918 64.658-11.301 83.649-11.882 11.458 21.358 34.048 35.152 74.236 39.484-5.704 3.833-11.523 10.349-13.881 21.374-7.773 3.718-32.379 12.793-47.142-12.599 0 0-8.264-15.109-24.082-16.292 0 0-15.344-.235-1.059 9.562 0 0 10.267 4.838 17.351 23.019 0 0 9.241 31.01 53.835 21.061v32.032s-.943 11.33-11.33 15.105c0 0-6.137 4.249.475 6.606 0 0 28.792 2.361 28.792-21.238v-34.929s-1.142-13.852 5.663-18.667v57.371s-.47 13.688-7.551 18.881c0 0-4.723 8.494 5.663 6.137 0 0 19.824-2.832 20.769-25.961l.449-58.06h4.765l.453 58.06c.943 23.129 20.768 25.961 20.768 25.961 10.383 2.357 5.663-6.137 5.663-6.137-7.08-5.193-7.551-18.881-7.551-18.881v-56.876c6.801 5.296 5.663 18.171 5.663 18.171v34.929c0 23.6 28.793 21.238 28.793 21.238 6.606-2.357.474-6.606.474-6.606-10.386-3.775-11.33-15.105-11.33-15.105v-45.786c0-17.854-7.518-27.309-14.87-32.3 42.859-4.25 63.426-18.089 72.903-39.591 18.773.516 52.557 2.803 84.873 11.919l.384-1.36c-32.131-9.063-65.692-11.408-84.655-11.96.898-2.172 1.682-4.431 2.378-6.755 19.25-.80 51.38-.79 82.66 5.46z"/>
    <path id="face" d="m258.19 94.132c9.231 8.363 14.631 18.462 14.631 29.343 0 50.804-37.872 52.181-84.585 52.181-46.721 0-84.589-7.035-84.589-52.181 0-10.809 5.324-20.845 14.441-29.174 15.208-13.881 40.946-6.531 70.147-6.531 29.07-.004 54.72-7.429 69.95 6.357z"/>
    <path id="eyes" d="m160.1 126.06 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z m94.43 0 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z"/>
    <path id="pupils" d="m154.46 126.38 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z m94.42 0 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z"/>
    <circle id="nose" cx="188.5" cy="148.56" r="4.401"/>
    <path id="mouth" d="m178.23 159.69c-.26-.738.128-1.545.861-1.805.737-.26 1.546.128 1.805.861 1.134 3.198 4.167 5.346 7.551 5.346s6.417-2.147 7.551-5.346c.26-.738 1.067-1.121 1.805-.861s1.121 1.067.862 1.805c-1.529 4.324-5.639 7.229-10.218 7.229s-8.68-2.89-10.21-7.22z"/>
    <path id="octo" d="m80.641 179.82 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m8.5 4.72 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.193 6.14 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m4.72 7.08 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.188 6.61 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m7.09 5.66 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.91 3.78 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.87 0 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m10.01 -1.64 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z"/>
    <path id="drop" d="m69.369 186.12l-3.066 10.683s-.8 3.861 2.84 4.546c3.8-.074 3.486-3.627 3.223-4.781z"/>
  </svg>
</div>

Using jQuery, for instance, you could do:

var _currentFill = "#f00"; // red
$svg = $("#octocat");
$("#face", $svg).attr('style', "fill:"+_currentFill); })

I provided a coloring book demo as an answer to another stackoverflow question: http://bl.ocks.org/4545199. Tested on Safari, Chrome, and Firefox.

What's the HTML to have a horizontal space between two objects?

<div> looks nice, but a bit complicated in setting all these display: block, float: left... Maybe because the general idea behind <div> is a block of a paragraph size or more.

I have found the following nice way for spacing:

<button>Button 1></button>
<button style="margin-left: 4em">Button 2</button>

JavaScript unit test tools for TDD

Karma or Protractor

Karma is a JavaScript test-runner built with Node.js and meant for unit testing.

The Protractor is for end-to-end testing and uses Selenium Web Driver to drive tests.

Both have been made by the Angular team. You can use any assertion-library you want with either.

Screencast: Karma Getting started

related:

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from a browser or headless with PhantomJS
  • Run on multiple clients at once
  • Option to launch, capture, and automatically shut down browsers
  • Option to run server/clients on development computer or separately
  • Run tests from a command line (can be integrated into ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (Jasmine, Mocha, QUnit built-in)
    • Your own assertions/refutes
    • Reporters
    • Browser Launchers
  • Plugin for WebStorm
  • Supported by Netbeans IDE

Cons:

mocha.js

I'm totally unqualified to comment on mocha.js's features, strengths, and weaknesses, but it was just recommended to me by someone I trust in the JS community.

List of features, as reported by its website:

  • browser support
  • simple async support, including promises
  • test coverage reporting
  • string diff support
  • javascript # API for running tests
  • proper exit status for CI support etc
  • auto-detects and disables coloring for non-ttys
  • maps uncaught exceptions to the correct test case
  • async test timeout support
  • test-specific timeouts
  • growl notification support
  • reports test durations
  • highlights slow tests
  • file watcher support
  • global variable leak detection
  • optionally run tests that match a regexp
  • auto-exit to prevent "hanging" with an active loop
  • easily meta-generate suites & test-cases
  • mocha.opts file support
  • clickable suite titles to filter test execution
  • node debugger support
  • detects multiple calls to done()
  • use any assertion library you want
  • extensible reporting, bundled with 9+ reporters
  • extensible test DSLs or "interfaces"
  • before, after, before each, after each hook
  • arbitrary transpiler support (coffee-script etc)
  • TextMate bundle

yolpo

yolpo

This no longer exists, redirects to sequential.js instead

Yolpo is a tool to visualize the execution of javascript. Javascript API developers are encouraged to write their use cases to show and tell their API. Such use cases forms the basis of regression tests.

AVA

AVA logo

Futuristic test runner with built-in support for ES2015. Even though JavaScript is single-threaded, IO in Node.js can happen in parallel due to its async nature. AVA takes advantage of this and runs your tests concurrently, which is especially beneficial for IO heavy tests. In addition, test files are run in parallel as separate processes, giving you even better performance and an isolated environment for each test file.

  • Minimal and fast
  • Simple test syntax
  • Runs tests concurrently
  • Enforces writing atomic tests
  • No implicit globals
  • Isolated environment for each test file
  • Write your tests in ES2015
  • Promise support
  • Generator function support
  • Async function support
  • Observable support
  • Enhanced asserts
  • Optional TAP o utput
  • Clean stack traces

Buster.js

A JavaScript test-runner built with Node.js. Very modular and flexible. It comes with its own assertion library, but you can add your own if you like. The assertions library is decoupled, so you can also use it with other test-runners. Instead of using assert(!...) or expect(...).not..., it uses refute(...) which is a nice twist imho.

A browser JavaScript testing toolkit. It does browser testing with browser automation (think JsTestDriver), QUnit style static HTML page testing, testing in headless browsers (PhantomJS, jsdom, ...), and more. Take a look at the overview!

A Node.js testing toolkit. You get the same test case library, assertion library, etc. This is also great for hybrid browser and Node.js code. Write your test case with Buster.JS and run it both in Node.js and in a real browser.

Screencast: Buster.js Getting started (2:45)

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from a browser or headless with PhantomJS (soon)
  • Run on multiple clients at once
  • Supports NodeJS testing
  • Don't need to run server/clients on development computer (no need for IE)
  • Run tests from a command line (can be integrated into ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Defer tests instead of commenting them out
  • SinonJS built-in
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (JsTestDriver built in)
    • Your own assertions/refutes
    • Reporters (xUnit XML, traditional dots, specification, tap, TeamCity and more built-in)
    • Customize/replace the HTML that is used to run the browser-tests
  • TextMate and Emacs integration

Cons:

  • Stil in beta so can be buggy
  • No plugin for Eclipse/IntelliJ (yet)
  • Doesn't group results by os/browser/version like TestSwarm *. It does, however, print out the browser name and version in the test results.
  • No history of previous test results like TestSwarm *
  • Doesn't fully work on windows as of May 2014

* TestSwarm is also a Continuous Integration server, while you need a separate CI server for Buster.js. It does, however, output xUnit XML reports, so it should be easy to integrate with Hudson, Bamboo or other CI servers.

TestSwarm

https://github.com/jquery/testswarm

TestSwarm is officially no longer under active development as stated on their GitHub webpage. They recommend Karma, browserstack-runner, or Intern.

Jasmine

Jasmine

This is a behavior-driven framework (as stated in quote below) that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on RSpec that are used for testing in Rails projects.

Jasmine specs can be run from an html page (in qUnit fashion) or from a test runner (as Karma).

Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.

If you have experience with this testing framework, please contribute with more info :)

Project home: http://jasmine.github.io/

QUnit

QUnit focuses on testing JavaScript in the browser while providing as much convenience to the developer as possible. Blurb from the site:

QUnit is a powerful, easy-to-use JavaScript unit test suite. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code

QUnit shares some history with TestSwarm (above):

QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone. QUnit's assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.

Project home: http://qunitjs.com/

Sinon

Another great tool is sinon.js by Christian Johansen, the author of Test-Driven JavaScript Development. Best described by himself:

Standalone test spies, stubs and mocks for JavaScript. No dependencies works with any unit testing framework.

Intern

The Intern Web site provides a direct feature comparison to the other testing frameworks on this list. It offers more features out of the box than any other JavaScript-based testing system.

JEST

A new but yet very powerful testing framework. It allows snapshot based testing as well this increases the testing speed and creates a new dynamic in terms of testing

Check out one of their talks: https://www.youtube.com/watch?v=cAKYQpTC7MA

Better yet: Getting Started

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

How to convert vector to array

What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?

If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.

Otherwise, you just have to copy each element:

double arr[100];
std::copy(v.begin(), v.end(), arr);

Ensure not only thar arr is big enough, but that arr gets filled up, or you have uninitialized values.

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

What is a constant reference? (not a reference to a constant)

As it mentioned in another answers, a reference is inherently const.

int &ref = obj;

Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.

When you declare a const reference, it is nothing but a reference which refers to a const object.

const int &ref = obj;

The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;

const int *const ptr = &obj;

So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;

A reference must be initialized only with an object

So when you do this, you are going to get an error;

int  &r = 0; // Error: a nonconst reference cannot be initialized to a literal

This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;

const int  &r = 0; // a valid approach

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.

enter image description here

Here what I did:

  1. When the VS installer stuck at the KB2999226 update I clicked cancel.
  2. Installer took me back to confirm cancellation, waited for a while then opened the windows task manager and ended the process of wuse.exe (windows standalone update installer)
  3. On the VS installer clicked "No" to return to installation process. The process was completed without errors.

Is Xamarin free in Visual Studio 2015?

No, it only contains a free 30 day trial. But I think there would be a package if you buy Visual Studio + Xamarin.

How to handle static content in Spring MVC?

My own experience with this problem is as follows. Most Spring-related web pages and books seem to suggest that the most appropriate syntax is the following.

    <mvc:resources mapping="/resources/**" location="/resources/" />

The above syntax suggests that you can place your static resources (CSS, JavaScript, images) in a folder named "resources" in the root of your application, i.e. /webapp/resources/.

However, in my experience (I am using Eclipse and the Tomcat plugin), the only approach that works is if you place your resources folder inside WEB_INF (or META-INF). So, the syntax I recommend is the following.

    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

In your JSP (or similar) , reference the resource as follows.

<script type="text/javascript"
        src="resources/my-javascript.js">
</script>

Needless to mention, the entire question only arose because I wanted my Spring dispatcher servlet (front controller) to intercept everything, everything dynamic, that is. So I have the following in my web.xml.

<servlet>
    <servlet-name>front-controller</servlet-name>
    <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
    <!-- spring automatically discovers /WEB-INF/<servlet-name>-servlet.xml -->
</servlet>

<servlet-mapping>
    <servlet-name>front-controller</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Finally, since I'm using current best practices, I have the following in my front controller servlet xml (see above).

<mvc:annotation-driven/>

And I have the following in my actual controller implementation, to ensure that I have a default method to handle all incoming requests.

@RequestMapping("/")

I hope this helps.

How to Correctly Use Lists in R?

Regarding vectors and the hash/array concept from other languages:

  1. Vectors are the atoms of R. Eg, rpois(1e4,5) (5 random numbers), numeric(55) (length-55 zero vector over doubles), and character(12) (12 empty strings), are all "basic".

  2. Either lists or vectors can have names.

    > n = numeric(10)
    > n
     [1] 0 0 0 0 0 0 0 0 0 0
    > names(n)
    NULL
    > names(n) = LETTERS[1:10]
    > n
    A B C D E F G H I J 
    0 0 0 0 0 0 0 0 0 0
    
  3. Vectors require everything to be the same data type. Watch this:

    > i = integer(5)
    > v = c(n,i)
    > v
    A B C D E F G H I J           
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
    > class(v)
    [1] "numeric"
    > i = complex(5)
    > v = c(n,i)
    > class(v)
    [1] "complex"
    > v
       A    B    C    D    E    F    G    H    I    J                          
    0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i
    
  4. Lists can contain varying data types, as seen in other answers and the OP's question itself.

I've seen languages (ruby, javascript) in which "arrays" may contain variable datatypes, but for example in C++ "arrays" must be all the same datatype. I believe this is a speed/efficiency thing: if you have a numeric(1e6) you know its size and the location of every element a priori; if the thing might contain "Flying Purple People Eaters" in some unknown slice, then you have to actually parse stuff to know basic facts about it.

Certain standard R operations also make more sense when the type is guaranteed. For example cumsum(1:9) makes sense whereas cumsum(list(1,2,3,4,5,'a',6,7,8,9)) does not, without the type being guaranteed to be double.


As to your second question:

Lists can be returned from functions even though you never passed in a List when you called the function

Functions return different data types than they're input all the time. plot returns a plot even though it doesn't take a plot as an input. Arg returns a numeric even though it accepted a complex. Etc.

(And as for strsplit: the source code is here.)

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

HttpServletRequest - Get query string parameters, no form data

The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.

The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":

GET /persons?age=42

The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":

PUT /persons?age=42

hair=grey

So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

For getting the element in react you need to use ref and inside the function you can use the ReactDOM.findDOMNode method.

But what I like to do more is to call the ref right inside the event

<input type="text" ref={ref => this.myTextInput = ref} />

This is some good link to help you figure out.

How to create a DataFrame from a text file in Spark

A txt File with PIPE (|) delimited file can be read as :


df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")

Use PHP to convert PNG to JPG with compression?

This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:

<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>

Hope that helps

Call a Class From another class

Suposse you have

Class1

public class Class1 {
    //Your class code above
}

Class2

public class Class2 {
}

and then you can use Class2 in different ways.

Class Field

public class Class1{
    private Class2 class2 = new Class2();
}

Method field

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2 class2 = new Class2();
         class2.invokeSomeMethod();
         //your actual code
    }
}

Static methods from Class2 Imagine this is your class2.

public class Class2 {
     public static void doSomething(){
     }
}

from class1 you can use doSomething from Class2 whenever you want

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2.doSomething();
         //your actual code
    }
}

How to set ANDROID_HOME path in ubuntu?

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

PHP Multiple Checkbox Array

<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays

Are strongly-typed functions as parameters possible in TypeScript?

In TS we can type functions in the in the following manners:

Functions types/signatures

This is used for real implementations of functions/methods it has the following syntax:

(arg1: Arg1type, arg2: Arg2type) : ReturnType

Example:

function add(x: number, y: number): number {
    return x + y;
}

class Date {
  setTime(time: number): number {
   // ...
  }

}

Function Type Literals

Function type literals are another way to declare the type of a function. They're usually applied in the function signature of a higher-order function. A higher-order function is a function which accepts functions as parameters or which returns a function. It has the following syntax:

(arg1: Arg1type, arg2: Arg2type) => ReturnType

Example:

type FunctionType1 = (x: string, y: number) => number;

class Foo {
    save(callback: (str: string) => void) {
       // ...
    }

    doStuff(callback: FunctionType1) {
       // ...
    }

}

Visual Studio Code how to resolve merge conflicts with git?

  1. Click "Source Control" button on left.
  2. See MERGE CHANGES in sidebar.
  3. Those files have merge conflicts.

VS Code > Source Control > Merge Changes (Example)

Changing background color of ListView items on Android

If the setBackgroundColor is added for onItemClick event, it will not work unless you can put it after the click event.

Try to add debug code in the adapter's getView method, you will find that getView will be called again whenever you click on the screen. So, after you set the background color, the system will redraw the screen with original setting. Don't know why it waste resource to rebuild the screen whenever it's being click, there already have other way that we can notify the system to redraw the screen when needed.

Maybe you can add some control flag to determine the background color for individual row, then modify the getView method to set the color according to this control flag. So, the background color will be changed when it redraw the screen.

I'm also looking for an official solution on it.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.

How to specify test directory for mocha?

The nice way to do this is to add a "test" npm script in package.json that calls mocha with the right arguments. This way your package.json also describes your test structure. It also avoids all these cross-platform issues in the other answers (double vs single quotes, "find", etc.)

To have mocha run all js files in the "test" directory:

"scripts": {
    "start": "node ./bin/www", -- not required for tests, just here for context
    "test": "mocha test/**/*.js"
  },

Then to run only the smoke tests call:

npm test

You can standardize the running of all tests in all projects this way, so when a new developer starts on your project or another, they know "npm test" will run the tests. There is good historical precedence for this (Maven, for example, most old school "make" projects too). It sure helps CI when all projects have the same test command.

Similarly, you might have a subset of faster "smoke" tests that you might want mocha to run:

"scripts": {
    "test": "mocha test/**/*.js"
    "smoketest": "mocha smoketest/**/*.js"
  },

Then to run only the smoke tests call:

npm smoketest

Another common pattern is to place your tests in the same directory as the source that they test, but call the test files *.spec.js. For example: src/foo/foo.js is tested by src/foo/foo.spec.js.

To run all the tests named *.spec.js by convention:

  "scripts": {
    "test": "mocha **/*.spec.js"
  },

Then to run all the tests call:

npm test

See the pattern here? Good. :) Consistency defeats mura.

How to fill DataTable with SQL Table

You need to modify the method GetData() and add your "experimental" code there, and return t1.

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
begin
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 
end

How can I convert a Unix timestamp to DateTime and vice versa?

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
    // Java timestamp is milliseconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Getting IPV4 address from a sockaddr structure

Just cast the entire sockaddr structure to a sockaddr_in. Then you can use:

char *ip = inet_ntoa(their_addr.sin_addr)

To retrieve the standard ip representation.

Set Matplotlib colorbar size to match graph

I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1 module cannot address GeoAxes, whereas adjusting fraction, pad, shrink, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar its own axes might be a better solution to address all the issues that have been mentioned.

Code

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))

# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.

cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)

Result

enter image description here

Later on, I find matplotlib.pyplot.colorbar official documentation also gives ax option, which are existing axes that will provide room for the colorbar. Therefore, it is useful for multiple subplots, see following.

Code

fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)

Result

enter image description here

Again, you can also achieve similar effects by specifying cax, a more accurate way from my perspective.

Code

fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)

Result

enter image description here

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Can I call methods in constructor in Java?

Better design would be

public static YourObject getMyObject(File configFile){
    //process and create an object configure it and return it
}

How to get form values in Symfony2 controller

In Symfony 2 ( to be more specific, the 2.3 version ) you can get a data of an field by

$var = $form->get('yourformfieldname')->getData();

or you can get all data sent

$data = $form->getData();

where '$data' is an array containing your form fields' values.

WCF change endpoint address at runtime

So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);   
var client = new EchoServiceClient(address); 
litResponse.Text = client.SendEcho("Hello World"); 
client.Close();

Actual working final version by valamas

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close(); 

How to hide command output in Bash

Use this.

{
  /your/first/command
  /your/second/command
} &> /dev/null

Explanation

To eliminate output from commands, you have two options:

  • Close the output descriptor file, which keeps it from accepting any more input. That looks like this:

    your_command "Is anybody listening?" >&-
    

    Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &> (below) is a special BASH syntax incompatible with >&-:

    /your/first/command >&- 2>&-
    

    Be careful to note the order: >&- closes stdout, which is what you want to do; &>- redirects stdout and stderr to a file named - (hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2 redirects stdout to descriptor 2 (stderr), >&3 redirects stdout to descriptor 3, and >&- redirects stdout to a dead end (i.e. it closes stdout).

    Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...

  • Redirect output to /dev/null, which accepts all output and does nothing with it. It looks like this:

    your_command "Hello?" > /dev/null
    

    For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:

    /your/first/command &> /dev/null
    

Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; ) syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.

{
  /your/first/command
  /your/second/command
} &> /dev/null

See the bash manual on redirections for more details, options, and syntax.

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

Maven plugin not using Eclipse's proxy settings

Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings. If the file doesn't exist, create it and put on something like this:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>192.168.1.100</host>
      <port>6666</port>
      <username></username>
      <password></password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
  </proxies>
  <profiles/>
  <activeProfiles/>
</settings>

After editing the file, it's just a matter of clicking on Update Settings button and it's done. I've just done it and it worked :)

Targeting .NET Framework 4.5 via Visual Studio 2010

There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).

  1. Backup your project file!!!

  2. Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.

  3. Open your project in VS2010.

  4. Create a text file in your project named Compile_4_5_CSharp.targets with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):

    <Project DefaultTargets="Build"
     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
        <!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
        <PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
            <DefineConstants Condition="'$(DefineConstants)'==''">
                TARGETTING_FX_4_5
            </DefineConstants>
            <DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
                $(DefineConstants);TARGETTING_FX_4_5
            </DefineConstants>
            <PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
            <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
        </PropertyGroup>
    
        <!-- Import the standard C# targets -->
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
    
        <!-- Add .NET 4.5 as an available platform -->
        <PropertyGroup>
           <AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
        </PropertyGroup>
    </Project>
    
  5. Unload your project (right click -> unload).

  6. Edit the project file (right click -> Edit *.csproj).

  7. Make the following changes in the project file:

    a. Replace the default Microsoft.CSharp.targets with the target file created in step 4

    <!-- Old Import Entry -->
    <!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
    
    <!-- New Import Entry -->
    <Import Project="Compile_4_5_CSharp.targets" />
    

    b. Change the default platform to .NET 4.5

    <!-- Old default platform entry -->
    <!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
    
    <!-- New default platform entry -->
    <Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
    

    c. Add AnyCPU platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup> tag in the file

    <PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
    
    .
    .
    .
    <ItemGroup>
    .
    .
    .
    
  8. Save your changes and close the *.csproj file.

  9. Reload your project (right click -> Reload Project).

  10. In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.

  11. Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.

  12. Build your project and check for errors.

  13. Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:

    using System;
    using System.Text;
    
    namespace testing
    {
        using net45check = System.Reflection.ReflectionContext;
    }
    
  14. When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:

    Error 6: The type or namespace name 'ReflectionContext' does not exist in
    the namespace 'System.Reflection' (are you missing an assembly reference?)
    

Handle file download from ajax post

there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.

First you need to separate the page processing from the results download.

1) Only the page calculations are made in the ajax call.

$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" },

       function(data, status) 
       {
            if (status == "success") 
            {
                /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */
                window.location.href = DownloadPage.php+"?ID="+29;
            }               
       }
);

// For example: in the CalculusPage.php

    if ( !empty($_POST["calculusFunction"]) ) 
    {
        $ID = $_POST["ID"];

        $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;
        ...
    }

// For example: in the DownloadPage.php

    $ID = $_GET["ID"];

    $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID;
    ...

    $filename="Export_Data.xls";
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: inline; filename=$filename");

    ...

I hope this solution can be useful for many, as it was for me.

WPF Image Dynamically changing Image source during runtime

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

Waiting until the task finishes

Swift 4

You can use Async Function for these situations. When you use DispatchGroup(),Sometimes deadlock may be occures.

var a: Int?
@objc func myFunction(completion:@escaping (Bool) -> () ) {

    DispatchQueue.main.async {
        let b: Int = 3
        a = b
        completion(true)
    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    myFunction { (status) in
        if status {
            print(self.a!)
        }
    }
}

throwing an exception in objective-c/cocoa

You should only throw exceptions if you find yourself in a situation that indicates a programming error, and want to stop the application from running. Therefore, the best way to throw exceptions is using the NSAssert and NSParameterAssert macros, and making sure that NS_BLOCK_ASSERTIONS is not defined.

Adding a column to an existing table in a Rails migration

You can also force to table columns in table using force: true, if you table is already exist.

example:

ActiveRecord::Schema.define(version: 20080906171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

Perform .join on value in array of objects

An old thread I know but still super relevant to anyone coming across this.

Array.map has been suggested here which is an awesome method that I use all the time. Array.reduce was also mentioned...

I would personally use an Array.reduce for this use case. Why? Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join.

The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. Array.join then loops over the contents of array to perform the join.

You can improve the readability of jackweirdys reduce answer by using template literals to get the code on to a single line. "Supported in all modern browsers too"

// a one line answer to this question using modern JavaScript
x.reduce((a, b) => `${a.name || a}, ${b.name}`);

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

mysql: SOURCE error 2?

I was having this issue and it turns out if you are using wamp server to run mysql, you have to use the file path within the wamp64 folder. So when the absolute path is: C:/wamp64/www/foldername/filename.sql The path you have to use is: www/foldername/filename.sql

In Python, how do I convert all of the items in a list to floats?

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)

Android Spinner : Avoid onItemSelected calls during initialization

haha...I have the same question. When initViews() just do like this.The sequence is the key, listener is the last. Good Luck !

spinner.setAdapter(adapter);
spinner.setSelection(position);
spinner.setOnItemSelectedListener(listener);

Date vs DateTime

The DateTime object has a Property which returns only the date portion of the value.

    public static void Main()
{
    System.DateTime _Now = DateAndTime.Now;
    Console.WriteLine("The Date and Time is " + _Now);
    //will return the date and time
    Console.WriteLine("The Date Only is " + _Now.Date);
    //will return only the date
    Console.Write("Press any key to continue . . . ");
    Console.ReadKey(true);
}

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

How to set UICollectionViewCell Width and Height programmatically

swift4 swift 4 ios collection view collectionview example xcode latest code working sample

Add this on Delegate section of the top

UICollectionViewDelegateFlowLayout

and use this function

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 20) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

///// sample complete code

create on collection view and collectionview cell in storyboard give reference to the collection as
@IBOutlet weak var cvContent: UICollectionView!

paste this in View controller

 import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var arrVeg = [String]()
    var arrFruits = [String]()
    var arrCurrent = [String]()
    
    @IBOutlet weak var cvContent: UICollectionView!
    
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        arrVeg = ["Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato"]
        
        arrVeg = ["Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange"]
        
        
        arrCurrent = arrVeg
    }
    //MARK: - CollectionView
    


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (self.view.frame.size.width - 20) / 3 //some width
        let height = width * 1.5 //ratio
        return CGSize(width: width, height: height)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return arrCurrent.count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
        cell.backgroundColor =  UIColor.green
        return cell
    }
}

Using LIMIT within GROUP BY to get N results per group?

Build the virtual columns(like RowID in Oracle)

Table:

CREATE TABLE `stack` 
(`year` int(11) DEFAULT NULL,
`id` varchar(10) DEFAULT NULL,
`rate` float DEFAULT NULL) 
ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

Data:

insert into stack values(2006,'p01',8);
insert into stack values(2001,'p01',5.9);
insert into stack values(2007,'p01',5.3);
insert into stack values(2009,'p01',4.4);
insert into stack values(2001,'p02',12.5);
insert into stack values(2004,'p02',12.4);
insert into stack values(2005,'p01',2.1);
insert into stack values(2000,'p01',0.8);
insert into stack values(2002,'p02',12.2);
insert into stack values(2002,'p01',3.9);
insert into stack values(2004,'p01',3.5);
insert into stack values(2003,'p02',10.3);
insert into stack values(2000,'p02',8.7);
insert into stack values(2006,'p02',4.6);
insert into stack values(2007,'p02',3.3);
insert into stack values(2003,'p01',7.4);
insert into stack values(2008,'p01',6.8);

SQL like this:

select t3.year,t3.id,t3.rate 
from (select t1.*, (select count(*) from stack t2 where t1.rate<=t2.rate and t1.id=t2.id) as rownum from stack t1) t3 
where rownum <=3 order by id,rate DESC;

If delete the where clause in t3, it shows like this:

enter image description here

GET "TOP N Record" --> add the rownum <=3 in where clause (the where-clause of t3);

CHOOSE "the year" --> add the BETWEEN 2000 AND 2009 in where clause (the where-clause of t3);

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Changed all dependencies to compile rather than implementation, then I rebuild the project without errors. Then I switched back to implementation rather than leaving it as compile.

Regex to split a CSV

In Java this pattern ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))" almost work for me:

String text = "\",\",\",,\",,\",asdasd a,sd s,ds ds,dasda,sds,ds,\"";
String regex = ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))";
Pattern p = Pattern.compile(regex);
String[] split = p.split(text);
for(String s:split) {
    System.out.println(s);
}

output:

","
",a,,"

",asdasd a,sd s,ds ds,dasda,sds,ds,"

Disadvantage: not work, when column have an odd number of quotes :(

How to replace master branch in Git, entirely, from another branch?

You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:

git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks

The result should be your master is now essentially seotweaks.

(-s ours is short for --strategy=ours)

From the docs about the 'ours' strategy:

This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.

Update from comments: If you get fatal: refusing to merge unrelated histories, then change the second line to this: git merge --allow-unrelated-histories -s ours master

Get the Year/Month/Day from a datetime in php?

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

How to find event listeners on a DOM node when debugging or from the JavaScript code?

It depends on how the events are attached. For illustration presume we have the following click handler:

var handler = function() { alert('clicked!') };

We're going to attach it to our element using different methods, some which allow inspection and some that don't.

Method A) single event handler

element.onclick = handler;
// inspect
console.log(element.onclick); // "function() { alert('clicked!') }"

Method B) multiple event handlers

if(element.addEventListener) { // DOM standard
    element.addEventListener('click', handler, false)
} else if(element.attachEvent) { // IE
    element.attachEvent('onclick', handler)
}
// cannot inspect element to find handlers

Method C): jQuery

$(element).click(handler);
  • 1.3.x

     // inspect
     var clickEvents = $(element).data("events").click;
     jQuery.each(clickEvents, function(key, value) {
         console.log(value) // "function() { alert('clicked!') }"
     })
    
  • 1.4.x (stores the handler inside an object)

     // inspect
     var clickEvents = $(element).data("events").click;
     jQuery.each(clickEvents, function(key, handlerObj) {
         console.log(handlerObj.handler) // "function() { alert('clicked!') }"
         // also available: handlerObj.type, handlerObj.namespace
     })
    
  • 1.7+ (very nice)

    Made using knowledge from this comment.

     events = $._data(this, 'events');
     for (type in events) {
       events[type].forEach(function (event) {
         console.log(event['handler']);
       });
     }
    

(See jQuery.fn.data and jQuery.data)

Method D): Prototype (messy)

$(element).observe('click', handler);
  • 1.5.x

     // inspect
     Event.observers.each(function(item) {
         if(item[0] == element) {
             console.log(item[2]) // "function() { alert('clicked!') }"
         }
     })
    
  • 1.6 to 1.6.0.3, inclusive (got very difficult here)

     // inspect. "_eventId" is for < 1.6.0.3 while 
     // "_prototypeEventID" was introduced in 1.6.0.3
     var clickEvents = Event.cache[element._eventId || (element._prototypeEventID || [])[0]].click;
     clickEvents.each(function(wrapper){
         console.log(wrapper.handler) // "function() { alert('clicked!') }"
     })
    
  • 1.6.1 (little better)

     // inspect
     var clickEvents = element.getStorage().get('prototype_event_registry').get('click');
     clickEvents.each(function(wrapper){
         console.log(wrapper.handler) // "function() { alert('clicked!') }"
     })
    

When clicking the resulting output in the console (which shows the text of the function), the console will navigate directly to the line of the function's declaration in the relevant JS file.

How to copy file from host to container using Dockerfile

I was able to copy a file from my host to the container within a dockerfile as such:

  1. Created a folder on my c driver --> c:\docker
  2. Create a test file in the same folder --> c:\docker\test.txt
  3. Create a docker file in the same folder --> c:\docker\dockerfile
  4. The contents of the docker file as follows,to copy a file from local host to the root of the container: FROM ubuntu:16.04

    COPY test.txt /

  5. Pull a copy of ubuntu from docker hub --> docker pull ubuntu:16.04
  6. Build the image from the dockerfile --> docker build -t myubuntu c:\docker\
  7. Build the container from your new image myubuntu --> docker run -d -it --name myubuntucontainer myubuntu "/sbin/init"
  8. Connect to the newly created container -->docker exec -it myubuntucontainer bash
  9. Check if the text.txt file is in the root --> ls

You should see the file.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

How to access a mobile's camera from a web app?

Nowadays at least with android it's relatively easy. Just use normal file input tag and when user clicks it the phone will ask if user wants to use camera (or file managers etc..) to upload a file. Just take a photo with the camera and it will automatically be added and uploaded.

No idea about iphone. Maybe someone can enlighten on that. EDIT: Iphone works similarly.

Sample of the input tag:

<input type="file" accept="image/*" capture="camera">

Check whether number is even or odd

Least significant bit (rightmost) can be used to check if the number is even or odd. For all Odd numbers, rightmost bit is always 1 in binary representation.

public static boolean checkOdd(long number){
   return ((number & 0x1) == 1);
}

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

How to finish current activity in Android

You can also use: finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

but, non-native implementations are faster e.g. https://gist.github.com/958841 see http://jsperf.com/encoding-xhr-image-data/6

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

The SETX command does not modify the current environment.

If you run the following batch file:

setx AAA aaa
echo AAA=%AAA%

It will print

AAA=

So your batch file is wrong. You have to use set:

set AAA=aaa

See What is the difference between SETX and SET in environment variables in Windows.

How do I show the value of a #define at compile-time?

In Microsoft C/C++, you can use the built-in _CRT_STRINGIZE() to print constants. Many of my stdafx.h files contain some combination of these:

#pragma message("_MSC_VER      is " _CRT_STRINGIZE(_MSC_VER))
#pragma message("_MFC_VER      is " _CRT_STRINGIZE(_MFC_VER))
#pragma message("_ATL_VER      is " _CRT_STRINGIZE(_ATL_VER))
#pragma message("WINVER        is " _CRT_STRINGIZE(WINVER))
#pragma message("_WIN32_WINNT  is " _CRT_STRINGIZE(_WIN32_WINNT))
#pragma message("_WIN32_IE     is " _CRT_STRINGIZE(_WIN32_IE))
#pragma message("NTDDI_VERSION is " _CRT_STRINGIZE(NTDDI_VERSION)) 

and outputs something like this:

_MSC_VER      is 1915
_MFC_VER      is 0x0E00
_ATL_VER      is 0x0E00
WINVER        is 0x0600
_WIN32_WINNT  is 0x0600
_WIN32_IE     is 0x0700
NTDDI_VERSION is 0x06000000

Regex to check with starts with http://, https:// or ftp://

I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

Taken from that page:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

yields the following:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

grep for special characters in Unix

A related note

To grep for carriage return, namely the \r character, or 0x0d, we can do this:

grep -F $'\r' application.log

Alternatively, use printf, or echo, for POSIX compatibility

grep -F "$(printf '\r')" application.log

And we can use hexdump, or less to see the result:

$ printf "a\rb" | grep -F $'\r' | hexdump -c
0000000   a  \r   b  \n

Regarding the use of $'\r' and other supported characters, see Bash Manual > ANSI-C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

How to clear textarea on click?

Try:

<input name="mytextbox" onfocus="if (this.value=='Please describe why') this.value = ''" type="text" value="Please Describe why">

Rotation of 3D vector?

Here is an elegant method using quaternions that are blazingly fast; I can calculate 10 million rotations per second with appropriately vectorised numpy arrays. It relies on the quaternion extension to numpy found here.

Quaternion Theory: A quaternion is a number with one real and 3 imaginary dimensions usually written as q = w + xi + yj + zk where 'i', 'j', 'k' are imaginary dimensions. Just as a unit complex number 'c' can represent all 2d rotations by c=exp(i * theta), a unit quaternion 'q' can represent all 3d rotations by q=exp(p), where 'p' is a pure imaginary quaternion set by your axis and angle.

We start by converting your axis and angle to a quaternion whose imaginary dimensions are given by your axis of rotation, and whose magnitude is given by half the angle of rotation in radians. The 4 element vectors (w, x, y, z) are constructed as follows:

import numpy as np
import quaternion as quat

v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian

vector = np.array([0.] + v)
rot_axis = np.array([0.] + axis)
axis_angle = (theta*0.5) * rot_axis/np.linalg.norm(rot_axis)

First, a numpy array of 4 elements is constructed with the real component w=0 for both the vector to be rotated vector and the rotation axis rot_axis. The axis angle representation is then constructed by normalizing then multiplying by half the desired angle theta. See here for why half the angle is required.

Now create the quaternions v and qlog using the library, and get the unit rotation quaternion q by taking the exponential.

vec = quat.quaternion(*v)
qlog = quat.quaternion(*axis_angle)
q = np.exp(qlog)

Finally, the rotation of the vector is calculated by the following operation.

v_prime = q * vec * np.conjugate(q)

print(v_prime) # quaternion(0.0, 2.7491163, 4.7718093, 1.9162971)

Now just discard the real element and you have your rotated vector!

v_prime_vec = v_prime.imag # [2.74911638 4.77180932 1.91629719] as a numpy array

Note that this method is particularly efficient if you have to rotate a vector through many sequential rotations, as the quaternion product can just be calculated as q = q1 * q2 * q3 * q4 * ... * qn and then the vector is only rotated by 'q' at the very end using v' = q * v * conj(q).

This method gives you a seamless transformation between axis angle <---> 3d rotation operator simply by exp and log functions (yes log(q) just returns the axis-angle representation!). For further clarification of how quaternion multiplication etc. work, see here

How to use classes from .jar files?

As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)

If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo

here is the complete select query

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        // code here 
    }
} else {
    echo "0 results";
}
$conn->close();
?>

How to show progress dialog in Android?

Point one you should remember when it comes to Progress dialog is that you should run it in a separate thread. If you run it in your UI thread you'll see no dialog.

If you are new to Android Threading then you should learn about AsyncTask. Which helps you to implement a painless Threads.

sample code

private class CheckTypesTask extends AsyncTask<Void, Void, Void>{
        ProgressDialog asyncDialog = new ProgressDialog(IncidentFormActivity.this);
        String typeStatus;


        @Override
        protected void onPreExecute() {
            //set message of the dialog
            asyncDialog.setMessage(getString(R.string.loadingtype));
            //show dialog
            asyncDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            //don't touch dialog here it'll break the application
            //do some lengthy stuff like calling login webservice

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //hide the dialog
            asyncDialog.dismiss();

            super.onPostExecute(result);
        }

}

Good luck.

How to pass model attributes from one Spring MVC controller to another controller?

Add all model attributes to the redirecting URL as query string.

How many socket connections possible?

depends on the application. if there is only a few packages from each client, 100K is very easy for linux. A engineer of my team had done a test years ago, the result shows : when there is no package from client after connection established, linux epoll can watch 400k fd for readablity at cpu usage level under 50%.

How can I strip all punctuation from a string in JavaScript using regex?

Here are the standard punctuation characters for US-ASCII: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

For Unicode punctuation (such as curly quotes, em-dashes, etc), you can easily match on specific block ranges. The General Punctuation block is \u2000-\u206F, and the Supplemental Punctuation block is \u2E00-\u2E7F.

Put together, and properly escaped, you get the following RegExp:

/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/

That should match pretty much any punctuation you encounter. So, to answer the original question:

var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');

>> "This is an example of a string with punctuation"

US-ASCII source: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix

Unicode source: http://kourge.net/projects/regexp-unicode-block

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Try this:

To accept theirs changes: git merge --strategy-option theirs

To accept yours: git merge --strategy-option ours

How to abort makefile if variable not set?

For simplicity and brevity:

$ cat Makefile
check-%:
        @: $(if $(value $*),,$(error $* is undefined))

bar:| check-foo
        echo "foo is $$foo"

With outputs:

$ make bar
Makefile:2: *** foo is undefined. Stop.
$ make bar foo="something"
echo "foo is $$foo"
foo is something

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

Replace \n with <br />

thatLine = thatLine.replace('\n', '<br />')

Strings in Python are immutable. You might need to recreate it with the assignment operator.