Programs & Examples On #Ingres

Use this tag for Ingres / Actian X questions. The Ingres v11 RDBMS is now known as Actian X and in addition to supporting OLTP, also supports analytic workloads with X100 tables and Vector engine, making it a hybrid OLTP and analytic database.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I had some issues playing on Android Phone. After few tries I found out that when Data Saver is on there is no auto play:

There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.

Source

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I got this exception while attempting to use a deleteBy custom method in the spring data repository. The operation was attempted from a JUnit test class.

The exception does not occur upon using the @Transactional annotation at the JUnit class level.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

for alamofire 4 use this ..

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(fileUrl, withName: "video")
       //fileUrl is your file path in iOS device and withName is parameter name

        }, to:"http://to_your_url_path")
        { (result) in
            switch result {
            case .success(let upload, _ , _):

                upload.uploadProgress(closure: { (progress) in

                    print("uploding")
                })

                upload.responseJSON { response in

                   print("done")

                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

Check for the name of the

templates

folder. it should be templates not template(without s).

CFNetwork SSLHandshake failed iOS 9

Updated Answer (post-WWDC 2016):

iOS apps will require secure HTTPS connections by the end of 2016. Trying turn ATS off may get your app rejected in the future.

App Transport Security, or ATS, is a feature that Apple introduced in iOS 9. When ATS is enabled, it forces an app to connect to web services over an HTTPS connection rather than non secure HTTP.

However, developers can still switch ATS off and allow their apps to send data over an HTTP connection as mentioned in above answers. At the end of 2016, Apple will make ATS mandatory for all developers who hope to submit their apps to the App Store. link

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

Swift extract regex matches

Even if the matchesInString() method takes a String as the first argument, it works internally with NSString, and the range parameter must be given using the NSString length and not as the Swift string length. Otherwise it will fail for "extended grapheme clusters" such as "flags".

As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange.

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]

Note: The forced unwrap Range($0.range, in: text)! is safe because the NSRange refers to a substring of the given string text. However, if you want to avoid it then use

        return results.flatMap {
            Range($0.range, in: text).map { String(text[$0]) }
        }

instead.


(Older answer for Swift 3 and earlier:)

So you should convert the given Swift string to an NSString and then extract the ranges. The result will be converted to a Swift string array automatically.

(The code for Swift 1.2 can be found in the edit history.)

Swift 2 (Xcode 7.3.1) :

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matches = matchesForRegexInText("[0-9]", text: string)
print(matches)
// ["4", "9"]

Swift 3 (Xcode 8)

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

1 Close Android Studio (AS)

2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all

3 Run AS as admin

4 Sync your project files

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

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

I used to have the same problem.

Your config use security="none" so cannot generate _csrf:

<http pattern="/login.jsp" security="none"/>

you can set access="IS_AUTHENTICATED_ANONYMOUSLY" for page /login.jsp replace above config:

<http>
    <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/**" access="ROLE_USER"/>
    <form-login login-page="/login.jsp"
            authentication-failure-url="/login.jsp?error=1"
            default-target-url="/index.jsp"/>
    <logout/>
    <csrf />
</http>

android studio 0.4.2: Gradle project sync failed error

All you have to do is remove .gradle from user, paste, and verify update in Android Studio and it will work perfectly!

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

ResourceBundle doesn't load files? You need to get the files into a resource first. How about just loading into a FileInputStream then a PropertyResourceBundle

   FileInputStream fis = new FileInputStream("skyscrapper.properties");
   resourceBundle = new PropertyResourceBundle(fis);

Or if you need the locale specific code, something like this should work

File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

Redirect to an external URL from controller action in Spring MVC

Did you try RedirectView where you can provide the contextRelative parameter?

UITableView with fixed section headers

The headers only remain fixed when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.

Spring,Request method 'POST' not supported

I had csrf enabled in my sprint security xml file, so I just added one line in the form:

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

This way I was able to submit the form having the model attribute.

File inside jar is not visible for spring

I was having an issue recursively loading resources in my Spring app, and found that the issue was I should be using resource.getInputStream. Here's an example showing how to recursively read in all files in config/myfiles that are json files.

Example.java

private String myFilesResourceUrl = "config/myfiles/**/";
private String myFilesResourceExtension = "json";

ResourceLoader rl = new ResourceLoader();

// Recursively get resources that match. 
// Big note: If you decide to iterate over these, 
// use resource.GetResourceAsStream to load the contents
// or use the `readFileResource` of the ResourceLoader class.
Resource[] resources = rl.getResourcesInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

// Recursively get resource and their contents that match. 
// This loads all the files into memory, so maybe use the same approach 
// as this method, if need be.
Map<Resource,String> contents = rl.getResourceContentsInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

ResourceLoader.java

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StreamUtils;

public class ResourceLoader {
  public Resource[] getResourcesInResourceFolder(String folder, String extension) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
      String resourceUrl = folder + "/*." + extension;
      Resource[] resources = resolver.getResources(resourceUrl);
      return resources;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public String readResource(Resource resource) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
      return StreamUtils.copyToString(stream, Charset.defaultCharset());
    }
  }

  public Map<Resource, String> getResourceContentsInResourceFolder(
      String folder, String extension) {
    Resource[] resources = getResourcesInResourceFolder(folder, extension);

    HashMap<Resource, String> result = new HashMap<>();
    for (var resource : resources) {
      try {
        String contents = readResource(resource);
        result.put(resource, contents);
      } catch (IOException e) {
        throw new RuntimeException("Could not load resource=" + resource + ", e=" + e);
      }
    }
    return result;
  }
}

Can't find bundle for base name /Bundle, locale en_US

The problem must be that the resource-bunde > base-name attribute at the faces-config.xml file has a different path to your properties. This happened to me on the firstcup Java EE tutorial, I gave a different package name on then project creation and then Glassfish was unable to find the properties folder which is on "firstcup.web".

I hope it helps.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I was getting similar problem for other reason (url pattern test-response not added in csrf token) I resolved it by allowing my URL pattern in following property in config/local.properties:

csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$

modified to

csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

Neither BindingResult nor plain target object for bean name available as request attribute

If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.

Pinging an IP address using PHP and echoing the result

This works fine with hostname, reverse IP (for internal networks) and IP.

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

Open page in new window without popup blocking

For the Submit button, add this code and then set your form target="newwin"

onclick=window.open("about:blank","newwin") 

Redirect in Spring MVC

Axtavt answer is correct.

This is how your resolver should look like (annotations based):

    @Bean
UrlBasedViewResolver resolver(){
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();

    resolver.setPrefix("/views/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);

    return resolver;
}

Obviously the name of your views directory should change based on your project.

Sending Multipart File as POST parameters with RestTemplate requests

I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:

pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>${commons-version}</version>
</dependency>

web.xml - Add multipart filter and mapping

<filter>
  <filter-name>multipartFilter</filter-name>
  <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>multipartFilter</filter-name>
  <url-pattern>/springrest/*</url-pattern>
</filter-mapping>

app-context.xml - Add multipart resolver

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize">
        <beans:value>10000000</beans:value>
    </beans:property>
</beans:bean>

Your Controller

@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri, 
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType, 
        @RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
    // Do something with file
    // Return results
}

Your client

public static Boolean updateStationImage(StationImage stationImage) {
    if(stationImage == null) {
        Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
        return null;
    }

    Log.d(TAG, "Uploading: " + stationImage.getImageUri());
    try {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
        formConverter.setCharset(Charset.forName("UTF8"));
        restTemplate.getMessageConverters().add(formConverter);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();

        parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
        parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
        parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
        parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());

        return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));

        Log.e(TAG + ":addStationImage", sw.toString());
    }

    return false;
}

That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.

What does the @Valid annotation indicate in Spring?

I think I know where your question is headed. And since this question is the one that pop ups in google's search main results, I can give a plain answer on what the @Valid annotation does.

I'll present 3 scenarios on how I've used @Valid

Model:

public class Employee{
private String name;
@NotNull(message="cannot be null")
@Size(min=1, message="cannot be blank")
private String lastName;
 //Getters and Setters for both fields.
 //...
}

JSP:

...
<form:form action="processForm" modelAttribute="employee">
 <form:input type="text" path="name"/>
 <br>
 <form:input type="text" path="lastName"/>
<form:errors path="lastName"/>
<input type="submit" value="Submit"/>
</form:form>
...

Controller for scenario 1:

     @RequestMapping("processForm")
        public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
        return "employee-confirmation-page";
    }

In this scenario, after submitting your form with an empty lastName field, you'll get an error page since you're applying validation rules but you're not handling it whatsoever.

Example of said error: Exception page

Controller for scenario 2:

 @RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult){
                return bindingResult.hasErrors() ? "employee-form" : "employee-confirmation-page";
            }

In this scenario, you're passing all the results from that validation to the bindingResult, so it's up to you to decide what to do with the validation results of that form.

Controller for scenario 3:

@RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
                return "employee-confirmation-page";
            }
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> invalidFormProcessor(MethodArgumentNotValidException ex){
  //Your mapping of the errors...etc
}

In this scenario you're still not handling the errors like in the first scenario, but you pass that to another method that will take care of the exception that @Valid triggers when processing the form model. Check this see what to do with the mapping and all that.

To sum up: @Valid on its own with do nothing more that trigger the validation of validation JSR 303 annotated fields (@NotNull, @Email, @Size, etc...), you still need to specify a strategy of what to do with the results of said validation.

Hope I was able to clear something for people that might stumble with this.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

To re-cap the question in the OP:

I am connecting [to a WCF service] using WCFStorm which is able to retrieve all the meta data properly, but when I call the actual method I get:

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

The WCFStorm tutorials addresses this issue in Working with IIS and SSL.

Their solution worked for me:

  1. To fix the error, generate a client config that matches the wcf service configuration. The easiest way to do this is with Visual Studio.

    • Open Visual Studio and add a service reference to the service. VS will generate an app.config file that matches the service

    • Edit the app.config file so that it can be read by WCFStorm. Please see Loading Client App.config files. Ensure that the endpoint/@name and endpoint/@contract attributes match the values in wcfstorm.

  2. Load the modified app.config to WCFStorm [using the Client Config toobar button].

  3. Invoke the method. This time the method invocation will no longer fail

Item (1) last bullet in effect means to remove the namespace prefix that VS prepends to the endpoint contract attribute, by default "ServiceReference1"

<endpoint ... contract="ServiceReference1.ListsService" ... />

so in the app.config that you load into WCFStorm you want for ListsService:

<endpoint ... contract="ListsService" ... />

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

How to use NSURLConnection to connect with SSL for an untrusted cert?

The category workaround posted by Nathan de Vries will pass the AppStore private API checks, and is useful in cases where you do not have control of the NSUrlConnection object. One example is NSXMLParser which will open the URL you supply, but does not expose the NSURLRequest or NSURLConnection.

In iOS 4 the workaround still seems to work, but only on the device, the Simulator does not invoke the allowsAnyHTTPSCertificateForHost: method anymore.

error: RPC failed; curl transfer closed with outstanding read data remaining

This error seems to happen more commonly with a slow, or troubled internet connection. I have connected with good internet speed then it is worked perfectly.

How to type a new line character in SQL Server Management Studio

In SSMS, you can't print new line with select, just using PRINT instead

DECLARE @text NVARCHAR(100)
SET @text = concat(N'This is line 1.', CHAR(10), N'This is line 2.')
PRINT @text

Use of Greater Than Symbol in XML

Use &gt; and &lt; for 'greater-than' and 'less-than' respectively

Making an iframe responsive

I present to you The Incredible Singing Cat solution =)

.wrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
}
.wrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

jsFiddle: http://jsfiddle.net/omarjuvera/8zkunqxy/2/
As you move the window bar, you'll see iframe to responsively resize


Alternatively, you may also use the intrinsic ratio technique - This is just an alternate option of the same solution above (tomato, tomato)

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
} 

.iframe-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  border: 0;
  width: 100%;
  height: 100%;
}

jquery smooth scroll to an anchor?

Using hanoo's script I created a jQuery function:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

usage:

$('#myelement').scrollIntoView();

Defaults for duration and easing are 400ms and "swing".

Spring MVC: How to perform validation?

With Spring MVC, there are 3 different ways to perform validation : using annotation, manually, or a mix of both. There is not a unique "cleanest and best way" to validate, but there is probably one that fits your project/problem/context better.

Let's have a User :

public class User {

    private String name;

    ...

}

Method 1 : If you have Spring 3.x+ and simple validation to do, use javax.validation.constraints annotations (also known as JSR-303 annotations).

public class User {

    @NotNull
    private String name;

    ...

}

You will need a JSR-303 provider in your libraries, like Hibernate Validator who is the reference implementation (this library has nothing to do with databases and relational mapping, it just does validation :-).

Then in your controller you would have something like :

@RequestMapping(value="/user", method=RequestMethod.POST)
public createUser(Model model, @Valid @ModelAttribute("user") User user, BindingResult result){
    if (result.hasErrors()){
      // do something
    }
    else {
      // do something else
    }
}

Notice the @Valid : if the user happens to have a null name, result.hasErrors() will be true.

Method 2 : If you have complex validation (like big business validation logic, conditional validation across multiple fields, etc.), or for some reason you cannot use method 1, use manual validation. It is a good practice to separate the controller’s code from the validation logic. Don't create your validation class(es) from scratch, Spring provides a handy org.springframework.validation.Validator interface (since Spring 2).

So let's say you have

public class User {

    private String name;

    private Integer birthYear;
    private User responsibleUser;
    ...

}

and you want to do some "complex" validation like : if the user's age is under 18, responsibleUser must not be null and responsibleUser's age must be over 21.

You will do something like this

public class UserValidator implements Validator {

    @Override
    public boolean supports(Class clazz) {
      return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
      User user = (User) target;

      if(user.getName() == null) {
          errors.rejectValue("name", "your_error_code");
      }

      // do "complex" validation here

    }

}

Then in your controller you would have :

@RequestMapping(value="/user", method=RequestMethod.POST)
    public createUser(Model model, @ModelAttribute("user") User user, BindingResult result){
        UserValidator userValidator = new UserValidator();
        userValidator.validate(user, result);

        if (result.hasErrors()){
          // do something
        }
        else {
          // do something else
        }
}

If there are validation errors, result.hasErrors() will be true.

Note : You can also set the validator in a @InitBinder method of the controller, with "binder.setValidator(...)" (in which case a mix use of method 1 and 2 would not be possible, because you replace the default validator). Or you could instantiate it in the default constructor of the controller. Or have a @Component/@Service UserValidator that you inject (@Autowired) in your controller : very useful, because most validators are singletons + unit test mocking becomes easier + your validator could call other Spring components.

Method 3 : Why not using a combination of both methods? Validate the simple stuff, like the "name" attribute, with annotations (it is quick to do, concise and more readable). Keep the heavy validations for validators (when it would take hours to code custom complex validation annotations, or just when it is not possible to use annotations). I did this on a former project, it worked like a charm, quick & easy.

Warning : you must not mistake validation handling for exception handling. Read this post to know when to use them.

References :

Check/Uncheck a checkbox on datagridview

The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach is selecting each checkbox and performing the operations.

To make it clear, store the index of the user selected checkbox before performing the foreach operation and after the foreach operation call the checkbox by mentioning the stored index and check it (In your case, make it True -- I think).

This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.

Modify your foreach something like this:

    //Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagridview1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
            if (chk.Selected == true)
            {
                chk.Selected = false;
            }
            else
            {
                chk.Selected = true;
            }
        }
    }
    //write the function for checking(making true) the user selected checkbox by calling the stored Index

The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

OK, first of all, you don't have to get a reference to the module into a different name; you already have a reference (from the import) and you can just use it. If you want a different name just use import swineflu as f.

Second, you are getting a reference to the class rather than instantiating the class.

So this should be:

import swineflu

fibo = swineflu.fibo()  # get an instance of the class
fibo.f()                # call the method f of the instance

A bound method is one that is attached to an instance of an object. An unbound method is, of course, one that is not attached to an instance. The error usually means you are calling the method on the class rather than on an instance, which is exactly what was happening in this case because you hadn't instantiated the class.

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

Look at the find command.

What you are looking for is something like

find . -name "*.xls" -type f -exec program 

Post edit

find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;

will execute xls2csv file.xls file.xls.csv

Closer to what you want.

How to populate a sub-document in mongoose after creating it?

I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)

applicantListToExport: function (query, callback) {
  this
   .find(query).select({'advtId': 0})
   .populate({
      path: 'influId',
      model: 'influencer',
      select: { '_id': 1,'user':1},
      populate: {
        path: 'userid',
        model: 'User'
      }
   })
 .populate('campaignId',{'campaignTitle':1})
 .exec(callback);
}

Set Google Maps Container DIV width and height 100%

This worked for me.

map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}

INSERT VALUES WHERE NOT EXISTS

Ingnoring the duplicated unique constraint isn't a solution?

INSERT IGNORE INTO tblSoftwareTitles...

White space at top of page

overflow: auto

Using overflow: auto on the <body> tag is a cleaner solution and will work a charm.

How to start Apache and MySQL automatically when Windows 8 comes up

Open:

C/users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up

If there is a problem finding the above directory:***

Press Windows + R and write shell:startup. Press Enter. It will move you to the directory.

Drag and drop the XAMPP control panel to the above directory

It will open XAMPP automatically.

If you want to auto start Apache and MySQL, click on config in XAMPP and check the Apache and XAMPP items (if unchecked) and save it. It will start it automatically.

Creating JSON on the fly with JObject

Sooner or later you will have property with special character. You can either use index or combination of index and property.

dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

How do I display local image in markdown?

The best solution is to provide a path relative to the folder where the md document is located.

Probably a browser is in trouble when it tries to resolve the absolute path of a local file. That can be solved by accessing the file trough a webserver, but even in that situation, the image path has to be right.

Having a folder at the same level of the document, containing all the images, is the cleanest and safest solution. It will load on GitHub, local, local webserver.

images_folder/img.jpg  < works


/images_folder/img.jpg  < this will work on webserver's only (please read the note!)

Using the absolute path, the image will be accessible only with a url like this: http://hostname.doesntmatter/image_folder/img.jpg

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

How to watch for a route change in AngularJS?

This is for the total beginner... like me:

HTML:

  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});

Hope this helps a total beginner like me. Here is the full working sample:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="#"> Home </a>_x000D_
    </li>_x000D_
    <li>_x000D_
      <a href="#Info"> Info </a>_x000D_
    </li>_x000D_
  </ul>_x000D_
_x000D_
  <div ng-app="myApp" ng-controller="MainCtrl">_x000D_
    <div ng-view>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
  <script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
    $routeProvider_x000D_
      .otherwise({ template: "<p>Coming soon</p>" })_x000D_
      .when("/", {_x000D_
        template: "<p>Home information</p>"_x000D_
      })_x000D_
      .when("/Info", {_x000D_
        template: "<p>Basic information</p>"_x000D_
        //templateUrl: "/content/views/Info.html"_x000D_
      });_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
  $scope.location = $location.path();_x000D_
  $rootScope.$on('$routeChangeStart', function () {_x000D_
    console.log("routeChangeStart");_x000D_
   //Place code here:...._x000D_
   });_x000D_
});_x000D_
  </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add local jar files to a Maven project?

Another interesting case is when you want to have in your project private maven jars. You may want to keep the capabilities of Maven to resolve transitive dependencies. The solution is fairly easy.

  1. Create a folder libs in your project
  2. Add the following lines in your pom.xml file

    <properties><local.repository.folder>${pom.basedir}/libs/</local.repository.folder>
    </properties>
    
    <repositories>
       <repository>
            <id>local-maven-repository</id>
            <url>file://${local.repository.folder}</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
       </repository>
    </repositories>
    
  3. Open the .m2/repository folder and copy the directory structure of the project you want to import into the libs folder.

E.g. suppose you want to import the dependency

<dependency>
    <groupId>com.mycompany.myproject</groupId>
    <artifactId>myproject</artifactId>
    <version>1.2.3</version>
</dependency>

Just go on .m2/repository and you will see the following folder

com/mycompany/myproject/1.2.3

Copy everything in your libs folder (again, including the folders under .m2/repository) and you are done.

how to query child objects in mongodb

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})

How to get the size of the current screen in WPF?

It works with

this.Width = System.Windows.SystemParameters.VirtualScreenWidth;
this.Height = System.Windows.SystemParameters.VirtualScreenHeight;

Tested on 2 monitors.

What is the difference between PUT, POST and PATCH?

Think of it this way...

POST - create

PUT - replace

PATCH - update

GET - read

DELETE - delete

Save results to csv file with Python

An easy example would be something like:

writer = csv.writer(open("filename.csv", "wb"))
String[] entries = "first#second#third".split("#");
writer.writerows(entries)
writer.close()

How to disable horizontal scrolling of UIScrollView?

In my case the width of the contentView was greater than the width of UIScrollView and that was the reason for unwanted horizontal scrolling. I solved it by setting the width of contentView equal to width of UIScrollView.

Hope it helps someone

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

How to normalize an array in NumPy to a unit vector?

Without sklearn and using just numpy. Just define a function:.

Assuming that the rows are the variables and the columns the samples (axis= 1):

import numpy as np

# Example array
X = np.array([[1,2,3],[4,5,6]])

def stdmtx(X):
    means = X.mean(axis =1)
    stds = X.std(axis= 1, ddof=1)
    X= X - means[:, np.newaxis]
    X= X / stds[:, np.newaxis]
    return np.nan_to_num(X)

output:

X
array([[1, 2, 3],
       [4, 5, 6]])

stdmtx(X)
array([[-1.,  0.,  1.],
       [-1.,  0.,  1.]])

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Manually type in a value in a "Select" / Drop-down HTML list?

I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.

The good news is that selectize.js does exactly this:

Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

I did it by listening query logs and appending to a log array:

//create query
$query=DB::table(...)...->where(...)...->orderBy(...)...
$log=[];//array of log lines
...
//invoked on query execution if query log is enabled
DB::listen(function ($query)use(&$log){
    $log[]=$query;//enqueue query data to logs
});
//enable query log
DB::enableQueryLog();
$res=$query->get();//execute

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

What is phtml, and when should I use a .phtml extension rather than .php?

You can choose any extension in the world if you setup Apache correctly. You could use .html to do PHP if you set up in your Apache config.

In conclusion, extension has nothing to do with the app or website itself. You can use the one you want, but normaly, use .php (to not reinvent the wheel)

But in 2019, you should use routing and forgot about extension at the end.

I recommend you using Laravel.

In answer to @KingCrunch: True, Apache not use it by default but you can easily use it if you change config. But this it not recommended since everybody know that it not really an option.

I already saw .html files that executed PHP using the html extension.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

We have come across this issue in desktop app.

Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.

enter image description here

What port is used by Java RMI connection?

In RMI, with regards to ports there are two distinct mechanisms involved:

  1. By default, the RMI Registry uses port 1099

  2. Client and server (stubs, remote objects) communicate over random ports unless a fixed port has been specified when exporting a remote object. The communcation is started via a socket factory which uses 0 as starting port, which means use any port that's available between 1 and 65535.

Simple file write function in C++

Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing

import org.springframework.transaction.annotation.Transactional;

unknowingly i have imported

import javax.transaction.Transactional;

Afer changing it everything worked fine.

So thought of sharing,If somebody does same mistake .

How to stop line breaking in vim

I'm not sure I understand completely, but you might be looking for the 'formatoptions' configuration setting. Try something like :set formatoptions-=t. The t option will insert line breaks to make text wrap at the width set by textwidth. You can also put this command in your .vimrc, just remove the colon (:).

How to generate a git patch for a specific commit?

What is the way to generate a patch only for the specific SHA1?

It's quite simple:

Option 1. git show commitID > myFile.patch

Option 2. git commitID~1..commitID > myFile.patch

Note: Replace commitID with actual commit id (SHA1 commit code).

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

How to execute a shell script on a remote server using Ansible?

local_action runs the command on the local server, not on the servers you specify in hosts parameter.

Change your "Execute the script" task to

- name: Execute the script
  command: sh /home/test_user/test.sh

and it should do it.

You don't need to repeat sudo in the command line because you have defined it already in the playbook.

According to Ansible Intro to Playbooks user parameter was renamed to remote_user in Ansible 1.4 so you should change it, too

remote_user: test_user

So, the playbook will become:

---
- name: Transfer and execute a script.
  hosts: server
  remote_user: test_user
  sudo: yes
  tasks:
     - name: Transfer the script
       copy: src=test.sh dest=/home/test_user mode=0777

     - name: Execute the script
       command: sh /home/test_user/test.sh

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I followed all the steps above indicated by Mihai-Andrei Dinculescu.
But in my case, I needed 1 more step because http OPTIONS was disabled in the Web.Config by the line below.

<remove name="OPTIONSVerbHandler" />

I just removed it from Web.Config (just comment it like below) and Cors works like a charm

<handlers>
  <!-- remove name="OPTIONSVerbHandler" / -->
</handlers>

Built in Python hash() function

It probably just asks the operating system provided function, rather than its own algorithm.

As other comments says, use hashlib or write your own hash function.

How to save data file into .RData?

There are three ways to save objects from your R session:

Saving all objects in your R session:

The save.image() function will save all objects currently in your R session:

save.image(file="1.RData") 

These objects can then be loaded back into a new R session using the load() function:

load(file="1.RData")

Saving some objects in your R session:

If you want to save some, but not all objects, you can use the save() function:

save(city, country, file="1.RData")

Again, these can be reloaded into another R session using the load() function:

load(file="1.RData") 

Saving a single object

If you want to save a single object you can use the saveRDS() function:

saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds") 

You can load these into your R session using the readRDS() function, but you will need to assign the result into a the desired variable:

city <- readRDS("city.rds")
country <- readRDS("country.rds")

But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):

city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The server at x3.chatforyoursite.com needs to output the following header:

Access-Control-Allow-Origin: http://www.example.com

Where http://www.example.com is your website address. You should check your settings on chatforyoursite.com to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.

get all characters to right of last dash

string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");

if (indexOfHyphen >= 0)
{
    string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
    Console.WriteLine(contentAfterLastHyphen );
}

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

How do I look inside a Python object?

In addition if you want to look inside list and dictionaries, you can use pprint()

Meaning of @classmethod and @staticmethod for beginner?

Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

Example

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')

Explanation

Let's assume an example of a class, dealing with date information (this will be our boilerplate):

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds a reference to a newly created instance.

Class Method

We have some tasks that can be nicely done using classmethods.

Let's assume that we want to create a lot of Date class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.

So what we must do here is:

  1. Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
  2. Instantiate Date by passing those values to the initialization call.

This will look like:

day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)

For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod. Let's create another "constructor".

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

date2 = Date.from_string('11-09-2012')

Let's look more carefully at the above implementation, and review what advantages we have here:

  1. We've implemented date string parsing in one place and it's reusable now.
  2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
  3. cls is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

Static method

What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (like a class method or instance method does).

Let's look at the next use case.

We have a date string that we want to validate somehow. This task is also logically bound to the Date class we've used so far, but doesn't require instantiation of it.

Here is where staticmethod can be useful. Let's look at the next piece of code:

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

    # usage:
    is_date = Date.is_date_valid('11-09-2012')

So, as we can see from usage of staticmethod, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.

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

solution is easy:

replace

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

by

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

JQuery .on() method with multiple event handlers to one selector

If you want to use the same function on different events the following code block can be used

$('input').on('keyup blur focus', function () {
   //function block
})

How many bytes in a JavaScript string?

You can try this:

  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 

It worked for me.

Make anchor link go some pixels above where it's linked to

I had this same issue, and there's a really quick and simple solution without CSS of JS. Just create a separate unstyled div with an ID like "aboutMeAnchor and just place it well above the section you actually want to land on.

Capturing console output from a .NET application (C#)

From PythonTR - Python Programcilari Dernegi, e-kitap, örnek:

Process p = new Process();   // Create new object
p.StartInfo.UseShellExecute = false;  // Do not use shell
p.StartInfo.RedirectStandardOutput = true;   // Redirect output
p.StartInfo.FileName = "c:\\python26\\python.exe";   // Path of our Python compiler
p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py";   // Path of the .py to be executed

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

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

window.location.href not working

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.

Difference between matches() and find() in Java Regex

matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

public static void main(String[] args) throws ParseException {
    Pattern p = Pattern.compile("\\d\\d\\d");
    Matcher m = p.matcher("a123b");
    System.out.println(m.find());
    System.out.println(m.matches());

    p = Pattern.compile("^\\d\\d\\d$");
    m = p.matcher("123");
    System.out.println(m.find());
    System.out.println(m.matches());
}

/* output:
true
false
true
true
*/

123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.

How do I capture the output of a script if it is being ran by the task scheduler?

Use the cmd.exe command processor to build a timestamped file name to log your scheduled task's output

To build upon answers by others here, it may be that you want to create an output file that has the date and/or time embedded in the name of the file. You can use the cmd.exe command processor to do this for you.

Note: This technique takes the string output of internal Windows environment variables and slices them up based on character position. Because of this, the exact values supplied in the examples below may not be correct for the region of Windows you use. Also, with some regional settings, some components of the date or time may introduce a space into the constructed file name when their value is less than 10. To mitigate this issue, surround your file name with quotes so that any unintended spaces in the file name won't break the command-line you're constructing. Experiment and find what works best for your situation.

Be aware that PowerShell is more powerful than cmd.exe. One way it is more powerful is that it can deal with different Windows regions. But this answer is about solving this issue using cmd.exe, not PowerShell, so we continue.

Using cmd.exe

You can access different components of the date and time by slicing the internal environment variables %date% and %time%, as follows (again, the exact slicing values are dependent on the region configured in Windows):

  • Year (4 digits): %date:~10,4%
  • Month (2 digits): %date:~4,2%
  • Day (2 digits): %date:~7,2%
  • Hour (2 digits): %time:~0,2%
  • Minute (2 digits): %time:~3,2%
  • Second (2 digits): %time:~6,2%

Suppose you want your log file to be named using this date/time format: "Log_[yyyyMMdd]_[hhmmss].txt". You'd use the following:

Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt

To test this, run the following command line:

cmd.exe /c echo "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

Putting it all together, to redirect both stdout and stderr from your script to a log file named with the current date and time, use might use the following as your command line:

cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1

Note the use of quotes around the file name to handle instances a date or time component may introduce a space character.

In my case, if the current date/time were 10/05/2017 9:05:34 AM, the above command-line would produce the following:

cmd /c YourProgram.cmd > "Log_20171005_ 90534.txt" 2>&1

Show whitespace characters in Visual Studio Code

VS Code 1.6.0 and Greater

As mentioned by aloisdg below, editor.renderWhitespace is now an enum taking either none, boundary or all. To view all whitespaces:

"editor.renderWhitespace": "all", 

Before VS Code 1.6.0

Before 1.6.0, you had to set editor.renderWhitespace to true:

"editor.renderWhitespace": true

How to check if String value is Boolean type in Java?

Apache commons-lang3 has BooleanUtils with a method toBooleanObject:

BooleanUtils.toBooleanObject(String str)

// where: 

BooleanUtils.toBooleanObject(null)    = null
BooleanUtils.toBooleanObject("true")  = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on")    = Boolean.TRUE
BooleanUtils.toBooleanObject("ON")    = Boolean.TRUE
BooleanUtils.toBooleanObject("off")   = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf")   = Boolean.FALSE
BooleanUtils.toBooleanObject("blue")  = null

How to disable 'X-Frame-Options' response header in Spring Security?

If you're using Java configs instead of XML configs, put this in your WebSecurityConfigurerAdapter.configure(HttpSecurity http) method:

http.headers().frameOptions().disable();

Is it possible to use if...else... statement in React render function?

You should Remember about TERNARY operator

:

so your code will be like this,

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // note: code does not work here
            { 
               this.props.hasImage ?  // if has image
               <MyImage />            // return My image tag 
               :
               <OtherElement/>        // otherwise return other element  

             }
        </div>
    )
}

Extract specific columns from delimited file using Awk

As mentioned by @Tom, the cut and awk approaches actually don't work for CSVs with quoted strings. An alternative is a module for python that provides the command line tool csvfilter. It works like cut, but properly handles CSV column quoting:

csvfilter -f 1,3,5 in.csv > out.csv

If you have python (and you should), you can install it simply like this:

pip install csvfilter

Please take note that the column indexing in csvfilter starts with 0 (unlike awk, which starts with $1). More info at https://github.com/codeinthehole/csvfilter/

How to convert MySQL time to UNIX timestamp using PHP?

You can mysql's UNIX_TIMESTAMP function directly from your query, here is an example:

SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');

Similarly, you can pass in the date/datetime field:

SELECT UNIX_TIMESTAMP(yourField);

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

Java - JPA - @Version annotation

But still I am not sure how it works?

Let's say an entity MyEntity has an annotated version property:

@Entity
public class MyEntity implements Serializable {    

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Version
    private Long version;

    //...
}

On update, the field annotated with @Version will be incremented and added to the WHERE clause, something like this:

UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))

If the WHERE clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException.

Does it mean that we should declare our version field as final

No but you could consider making the setter protected as you're not supposed to call it.

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

Converting a vector<int> to string

template<typename T>
string str(T begin, T end)
{
    stringstream ss;
    bool first = true;
    for (; begin != end; begin++)
    {
        if (!first)
            ss << ", ";
        ss << *begin;
        first = false;
    }
    return ss.str();
}

This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

Random state (Pseudo-random number) in Scikit learn

sklearn.model_selection.train_test_split(*arrays, **options)[source]

Split arrays or matrices into random train and test subsets

Parameters: ... 
    random_state : int, RandomState instance or None, optional (default=None)

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I also encountered this question, I solved it through adding two conditions one is:

resultCode != null

the other is:

resultCode != RESULT_CANCELED

m2eclipse error

My issue was that eclipse could not find the mvn.bat file within the installation directory. The solution is to create a mvn.bat file with the following code:

"%~dp0\mvn.cmd" %*

Save that file. Place it inside the [Maven Installation Folder]\bin directory.

Ruby Array find_first object?

Guess you just missed the find method in the docs:

my_array.find {|e| e.satisfies_condition? }

Cannot push to GitHub - keeps saying need merge

This problem is usually caused by creating a readme.md file, which is counted as a commit, is not synchronized locally on the system, and is lacking behind the head, hence, it shows a git pull request. You can try avoiding the readme file and then try to commit. It worked in my case.

How to control the line spacing in UILabel

Here is a class that subclass UILabel to have line-height property : https://github.com/LemonCake/MSLabel

Nesting optgroups in a dropdownlist/select

I think if you have something that structured and complex, you might consider something other than a single drop-down box.

How to convert a Hibernate proxy to a real entity object

I've written following code which cleans object from proxies (if they are not already initialized)

public class PersistenceUtils {

    private static void cleanFromProxies(Object value, List<Object> handledObjects) {
        if ((value != null) && (!isProxy(value)) && !containsTotallyEqual(handledObjects, value)) {
            handledObjects.add(value);
            if (value instanceof Iterable) {
                for (Object item : (Iterable<?>) value) {
                    cleanFromProxies(item, handledObjects);
                }
            } else if (value.getClass().isArray()) {
                for (Object item : (Object[]) value) {
                    cleanFromProxies(item, handledObjects);
                }
            }
            BeanInfo beanInfo = null;
            try {
                beanInfo = Introspector.getBeanInfo(value.getClass());
            } catch (IntrospectionException e) {
                // LOGGER.warn(e.getMessage(), e);
            }
            if (beanInfo != null) {
                for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                    try {
                        if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                            Object fieldValue = property.getReadMethod().invoke(value);
                            if (isProxy(fieldValue)) {
                                fieldValue = unproxyObject(fieldValue);
                                property.getWriteMethod().invoke(value, fieldValue);
                            }
                            cleanFromProxies(fieldValue, handledObjects);
                        }
                    } catch (Exception e) {
                        // LOGGER.warn(e.getMessage(), e);
                    }
                }
            }
        }
    }

    public static <T> T cleanFromProxies(T value) {
        T result = unproxyObject(value);
        cleanFromProxies(result, new ArrayList<Object>());
        return result;
    }

    private static boolean containsTotallyEqual(Collection<?> collection, Object value) {
        if (CollectionUtils.isEmpty(collection)) {
            return false;
        }
        for (Object object : collection) {
            if (object == value) {
                return true;
            }
        }
        return false;
    }

    public static boolean isProxy(Object value) {
        if (value == null) {
            return false;
        }
        if ((value instanceof HibernateProxy) || (value instanceof PersistentCollection)) {
            return true;
        }
        return false;
    }

    private static Object unproxyHibernateProxy(HibernateProxy hibernateProxy) {
        Object result = hibernateProxy.writeReplace();
        if (!(result instanceof SerializableProxy)) {
            return result;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private static <T> T unproxyObject(T object) {
        if (isProxy(object)) {
            if (object instanceof PersistentCollection) {
                PersistentCollection persistentCollection = (PersistentCollection) object;
                return (T) unproxyPersistentCollection(persistentCollection);
            } else if (object instanceof HibernateProxy) {
                HibernateProxy hibernateProxy = (HibernateProxy) object;
                return (T) unproxyHibernateProxy(hibernateProxy);
            } else {
                return null;
            }
        }
        return object;
    }

    private static Object unproxyPersistentCollection(PersistentCollection persistentCollection) {
        if (persistentCollection instanceof PersistentSet) {
            return unproxyPersistentSet((Map<?, ?>) persistentCollection.getStoredSnapshot());
        }
        return persistentCollection.getStoredSnapshot();
    }

    private static <T> Set<T> unproxyPersistentSet(Map<T, ?> persistenceSet) {
        return new LinkedHashSet<T>(persistenceSet.keySet());
    }

}

I use this function over result of my RPC services (via aspects) and it cleans recursively all result objects from proxies (if they are not initialized).

What's the difference between IFrame and Frame?

The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.

Read IFrames security summary.

jQuery changing css class to div

This may not be exactly on target because I am not completely clear on what you want to do. However, assuming you mean you want to assign a different class to a div in response to an event, the answer is yes, you can certainly do this with jQuery. I am only a jQuery beginner, but I have used the following in my code:

$(document).ready(function() {
    $("#someElementID").click(function() {  // this is your event
        $("#divID").addClass("second");     // here your adding the new class
    )}; 
)};

If you wanted to replace the first class with the second class, I believe you would use removeClass first and then addClass as I did above. toggleClass may also be worth a look. The jQuery documentation is well written for these type of changes, with examples.

Someone else my have a better option, but I hope that helps!

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

Reliable way for a Bash script to get the full path to itself

Use:

SCRIPT_PATH=$(dirname `which $0`)

which prints to standard output the full path of the executable that would have been executed when the passed argument had been entered at the shell prompt (which is what $0 contains)

dirname strips the non-directory suffix from a file name.

Hence you end up with the full path of the script, no matter if the path was specified or not.

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!

Find when a file was deleted in Git

git log --full-history -- [file path] shows the changes of a file and works even if the file was deleted.

Example:

git log --full-history  -- myfile

If you want to see only the last commit, which deleted the file, use -1 in addition to the command above. Example:

git log --full-history -1 -- [file path]

See also my article: Which commit deleted a file.

How to write PNG image to string with the PIL?

save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:

buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()

AngularJS 1.2 $injector:modulerr

A noob error can be forgetting to include the module js

<script src="app/modules/myModule.js"></script>

files in the index.html at all

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

How can I shrink the drawable on a button?

Here the function which I created for scaling vector drawables. I used it for setting TextView compound drawable.

/**
 * Used to load vector drawable and set it's size to intrinsic values
 *
 * @param context Reference to {@link Context}
 * @param resId   Vector image resource id
 * @param tint    If not 0 - colour resource to tint the drawable with.
 * @param newWidth If not 0 then set the drawable's width to this value and scale 
 *                 height accordingly.
 * @return On success a reference to a vector drawable
 */
@Nullable
public static Drawable getVectorDrawable(@NonNull Context context,
                                         @DrawableRes int resId,
                                         @ColorRes int tint,
                                         float newWidth)
{
    VectorDrawableCompat drawableCompat =
            VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
    if (drawableCompat != null)
    {
        if (tint != 0)
        {
            drawableCompat.setTint(ResourcesCompat.getColor(context.getResources(), tint, context.getTheme()));
        }

        drawableCompat.setBounds(0, 0, drawableCompat.getIntrinsicWidth(), drawableCompat.getIntrinsicHeight());

        if (newWidth != 0.0)
        {
            float scale = newWidth / drawableCompat.getIntrinsicWidth();
            float height = scale * drawableCompat.getIntrinsicHeight();
            ScaleDrawable scaledDrawable = new ScaleDrawable(drawableCompat, Gravity.CENTER, 1.0f, 1.0f);
            scaledDrawable.setBounds(0,0, (int) newWidth, (int) height);
            scaledDrawable.setLevel(10000);
            return scaledDrawable;
        }
    }
    return drawableCompat;
}

Get DOM content of cross-domain iframe

There's a workaround to achieve it.

  1. First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.

  2. In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.

How to run JUnit tests with Gradle?

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.

Correct way to initialize HashMap and can HashMap hold different value types?

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

apache redirect from non www to www

Try this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com$1 [R=301]

Definitive way to trigger keypress events with jQuery

console.log( String.fromCharCode(event.charCode) );

no need to map character i guess.

Is it possible to find out the users who have checked out my project on GitHub?

Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.

How to dynamically create CSS class in JavaScript and apply?

I was looking through some of the answers here, and I couldn't find anything that automatically adds a new stylesheet if there are none, and if not simply modifies an existing one that already contains the style needed, so I made a new function (should work accross all browsers, though not tested, uses addRule and besides that only basic native JavaScript, let me know if it works):

function myCSS(data) {
    var head = document.head || document.getElementsByTagName("head")[0];
    if(head) {
        if(data && data.constructor == Object) {
            for(var k in data) {
                var selector = k;
                var rules = data[k];

                var allSheets = document.styleSheets;
                var cur = null;

                var indexOfPossibleRule = null,
                    indexOfSheet = null;
                for(var i = 0; i < allSheets.length; i++) {
                    indexOfPossibleRule = findIndexOfObjPropInArray("selectorText",selector,allSheets[i].cssRules);
                    if(indexOfPossibleRule != null) {
                        indexOfSheet = i;
                        break;
                    }
                }

                var ruleToEdit = null;
                if(indexOfSheet != null) {

                    ruleToEdit = allSheets[indexOfSheet].cssRules[indexOfPossibleRule];

                } else {
                    cur = document.createElement("style");
                    cur.type =  "text/css";
                    head.appendChild(cur);
                    cur.sheet.addRule(selector,"");
                    ruleToEdit = cur.sheet.cssRules[0];
                    console.log("NOPE, but here's a new one:", cur);
                }
                applyCustomCSSruleListToExistingCSSruleList(rules, ruleToEdit, (err) => {
                    if(err) {
                        console.log(err);
                    } else {
                        console.log("successfully added ", rules, " to ", ruleToEdit);
                    }
                });
            }
        } else {
            console.log("provide one paramter as an object containing the cssStyles, like: {\"#myID\":{position:\"absolute\"}, \".myClass\":{background:\"red\"}}, etc...");
        }
    } else {
        console.log("run this after the page loads");
    }

};  

then just add these 2 helper functions either inside the above function, or anywhere else:

function applyCustomCSSruleListToExistingCSSruleList(customRuleList, existingRuleList, cb) {
    var err = null;
    console.log("trying to apply ", customRuleList, " to ", existingRuleList);
    if(customRuleList && customRuleList.constructor == Object && existingRuleList && existingRuleList.constructor == CSSStyleRule) {
        for(var k in customRuleList) {
            existingRuleList["style"][k] = customRuleList[k];
        }

    } else {
        err = ("provide first argument as an object containing the selectors for the keys, and the second argument is the CSSRuleList to modify");
    }
    if(cb) {
        cb(err);
    }
}

function findIndexOfObjPropInArray(objPropKey, objPropValue, arr) {
    var index = null;
    for(var i = 0; i < arr.length; i++) {
        if(arr[i][objPropKey] == objPropValue) {
            index = i;
            break;
        }
    }
    return index;
}

(notice that in both of them I use a for loop instead of .filter, since the CSS style / rule list classes only have a length property, and no .filter method.)

Then to call it:

myCSS({
    "#coby": {
        position:"absolute",
        color:"blue"
    },
    ".myError": {
        padding:"4px",
        background:"salmon"
    }
})

Let me know if it works for your browser or gives an error.

Text Progress Bar in the Console

Check this library: clint

it has a lot of features including a progress bar:

from time import sleep  
from random import random  
from clint.textui import progress  
if __name__ == '__main__':
    for i in progress.bar(range(100)):
        sleep(random() * 0.2)

    for i in progress.dots(range(100)):
        sleep(random() * 0.2)

this link provides a quick overview of its features

What is the difference between parseInt(string) and Number(string) in JavaScript?

Addendum to @sjngm's answer:

They both also ignore whitespace:

var foo = "    3     ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3

How to add a vertical Separator?

This is not exactly what author asked, but still, it is very simple and works exactly as expected.

Rectangle does the job:

<StackPanel Grid.Column="2" Orientation="Horizontal">
    <Button >Next</Button>
    <Button >Prev</Button>
    <Rectangle VerticalAlignment="Stretch" Width="1" Margin="2" Stroke="Black" />
    <Button>Filter all</Button>
</StackPanel>

PHP __get and __set magic methods

__get, __set, __call and __callStatic are invoked when the method or property is inaccessible. Your $bar is public and therefor not inaccessible.

See the section on Property Overloading in the manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.

Content-Disposition:What are the differences between "inline" and "attachment"?

If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.

With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

How to make a PHP SOAP call using the SoapClient class

getLastRequest():

This method works only if the SoapClient object was created with the trace option set to TRUE.

TRUE in this case is represented by 1

$wsdl = storage_path('app/mywsdl.wsdl');
try{

  $options = array(
               // 'soap_version'=>SOAP_1_1,
               'trace'=>1,
               'exceptions'=>1,

                'cache_wsdl'=>WSDL_CACHE_NONE,
             //   'stream_context' => stream_context_create($arrContextOptions)
        );
           // $client = new \SoapClient($wsdl, array('cache_wsdl' => WSDL_CACHE_NONE) );
        $client = new \SoapClient($wsdl, array('cache_wsdl' => WSDL_CACHE_NONE));
        $client     = new \SoapClient($wsdl,$options); 

worked for me.

List attributes of an object

It's often mentioned that to list a complete list of attributes you should use dir(). Note however that contrary to popular belief dir() does not bring out all attributes. For example you might notice that __name__ might be missing from a class's dir() listing even though you can access it from the class itself. From the doc on dir() (Python 2, Python 3):

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

A function like the following tends to be more complete, although there's no guarantee of completeness since the list returned by dir() can be affected by many factors including implementing the __dir__() method, or customizing __getattr__() or __getattribute__() on the class or one of its parents. See provided links for more details.

def dirmore(instance):
    visible = dir(instance)
    visible += [a for a in set(dir(type)).difference(visible)
                if hasattr(instance, a)]
    return sorted(visible)

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

Excel: Search for a list of strings within a particular string using array formulas?

Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable

OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))

or case-sensitive

OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))

Where the range for the search terms is G1:G7

Remember to press CTRL+SHIFT+ENTER

Get only part of an Array in Java?

If you are using Java 1.6 or greater, you can use Arrays.copyOfRange to copy a portion of the array. From the javadoc:

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

Here is a simple example:

/**
 * @Program that Copies the specified range of the specified array into a new 
 * array.
 * CopyofRange8Array.java 
 * Author:-RoseIndia Team
 * Date:-15-May-2008
 */
import java.util.*;
public class CopyofRange8Array {
    public static void main(String[] args) {
       //creating a short array
       Object T[]={"Rose","India","Net","Limited","Rohini"};
        // //Copies the specified  short array upto specified range,
        Object T1[] = Arrays.copyOfRange(T, 1,5);
        for (int i = 0; i < T1.length; i++) 
            //Displaying the Copied short array upto specified range
            System.out.println(T1[i]);
    }

}

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.

string result = await Request.Content.ReadAsStringAsync();

There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:

public async Task<IHttpActionResult> GetSomething()
{
    var rawMessage = await Request.Content.ReadAsStringAsync();
    // ...
    return Ok();
}

EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:

public IHttpActionResult GetSomething()
{
    var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = reader.ReadToEnd();

    return Ok();
}

In this case, your endpoint doesn't need to be async (unless you have other async-methods)

What is a stack trace, and how can I use it to debug my application errors?

The other posts describe what a stack trace is, but it can still be hard to work with.

If you get a stack trace and want to trace the cause of the exception, a good start point in understanding it is to use the Java Stack Trace Console in Eclipse. If you use another IDE there may be a similar feature, but this answer is about Eclipse.

First, ensure that you have all of your Java sources accessible in an Eclipse project.

Then in the Java perspective, click on the Console tab (usually at the bottom). If the Console view is not visible, go to the menu option Window -> Show View and select Console.

Then in the console window, click on the following button (on the right)

Consoles button

and then select Java Stack Trace Console from the drop-down list.

Paste your stack trace into the console. It will then provide a list of links into your source code and any other source code available.

This is what you might see (image from the Eclipse documentation):

Diagram from Eclipse documentation

The most recent method call made will be the top of the stack, which is the top line (excluding the message text). Going down the stack goes back in time. The second line is the method that calls the first line, etc.

If you are using open-source software, you might need to download and attach to your project the sources if you want to examine. Download the source jars, in your project, open the Referenced Libraries folder to find your jar for your open-source module (the one with the class files) then right click, select Properties and attach the source jar.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.

how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;

PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0

(swedish translated: 'It is not possible to find the module' )

in this perticular case, the php.ini was: extension_dir = "C:/php"

the dll is put in two places C:\php and C:\php\ext

IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Conditional Replace Pandas

Try this:

df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)

or

df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

How to check file MIME type with javascript before upload?

Short answer is no.

As you note the browsers derive type from the file extension. Mac preview also seems to run off the extension. I'm assuming its because its faster reading the file name contained in the pointer, rather than looking up and reading the file on disk.

I made a copy of a jpg renamed with png.

I was able to consistently get the following from both images in chrome (should work in modern browsers).

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

Which you could hack out a String.indexOf('jpeg') check for image type.

Here is a fiddle to explore http://jsfiddle.net/bamboo/jkZ2v/1/

The ambigious line I forgot to comment in the example

console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

  • Splits the base64 encoded img data, leaving on the image
  • Base64 decodes the image
  • Matches only the first line of the image data

The fiddle code uses base64 decode which wont work in IE9, I did find a nice example using VB script that works in IE http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html

The code to load the image was taken from Joel Vardy, who is doing some cool image canvas resizing client side before uploading which may be of interest https://joelvardy.com/writing/javascript-image-upload

Reading e-mails from Outlook with Python through MAPI

I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following methods:

.items() - yields a tuple(index, Item)...

.prop() - helping to introspect outlook object exposing available properties (methods and attributes)

from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch

outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

class Oli():
    def __init__(self, outlook_object):
        self._obj = outlook_object

    def items(self):
        array_size = self._obj.Count
        for item_index in xrange(1,array_size+1):
            yield (item_index, self._obj[item_index])

    def prop(self):
        return sorted( self._obj._prop_map_get_.keys() )

for inx, folder in Oli(mapi.Folders).items():
    # iterate all Outlook folders (top level)
    print "-"*70
    print folder.Name

    for inx,subfolder in Oli(folder.Folders).items():
        print "(%i)" % inx, subfolder.Name,"=> ", subfolder

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Use of for_each on map elements

Just an example:

template <class key, class value>
class insertIntoVec
{
public:
    insertIntoVec(std::vector<value>& vec_in):m_vec(vec_in)
    {}

    void operator () (const std::pair<key, value>& rhs)  
    {   
        m_vec.push_back(rhs.second);
    }

private:
    std::vector<value>& m_vec;
};

int main()
{
std::map<int, std::string> aMap;
aMap[1] = "test1";
aMap[2] = "test2";
aMap[3] = "test3";
aMap[4] = "test4";

std::vector<std::string> aVec;

aVec.reserve(aMap.size());
std::for_each(aMap.begin(), aMap.end(),
          insertIntoVec<int, std::string>(aVec) 
    );

}

Routing for custom ASP.NET MVC 404 Error page

Here is true answer which allows fully customize of error page in single place. No need to modify web.config or create separate code.

Works also in MVC 5.

Add this code to controller:

        if (bad) {
            Response.Clear();
            Response.TrySkipIisCustomErrors = true;
            Response.Write(product + I(" Toodet pole"));
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            //Response.ContentType = "text/html; charset=utf-8";
            Response.End();
            return null;
        }

Based on http://www.eidias.com/blog/2014/7/2/mvc-custom-error-pages

CSS Cell Margin

If you have control of the width of the table, insert a padding-left on all table cells and insert a negative margin-left on the whole table.

table {
    margin-left: -20px;
    width: 720px;
}

table td {
    padding-left: 20px;
}

Note, the width of the table needs to include the padding/margin width. Using the above as an example, the visual width of the table will be 700px.

This is not the best solution if you're using borders on your table cells.

How can I switch my signed in user in Visual Studio 2013?

Start Visual Studio Tools -> Import and Export Settings -> Export selected environment settings You need to be really quick to navigate the menu before Licensing pop-up appears, (this step is optional: worst case scenario you would have to restore all the settings manually). Once in "Import and Export Settings" dialogue you can relax.

Exit Visual Studio.

From the command prompt run: devenv /resetuserdata for the particular Visual Studio version.

Safest way is to right-click on the shortcut -> Properties -> Shortcut -> Target -> copy. Final command should look something like:

"C:\Program Files (x86)\Microsoft Visual Studio NN.N\Common7\IDE\devenv.exe" /resetuserdata

Go through log-in and initial settings.

Tools -> Import and Export Settings -> Import selected environment settings to restore your original settings.

This worked when the error:

We were unable to establish the connection because it is configured for user email@address but you attempted to connect using user email@address. To connect as a different user perform a switch user operation. To connect with the configured identity just attempt the last operation again.

...has both instances of email@address identical.

How do I trim whitespace?

Having looked at quite a few solutions here with various degrees of understanding, I wondered what to do if the string was comma separated...

the problem

While trying to process a csv of contact information, I needed a solution this problem: trim extraneous whitespace and some junk, but preserve trailing commas, and internal whitespace. Working with a field containing notes on the contacts, I wanted to remove the garbage, leaving the good stuff. Trimming out all the punctuation and chaff, I didn't want to lose the whitespace between compound tokens as I didn't want to rebuild later.

regex and patterns: [\s_]+?\W+

The pattern looks for single instances of any whitespace character and the underscore ('_') from 1 to an unlimited number of times lazily (as few characters as possible) with [\s_]+? that come before non-word characters occurring from 1 to an unlimited amount of time with this: \W+ (is equivalent to [^a-zA-Z0-9_]). Specifically, this finds swaths of whitespace: null characters (\0), tabs (\t), newlines (\n), feed-forward (\f), carriage returns (\r).

I see the advantage to this as two-fold:

  1. that it doesn't remove whitespace between the complete words/tokens that you might want to keep together;

  2. Python's built in string method strip()doesn't deal inside the string, just the left and right ends, and default arg is null characters (see below example: several newlines are in the text, and strip() does not remove them all while the regex pattern does). text.strip(' \n\t\r')

This goes beyond the OPs question, but I think there are plenty of cases where we might have odd, pathological instances within the text data, as I did (some how the escape characters ended up in some of the text). Moreover, in list-like strings, we don't want to eliminate the delimiter unless the delimiter separates two whitespace characters or some non-word character, like '-,' or '-, ,,,'.

NB: Not talking about the delimiter of the CSV itself. Only of instances within the CSV where the data is list-like, ie is a c.s. string of substrings.

Full disclosure: I've only been manipulating text for about a month, and regex only the last two weeks, so I'm sure there are some nuances I'm missing. That said, for smaller collections of strings (mine are in a dataframe of 12,000 rows and 40 odd columns), as a final step after a pass for removal of extraneous characters, this works exceptionally well, especially if you introduce some additional whitespace where you want to separate text joined by a non-word character, but don't want to add whitespace where there was none before.

An example:

import re


text = "\"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, [email protected], ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, , , , \r, , \0, ff dd \n invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, \n i69rpofhfsp9t7c practice 20ignition - 20june \t\n .2134.pdf 2109                                                 \n\n\n\nklkjsdf\""

print(f"Here is the text as formatted:\n{text}\n")
print()
print("Trimming both the whitespaces and the non-word characters that follow them.")
print()
trim_ws_punctn = re.compile(r'[\s_]+?\W+')
clean_text = trim_ws_punctn.sub(' ', text)
print(clean_text)
print()
print("what about 'strip()'?")
print(f"Here is the text, formatted as is:\n{text}\n")
clean_text = text.strip(' \n\t\r')  # strip out whitespace?
print()
print(f"Here is the text, formatted as is:\n{clean_text}\n")

print()
print("Are 'text' and 'clean_text' unchanged?")
print(clean_text == text)

This outputs:

Here is the text as formatted:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, [email protected], ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf" 

using regex to trim both the whitespaces and the non-word characters that follow them.

"portfolio, derp, hello-world, hello-, world, founders, mentors, ffib, biff, 1, 12.18.02, 12, 2013, 9874890288, ff, series a, exit, general mailing, fr, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk,  [email protected], dd invites,subscribed,, master, dd invites,subscribed, ff dd invites, subscribed, alumni spring 2012 deck: https: www.dropbox.com s, i69rpofhfsp9t7c practice 20ignition 20june 2134.pdf 2109 klkjsdf"

Very nice.
What about 'strip()'?

Here is the text, formatted as is:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, [email protected], ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"


Here is the text, after stipping with 'strip':


"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, [email protected], ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"
Are 'text' and 'clean_text' unchanged? 'True'

So strip removes one whitespace from at a time. So in the OPs case, strip() is fine. but if things get any more complex, regex and a similar pattern may be of some value for more general settings.

see it in action

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Generate random number between two numbers in JavaScript

Example

Return a random number between 1 and 10:

Math.floor((Math.random() * 10) + 1);

The result could be: 3

Try yourself: here

--

or using lodash / undescore:

_.random(min, max)

Docs: - lodash - undescore

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

C read file line by line

//open and get the file handle
FILE* fh;
fopen_s(&fh, filename, "r");

//check if file exists
if (fh == NULL){
    printf("file does not exists %s", filename);
    return 0;
}


//read line by line
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, fh) != NULL)  {
    printf(line);
}
free(line);    // dont forget to free heap memory

How to add an element at the end of an array?

To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).

What you can do is create a new array one element larger and fill in the new element in the last slot:

public static int[] append(int[] array, int value) {
     int[] result = Arrays.copyOf(array, array.length + 1);
     result[result.length - 1] = value;
     return result;
}

This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.

One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.

And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.

How to sort alphabetically while ignoring case sensitive?

Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...) API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute(), which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,

boolean isUrlExists(String url) {
    try {
      return (restTemplate.execute(url, HttpMethod.HEAD,
              { ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
              { ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
    } catch (Exception e) {
      log.warn("Problem checking if $url exists", e)
    }
    false
  }

How do I change the android actionbar title and icon

You can also do as follow :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        setSupportActionBar(toolbar)
        setTitle("Activity 2")
    }

How to start jenkins on different port rather than 8080 using command prompt in Windows?

On Windows (with Windows Service).

Edit the file C:\Program Files (x86)\Jenkins\jenkins.xml with 8083 if you want 8083 port.

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

Add regression line equation and R^2 on graph

Here is one solution

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA

lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
         list(a = format(unname(coef(m)[1]), digits = 2),
              b = format(unname(coef(m)[2]), digits = 2),
             r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));
}

p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups

Output

How to apply slide animation between two activities in Android?

Hopefully, it will work for you.

startActivityForResult( intent, 1 , ActivityOptions.makeCustomAnimation(getActivity(),R.anim.slide_out_bottom,R.anim.slide_in_bottom).toBundle());

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn

 List<AttributeHistory> findByValueIn(List<String> values);

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Please keep your

<form method="POST" action="XYZ">

@RequestMapping(value="/XYZ", method=RequestMethod.POST)
    public void handleSave(@RequestParam String action){

Your form action attribute value must match to value of @RequestMapping, So that Spring MVC can resolve it.

Also, as you told it is giving 404 after changing, for this, can you please check whether control is entering inside handleSave() method.

I think, as you are not returning any thing from handleSave() method, you have to look at it.

if it still not work, can you please post your spring logs.

Also, make sure that your request should come like

/PORTAL/save

if there is anything between like PORTAL/jsp/save the mention in @RequestMapping(value="/jsp/save")

Best way to implement multi-language/globalization in large .NET project

I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.

  • One did it in the config file (not my favourite)
  • One did it using a database - this worked pretty well, but was a pain in the you know what to maintain.
  • One used resource files the way you're suggesting and I have to say it was my favourite approach.
  • The most basic one did it using an include file full of strings - ugly.

I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.

AngularJS ngClass conditional

Angular syntax is to use the : operator to perform the equivalent of an if modifier

<div ng-class="{ 'clearfix' : (row % 2) == 0 }">

Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

Table 'mysql.user' doesn't exist:ERROR

'Error Code: 1046'. 

This error shows that the table does not exist may sometimes be caused by having selected a different database and running a query referring to another table. The results indicates 'No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar'. Will solve the issue and it worked for me very well.

Python Save to file

myFile = open('today','r')

ips = {}

for line in myFile:
    parts = line.split()
    if parts[1] == 'Failure':
        ips.setdefault(parts[0], 0)
        ips[parts[0]] += 1

of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
    of.write(k+'\n')

Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.

Creating watermark using html and css

Possibly this can be of great help for you.

div.image
{
width:500px;
height:250px;  
border:2px solid;
border-color:#CD853F;
}
div.box
{
width:400px;
height:180px;
margin:30px 50px;
background-color:#ffffff;
border:1px solid;
border-color:#CD853F;
opacity:0.6;
filter:alpha(opacity=60);
}
   div.box p
{
margin:30px 40px;
font-weight:bold;
color:#CD853F;
}

Check this link once.

Error: getaddrinfo ENOTFOUND in nodejs for get call

Struggling for hours, couldn't afford for more.

The solution that worked for me in less than 3 minutes was:

npm install axios

Code ended up even shorter:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface[]>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Set background colour of cell to RGB value of data in cell

You can use VBA - something like

Range("A1:A6").Interior.Color = RGB(127,187,199)

Just pass in the cell value.

ps1 cannot be loaded because running scripts is disabled on this system

The following three steps are used to fix Running Scripts is disabled on this System error

Step1 : To fix this kind of problem, we have to start power shell in administrator mode.

Step2 : Type the following command set-ExecutionPolicy RemoteSigned Step3: Press Y for your Confirmation.

Visit the following for more information https://youtu.be/J_596H-sWsk

How to write a confusion matrix in Python?

In a general sense, you're going to need to change your probability array. Instead of having one number for each instance and classifying based on whether or not it is greater than 0.5, you're going to need a list of scores (one for each class), then take the largest of the scores as the class that was chosen (a.k.a. argmax).

You could use a dictionary to hold the probabilities for each classification:

prob_arr = [{classification_id: probability}, ...]

Choosing a classification would be something like:

for instance_scores in prob_arr :
    predicted_classes = [cls for (cls, score) in instance_scores.iteritems() if score = max(instance_scores.values())]

This handles the case where two classes have the same scores. You can get one score, by choosing the first one in that list, but how you handle that depends on what you're classifying.

Once you have your list of predicted classes and a list of expected classes you can use code like Torsten Marek's to create the confusion array and calculate the accuracy.

How to do this in Laravel, subquery where in

The script is tested in Laravel 5.x and 6.x. The static closure can improve performance in some cases.

Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
            ->whereIn('id', static function ($query) {
                $query->select(['product_id'])
                    ->from((new ProductCategory)->getTable())
                    ->whereIn('category_id', [15, 223]);
            })
            ->where('active', 1)
            ->get();

generates the SQL

SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products` 
WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE 
`category_id` IN (?, ?)) AND `active` = ?

List comprehension on a nested list?

    deck = [] 
    for rank in ranks:
        for suit in suits:
            deck.append(('%s%s')%(rank, suit))

This can be achieved using list comprehension:

[deck.append((rank,suit)) for suit in suits for rank in ranks ]

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

How to Maximize a firefox browser window using Selenium WebDriver with node.js

The statement :: driver.manage().window.maximize(); Works perfectly, but the window maximizes only after loading the page on browser, it does not maximizes at the time of initializing the browser.

here : (driver) is called object of Firefox driver, it may be any thing depending on the initializing of Firefox object by you only.

Is it possible to declare two variables of different types in a for loop?

Not possible, but you can do:

float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
  //...
}

Or, explicitly limit the scope of f and i using additional brackets:

{
    float f; 
    int i;
    for (i = 0,f = 0.0; i < 5; i++)
    {
       //...
    }
}

Why does PEP-8 specify a maximum line length of 79 characters?

Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

Put quotes around a variable string in JavaScript

To represent the text below in JavaScript:

"'http://example.com'"

Use:

"\"'http://example.com'\""

Or:

'"\'http://example.com\'"'

Note that: We always need to escape the quote that we are surrounding the string with using \

JS Fiddle: http://jsfiddle.net/efcwG/

General Pointers:

  • You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
  • Or you can put quotes inside a string by using the \ escape character:

Example

var answer='It\'s alright';
var answer="He is called \"Johnny\"";
  • Or you can use a combination of both as shown on top.

http://www.w3schools.com/js/js_obj_string.asp

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

Exception thrown in catch and finally clause

I think you just have to walk the finally blocks:

  1. Print "1".
  2. finally in q print "3".
  3. finally in main print "2".

How to iterate a loop with index and element in Swift

Basic enumerate

for (index, element) in arrayOfValues.enumerate() {
// do something useful
}

or with Swift 3...

for (index, element) in arrayOfValues.enumerated() {
// do something useful
}

Enumerate, Filter and Map

However, I most often use enumerate in combination with map or filter. For example with operating on a couple of arrays.

In this array I wanted to filter odd or even indexed elements and convert them from Ints to Doubles. So enumerate() gets you index and the element, then filter checks the index, and finally to get rid of the resulting tuple I map it to just the element.

let evens = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 == 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })
let odds = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 != 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today is DateTime.Now with time set to zero.

It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format: https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx

DateTime.Now.Ticks is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).

If the Kind property is DateTimeKind.Local it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.

So, using DateTime.Now and DateTime.Today is perfectly OK.

You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.

Checking if a variable is defined?

As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean.

But if you absolutely need a boolean. Use !! (bang bang) or "falsy falsy reveals the truth".

› irb
>> a = nil
=> nil
>> defined?(a)
=> "local-variable"
>> defined?(b)
=> nil
>> !!defined?(a)
=> true
>> !!defined?(b)
=> false

Why it doesn't usually pay to coerce:

>> (!!defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red)) == (defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red))
=> true

Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.

>> puts "var is defined? #{!!defined?(a)} vs #{defined?(a)}"
var is defined? true vs local-variable
=> nil

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

Dynamically create an array of strings with malloc

char **orderIds;

orderIds = malloc(variableNumberOfElements * sizeof(char*));

for(int i = 0; i < variableNumberOfElements; i++) {
  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
  strcpy(orderIds[i], your_string[i]);
}

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

Where to download visual studio express 2005?

As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.

From Here

Dynamically Dimensioning A VBA Array?

You have to use the ReDim statement to dynamically size arrays.

Public Sub Test()
    Dim NumberOfZombies As Integer
    NumberOfZombies = 20000
    Dim Zombies() As New Zombie
    ReDim Zombies(NumberOfZombies)

End Sub

This can seem strange when you already know the size of your array, but there you go!

What is the meaning of polyfills in HTML5?

A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Use JSON.stringify(<data>).

Change your code: data: sendInfo to data: JSON.stringify(sendInfo). Hope this can help you.

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
(
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN ( WITH x(x) AS
    (
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    )
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
  );
GO

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN STRING_SPLIT(@Values, ',') AS s
    ON LTRIM(s.value) = foo.myField;

How to pretty print XML from Java?

I should have looked for this page first before coming up with my own solution! Anyway, mine uses Java recursion to parse the xml page. This code is totally self-contained and does not rely on third party libraries. Also .. it uses recursion!

// you call this method passing in the xml text
public static void prettyPrint(String text){
    prettyPrint(text, 0);
}

// "index" corresponds to the number of levels of nesting and/or the number of tabs to print before printing the tag
public static void prettyPrint(String xmlText, int index){
    boolean foundTagStart = false;
    StringBuilder tagChars = new StringBuilder();
    String startTag = "";
    String endTag = "";
    String[] chars = xmlText.split("");
    // find the next start tag
    for(String ch : chars){
        if(ch.equalsIgnoreCase("<")){
            tagChars.append(ch);
            foundTagStart = true;
        } else if(ch.equalsIgnoreCase(">") && foundTagStart){
            startTag = tagChars.append(ch).toString();
            String tempTag = startTag;
            endTag = (tempTag.contains("\"") ? (tempTag.split(" ")[0] + ">") : tempTag).replace("<", "</"); // <startTag attr1=1 attr2=2> => </startTag>
            break;
        } else if(foundTagStart){
            tagChars.append(ch);
        }
    }
    // once start and end tag are calculated, print start tag, then content, then end tag
    if(foundTagStart){
        int startIndex = xmlText.indexOf(startTag);
        int endIndex = xmlText.indexOf(endTag);
        // handle if matching tags NOT found
        if((startIndex < 0) || (endIndex < 0)){
            if(startIndex < 0) {
                // no start tag found
                return;
            } else {
                // start tag found, no end tag found (handles single tags aka "<mytag/>" or "<?xml ...>")
                printTabs(index);
                System.out.println(startTag);
                // move on to the next tag
                // NOTE: "index" (not index+1) because next tag is on same level as this one
                prettyPrint(xmlText.substring(startIndex+startTag.length(), xmlText.length()), index);
                return;
            }
        // handle when matching tags found
        } else {
            String content = xmlText.substring(startIndex+startTag.length(), endIndex);
            boolean isTagContainsTags = content.contains("<"); // content contains tags
            printTabs(index);
            if(isTagContainsTags){ // ie: <tag1><tag2>stuff</tag2></tag1>
                System.out.println(startTag);
                prettyPrint(content, index+1); // "index+1" because "content" is nested
                printTabs(index);
            } else {
                System.out.print(startTag); // ie: <tag1>stuff</tag1> or <tag1></tag1>
                System.out.print(content);
            }
            System.out.println(endTag);
            int nextIndex = endIndex + endTag.length();
            if(xmlText.length() > nextIndex){ // if there are more tags on this level, continue
                prettyPrint(xmlText.substring(nextIndex, xmlText.length()), index);
            }
        }
    } else {
        System.out.print(xmlText);
    }
}

private static void printTabs(int counter){
    while(counter-- > 0){ 
        System.out.print("\t");
    }
}

How do you uninstall the package manager "pip", if installed from source?

That way you haven't installed pip, you installed just the easy_install i.e. setuptools.

First you should remove all the packages you installed with easy_install using (see uninstall):

easy_install -m PackageName

This includes pip if you installed it using easy_install pip.

After this you remove the setuptools following the instructions from here:

If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:

setuptools-*.egg

If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:

pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/

How do I run a Python program in the Command Prompt in Windows 7?

first make sure u enter the path environmental variable

C:\ path %path%;C:\Python27 press Enter

C:\Python27>python file_name press Enter

How can I export tables to Excel from a webpage

It is possible to use the old Excel 2003 XML format (before OpenXML) to create a string that contains your desired XML, then on the client side you could use a data URI to open the file using the XSL mime type, or send the file to the client using the Excel mimetype "Content-Type: application/vnd.ms-excel" from the server side.

  1. Open Excel and create a worksheet with your desired formatting and colors.
  2. Save the Excel workbook as "XML Spreadsheet 2003 (*.xml)"
  3. Open the resulting file in a text editor like notepad and copy the value into a string in your application
  4. Assuming you use the client side approach with a data uri the code would look like this:
    
    <script type="text/javascript">
    var worksheet_template = '<?xml version="1.0"?><ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'+
                 '<ss:Styles><ss:Style ss:ID="1"><ss:Font ss:Bold="1"/></ss:Style></ss:Styles><ss:Worksheet ss:Name="Sheet1">'+
                 '<ss:Table>{{ROWS}}</ss:Table></ss:Worksheet></ss:Workbook>';
    var row_template = '<ss:Row ss:StyleID="1"><ss:Cell><ss:Data ss:Type="String">{{name}}</ss:Data></ss:Cell></ss:Row>';
    </script>
    
    
  5. Then you can use string replace to create a collection of rows to be inserted into your worksheet template
    
    <script type="text/javascript">
    var rows = document.getElementById("my-table").getElementsByTagName('tr'),
      row_data = '';
    for (var i = 0, length = rows.length; i < length; ++i) {
    row_data += row_template.replace('{{name}}', rows[i].getElementsByTagName('td')[0].innerHTML);
    }
    </script>
    
    
  6. Once you have the information collected, create the final string and open a new window using the data URI

    
    <script type="text/javascript">
    var worksheet = worksheet_template.replace('{{ROWS}}', row_data);

    window.open('data:application/vnd.ms-excel,'+worksheet); </script>

It is worth noting that older browsers do not support the data URI scheme, so you may need to produce the file server side for those browser that do not support it.

You may also need to perform base64 encoding on the data URI content, which may require a js library, as well as adding the string ';base64' after the mime type in the data URI.

Pip install Matplotlib error with virtualenv

Under Windows this worked for me:

python -m pip install -U pip setuptools
python -m pip install matplotlib

(from https://matplotlib.org/users/installing.html)

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

How to compare if two structs, slices or maps are equal?

If you're comparing them in unit test, a handy alternative is EqualValues function in testify.

Convert text into number in MySQL query

Simply use CAST,

CAST(column_name AS UNSIGNED)

The type for the cast result can be one of the following values:

BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]

How to check if NSString begins with a certain character

NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
   expectedString = [givenString substringFromIndex:1];
}

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

Increase max execution time for php

There's probably a limit set in your webserver. Some browsers/proxies will also implement a timeout. Invoking long running processes via an HTTP request is just plain silly. The right way to solve the problem (assuming you can't make the processing any faster) is to use the HTTP request to trigger processing outside of the webserver session group then poll the status via HTTP until you've got a result set.

Java Class that implements Map and keeps insertion order?

I suggest a LinkedHashMap or a TreeMap. A LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the elements.

Since it doesn't have to keep the elements sorted, LinkedHashMap should be faster for most cases; TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each.

If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap or SortedMap. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.

How to nicely format floating numbers to string without unnecessary decimal 0's

The best way to do this is as below:

public class Test {

    public static void main(String args[]){
        System.out.println(String.format("%s something", new Double(3.456)));
        System.out.println(String.format("%s something", new Double(3.456234523452)));
        System.out.println(String.format("%s something", new Double(3.45)));
        System.out.println(String.format("%s something", new Double(3)));
    }
}

Output:

3.456 something
3.456234523452 something
3.45 something
3.0 something

The only issue is the last one where .0 doesn't get removed. But if you are able to live with that then this works best. %.2f will round it to the last two decimal digits. So will DecimalFormat. If you need all the decimal places, but not the trailing zeros then this works best.

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How to write a CSS hack for IE 11?

You can use js and add a class in html to maintain the standard of conditional comments:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

Or use a lib like bowser:

https://github.com/ded/bowser

Or modernizr for feature detection:

http://modernizr.com/

Equivalent of Math.Min & Math.Max for Dates?

There's no built in method to do that. You can use the expression:

(date1 > date2 ? date1 : date2)

to find the maximum of the two.

You can write a generic method to calculate Min or Max for any type (provided that Comparer<T>.Default is set appropriately):

public static T Max<T>(T first, T second) {
    if (Comparer<T>.Default.Compare(first, second) > 0)
        return first;
    return second;
}

You can use LINQ too:

new[]{date1, date2, date3}.Max()

Change event on select with knockout binding, how can I know if it is a real change?

I had a similar problem and I just modified the event handler to check the type of the variable. The type is only set after the user selects a value, not when the page is first loaded.

self.permissionChanged = function (l) {
    if (typeof l != 'undefined') {
        ...
    }
}

This seems to work for me.

Print newline in PHP in single quotes

No, because single-quotes even inhibit hex code replacement.

echo 'Hello, world!' . "\xA";

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

I had the same problem when my plugin was depending on another project, which exported some packages in its manifest file. Instead of changing access rules, I have managed to solve the problem by adding the required packages into its Export-Package section. This makes the packages legally visible. Eclipse actually provides this fix on the "Access restriction" error marker.