Programs & Examples On #Tobject

Entity Framework Core: A second operation started on this context before a previous operation completed

In some cases, this error occurs when calling an async method without the await keyword, which can simply be solved by adding await before the method call. however, the answer might not be related to the mentioned question but it can help solving a similar error.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I added @Component annotation from import org.springframework.stereotype.Component and the problem was solved.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Update your schema_version record to mach the "Resolved locally" value which in your case is -1729781252

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

My error was solved after adding this dependency.

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.16.Final</version>
    </dependency>

Deprecation warning in Moment.js - Not in a recognized ISO format

Check out all their awesome documentation!

Here is where they discuss the Warning Message.

String + Format

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

moment("12-25-1995", "MM-DD-YYYY");

String + Formats (multiple formats)

If you have more than one format, check out their String + Formats (with an 's').

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);

Please checkout the documentation for anything more specific.

Timezone

Checkout Parsing in Zone, the equivalent documentation for timezones.

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto");

EDIT

//...
var dateFormat = "YYYY-M-D H:m"; //<-------- This part will get rid of the warning.
var aus1_s, aus2_s, aus3_s, aus4_s, aus5_s, aus6_s, aus6_e;
if ($("#custom1 :selected").val() == "AU" ) {
    var region = 'Australia/Sydney';

    aus1_s = moment.tz('2016-9-26 19:30', dateFormat, region);              
    aus2_s = moment.tz('2016-10-2 19:30', dateFormat, region);              
    aus3_s = moment.tz('2016-10-9 19:30', dateFormat, region);                  
    aus4_s = moment.tz('2016-10-16 19:30', dateFormat, region);                 
    aus5_s = moment.tz('2016-10-23 19:30', dateFormat, region);
    aus6_s = moment.tz('2016-10-30 19:30', dateFormat, region);
    aus6_e = moment.tz('2016-11-5 19:30', dateFormat, region);
} else if ($("#custom1 :selected").val() == "NZ" ) {
    var region = 'Pacific/Auckland';

    aus1_s =  moment.tz('2016-9-28 20:30', dateFormat, region);
    aus2_s =  moment.tz('2016-10-4 20:30', dateFormat, region);
    aus3_s =  moment.tz('2016-10-11 20:30', dateFormat, region);
    aus4_s =  moment.tz('2016-10-18 20:30', dateFormat, region);
    aus5_s =  moment.tz('2016-10-25 20:30', dateFormat, region);
    aus6_s =  moment.tz('2016-11-2 20:30', dateFormat, region);
    aus6_e =  moment.tz('2016-11-9 20:30', dateFormat, region);
}
//...

How do I mock a REST template exchange?

If you are using RestTemplateBuilder may be the usual thing wouldn't work. You need to add this in your test class along with when(condition).

@Before    
public void setup() {        
     ReflectionTestUtils.setField(service, "restTemplate", restTemplate);    
}

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was unable to access to S3 because

  • first I configured key access on the instance (it was impossible to attach role after the launch then)
  • forgot about it for a few months
  • attached role to instance
  • tried to access. The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

NotificationCenter issue on Swift 3

I think it has changed again.

For posting this works in Xcode 8.2.

NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)

Listing files in a specific "folder" of a AWS S3 bucket

Everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

Objects that end with the delimiter (/ in most cases) are usually perceived as a folder, but it's not always the case. It depends on the application. Again, in your case, you're interpretting it as a folder. S3 is not. It's just another object.

In your case above, the object users/<user-id>/contacts/<contact-id>/ exists in S3 as a distinct object, but the object users/<user-id>/ does not. That's the difference in your responses. Why they're like that, we cannot tell you, but someone made the object in one case, and didn't in the other. You don't see it in the AWS Management Console because the console is interpreting it as a folder and hiding it from you.

Since S3 just sees these things as objects, it won't "exclude" certain things for you. It's up to the client to deal with the objects as they should be dealt with.

Your Solution

Since you're the one that doesn't want the folder objects, you can exclude it yourself by checking the last character for a /. If it is, then ignore the object from the response.

_tkinter.TclError: no display name and no $DISPLAY environment variable

I want to add an answer here that noone has explicitly stated with implementation.

This is a great resource to refer to for this failure: https://matplotlib.org/faq/usage_faq.html

In my case, using matplotlib.use did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:

export MPLBACKEND=Agg

This takes care of the issue.

My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest, however would fail when using parallelism along with circleci tests split feature. However, declaring this env variable resolved the issue.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

How to get response from S3 getObject in Node.js?

Alternatively you could use minio-js client library get-object.js

var Minio = require('minio')

var s3Client = new Minio({
  endPoint: 's3.amazonaws.com',
  accessKey: 'YOUR-ACCESSKEYID',
  secretKey: 'YOUR-SECRETACCESSKEY'
})

var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
  if (e) {
    return console.log(e)
  }
  dataStream.on('data', function(chunk) {
    size += chunk.length
  })
  dataStream.on('end', function() {
    console.log("End. Total size = " + size)
  })
  dataStream.on('error', function(e) {
    console.log(e)
  })
})

Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was just banging my head against a wall just trying to get S3 uploads to work with large files. Initially my error was:

An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied

Then I tried copying a smaller file and got:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I could list objects fine but I couldn't do anything else even though I had s3:* permissions in my Role policy. I ended up reworking the policy to this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::my-bucket/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucketMultipartUploads",
                "s3:AbortMultipartUpload",
                "s3:ListMultipartUploadParts"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "*"
        }
    ]
}

Now I'm able to upload any file. Replace my-bucket with your bucket name. I hope this helps somebody else that's going thru this.

$lookup on ObjectId's in an array

Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var productSchema = Schema({ ... });

var orderSchema = Schema({
  _id     : Number,
  products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});

var Product = mongoose.model("Product", productSchema);
var Order   = mongoose.model("Order", orderSchema);

...

Order
    .find(...)
    .populate("products")
    ...

How to pass List<String> in post method using Spring MVC?

You are using wrong JSON. In this case you should use JSON that looks like this:

["orange", "apple"]

If you have to accept JSON in that form :

{"fruits":["apple","orange"]}

You'll have to create wrapper object:

public class FruitWrapper{

    List<String> fruits;

    //getter
    //setter
}

and then your controller method should look like this:

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}

Spring Boot @autowired does not work, classes in different package

Just put the packages inside the @SpringBootApplication tag.

@SpringBootApplication(scanBasePackages = { "com.pkg1", "com.pkg2", .....})

Let me know.

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

UIAlertView first deprecated IOS 9

Swift version of new implementation is :

 let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
 alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
 self.presentViewController(alert, animated: true){}

How to make HTTP Post request with JSON body in Swift

    // prepare json data
    let mapDict = [ "1":"First", "2":"Second"]

    let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
    let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData

    // create post request
    let url = NSURL(string: "http://httpbin.org/post")!
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"

    // insert json data to the request
    request.httpBody = jsonData as Data


    let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
            return
        }
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

            print("Result",result!)

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

How to execute logic on Optional if not present?

There is an .orElseRun method, but it is called .orElseGet.

The main problem with your pseudocode is that .isPresent doesn't return an Optional<>. But .map returns an Optional<> which has the orElseRun method.

If you really want to do this in one statement this is possible:

public Optional<Obj> getObjectFromDB() {
    return dao.find()
        .map( obj -> { 
            obj.setAvailable(true);
            return Optional.of(obj); 
         })
        .orElseGet( () -> {
            logger.fatal("Object not available"); 
            return Optional.empty();
    });
}

But this is even clunkier than what you had before.

Can't Autowire @Repository annotated interface in Spring Boot

Here is the mistake: as someone said before, you are using org.pharmacy insted of com.pharmacy in componentscan

    package **com**.pharmacy.config;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;


    @SpringBootApplication
    @ComponentScan("**org**.pharmacy")
    public class SpringBootRunner {

UIButton action in table view cell

in Swift 4

in cellForRowAt indexPath:

 cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)

function that run after user pressed button:

@objc func onClicked(sender: UIButton){
        let tag = sender.tag


    }

Amazon S3 exception: "The specified key does not exist"

In my case the error was appearing because I had uploaded the whole folder, containing the website files, into the container.

I solved it by moving all the files outside the folder, right into the container.

Convert array to JSON string in swift

For Swift 3.0 you have to use this:

var postString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
        let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

        postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
    } catch {
        print(error.localizedDescription)
    }
    request.httpBody = postString.data(using: .utf8)

100% working TESTED

Proper MIME type for .woff2 fonts

In IIS you can declare the mime type for WOFF2 font files by adding the following to your project's web.config:

<system.webServer>
  <staticContent>
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

Update: The mime type may be changing according to the latest W3C Editor's Draft WOFF2 spec. See Appendix A: Internet Media Type Registration section 6.5. WOFF 2.0 which states the latest proposed format is font/woff2

Swift GET request with parameters

You can extend your Dictionary to only provide stringFromHttpParameter if both key and value conform to CustomStringConvertable like this

extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
  func stringFromHttpParameters() -> String {
    var parametersString = ""
    for (key, value) in self {
      parametersString += key.description + "=" + value.description + "&"
    }
    return parametersString
  }
}

this is much cleaner and prevents accidental calls to stringFromHttpParameters on dictionaries that have no business calling that method

Read file from aws s3 bucket using node fs

This will do it:

new AWS.S3().getObject({ Bucket: this.awsBucketName, Key: keyName }, function(err, data)
{
    if (!err)
        console.log(data.Body.toString());
});

How can you test if an object has a specific property?

Real similar to a javascript check:

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Spring Boot, Spring Data JPA with multiple DataSources

don't know why, but it works. Two configuration are the same, just change xxx to your name.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "xxxEntityManager",
    transactionManagerRef = "xxxTransactionManager",
    basePackages = {"aaa.xxx"})
 public class RepositoryConfig {
@Autowired
private Environment env;

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.xxx")
public DataSource xxxDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
public LocalContainerEntityManagerFactoryBean xxxEntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(xxxDataSource());
    em.setPackagesToScan(new String[] {"aaa.xxx"});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    em.setJpaPropertyMap(properties);

    return em;
}

@Bean(name = "xxxTransactionManager")
public PlatformTransactionManager xxxTransactionManager() {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(xxxEntityManager().getObject());
    return tm;
}

}

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.

how to save and read array of array in NSUserdefaults in swift?

Swift 4.0

Store:

let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]    

 //store in user default
 UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")

Fetch:

if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
        print(arr)
    }

Spring Boot - Cannot determine embedded database driver class for database type NONE

From the Spring manual.

Spring Boot can auto-configure embedded H2, HSQL, and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.

For example, typical POM dependencies would be:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

For me leaving out the spring-boot-starter-data-jpa dependency and just using the spring-boot-starter-jdbc dependency worked like a charm, as long as I had h2 (or hsqldb) included as dependencies.

How do I import a Swift file from another Swift file?

In Objective-C, if you wanted to use a class in another file you had to import it:

#import "SomeClass.h"

However, in Swift, you don't have to import at all. Simply use it as if it was already imported.

Example

// This is a file named SomeClass.swift

class SomeClass : NSObject {

}

// This is a different file, named OtherClass.swift

class OtherClass : NSObject {
    let object = SomeClass()
}

As you can see, no import was needed. Hope this helps.

Spring boot Security Disable security

As previously multiple solutions mentioned to disable security through commenting of

@EnableWebSecurity

annotation and other is through properties in application.properties or yml. But those properties are showing as deprecated in latest spring boot version.

So, I would like to share another approach to configure default username and password in your application-dev.properties or application-dev.yml and use them to login into swagger and etc in development environment.

spring.security.user.name=admin
spring.security.user.password=admin

So, this approach will also provides you some kind of security as well and you can share this information with your development team. You can also configure user roles as well, but its not required in development level.

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

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

How to test Spring Data repositories?

When you really want to write an i-test for a spring data repository you can do it like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {

    @Autowired
    private WebBookingRepository repository;

    @Test
    public void testSaveAndFindAll() {
        WebBooking webBooking = new WebBooking();
        webBooking.setUuid("some uuid");
        webBooking.setItems(Arrays.asList(new WebBookingItem()));
        repository.save(webBooking);

        Iterable<WebBooking> findAll = repository.findAll();

        assertThat(findAll).hasSize(1);
        webBooking.setId(1L);
        assertThat(findAll).containsOnly(webBooking);
    }
}

To follow this example you have to use these dependencies:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.9.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Using a HTTP debugging proxy can cause this - such as Fiddler.

I was loading a PFX certificate from a local file (authentication to Apple.com) and it failed because Fiddler wasn't able to pass this certificate on.

Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

Cannot deserialize the current JSON array (e.g. [1,2,3])

That's because the json you're getting is an array of your RootObject class, rather than a single instance, change your DeserialiseObject<RootObject> to be something like DeserialiseObject<RootObject[]> (un-tested).

You'll then have to either change your method to return a collection of RootObject or do some further processing on the deserialised object to return a single instance.

If you look at a formatted version of the response you provided:

[
   {
      "id":3636,
      "is_default":true,
      "name":"Unit",
      "quantity":1,
      "stock":"100000.00",
      "unit_cost":"0"
   },
   {
      "id":4592,
      "is_default":false,
      "name":"Bundle",
      "quantity":5,
      "stock":"100000.00",
      "unit_cost":"0"
   }
]

You can see two instances in there.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

Could not resolve placeholder in string value

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

Attempt to set a non-property-list object as an NSUserDefaults

The code you posted tries to save an array of custom objects to NSUserDefaults. You can't do that. Implementing the NSCoding methods doesn't help. You can only store things like NSArray, NSDictionary, NSString, NSData, NSNumber, and NSDate in NSUserDefaults.

You need to convert the object to NSData (like you have in some of the code) and store that NSData in NSUserDefaults. You can even store an NSArray of NSData if you need to.

When you read back the array you need to unarchive the NSData to get back your BC_Person objects.

Perhaps you want this:

- (void)savePersonArrayData:(BC_Person *)personObject {
    [mutableDataArray addObject:personObject];

    NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
    for (BC_Person *personObject in mutableDataArray) { 
        NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
        [archiveArray addObject:personEncodedObject];
    }

    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:archiveArray forKey:@"personDataArray"];
}

How to check if the request is an AJAX request with PHP

You could try using a $_SESSION variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].

JavaScript OOP in NodeJS: how?

I suggest to use the inherits helper that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on the linked page.

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

The remote server returned an error: (403) Forbidden

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

How do I deserialize a complex JSON object in C# .NET?

You can solve your problem like below bunch of codes

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject<T>
    {
        public List<T> response{ get; set; }

    }

var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));

Make function wait until element exists

If you want a generic solution using MutationObserver you can use this function

// MIT Licensed
// Author: jwilson8767

/**
 * Waits for an element satisfying selector to exist, then resolves promise with the element.
 * Useful for resolving race conditions.
 *
 * @param selector
 * @returns {Promise}
 */
export function elementReady(selector) {
  return new Promise((resolve, reject) => {
    const el = document.querySelector(selector);
    if (el) {resolve(el);}
    new MutationObserver((mutationRecords, observer) => {
      // Query for elements matching the specified selector
      Array.from(document.querySelectorAll(selector)).forEach((element) => {
        resolve(element);
        //Once we have resolved we don't need the observer anymore.
        observer.disconnect();
      });
    })
      .observe(document.documentElement, {
        childList: true,
        subtree: true
      });
  });
}

Source: https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
Example how to use it

elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});

Note: MutationObserver has a great browser support; https://caniuse.com/#feat=mutationobserver

Et voilà ! :)

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

Usage:

var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);

Logic:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string> 
        {
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

How can I create objects while adding them into a vector?

To answer the first part of your question, you must create an object of type Player before you can use it. When you say push_back(Player), it means "add the Player class to the vector", not "add an object of type Player to the vector" (which is what you meant).

You can create the object on the stack like this:

Player player;
vectorOfGamers.push_back(player);    // <-- name of variable, not type

Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):

vectorOfGamers.push_back(Player());    // <-- parentheses create a "temporary"

To answer the second part, you can create a vector of the base type, which will allow you to push back objects of any subtype; however, this won't work as expected:

vector<Gamer> gamers;
gamers.push_back(Dealer());    // Doesn't work properly!

since when the dealer object is put into the vector, it gets copied as a Gamer object -- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:

vector<Gamer*> gamers;
gamers.push_back(new Dealer());    // <-- Allocate on heap with `new`, since we
                                   // want the object to persist while it's
                                   // pointed to

File inside jar is not visible for spring

If your spring-context.xml and my.config files are in different jars then you will need to use classpath*:my.config?

More info here

Also, make sure you are using resource.getInputStream() not resource.getFile() when loading from inside a jar file.

Resize UIImage and change the size of UIImageView

If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

EDIT----

Ok, so seeing your comment I propose this:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Remove cascading from the child entity Transaction, it should be just:

@Entity class Transaction {
    @ManyToOne // no cascading here!
    private Account account;
}

(FetchType.EAGER can be removed as well as it's the default for @ManyToOne)

That's all!

Why? By saying "cascade ALL" on the child entity Transaction you require that every DB operation gets propagated to the parent entity Account. If you then do persist(transaction), persist(account) will be invoked as well.

But only transient (new) entities may be passed to persist (Transaction in this case). The detached (or other non-transient state) ones may not (Account in this case, as it's already in DB).

Therefore you get the exception "detached entity passed to persist". The Account entity is meant! Not the Transaction you call persist on.


You generally don't want to propagate from child to parent. Unfortunately there are many code examples in books (even in good ones) and through the net, which do exactly that. I don't know, why... Perhaps sometimes simply copied over and over without much thinking...

Guess what happens if you call remove(transaction) still having "cascade ALL" in that @ManyToOne? The account (btw, with all other transactions!) will be deleted from the DB as well. But that wasn't your intention, was it?

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How can I get Apache gzip compression to work?

It is better to implement it as in the snippet below.

Just paste the content below in your .htaccess file, then, check the performance using: Google PageSpeed, Pingdom Tools and GTmetrics.

# Enable GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</ifmodule>

# Expires Headers - 2678400s = 31 days
<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 2678400 seconds"
  ExpiresByType image/jpeg "access plus 2678400 seconds"
  ExpiresByType image/png "access plus 2678400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 2678400 seconds"
  ExpiresByType application/x-javascript "access plus 2678400 seconds"
</ifmodule>

# Cache Headers
<ifmodule mod_headers.c>
  # Cache specified files for 31 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 31 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</ifmodule>

Add new row to excel Table (VBA)

You don't say which version of Excel you are using. This is written for 2007/2010 (a different apprach is required for Excel 2003 )

You also don't say how you are calling addDataToTable and what you are passing into arrData.
I'm guessing you are passing a 0 based array. If this is the case (and the Table starts in Column A) then iCount will count from 0 and .Cells(lLastRow + 1, iCount) will try to reference column 0 which is invalid.

You are also not taking advantage of the ListObject. Your code assumes the ListObject1 is located starting at row 1. If this is not the case your code will place the data in the wrong row.

Here's an alternative that utilised the ListObject

Sub MyAdd(ByVal strTableName As String, ByRef arrData As Variant)
    Dim Tbl As ListObject
    Dim NewRow As ListRow

    ' Based on OP 
    ' Set Tbl = Worksheets(4).ListObjects(strTableName)
    ' Or better, get list on any sheet in workbook
    Set Tbl = Range(strTableName).ListObject
    Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)

    ' Handle Arrays and Ranges
    If TypeName(arrData) = "Range" Then
        NewRow.Range = arrData.Value
    Else
        NewRow.Range = arrData
    End If
End Sub

Can be called in a variety of ways:

Sub zx()
    ' Pass a variant array copied from a range
    MyAdd "MyTable", [G1:J1].Value
    ' Pass a range
    MyAdd "MyTable", [G1:J1]
    ' Pass an array
    MyAdd "MyTable", Array(1, 2, 3, 4)
End Sub

How to call a parent method from child class in javascript?

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:

class Foo {
    static classMethod() {
        return 'hello';
    }
}

class Bar extends Foo {
    static classMethod() {
        return super.classMethod() + ', too';
    }
}
Bar.classMethod(); // 'hello, too'

Also, you can use super to call parent constructor:

class Foo {}

class Bar extends Foo {
    constructor(num) {
        let tmp = num * 2; // OK
        this.num = num; // ReferenceError
        super();
        this.num = num; // OK
    }
}

And of course you can use it to access parent class properties super.prop. So, use ES6 and be happy.

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

In PowerShell, how can I test if a variable holds a numeric value?

-is and -as operators requires a type you can compare against. If you're not sure what the type might be, try to evaluate the content (partial type list):

(Invoke-Expression '1.5').GetType().Name -match 'byte|short|int32|long|sbyte|ushort|uint32|ulong|float|double|decimal'

Good or bad, it can work against hex values as well (Invoke-Expression '0xA' ...)

Mockito, JUnit and Spring

The difference in whether you have to instantiate your @InjectMocks annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks. In 1.9, which will also handle some constructor injection of your @Mock fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.

This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.

And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

Most simple code to populate JTable from ResultSet

I think the simplest way to build a model from an instance of ResultSet, could be as follows.

public static void main(String[] args) throws Exception {
    // The Connection is obtained

    ResultSet rs = stmt.executeQuery("select * from product_info");

    // It creates and displays the table
    JTable table = new JTable(buildTableModel(rs));

    // Closes the Connection

    JOptionPane.showMessageDialog(null, new JScrollPane(table));

}

The method buildTableModel:

public static DefaultTableModel buildTableModel(ResultSet rs)
        throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}

UPDATE

Do you like to use javax.swing.SwingWorker? Do you like to use the try-with-resources statement?

public class GUI extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }

    private final JButton button;
    private final JTable table;
    private final DefaultTableModel tableModel = new DefaultTableModel();

    public GUI() throws HeadlessException {

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        table = new JTable(tableModel);
        add(new JScrollPane(table), BorderLayout.CENTER);

        button = new JButton("Load Data");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        loadData();
                        return null;
                    }
                }.execute();
            }
        });
        add(button, BorderLayout.PAGE_START);

        setSize(640, 480);
    }

    private void loadData() {
        LOG.info("START loadData method");

        button.setEnabled(false);

        try (Connection conn = DriverManager.getConnection(url, usr, pwd);
                Statement stmt = conn.createStatement()) {

            ResultSet rs = stmt.executeQuery("select * from customer");
            ResultSetMetaData metaData = rs.getMetaData();

            // Names of columns
            Vector<String> columnNames = new Vector<String>();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                columnNames.add(metaData.getColumnName(i));
            }

            // Data of the table
            Vector<Vector<Object>> data = new Vector<Vector<Object>>();
            while (rs.next()) {
                Vector<Object> vector = new Vector<Object>();
                for (int i = 1; i <= columnCount; i++) {
                    vector.add(rs.getObject(i));
                }
                data.add(vector);
            }

            tableModel.setDataVector(data, columnNames);
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Exception in Load Data", e);
        }
        button.setEnabled(true);

        LOG.info("END loadData method");
    }

}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

Using Powershell to stop a service remotely without WMI or remoting

Thanks to everyone's contributions to this question, I've come up with the following script. Change the values for $SvcName and $SvrName to suit your needs. This script will start the remote service if it is stopped, or stop it if it is started. And it uses the cool .WaitForStatus method to wait while the service responds.

#Change this values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'remotePC'

#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
    'Stopped' {
        Write-host "Starting $SvcName..."
        $Verb = "start"
        $WaitForIt = 'Running'
        $svc.Start()}
    'Running' {
        Write-host "Stopping $SvcName..."
        $Verb = "stop"
        $WaitForIt = 'Stopped'
        $svc.Stop()}
    Default {
        Write-host "$SvcName is $($svc.status).  Taking no action."}
}
if ($WaitForIt -ne "") {
    Try {  # For some reason, we cannot use -ErrorAction after the next statement:
        $svc.WaitForStatus($WaitForIt,'00:02:00')
    } Catch {
        Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
    }
    $svc = (get-service -computername $SvrName -name $SvcName)
    if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
    Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}

Of course, the account you run this under will need the proper privileges to access the remote computer and start and stop services. And when executing this against older remote machines, you might first have to install WinRM 3.0 on the older machine.

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

Requested bean is currently in creation: Is there an unresolvable circular reference?

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

Check if registry key exists using VBScript

Simplest way avoiding RegRead and error handling tricks. Optional friendly consts for the registry:

Const HKEY_CLASSES_ROOT   = &H80000000
Const HKEY_CURRENT_USER   = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS          = &H80000003
Const HKEY_CURRENT_CONFIG = &H80000005

Then check with:

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")

If oReg.EnumKey(HKEY_LOCAL_MACHINE, "SYSTEM\Example\Key\", "", "") = 0 Then
  MsgBox "Key Exists"
Else
  MsgBox "Key Not Found"
End If

IMPORTANT NOTES FOR THE ABOVE:

  • There are 4 parameters being passed to EnumKey, not the usual 3.
  • Equals zero means the key EXISTS.
  • The slash after key name is optional and not required.

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

In my case setting the referenced object to NULL in my object before the merge o save method solve the problem, in my case the referenced object was catalog, that doesn't need to be saved, because in some cases I don't have it even.

    fisEntryEB.setCatStatesEB(null);

    (fisEntryEB) getSession().merge(fisEntryEB);

No matching bean of type ... found for dependency

Add this to you applicationContext:

 <bean id="userService" class="com.example.my.services.user.UserServiceImpl ">

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Jersey Exception : SEVERE: A message body reader for Java class

I know that this post is old and you figured this out a long time ago, but just to save the people who will read this some time.

You probably forgot to add annotation to the entity you are passing to the endpoint, so Jersey does not know how to process the POJO it receives. Annotate the pojo with something like this:

@XmlRootElement(name = "someName")

AmazonS3 putObject with InputStream length example

Just passing the file object to the putobject method worked for me. If you are getting a stream, try writing it to a temp file before passing it on to S3.

amazonS3.putObject(bucketName, id,fileObject);

I am using Aws SDK v1.11.414

The answer at https://stackoverflow.com/a/35904801/2373449 helped me

How to check if a specified key exists in a given S3 bucket using Java

Use ListObjectsRequest setting Prefix as your key.

.NET code:

 public bool Exists(string key)
    {

        using (Amazon.S3.AmazonS3Client client = (Amazon.S3.AmazonS3Client)Amazon.AWSClientFactory.CreateAmazonS3Client(m_accessKey, m_accessSecret))
        {
            ListObjectsRequest request = new ListObjectsRequest();
            request.BucketName = m_bucketName;
            request.Prefix = key;
            using (ListObjectsResponse response = client.ListObjects(request))
            {

                foreach (S3Object o in response.S3Objects)
                {
                    if( o.Key == key )
                        return true;
                }
                return false;
            }
        }
    }.

Handling warning for possible multiple enumeration of IEnumerable

First off, that warning does not always mean so much. I usually disabled it after making sure it's not a performance bottle neck. It just means the IEnumerable is evaluated twice, wich is usually not a problem unless the evaluation itself takes a long time. Even if it does take a long time, in this case your only using one element the first time around.

In this scenario you could also exploit the powerful linq extension methods even more.

var firstObject = objects.First();
return DoSomeThing(firstObject).Concat(DoSomeThingElse(objects).ToList();

It is possible to only evaluate the IEnumerable once in this case with some hassle, but profile first and see if it's really a problem.

How to list all AWS S3 objects in a bucket using Java

You don't want to list all 1000 object in your bucket at a time. A more robust solution will be to fetch a max of 10 objects at a time. You can do this with the withMaxKeys method.

The following code creates an S3 client, fetches 10 or less objects at a time and filters based on a prefix and generates a pre-signed url for the fetched object:

import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;

import java.net.URL;
import java.util.Date;

/**
 * @author shabab
 * @since 21 Sep, 2020
 */
public class AwsMain {

    static final String ACCESS_KEY = "";
    static final String SECRET = "";
    static final Regions BUCKET_REGION = Regions.DEFAULT_REGION;
    static final String BUCKET_NAME = "";

    public static void main(String[] args) {
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET);

        try {
            final AmazonS3 s3Client = AmazonS3ClientBuilder
                    .standard()
                    .withRegion(BUCKET_REGION)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .build();

            ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(BUCKET_NAME).withMaxKeys(10);
            ListObjectsV2Result result;

            do {
                result = s3Client.listObjectsV2(req);

                result.getObjectSummaries()
                        .stream()
                        .filter(s3ObjectSummary -> {
                            return s3ObjectSummary.getKey().contains("Market-subscriptions/")
                                    && !s3ObjectSummary.getKey().equals("Market-subscriptions/");
                        })
                        .forEach(s3ObjectSummary -> {

                            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                                    new GeneratePresignedUrlRequest(BUCKET_NAME, s3ObjectSummary.getKey())
                                            .withMethod(HttpMethod.GET)
                                            .withExpiration(getExpirationDate());

                            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

                            System.out.println(s3ObjectSummary.getKey() + " Pre-Signed URL: " + url.toString());
                        });

                String token = result.getNextContinuationToken();
                req.setContinuationToken(token);

            } while (result.isTruncated());
        } catch (SdkClientException e) {
            e.printStackTrace();
        }

    }

    private static Date getExpirationDate() {
        Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 60;
        expiration.setTime(expTimeMillis);

        return expiration;
    }
}

How to stop a vb script running in windows

Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.

Guid is all 0's (zeros)?

In the spirit of being complete, the answers that instruct you to use Guid.NewGuid() are correct.

In addressing your subsequent edit, you'll need to post the code for your RequestObject class. I'm suspecting that your guid property is not marked as a DataMember, and thus is not being serialized over the wire. Since default(Guid) is the same as new Guid() (i.e. all 0's), this would explain the behavior you're seeing.

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

Injection of autowired dependencies failed;

public class Organization {

    @Id
    @Column(name="org_id")
    @GeneratedValue
    private int id;

    @Column(name="org_name")
    private String name;

    @Column(name="org_office_address1")
    private String address1;

    @Column(name="org_office_addres2")
    private String address2;

    @Column(name="city")
    private String city;

    @Column(name="state")
    private String state;

    @Column(name="country")
    private String country;

    @JsonIgnore
    @OneToOne
    @JoinColumn(name="pkg_id")
    private int pkgId;

    public int getPkgId() {
        return pkgId;
    }

    public void setPkgId(int pkgId) {
        this.pkgId = pkgId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="pincode")
    private String pincode;

    @OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);

    @Column(name="status")
    private String status = "ACTIVE";

    @Column(name="project_id")
    private int redmineProjectId;

    public int getRedmineProjectId() {
        return redmineProjectId;
    }

    public void setRedmineProjectId(int redmineProjectId) {
        this.redmineProjectId = redmineProjectId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Set<OrganizationBranch> getOrganizationBranch() {
        return organizationBranch;
    }

    public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
        this.organizationBranch = organizationBranch;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}

You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired

Java for loop syntax: "for (T obj : objects)"

public class ForEachLoopExample {

    public static void main(String[] args) {

        System.out.println("For Each Loop Example: ");

        int[] intArray = { 1,2,3,4,5 };

        //Here iteration starts from index 0 to last index
        for(int i : intArray)
            System.out.println(i);
    }

}

vba error handling in loop

There is another way of controlling error handling that works well for loops. Create a string variable called here and use the variable to determine how a single error handler handles the error.

The code template is:

On error goto errhandler

Dim here as String

here = "in loop"
For i = 1 to 20 
    some code
Next i

afterloop:
here = "after loop"
more code

exitproc:    
exit sub

errhandler:
If here = "in loop" Then 
    resume afterloop
elseif here = "after loop" Then
    msgbox "An error has occurred" & err.desc
    resume exitproc
End if

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

Programmatically get height of navigation bar

Did you try this?

let barHeight = self.navigationController?.navigationBar.frame.height ?? 0

How do I use a custom Serializer with Jackson?

Jackson's JSON Views might be a simpler way of achieving your requirements, especially if you have some flexibility in your JSON format.

If {"id":7, "itemNr":"TEST", "createdBy":{id:3}} is an acceptable representation then this will be very easy to achieve with very little code.

You would just annotate the name field of User as being part of a view, and specify a different view in your serialisation request (the un-annotated fields would be included by default)

For example: Define the views:

public class Views {
    public static class BasicView{}
    public static class CompleteUserView{}
}

Annotate the User:

public class User {
    public final int id;

    @JsonView(Views.CompleteUserView.class)
    public final String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

And serialise requesting a view which doesn't contain the field you want to hide (non-annotated fields are serialised by default):

objectMapper.getSerializationConfig().withView(Views.BasicView.class);

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

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

JSON - Iterate through JSONArray

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/

C# Create New T()

Why hasn't anyone suggested Activator.CreateInstance ?

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

T obj = (T)Activator.CreateInstance(typeof(T));

Most efficient conversion of ResultSet to JSON?

In addition to suggestions made by @Jim Cook. One other thought is to use a switch instead of if-elses:

while(rs.next()) {
  int numColumns = rsmd.getColumnCount();
  JSONObject obj = new JSONObject();

  for( int i=1; i<numColumns+1; i++) {
    String column_name = rsmd.getColumnName(i);

    switch( rsmd.getColumnType( i ) ) {
      case java.sql.Types.ARRAY:
        obj.put(column_name, rs.getArray(column_name));     break;
      case java.sql.Types.BIGINT:
        obj.put(column_name, rs.getInt(column_name));       break;
      case java.sql.Types.BOOLEAN:
        obj.put(column_name, rs.getBoolean(column_name));   break;
      case java.sql.Types.BLOB:
        obj.put(column_name, rs.getBlob(column_name));      break;
      case java.sql.Types.DOUBLE:
        obj.put(column_name, rs.getDouble(column_name));    break;
      case java.sql.Types.FLOAT:
        obj.put(column_name, rs.getFloat(column_name));     break;
      case java.sql.Types.INTEGER:
        obj.put(column_name, rs.getInt(column_name));       break;
      case java.sql.Types.NVARCHAR:
        obj.put(column_name, rs.getNString(column_name));   break;
      case java.sql.Types.VARCHAR:
        obj.put(column_name, rs.getString(column_name));    break;
      case java.sql.Types.TINYINT:
        obj.put(column_name, rs.getInt(column_name));       break;
      case java.sql.Types.SMALLINT:
        obj.put(column_name, rs.getInt(column_name));       break;
      case java.sql.Types.DATE:
        obj.put(column_name, rs.getDate(column_name));      break;
      case java.sql.Types.TIMESTAMP:
        obj.put(column_name, rs.getTimestamp(column_name)); break;
      default:
        obj.put(column_name, rs.getObject(column_name));    break;
    }
  }

  json.put(obj);
}

org.hibernate.PersistentObjectException: detached entity passed to persist

Two solutions 1. use merge if you want to update the object 2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it) 3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL) @JoinColumn(name = "stock_id")

Then use CascadeType.ALL to CascadeType.MERGE

thanks Shahid Abbasi

What could cause java.lang.reflect.InvocationTargetException?

  1. List all jar files from the Eclipse Navigator mode
  2. Verify that all the jar files are in binary mode

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

How to check for null in a single statement in scala?

Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:

getObject ifNotNull ( QueueManager.add(_) )

I find it reads better.

And, in a more general way, I sometimes write

val returnVal = getObject ifNotNull { obj =>
  returnSomethingFrom(obj)
} otherwise {
  returnSomethingElse
}

... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.

(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

How to deserialize JS date using Jackson?

@JsonFormat only work for standard format supported by the jackson version that you are using.

Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6

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 .

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

Java Wait for thread to finish

You can use join() to wait for all threads to finish. Keep all objects of threads in the global ArrayList at the time of creating threads. After that keep it in loop like below:

for (int i = 0; i < 10; i++) 
{
    Thread T1 = new Thread(new ThreadTest(i));                
    T1.start();                
    arrThreads.add(T1);
} 

for (int i = 0; i < arrThreads.size(); i++) 
{
    arrThreads.get(i).join(); 
}

Check here for complete details: http://www.letmeknows.com/2017/04/24/wait-for-threads-to-finish-java

Set drawable size programmatically

You can use LayerDrawable from only one layer and setLayerInset method:

Drawable[] layers = new Drawable[1];
layers[0] = application.getResources().getDrawable(R.drawable.you_drawable);

LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setLayerInset(0, 10, 10, 10, 10);

How to tell a Mockito mock object to return something different the next time it is called?

You could also Stub Consecutive Calls (#10 in 2.8.9 api). In this case, you would use multiple thenReturn calls or one thenReturn call with multiple parameters (varargs).

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

public class TestClass {

    private Foo mockFoo;

    @Before
    public void setup() {
        setupFoo();
    }

    @Test
    public void testFoo() {
        TestObject testObj = new TestObject(mockFoo);

        assertEquals(0, testObj.bar());
        assertEquals(1, testObj.bar());
        assertEquals(-1, testObj.bar());
        assertEquals(-1, testObj.bar());
    }

    private void setupFoo() {
        mockFoo = mock(Foo.class);

        when(mockFoo.someMethod())
            .thenReturn(0)
            .thenReturn(1)
            .thenReturn(-1); //any subsequent call will return -1

        // Or a bit shorter with varargs:
        when(mockFoo.someMethod())
            .thenReturn(0, 1, -1); //any subsequent call will return -1
    }
}

Get domain name

I know this is old. I just wanted to dump this here for anyone that was looking for an answer to getting a domain name. This is in coordination with Peter's answer. There "is" a bug as stated by Rich. But, you can always make a simple workaround for that. The way I can tell if they are still on the domain or not is by pinging the domain name. If it responds, continue on with whatever it was that I needed the domain for. If it fails, I drop out and go into "offline" mode. Simple string method.

 string GetDomainName()
    {
        string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        Ping ping = new Ping();

        try
        {
            PingReply reply = ping.Send(_domain);

            if (reply.Status == IPStatus.Success)
            {
                return _domain;
            }
            else
            {
                return reply.Status.ToString();
            }
        }
        catch (PingException pExp)
        {
            if (pExp.InnerException.ToString() == "No such host is known")
            {
                return "Network not detected!";
            }

            return "Ping Exception";
        }
    }

Get Hard disk serial Number

Here's some code that may help:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

string serial_number="";

foreach (ManagementObject wmi_HD in searcher.Get())
{
    serial_number = wmi_HD["SerialNumber"].ToString();
}

MessageBox.Show(serial_number);

Getting reference to the top-most view/window in iOS application

Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.

It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.

UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)

Mockito. Verify method arguments

I have used Mockito.verify in this way

@UnitTest
public class JUnitServiceTest
{
    @Mock
    private MyCustomService myCustomService;


    @Test
    public void testVerifyMethod()
    {
       Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
       Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
       Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
       Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
       Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
       Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); //   no other method called except this
    }
}

how to check if object already exists in a list

Simple but it works

MyList.Remove(nextObject)
MyList.Add(nextObject)

or

 if (!MyList.Contains(nextObject))
    MyList.Add(nextObject);

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Checking for a null int value from a Java ResultSet

The default for ResultSet.getInt when the field value is NULL is to return 0, which is also the default value for your iVal declaration. In which case your test is completely redundant.

If you actually want to do something different if the field value is NULL, I suggest:

int iVal = 0;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
    iVal = rs.getInt("ID_PARENT");
    if (rs.wasNull()) {
        // handle NULL field value
    }
}

(Edited as @martin comments below; the OP code as written would not compile because iVal is not initialised)

Generating a PNG with matplotlib when DISPLAY is undefined

When signing into the server to execute the code use this instead:

ssh -X username@servername

the -X will get rid of the no display name and no $DISPLAY environment variable error

:)

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

"Invalid JSON primitive" in Ajax processing

Just a guess what does the variable json contain after

var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?

If it is a valid json object like {'foo':'foovalue', 'bar':'barvalue'} then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue thus you get the error "Invalid JSON primitive: foo"

Try instead setting the data as string

$.ajax({
    ...
    data: "{'foo':'foovalue', 'bar':'barvalue'}", //note the additional quotation marks
    ...
})

This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.

"detached entity passed to persist error" with JPA/EJB code

I know its kind of too late and proly every one got the answer. But little bit more to add to this: when GenerateType is set, persist() on an object is expected to get an id generated.

If there is a value set to the Id by user already, hibernate treats it as saved record and so it is treated as detached.

if the id is null - in this situation a null pointer exception is raised when the type is AUTO or IDENTITY etc unless the id is generated from a table or a sequece etc.

design: this happens when the table has a bean property as primary key. GenerateType must be set only when an id is autogenerated. remove this and the insert should work with the user specified id. (it is a bad design to have a property mapped to primary key field)

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

Update your pom.xml

<dependency>
  <groupId>asm</groupId>
  <artifactId>asm</artifactId>
  <version>3.1</version>
</dependency>

How to store custom objects in NSUserDefaults

Synchronize the data/object that you have saved into NSUserDefaults

-(void)saveCustomObject:(Player *)object
{ 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"testing"];
    [prefs synchronize];
}

Hope this will help you. Thanks

Create a custom callback in JavaScript

It is good practice to make sure the callback is an actual function before attempting to execute it:

if (callback && typeof(callback) === "function") {

  callback();
}

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

You should add return statement while you are forwarding or redirecting the flow.

Example:

if forwardind,

    request.getRequestDispatcher("/abs.jsp").forward(request, response);
    return;

if redirecting,

    response.sendRedirect(roundTripURI);
    return;

Storing Objects in HTML5 localStorage

localStorage.setItem('user', JSON.stringify(user));

Then to retrieve it from the store and convert to an object again:

var user = JSON.parse(localStorage.getItem('user'));

If we need to delete all entries of the store we can simply do:

localStorage.clear();

Select Multiple Fields from List in Linq

This is task for which anonymous types are very well suited. You can return objects of a type that is created automatically by the compiler, inferred from usage.

The syntax is of this form:

new { Property1 = value1, Property2 = value2, ... }

For your case, try something like the following:

var listObject = getData();
var catNames = listObject.Select(i =>
    new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
    .Distinct().OrderByDescending(s => s).ToArray();

"The Controls collection cannot be modified because the control contains code blocks"

I had the same issue with my system, I removed the JavaScript code from the of my page and put it at body just before closing body tag

WPF MVVM ComboBox SelectedItem or SelectedValue not working

Have you tried implementing INotifyPropertyChanged in your viewmodel, and then raise the PropertyChanged event when the SelectedItem gets set?

If this in itself doesn't fix it, then you will be able to manually raise the PropertyChanged event yourself when navigating back to the page, and that should be enough to get WPF to redraw itself and show the correct selected item.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

How the synchronized Java keyword works

When you add the synchronized keyword to a static method, the method can only be called by a single thread at a time.

In your case, every method call will:

  • create a new SessionFactory
  • create a new Session
  • fetch the entity
  • return the entity back to the caller

However, these were your requirements:

  • I want this to prevent access to info to the same DB instance.
  • preventing getObjectById being called for all classes when it is called by a particular class

So, even if the getObjectById method is thread-safe, the implementation is wrong.

SessionFactory best practices

The SessionFactory is thread-safe, and it's a very expensive object to create as it needs to parse the entity classes and build the internal entity metamodel representation.

So, you shouldn't create the SessionFactory on every getObjectById method call.

Instead, you should create a singleton instance for it.

private static final SessionFactory sessionFactory = new Configuration()
    .configure()
    .buildSessionFactory();

The Session should always be closed

You didn't close the Session in a finally block, and this can leak database resources if an exception is thrown when loading the entity.

According to the Session.load method JavaDoc might throw a HibernateException if the entity cannot be found in the database.

You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.

That's why you need to use a finally block to close the Session, like this:

public static synchronized Object getObjectById (Class objclass, Long id) {    
     Session session = null;
     try {
         session = sessionFactory.openSession();
         return session.load(objclass, id);
     } finally {
         if(session != null) {
             session.close(); 
         }
     }
 }

Preventing multi-thread access

In your case, you wanted to make sure only one thread gets access to that particular entity.

But the synchronized keyword only prevents two threads from calling the getObjectById concurrently. If the two threads call this method one after the other, you will still have two threads using this entity.

So, if you want to lock a given database object so no other thread can modify it, then you need to use database locks.

The synchronized keyword only works in a single JVM. If you have multiple web nodes, this will not prevent multi-thread access across multiple JVMs.

What you need to do is use LockModeType.PESSIMISTIC_READ or LockModeType.PESSIMISTIC_WRITE while applying the changes to the DB, like this:

Session session = null;
EntityTransaction tx = null;

try {
    session = sessionFactory.openSession();
    
    tx = session.getTransaction();
    tx.begin();

    Post post = session.find(
        Post.class, 
        id, 
        LockModeType.LockModeType.PESSIMISTIC_READ
    );

    post.setTitle("High-Performance Java Perisstence");

    tx.commit();
} catch(Exception e) {
    LOGGER.error("Post entity could not be changed", e);
    if(tx != null) {
        tx.rollback(); 
    }
} finally {
    if(session != null) {
        session.close(); 
    }
}

So, this is what I did:

  • I created a new EntityTransaction and started a new database transaction
  • I loaded the Post entity while holding a lock on the associated database record
  • I changed the Post entity and committed the transaction
  • In the case of an Exception being thrown, I rolled back the transaction

Error handling in C code

I personally prefer the former approach (returning an error indicator).

Where necessary the return result should just indicate that an error occurred, with another function being used to find out the exact error.

In your getSize() example I'd consider that sizes must always be zero or positive, so returning a negative result can indicate an error, much like UNIX system calls do.

I can't think of any library that I've used that goes for the latter approach with an error object passed in as a pointer. stdio, etc all go with a return value.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

Will using 'var' affect performance?

There's no extra IL code for the var keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.

The only trick is that var will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.


Update 8 Years Later

I need to update this as my understanding has changed. I now believe it may be possible for var to affect performance in the situation where a method returns an interface, but you would have used an exact type. For example, if you have this method:

IList<int> Foo()
{
    return Enumerable.Range(0,10).ToList();
}

Consider these three lines of code to call the method:

List<int> bar1 = Foo();
IList<int> bar = Foo();
var bar3 = Foo();

All three compile and execute as expected. However, the first two lines are not exactly the same, and the third line will match the second, rather than the first. Because the signature of Foo() is to return an IList<int>, that is how the compiler will build the bar3 variable.

From a performance standpoint, mostly you won't notice. However, there are situations where the performance of the third line may not be quite as fast as the performance of the first. As you continue to use the bar3 variable, the compiler may not be able to dispatch method calls the same way.

Note that it's possible (likely even) the jitter will be able to erase this difference, but it's not guaranteed. Generally, you should still consider var to be a non-factor in terms of performance. It's certainly not at all like using a dynamic variable. But to say it never makes a difference at all may be overstating it.

Fastest Convert from Collection to List<T>

managementObjects.Cast<ManagementBaseObject>().ToList(); is a good choice.

You could improve performance by pre-initialising the list capacity:


    public static class Helpers
    {
        public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
        {
            var output = new List<T>(other.Count);

            output.AddRange(other.Cast<T>());

            return output;
        }
    }

Set JavaScript variable = null, or leave undefined?

It depends on the context.

  • "undefined" means this value does not exist. typeof returns "undefined"

  • "null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.

Create SQL script that create database and tables

Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:

Right-click on the Database, select Tasks and then Generate Scripts, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.

If you are happy with the default options, you can do the whole job in a matter of seconds.

If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).

Alter user defined type in SQL Server

there's a good example of a more comprehensive script here

It's worth noting that this script will include views if you have any. I ran it and instead of exec'ing inline generated a script as the output which I then tweaked and ran.

Also, if you have functions/sprocs using the user defeined types you'll need to drop those before running your script.

Lesson Learned: in future, don't bother with UDTs they're more hassle than they're worth.

SET NOCOUNT ON

DECLARE @udt VARCHAR(150)
DECLARE @udtschema VARCHAR(150)
DECLARE @newudtschema VARCHAR(150)
DECLARE @newudtDataType VARCHAR(150)
DECLARE @newudtDataSize smallint
DECLARE @OtherParameter VARCHAR(50)

SET @udt = 'Name' -- Existing UDDT
SET @udtschema = 'dbo' -- Schema of the UDDT
SET @newudtDataType = 'varchar' -- Data type for te new UDDT
SET @newudtDataSize = 500 -- Lenght of the new UDDT
SET @newudtschema = 'dbo' -- Schema of the new UDDT
SET @OtherParameter = ' NULL' -- Other parameters like NULL , NOT NULL
DECLARE @Datatype VARCHAR(50),
    @Datasize SMALLINT

DECLARE @varcharDataType VARCHAR(50)

DECLARE @Schemaname VARCHAR(50),
    @TableName VARCHAR(50),
    @FiledName VARCHAR(50)

CREATE TABLE #udtflds
    (
      Schemaname VARCHAR(50),
      TableName VARCHAR(50),
      FiledName VARCHAR(50)
    )

SELECT TOP 1
        @Datatype = Data_type,
        @Datasize = character_maximum_length
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   Domain_name = @udt
        AND Domain_schema = @udtschema

SET @varcharDataType = @Datatype
IF @DataType Like '%char%'
    AND @Datasize IS NOT NULL
    AND ( @newudtDataType <> 'varchar(max)'
          OR @newudtDataType <> 'nvarchar(max)'
        )
    BEGIN
        SET @varcharDataType = @varcharDataType + '('
            + CAST(@Datasize AS VARCHAR(50)) + ')'
    END

INSERT  INTO #udtflds
        SELECT  TABLE_SCHEMA,
                TABLE_NAME,
                Column_Name
        FROM    INFORMATION_SCHEMA.COLUMNS
        WHERE   Domain_name = @udt
                AND Domain_schema = @udtschema

DECLARE @exec VARCHAR(500)

DECLARE alter_cursor CURSOR
    FOR SELECT  Schemaname,
                TableName,
                FiledName
        FROM    #udtflds

OPEN alter_cursor
FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @exec = 'Alter Table ' + @Schemaname + '.' + @TableName
            + '  ALTER COLUMN ' + @FiledName + ' ' + @varcharDataType
        EXECUTE ( @exec
               )
        FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

    END

CLOSE alter_cursor

SET @exec = 'DROP TYPE [' + @udtschema + '].[' + @udt + ']'
EXEC ( @exec
    )

SET @varcharDataType = @newudtDataType

IF @newudtDataType Like '%char%'
    AND @newudtDataSize IS NOT NULL
    AND ( @newudtDataType <> 'varchar(max)'
          OR @newudtDataType <> 'nvarchar(max)'
        )
    BEGIN
        SET @varcharDataType = @varcharDataType + '('
            + CAST(@newudtDataSize AS VARCHAR(50)) + ')'
    END

SET @exec = 'CREATE TYPE [' + @newudtschema + '].[' + @udt + '] FROM '
    + @varcharDataType + ' ' + @OtherParameter
EXEC ( @exec
    )

OPEN alter_cursor
FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @exec = 'Alter Table ' + @Schemaname + '.' + @TableName
            + '  ALTER COLUMN ' + @FiledName + ' ' + '[' + @newudtschema
            + '].[' + @udt + ']'
        EXECUTE ( @exec
               )
        FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName
    END

CLOSE alter_cursor
DEALLOCATE alter_cursor
SELECT  *
FROM    #udtflds

DROP TABLE #udtflds

1: http://www.sql-server-performance.com/2008/how-to-alter-a-uddt/ has replaced http://www.sql-server-performance.com/faq/How_to_alter_a%20_UDDT_p1.aspx

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also try this.

consider today's date '28 Dec 2018'(for example)

 this.date = new Date().toISOString().slice(0,10); 

new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)

toISOString will convert to : 2018-12-28T06:15:27.479Z

slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

Nodejs - Redirect url

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

When should I use git pull --rebase?

git pull --rebase may hide a history rewriting from a collaborator git push --force. I recommend to use git pull --rebase only if you know you forgot to push your commits before someone else does the same.

If you did not commit anything, but your working space is not clean, just git stash before to git pull. This way you won't silently rewrite your history (which could silently drop some of your work).

How do I parse JSON with Ruby on Rails?

require 'json'
out=JSON.parse(input)

This will return a Hash

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Had the same issue trying to debug a DNN (Dot Net Nuke) module. Turned out you need to have compilation debug="true":

<compilation debug="true" strict="false" targetFramework="4.0"> 

in your web.config. By default it is false in DNN. Original source here: http://www.dnnsoftware.com/forums/forumid/111/postid/189880/scope/posts

Detect changes in the DOM

I have recently written a plugin that does exactly that - jquery.initialize

You use it the same way as .each function

$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

The difference from .each is - it takes your selector, in this case .some-element and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.

In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .detach() it from body and then add it again, it will not be initialized again.

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

Plugin is based on MutationObserver - it will work on IE9 and 10 with dependencies as detailed on the readme page.

Selecting data from two different servers in SQL Server

Simplified solution for adding linked servers

First server

EXEC sp_addlinkedserver @server='ip,port\instancename'

Second Login

EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'

Execute queries from linked to local db

INSERT INTO Tbl (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

How do I assert my exception message with JUnit Test annotation?

I never liked the way of asserting exceptions with Junit. If I use the "expected" in the annotation, seems from my point of view we're violating the "given, when, then" pattern because the "then" is placed at the top of the test definition.

Also, if we use "@Rule", we have to deal with so much boilerplate code. So, if you can install new libraries for your tests, I'd suggest to have a look to the AssertJ (that library now comes with SpringBoot)

Then a test which is not violating the "given/when/then" principles, and it is done using AssertJ to verify:

1 - The exception is what we're expecting. 2 - It has also an expected message

Will look like this:

 @Test
void should_throwIllegalUse_when_idNotGiven() {

    //when
    final Throwable raisedException = catchThrowable(() -> getUserDAO.byId(null));

    //then
    assertThat(raisedException).isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("Id to fetch is mandatory");
}

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

MVC 3: How to render a view without its layout page when loaded via ajax?

For a Ruby on Rails application, I was able to prevent a layout from loading by specifying render layout: false in the controller action that I wanted to respond with ajax html.

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

Rename a column in MySQL

In Server version: 5.6.34 MySQL Community Server

ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name data_type;

Multi-dimensional arrays in Bash

This works thanks to 1. "indirect expansion" with ! which adds one layer of indirection, and 2. "substring expansion" which behaves differently with arrays and can be used to "slice" them as described https://stackoverflow.com/a/1336245/317623

# Define each array and then add it to the main one
SUB_0=("name0" "value 0")
SUB_1=("name1" "value;1")
MAIN_ARRAY=(
  SUB_0[@]
  SUB_1[@]
)

# Loop and print it.  Using offset and length to extract values
COUNT=${#MAIN_ARRAY[@]}
for ((i=0; i<$COUNT; i++))
do
  NAME=${!MAIN_ARRAY[i]:0:1}
  VALUE=${!MAIN_ARRAY[i]:1:1}
  echo "NAME ${NAME}"
  echo "VALUE ${VALUE}"
done

It's based off of this answer here

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

PHP - Check if two arrays are equal

Use php function array_diff(array1, array2);

It will return a the difference between arrays. If its empty then they're equal.

example:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3'
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value4'
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print array = (0 => ['c'] => 'value4' ) 

Example 2:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print empty; 

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

how to hide the content of the div in css

This is a late answer but still, guess setting the color to transparent is the best option.

#mybox:hover{
background-color:red;
}

How to fix libeay32.dll was not found error

For windows, you need to download the latest version of the open SSL binaries at this time is:

openssl-1.0.2k-x64_86-win64.zip

openSSL list

this problem happened to me when I tried to run MongoDB bin in windows 10

source to download: https://indy.fulgan.com/SSL/

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

Cannot drop database because it is currently in use

It's too late, but it may be useful for future users.

You can use the below query before dropping the database query:

 alter database [MyDatbase] set single_user with rollback immediate

 drop database [MyDatabase]

It will work. You can also refer to

How do I specify "close existing connections" in sql script

I hope it will help you :)

Run JavaScript code on window close or page refresh?

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}
// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);
   

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

How to get the current time as datetime

You can try this

func getTime() -> (hour:Int, min:Int, sec:Int) {
        let currentDateTime = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Hour,.Minute,.Second], fromDate: currentDateTime)
        let hour = components.hour
        let min = components.minute
        let sec = components.second
        return (hour,min,sec)
    }

Now call that method and receive the date with hour,min and second

    let currentTime = self.getTime()
    print("Hour: \(currentTime.hour) Min: \(currentTime.min) Sec: \(currentTime.sec))")

How to get on scroll events?

for angular 4, the working solution was to do inside the component

@HostListener('window:scroll', ['$event']) onScrollEvent($event){
  console.log($event);
  console.log("scrolling");
} 

How do I prevent 'git diff' from using a pager?

I like to disable paging from time to time, when I know the output is not very long. For this, I found a neat trick using Git aliases:

git config --global --add alias.n '!git --no-pager'

Or add the following to the [alias] section of ~/.gitconfig:

n = !git --no-pager

This means that you can use the prefix n to turn off paging for any Git command, i.e.:

git n diff # Show the diff without pager
git n log -n 3 # Show the last three commits without pager
git n show v1.1 # Show information about a tag

Find current directory and file's directory

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

You might need to stop the "Web Deployment Agent Service"

Press Win+R and type services.msc

Right click on Web Deployment Agent Service and select "Stop"

Restart XAMPP

Also after double clicking "Web Deployment Agent Service" you can make the Startup type to Manual, So that "Web Deployment Agent Service" will not start automatically

Sort an array in Java

just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort

parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.

the two methods that can be used to sort int array,

parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)

Why is the minidlna database not being refreshed?

AzP already provided most of the information, but some of it is incorrect.

First of all, there is no such option inotify_interval. The only option that exists is notify_interval and has nothing to do with inotify.

So to clarify, notify_interval controls how frequently the (mini)dlna server announces itself in the network. The default value of 895 means it will announce itself about once every 15 minutes, meaning clients will need at most 15 minutes to find the server. I personally use 1-5 minutes depending on client volatility in the network.

In terms of getting minidlna to find files that have been added, there are two options:

  • The first is equivalent to removing the file files.db and consists in restarting minidlna while passing the -R argument, which forces a full rescan and builds the database from scratch. Since version 1.2.0 there's now also the -r argument which performs a rebuild action. This preserves any existing database and drops and adds old and new records, respectively.
  • The second is to rely on inotify events by setting inotify=yes and restarting minidlna. If inotify is set to =no, the only option to update the file database is the forced full rescan.

Additionally, in order to have inotify working, the file-system must support inotify events, which is not the case in most remote file-systems. If you have minidlna running over NFS it will not see any inotify events because these are generated on the server side and not on the client.

Finally, even if inotify is working and is supported by the file-system, the user under which minidlna is running must be able to read the file, otherwise it will not be able to retrieve necessary metadata. In this case, the logfile (usually /var/log/minidlna.log) should contain useful information.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

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

Updated for swift 3:

// function defination:

@IBAction func showAlertDialog(_ sender: UIButton) {
        // Declare Alert
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)

        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
             print("Ok button click...")
             self.logoutFun()
        })

        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button click...")
        }

        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)

        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
    }

// logoutFun() function definaiton :

func logoutFun()
{
    print("Logout Successfully...!")
}

Converting String to Double in Android

I would do it this way:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

EDIT: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.

Generate PDF from Swagger API documentation

For me the easiest solution was to import swagger (v2) into Postman and then go to the web view. There you can choose "single column" view and use the browser to print to pdf. Not a automated/integrated solution but good for single-use. It handles paper-width much better than printing from editor2.swagger.io, where scrollbars cause portions of the content to be hidden.

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

Is it safe to use Project Lombok?

Lombok is great, but...

Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.

Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.

I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.

Retrieving Data from SQL Using pyodbc

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=db-server;'
                  'Database=db;'
                  'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
    print(r)

How to convert DateTime to a number with a precision greater than days in T-SQL?

SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)

yields 39977.9590277778

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

Get a list of checked checkboxes in a div using jQuery

This works for me.

var selecteditems = [];

$("#Div").find("input:checked").each(function (i, ob) { 
    selecteditems.push($(ob).val());
});

php resize image on upload

This thing worked for me. No any external liabraries used

    define ("MAX_SIZE","3000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["image-1"]["name"];
    $uploadedfile = $_FILES['image-1']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['image-1']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {
            echo "Unknown Extension..!";
        }
        else
        {

 $size=filesize($_FILES['image-1']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    echo "File Size Excedeed..!!";
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}

list($width,$height)=getimagesize($uploadedfile);


$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];

$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];



imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

htdocs is your default document-root directory, so you have to use localhost/index.html to see that html file. In other words, localhost is mapped to xampp/htdocs, so index.html is at localhost itself. You can change the location of document root by modifying httpd.conf and restarting the server.

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

Refresh DataGridView when updating data source

Observablecollection :Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.

Observablecollection<ItemState> itemStates = new Observablecollection<ItemState>();

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });
  }
 dataGridView1.DataSource = itemStates;

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

Simple dynamic breadcrumb

use parse_url and then output the result in a loop:

$urlinfo = parse_url($the_url);
echo makelink($urlinfo['hostname']);
foreach($breadcrumb in $urlinfo['path']) {
  echo makelink($breadcrumb);
}

function makelink($str) {
  return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>';
}

(pseudocode)

How to update a value in a json file and save it through node.js

addition to the previous answer add file path directory for the write operation

 fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Unable to merge dex

Simple solution worked for me:

  1. Don't compile/implement two versions of same dependencies.
  2. Don't use .jar file in libs folder of your project, if you are compiling it directly from gradle. Above point applies here too.

Then Clean and Rebuild project.

Python copy files to a new directory and rename if file name already exists

I always use the time-stamp - so its not possible, that the file exists already:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

How to get main div container to align to centre?

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

Using Python to execute a command on every file in a folder

Use os.walk to iterate recursively over directory content:

import os

root_dir = '.'

for directory, subdirectories, files in os.walk(root_dir):
    for file in files:
        print os.path.join(directory, file)

No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

How to config routeProvider and locationProvider in angularJS?

AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider isn’t available in the standard angular.js script any longer.

After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:

var app = angular.module('customersApp', []);

app.config(function ($routeProvider) {

    $routeProvider.when('/', {
        controller: 'customersController',
        templateUrl: '/app/views/customers.html'
    });

});

How do you fix it?

Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:

var app = angular.module('customersApp', ['ngRoute']);

If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:

 var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);

Your Code can be as follows:

    var app = angular.module('app', ['ngRoute']);   

    app.config(function($routeProvider) {

    $routeProvider
        .when('/controllerone', {
                controller: 'friendDetails',
                templateUrl: 'controller3.html'

            }, {
                controller: 'friendsName',
                templateUrl: 'controller3.html'

            }

    )
        .when('/controllerTwo', {
            controller: 'simpleControoller',
            templateUrl: 'views.html'
        })
        .when('/controllerThree', {
            controller: 'simpleControoller',
            templateUrl: 'view2.html'
        })
        .otherwise({
            redirectTo: '/'
        });

});

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

Ignoring NaNs with str.contains

df[df.col.str.contains("foo").fillna(False)]

How can I find the length of a number?

There are three way to do it.

var num = 123;
alert(num.toString().length);

better performance one (best performance in ie11)

var num = 123;
alert((num + '').length);

Math (best performance in Chrome, firefox but slowest in ie11)

var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)

there is a jspref here http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

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

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

User.java

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

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

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

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

    public Long getIdUser() {
        return idUser;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public Area getArea() {
        return area;
    }

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

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

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

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

Area.java

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

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

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

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

    public Long getIdArea() {
        return idArea;
    }

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

    public String getAreaName() {
        return areaName;
    }

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

    public User getUser() {
        return user;
    }

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

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable. It uses the Trim function to remove both types of spaces and means before and after spaces of string.

SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

WPF popup window

XAML

<Popup Name="myPopup">
      <TextBlock Name="myPopupText" 
                 Background="LightBlue" 
                 Foreground="Blue">
        Popup Text
      </TextBlock>
</Popup>

c#

    Popup codePopup = new Popup();
    TextBlock popupText = new TextBlock();
    popupText.Text = "Popup Text";
    popupText.Background = Brushes.LightBlue;
    popupText.Foreground = Brushes.Blue;
    codePopup.Child = popupText;

you can find more details about the Popup Control from MSDN documentation.

MSDN documentation on Popup control

Java ArrayList of Arrays?

Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach.

Code:

Since Java doesn't supply a Pair class, you'll need to define your own.

class Pair<A, B> {
  public final A first;
  public final B second;

  public Pair(final A first, final B second) {
    this.first = first;
    this.second = second;
  }

  //
  // Override 'equals', 'hashcode' and 'toString'
  //
}

and then use it as:

List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();

[ Here I used List because it's considered a good practice to program to interfaces. ]

Reading binary file and looping over each byte

This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.

In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.

First, here are the results for what currently are the latest versions of Python 2 & 3:

Fastest to slowest execution speeds with 32-bit Python 2.7.16
  numpy version 1.16.5
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1                  Tcll (array.array) :   3.8943 secs, rel speed   1.00x,   0.00% slower (262.95 KiB/sec)
2  Vinay Sajip (read all into memory) :   4.1164 secs, rel speed   1.06x,   5.71% slower (248.76 KiB/sec)
3            codeape + iter + partial :   4.1616 secs, rel speed   1.07x,   6.87% slower (246.06 KiB/sec)
4                             codeape :   4.1889 secs, rel speed   1.08x,   7.57% slower (244.46 KiB/sec)
5               Vinay Sajip (chunked) :   4.1977 secs, rel speed   1.08x,   7.79% slower (243.94 KiB/sec)
6           Aaron Hall (Py 2 version) :   4.2417 secs, rel speed   1.09x,   8.92% slower (241.41 KiB/sec)
7                     gerrit (struct) :   4.2561 secs, rel speed   1.09x,   9.29% slower (240.59 KiB/sec)
8                     Rick M. (numpy) :   8.1398 secs, rel speed   2.09x, 109.02% slower (125.80 KiB/sec)
9                           Skurmedel :  31.3264 secs, rel speed   8.04x, 704.42% slower ( 32.69 KiB/sec)

Benchmark runtime (min:sec) - 03:26

Fastest to slowest execution speeds with 32-bit Python 3.8.0
  numpy version 1.17.4
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1  Vinay Sajip + "yield from" + "walrus operator" :   3.5235 secs, rel speed   1.00x,   0.00% slower (290.62 KiB/sec)
2                       Aaron Hall + "yield from" :   3.5284 secs, rel speed   1.00x,   0.14% slower (290.22 KiB/sec)
3         codeape + iter + partial + "yield from" :   3.5303 secs, rel speed   1.00x,   0.19% slower (290.06 KiB/sec)
4                      Vinay Sajip + "yield from" :   3.5312 secs, rel speed   1.00x,   0.22% slower (289.99 KiB/sec)
5      codeape + "yield from" + "walrus operator" :   3.5370 secs, rel speed   1.00x,   0.38% slower (289.51 KiB/sec)
6                          codeape + "yield from" :   3.5390 secs, rel speed   1.00x,   0.44% slower (289.35 KiB/sec)
7                                      jfs (mmap) :   4.0612 secs, rel speed   1.15x,  15.26% slower (252.14 KiB/sec)
8              Vinay Sajip (read all into memory) :   4.5948 secs, rel speed   1.30x,  30.40% slower (222.86 KiB/sec)
9                        codeape + iter + partial :   4.5994 secs, rel speed   1.31x,  30.54% slower (222.64 KiB/sec)
10                                        codeape :   4.5995 secs, rel speed   1.31x,  30.54% slower (222.63 KiB/sec)
11                          Vinay Sajip (chunked) :   4.6110 secs, rel speed   1.31x,  30.87% slower (222.08 KiB/sec)
12                      Aaron Hall (Py 2 version) :   4.6292 secs, rel speed   1.31x,  31.38% slower (221.20 KiB/sec)
13                             Tcll (array.array) :   4.8627 secs, rel speed   1.38x,  38.01% slower (210.58 KiB/sec)
14                                gerrit (struct) :   5.0816 secs, rel speed   1.44x,  44.22% slower (201.51 KiB/sec)
15                 Rick M. (numpy) + "yield from" :  11.8084 secs, rel speed   3.35x, 235.13% slower ( 86.72 KiB/sec)
16                                      Skurmedel :  11.8806 secs, rel speed   3.37x, 237.18% slower ( 86.19 KiB/sec)
17                                Rick M. (numpy) :  13.3860 secs, rel speed   3.80x, 279.91% slower ( 76.50 KiB/sec)

Benchmark runtime (min:sec) - 04:47

I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.

Here's the code used to do the benchmarking:

from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback

try:
    xrange
except NameError:  # Python 3
    xrange = range


class KiB(int):
    """ KibiBytes - multiples of the byte units for quantities of information. """
    def __new__(self, value=0):
        return 1024*value


BIG_TEST_FILE = 1  # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100  # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3  # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
    FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
    FILE_SIZE = SML_TEST_FILE  # For quicker testing.

# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
    # Make accessible in algorithms.
    from __main__ import array, deque, get_buffer_size, mmap, np, struct
    from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
    from functools import partial
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
""")


def get_buffer_size(path):
    """ Determine optimal buffer size for reading files. """
    st = os.stat(path)
    try:
        bufsize = st.st_blksize # Available on some Unix systems (like Linux)
    except AttributeError:
        bufsize = io.DEFAULT_BUFFER_SIZE
    return bufsize

# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
    # Verify generator reads correct number of bytes (assumes values are correct).
    bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
    assert bytes_read == FILE_SIZE, \
           'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
                bytes_read, FILE_SIZE)
"""

TIMING = namedtuple('TIMING', 'label, exec_time')

class Algorithm(namedtuple('CodeFragments', 'setup, test')):

    # Default timeit "stmt" code fragment.
    _TEST = """
        #for b in file_byte_iterator(TEMP_FILENAME):  # Loop over every byte.
        #    pass  # Do stuff with byte...
        deque(file_byte_iterator(TEMP_FILENAME), maxlen=0)  # Data sink.
    """

    # Must overload __new__ because (named)tuples are immutable.
    def __new__(cls, setup, test=None):
        """ Dedent (unindent) code fragment string arguments.
        Args:
          `setup` -- Code fragment that defines things used by `test` code.
                     In this case it should define a generator function named
                     `file_byte_iterator()` that will be passed that name of a test file
                     of binary data. This code is not timed.
          `test` -- Code fragment that uses things defined in `setup` code.
                    Defaults to _TEST. This is the code that's timed.
        """
        test =  cls._TEST if test is None else test  # Use default unless one is provided.

        # Uncomment to replace all performance tests with one that verifies the correct
        # number of bytes values are being generated by the file_byte_iterator function.
        #test = VERIFY_NUM_READ

        return tuple.__new__(cls, (dedent(setup), dedent(test)))


algorithms = {

    'Aaron Hall (Py 2 version)': Algorithm("""
        def file_byte_iterator(path):
            with open(path, "rb") as file:
                callable = partial(file.read, 1024)
                sentinel = bytes() # or b''
                for chunk in iter(callable, sentinel):
                    for byte in chunk:
                        yield byte
    """),

    "codeape": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                while True:
                    chunk = f.read(chunksize)
                    if chunk:
                        for b in chunk:
                            yield b
                    else:
                        break
    """),

    "codeape + iter + partial": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                for chunk in iter(partial(f.read, chunksize), b''):
                    for b in chunk:
                        yield b
    """),

    "gerrit (struct)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                fmt = '{}B'.format(FILE_SIZE)  # Reads entire file at once.
                for b in struct.unpack(fmt, f.read()):
                    yield b
    """),

    'Rick M. (numpy)': Algorithm("""
        def file_byte_iterator(filename):
            for byte in np.fromfile(filename, 'u1'):
                yield byte
    """),

    "Skurmedel": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                byte = f.read(1)
                while byte:
                    yield byte
                    byte = f.read(1)
    """),

    "Tcll (array.array)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                arr = array.array('B')
                arr.fromfile(f, FILE_SIZE)  # Reads entire file at once.
                for b in arr:
                    yield b
    """),

    "Vinay Sajip (read all into memory)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                bytes_read = f.read()  # Reads entire file at once.
            for b in bytes_read:
                yield b
    """),

    "Vinay Sajip (chunked)": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                chunk = f.read(chunksize)
                while chunk:
                    for b in chunk:
                        yield b
                    chunk = f.read(chunksize)
    """),

}  # End algorithms

#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
    algorithms.update({

        'codeape + iter + partial + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    for chunk in iter(partial(f.read, chunksize), b''):
                        yield from chunk
        """),

        'codeape + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while True:
                        chunk = f.read(chunksize)
                        if chunk:
                            yield from chunk
                        else:
                            break
        """),

        "jfs (mmap)": Algorithm("""
            def file_byte_iterator(filename):
                with open(filename, "rb") as f, \
                     mmap(f.fileno(), 0, access=ACCESS_READ) as s:
                    yield from s
        """),

        'Rick M. (numpy) + "yield from"': Algorithm("""
            def file_byte_iterator(filename):
            #    data = np.fromfile(filename, 'u1')
                yield from np.fromfile(filename, 'u1')
        """),

        'Vinay Sajip + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    chunk = f.read(chunksize)
                    while chunk:
                        yield from chunk  # Added in Py 3.3
                        chunk = f.read(chunksize)
        """),

    })  # End Python 3.3 update.

if sys.version_info >= (3, 5):
    algorithms.update({

        'Aaron Hall + "yield from"': Algorithm("""
            from pathlib import Path

            def file_byte_iterator(path):
                ''' Given a path, return an iterator over the file
                    that lazily loads the file.
                '''
                path = Path(path)
                bufsize = get_buffer_size(path)

                with path.open('rb') as file:
                    reader = partial(file.read1, bufsize)
                    for chunk in iter(reader, bytes()):
                        yield from chunk
        """),

    })  # End Python 3.5 update.

if sys.version_info >= (3, 8, 0):
    algorithms.update({

        'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk  # Added in Py 3.3
        """),

        'codeape + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk
        """),

    })  # End Python 3.8.0 update.update.


#### Main ####

def main():
    global TEMP_FILENAME

    def cleanup():
        """ Clean up after testing is completed. """
        try:
            os.remove(TEMP_FILENAME)  # Delete the temporary file.
        except Exception:
            pass

    atexit.register(cleanup)

    # Create a named temporary binary file of pseudo-random bytes for testing.
    fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
    with os.fdopen(fd, 'wb') as file:
         os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))

    # Execute and time each algorithm, gather results.
    start_time = time.time()  # To determine how long testing itself takes.

    timings = []
    for label in algorithms:
        try:
            timing = TIMING(label,
                            min(timeit.repeat(algorithms[label].test,
                                              setup=COMMON_SETUP + algorithms[label].setup,
                                              repeat=TIMINGS, number=EXECUTIONS)))
        except Exception as exc:
            print('{} occurred timing the algorithm: "{}"\n  {}'.format(
                    type(exc).__name__, label, exc))
            traceback.print_exc(file=sys.stdout)  # Redirect to stdout.
            sys.exit(1)
        timings.append(timing)

    # Report results.
    print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
            64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
    print('  numpy version {}'.format(np.version.full_version))
    print('  Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
    print('  {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
    print()

    longest = max(len(timing.label) for timing in timings)  # Len of longest identifier.
    ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
    fastest = ranked[0].exec_time
    for rank, timing in enumerate(ranked, 1):
        print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
              '({:6.2f} KiB/sec)'.format(
                    rank,
                    timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
                    round((timing.exec_time/fastest - 1) * 100, 2),
                    (FILE_SIZE/timing.exec_time) / KiB(1),  # per sec.
                    width=longest))
    print()
    mins, secs = divmod(time.time()-start_time, 60)
    print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
                                                               int(round(secs))))

main()

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

delete a column with awk or sed

GNU awk 4.1

awk -i inplace NF--

This will remove the last field of each line.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Why do you use typedef when declaring an enum in C++?

This is kind of old, but anyway, I hope you'll appreciate the link that I am about to type as I appreciated it when I came across it earlier this year.

Here it is. I should quote the explanation that is always in my mind when I have to grasp some nasty typedefs:

In variable declarations, the introduced names are instances of the corresponding types. [...] However, when the typedef keyword precedes the declaration, the introduced names are aliases of the corresponding types

As many people previously said, there is no need to use typedefs declaring enums in C++. But that's the explanation of the typedef's syntax! I hope it helps (Probably not OP, since it's been almost 10 years, but anyone that is struggling to understand these kind of things).

malloc for struct and pointer in C

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retVal == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

Adding 30 minutes to time formatted as H:i in PHP

Just to expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):

// Return adjusted start and end times as an array.

function expandTimeByMinutes( $time, $beforeMinutes, $afterMinutes ) {

    $time = DateTime::createFromFormat( 'H:i', $time );
    $time->sub( new DateInterval( 'PT' . ( (integer) $beforeMinutes ) . 'M' ) );
    $startTime = $time->format( 'H:i' );
    $time->add( new DateInterval( 'PT' . ( (integer) $beforeMinutes + (integer) $afterMinutes ) . 'M' ) );
    $endTime = $time->format( 'H:i' );

    return [
        'startTime' => $startTime,
        'endTime'   => $endTime,
    ];
}

$adjustedStartEndTime = expandTimeByMinutes( '10:00', 30, 30 );

echo '<h1>Adjusted Start Time: ' . $adjustedStartEndTime['startTime'] . '</h1>' . PHP_EOL . PHP_EOL;
echo '<h1>Adjusted End Time: '   . $adjustedStartEndTime['endTime']   . '</h1>' . PHP_EOL . PHP_EOL;

replacing NA's with 0's in R dataframe

Here are two quickie approaches I know of:

In base

AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1

Not in base

library(qdap)
NAer(airquality)

PS P.S. Does my command above create a new dataframe called AQ1?

Look at AQ1 and see

PHP's array_map including keys

Here's my very simple, PHP 5.5-compatible solution:

function array_map_assoc(callable $f, array $a) {
    return array_column(array_map($f, array_keys($a), $a), 1, 0);
}

The callable you supply should itself return an array with two values, i.e. return [key, value]. The inner call to array_map therefore produces an array of arrays. This then gets converted back to a single-dimension array by array_column.

Usage

$ordinals = [
    'first' => '1st',
    'second' => '2nd',
    'third' => '3rd',
];

$func = function ($k, $v) {
    return ['new ' . $k, 'new ' . $v];
};

var_dump(array_map_assoc($func, $ordinals));

Output

array(3) {
  ["new first"]=>
  string(7) "new 1st"
  ["new second"]=>
  string(7) "new 2nd"
  ["new third"]=>
  string(7) "new 3rd"
}

Partial application

In case you need to use the function many times with different arrays but the same mapping function, you can do something called partial function application (related to ‘currying’), which allows you to only pass in the data array upon invocation:

function array_map_assoc_partial(callable $f) {
    return function (array $a) use ($f) {
        return array_column(array_map($f, array_keys($a), $a), 1, 0);
    };
}

...
$my_mapping = array_map_assoc_partial($func);
var_dump($my_mapping($ordinals));

Which produces the same output, given $func and $ordinals are as earlier.

NOTE: if your mapped function returns the same key for two different inputs, the value associated with the later key will win. Reverse the input array and output result of array_map_assoc to allow earlier keys to win. (The returned keys in my example cannot collide as they incorporate the key of the source array, which in turn must be unique.)


Alternative

Following is a variant of the above, which might prove more logical to some, but requires PHP 5.6:

function array_map_assoc(callable $f, array $a) {
    return array_merge(...array_map($f, array_keys($a), $a));
}

In this variant, your supplied function (over which the data array is mapped) should instead return an associative array with one row, i.e. return [key => value]. The result of mapping the callable is then simply unpacked and passed to array_merge. As earlier, returning a duplicate key will result in later values winning.

n.b. Alex83690 has noted in a comment that using array_replace here in the stead of array_merge would preserve integer keys. array_replace does not modify the input array, so is safe for functional code.

If you are on PHP 5.3 to 5.5, the following is equivalent. It uses array_reduce and the binary + array operator to convert the resulting two-dimensional array down to a one-dimensional array whilst preserving keys:

function array_map_assoc(callable $f, array $a) {
    return array_reduce(array_map($f, array_keys($a), $a), function (array $acc, array $a) {
        return $acc + $a;
    }, []);
}

Usage

Both of these variants would be used thus:

$ordinals = [
    'first' => '1st',
    'second' => '2nd',
    'third' => '3rd',
];

$func = function ($k, $v) {
    return ['new ' . $k => 'new ' . $v];
};

var_dump(array_map_assoc($func, $ordinals));

Note the => instead of , in $func.

The output is the same as before, and each can be partially applied in the same way as before.


 Summary

The goal of the original question is to make the invocation of the call as simple as possible, at the expense of having a more complicated function that gets invoked; especially, to have the ability to pass the data array in as a single argument, without splitting the keys and values. Using the function supplied at the start of this answer:

$test_array = ["first_key" => "first_value",
               "second_key" => "second_value"];

$array_map_assoc = function (callable $f, array $a) {
    return array_column(array_map($f, array_keys($a), $a), 1, 0);
};

$f = function ($key, $value) {
    return [$key, $key . ' loves ' . $value];
};

var_dump(array_values($array_map_assoc($f, $test_array)));

Or, for this question only, we can make a simplification to array_map_assoc() function that drops output keys, since the question does not ask for them:

$test_array = ["first_key" => "first_value",
               "second_key" => "second_value"];

$array_map_assoc = function (callable $f, array $a) {
    return array_map($f, array_keys($a), $a);
};

$f = function ($key, $value) {
    return $key . ' loves ' . $value;
};

var_dump($array_map_assoc($f, $test_array));

So the answer is NO, you can't avoid calling array_keys, but you can abstract out the place where array_keys gets called into a higher-order function, which might be good enough.

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

If you want an Iterator over an array, you could use one of the direct implementations out there instead of wrapping the array in a List. For example:

Apache Commons Collections ArrayIterator

Or, this one, if you'd like to use generics:

com.Ostermiller.util.ArrayIterator

Note that if you want to have an Iterator over primitive types, you can't, because a primitive type can't be a generic parameter. E.g., if you want an Iterator<int>, you have to use an Iterator<Integer> instead, which will result in a lot of autoboxing and -unboxing if that's backed by an int[].

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

How to read pickle file?

I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):

https://pickleviewer.com/

Using array map to filter results with if conditional

You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter + .map.

$scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
    if(obj.selected === true){
        ids.push(obj.id);
    }
    return ids;
}, []);

Just for the sake of clarity, here's the sample .reduce I used in the JSPerf test:

_x000D_
_x000D_
  var things = [_x000D_
    {id: 1, selected: true},_x000D_
    {id: 2, selected: true},_x000D_
    {id: 3, selected: true},_x000D_
    {id: 4, selected: true},_x000D_
    {id: 5, selected: false},_x000D_
    {id: 6, selected: true},_x000D_
    {id: 7, selected: false},_x000D_
    {id: 8, selected: true},_x000D_
    {id: 9, selected: false},_x000D_
    {id: 10, selected: true},_x000D_
  ];_x000D_
  _x000D_
   _x000D_
var ids = things.reduce((ids, thing) => {_x000D_
  if (thing.selected) {_x000D_
    ids.push(thing.id);_x000D_
  }_x000D_
  return ids;_x000D_
}, []);_x000D_
_x000D_
console.log(ids)
_x000D_
_x000D_
_x000D_


EDIT 1

Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

Why do I keep getting Delete 'cr' [prettier/prettier]?

In the root open the .editorconfig file and change:

end_of_line = lf

to

end_of_line = auto

This should fix it for new files.

Func vs. Action vs. Predicate

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).

Predicate is a special kind of Func often used for comparisons.

Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.

Here is a small example for Action and Func without using Linq:

class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction(123);           // Prints out "123"
                                 // can be also called as myAction.Invoke(123);

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}

How to apply shell command to each line of a command output?

You can use a basic prepend operation on each line:

ls -1 | while read line ; do echo $line ; done

Or you can pipe the output to sed for more complex operations:

ls -1 | sed 's/^\(.*\)$/echo \1/'

Call a function from another file?

You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.

How to show an alert box in PHP?

use this code

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

The problem was:

  1. you missed "
  2. It should be alert not alery

How to trigger an event in input text after I stop typing/writing?

We can use useDebouncedCallback to perform this task in react.

import { useDebouncedCallback } from 'use-debounce'; - install npm packge for same if not installed

const [searchText, setSearchText] = useState('');

const onSearchTextChange = value => {
    setSearchText(value);
  };

//call search api
  const [debouncedOnSearch] = useDebouncedCallback(searchIssues, 500);
  useEffect(() => {
    debouncedOnSearch(searchText);
  }, [searchText, debouncedOnSearch]);

What does $1 mean in Perl?

The $number variables contain the parts of the string that matched the capture groups ( ... ) in the pattern for your last regex match if the match was successful.

For example, take the following string:

$text = "the quick brown fox jumps over the lazy dog.";

After the statement

$text =~ m/ (b.+?) /;

$1 equals the text "brown".

How to create Select List for Country and States/province in MVC

I too liked Jordan's answer and implemented it myself. I only needed to abbreviations so in case someone else needs the same:

    public static IEnumerable<SelectListItem> GetStatesList()
    {
        IList<SelectListItem> states = new List<SelectListItem>
        {
            new SelectListItem() {Text="AL", Value="AL"},
            new SelectListItem() { Text="AK", Value="AK"},
            new SelectListItem() { Text="AZ", Value="AZ"},
            new SelectListItem() { Text="AR", Value="AR"},
            new SelectListItem() { Text="CA", Value="CA"},
            new SelectListItem() { Text="CO", Value="CO"},
            new SelectListItem() { Text="CT", Value="CT"},
            new SelectListItem() { Text="DC", Value="DC"},
            new SelectListItem() { Text="DE", Value="DE"},
            new SelectListItem() { Text="FL", Value="FL"},
            new SelectListItem() { Text="GA", Value="GA"},
            new SelectListItem() { Text="HI", Value="HI"},
            new SelectListItem() { Text="ID", Value="ID"},
            new SelectListItem() { Text="IL", Value="IL"},
            new SelectListItem() { Text="IN", Value="IN"},
            new SelectListItem() { Text="IA", Value="IA"},
            new SelectListItem() { Text="KS", Value="KS"},
            new SelectListItem() { Text="KY", Value="KY"},
            new SelectListItem() { Text="LA", Value="LA"},
            new SelectListItem() { Text="ME", Value="ME"},
            new SelectListItem() { Text="MD", Value="MD"},
            new SelectListItem() { Text="MA", Value="MA"},
            new SelectListItem() { Text="MI", Value="MI"},
            new SelectListItem() { Text="MN", Value="MN"},
            new SelectListItem() { Text="MS", Value="MS"},
            new SelectListItem() { Text="MO", Value="MO"},
            new SelectListItem() { Text="MT", Value="MT"},
            new SelectListItem() { Text="NE", Value="NE"},
            new SelectListItem() { Text="NV", Value="NV"},
            new SelectListItem() { Text="NH", Value="NH"},
            new SelectListItem() { Text="NJ", Value="NJ"},
            new SelectListItem() { Text="NM", Value="NM"},
            new SelectListItem() { Text="NY", Value="NY"},
            new SelectListItem() { Text="NC", Value="NC"},
            new SelectListItem() { Text="ND", Value="ND"},
            new SelectListItem() { Text="OH", Value="OH"},
            new SelectListItem() { Text="OK", Value="OK"},
            new SelectListItem() { Text="OR", Value="OR"},
            new SelectListItem() { Text="PA", Value="PA"},
            new SelectListItem() { Text="PR", Value="PR"},
            new SelectListItem() { Text="RI", Value="RI"},
            new SelectListItem() { Text="SC", Value="SC"},
            new SelectListItem() { Text="SD", Value="SD"},
            new SelectListItem() { Text="TN", Value="TN"},
            new SelectListItem() { Text="TX", Value="TX"},
            new SelectListItem() { Text="UT", Value="UT"},
            new SelectListItem() { Text="VT", Value="VT"},
            new SelectListItem() { Text="VA", Value="VA"},
            new SelectListItem() { Text="WA", Value="WA"},
            new SelectListItem() { Text="WV", Value="WV"},
            new SelectListItem() { Text="WI", Value="WI"},
            new SelectListItem() { Text="WY", Value="WY"}
        };
        return states;
    }

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

How to set a value for a selectize.js input?

First load select dropdown and then selectize it. It will work with normal $(select).val().

How to right align widget in horizontal linear layout Android?

setting the view's layout_weight="1" would do the trick.!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

How do I use T-SQL's Case/When?

SELECT
   CASE 
   WHEN xyz.something = 1 THEN 'SOMETEXT'
   WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
   WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
   ELSE 'SOMETHING UNKNOWN'
   END AS ColumnName;

How do I get the full url of the page I am on in C#

If you need the port number also, you can use

Request.Url.Authority

Example:

string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();

if (Request.ServerVariables["HTTPS"] == "on")
{
    url = "https://" + url;
}
else 
{
    url = "http://" + url;
}

Get selected row item in DataGrid WPF

private void Fetching_Record_Grid_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
    IInputElement element = e.MouseDevice.DirectlyOver;
    if (element != null && element is FrameworkElement)
    {
        if (((FrameworkElement)element).Parent is DataGridCell)
        {
            var grid = sender as DataGrid;
            if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
            {
                //var rowView = grid.SelectedItem as DataRowView;
                try
                {
                    Station station = (Station)grid.SelectedItem;
                    id_txt.Text =  station.StationID.Trim() ;
                    description_txt.Text =  station.Description.Trim();
                }
                catch
                {

                }
            }
        }
    }
}

Where does mysql store data?

From here:

Windows

  1. Locate the my.ini, which store in the MySQL installation folder.

For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini

  1. Open the “my.ini” with our favor text editor.
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
 
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"

Find the “datadir”, this is the where does MySQL stored the data in Windows.


Linux

  1. Locate the my.cnf with the find / -name my.cnf command.
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
  1. View the my.cnf file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
[mysqld]
#
# * Basic Settings
#
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port   = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
language = /usr/share/mysql/english
skip-external-locking
  1. Find the “datadir”, this is where does MySQL stored the data in Linux system.

How to delete rows in tables that contain foreign keys to other tables

You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.

ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE 

How do I concatenate multiple C++ strings on one line?

You may use this header for this regard: https://github.com/theypsilon/concat

using namespace concat;

assert(concat(1,2,3,4,5) == "12345");

Under the hood you will be using a std::ostringstream.

Specifying width and height as percentages without skewing photo proportions in HTML

There is actually a way to do this with html only. Just sets:

<img src="#" width height="50%">

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

Compiling dynamic HTML strings from database

Try this below code for binding html through attr

.directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'attrs.dynamic' , function(html){
          element.html(scope.dynamic);
          $compile(element.contents())(scope);
        });
      }
    };
  });

Try this element.html(scope.dynamic); than element.html(attr.dynamic);

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

Format a datetime into a string with milliseconds

With Python 3.6 you can use:

from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')

Output:

'2019-05-10 09:08:53.155'

More info here: https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat

Difference between id and name attributes in HTML

Generally, it is assumed that name is always superseded by id. This is true, to some extent, but not for form fields and frame names, practically speaking. For example, with form elements the name attribute is used to determine the name-value pairs to be sent to a server-side program and should not be eliminated. Browsers do not use id in that manner. To be on the safe side, you could use name and id attributes on form elements. So, we would write the following:

<form id="myForm" name="myForm">
     <input type="text" id="userName" name="userName" />
</form>

To ensure compatibility, having matching name and id attribute values when both are defined is a good idea. However, be careful—some tags, particularly radio buttons, must have nonunique name values, but require unique id values. Once again, this should reference that id is not simply a replacement for name; they are different in purpose. Furthermore, do not discount the old-style approach, a deep look at modern libraries shows such syntax style used for performance and ease purposes at times. Your goal should always be in favor of compatibility.

Now in most elements, the name attribute has been deprecated in favor of the more ubiquitous id attribute. However, in some cases, particularly form fields (<button>, <input>, <select>, and <textarea>), the name attribute lives on because it continues to be required to set the name-value pair for form submission. Also, we find that some elements, notably frames and links, may continue to use the name attribute because it is often useful for retrieving these elements by name.

There is a clear distinction between id and name. Very often when name continues on, we can set the values the same. However, id must be unique, and name in some cases shouldn’t—think radio buttons. Sadly, the uniqueness of id values, while caught by markup validation, is not as consistent as it should be. CSS implementation in browsers will style objects that share an id value; thus, we may not catch markup or style errors that could affect our JavaScript until runtime.

This is taken from the book JavaScript- The Complete Reference by Thomas-Powell

Force an SVN checkout command to overwrite current files

I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:

rm -rf lib
svn up

This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.

How do I convert csv file to rdd

You can use the spark-csv library: https://github.com/databricks/spark-csv

This is directly from the documentation:

import org.apache.spark.sql.SQLContext

SQLContext sqlContext = new SQLContext(sc);

HashMap<String, String> options = new HashMap<String, String>();
options.put("header", "true");
options.put("path", "cars.csv");

DataFrame df = sqlContext.load("com.databricks.spark.csv", options);

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

remove None value from a list without removing the 0 value

Iteration vs Space, usage could be an issue. In different situations profiling may show either to be "faster" and/or "less memory" intensive.

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None entries.

The second approach goes through the list once, and then again each time until a None is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None entries in the front, but the worst case would be if lots of None entries were in the back.

The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.

Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.

Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy (example if L is numpy.array: L = L[L != numpy.array(None) (from here)) or cython may be worthwhile alternatives instead of attempting to micromanage Python optimizations.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

How can Bash execute a command in a different directory context?

You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

# do something with /etc as the working directory
cd /etc
:

# do something with /tmp as the working directory
cd /tmp
:

You use the builtins just like any other command, and can change directory context as many times as you like in a script.

Checking for an empty file in C++

Seek to the end of the file and check the position:

 fseek(fileDescriptor, 0, SEEK_END);
 if (ftell(fileDescriptor) == 0) {
     // file is empty...
 } else {
     // file is not empty, go back to the beginning:
     fseek(fileDescriptor, 0, SEEK_SET);
 }

If you don't have the file open already, just use the fstat function and check the file size directly.

Fastest Way to Find Distance Between Two Lat/Long Points

if you are using MySQL 5.7.*, then you can use st_distance_sphere(POINT, POINT).

Select st_distance_sphere(POINT(-2.997065, 53.404146 ), POINT(58.615349, 23.56676 ))/1000  as distcance

REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

Getting HTTP code in PHP using curl

First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
    return false;
}

Make sure you only fetch the headers, not the body content:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body

For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):


As a whole:

$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo 'HTTP code: ' . $httpcode;

Removing viewcontrollers from navigation stack

Use this code and enjoy:

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

// [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.
[navigationArray removeObjectAtIndex: 2];  // You can pass your index here
self.navigationController.viewControllers = navigationArray;
[navigationArray release];

Hope this will help you.

Edit: Swift Code

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray

Edit: To remove all ViewController except last one -> no Back Button in the upper left corner

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
let temp = navigationArray.last
navigationArray.removeAll()
navigationArray.append(temp!) //To remove all previous UIViewController except the last one
self.navigationController?.viewControllers = navigationArray

Finding the direction of scrolling in a UIScrollView?

If you work with UIScrollView and UIPageControl, this method will also change the PageControl's page view.

  func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let targetOffset = targetContentOffset.memory.x
    let widthPerPage = scrollView.contentSize.width / CGFloat(pageControl.numberOfPages)

    let currentPage = targetOffset / widthPerPage
    pageControl.currentPage = Int(currentPage)
}

Thanks @Esq 's Swift code.

Removing "http://" from a string

Try this out:

$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url); 

EDIT:

Or, a simple way to always remove the protocol:

$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url); 

jQuery - Add active class and remove active from other element on click

$(document).ready(function() {
    $(".tab").click(function () {
        if(!$(this).hasClass('active'))
        {
            $(".tab.active").removeClass("active");
            $(this).addClass("active");        
        }
    });
});

Force uninstall of Visual Studio

Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.

They abandoned the solution for a while; however work has begun again as of April 2016.

There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".

jQuery trigger event when click outside the element

try this one

    $(document).click(function(event) {

        if(event.target.id === 'xxx' )
            return false;
        else {
              // do some this here
        }

    });

How to remove a Gitlab project?

  • Click on Project you want to delete.
  • Click Setting on right buttom corner.
  • click general than go to advance
  • than remove project

get UTC timestamp in python with datetime

Also note the calendar.timegm() function as described by this blog entry:

import calendar
calendar.timegm(utc_timetuple)

The output should agree with the solution of vaab.

Does Java have an exponential operator?

you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)

System.out.println(Math.pow(2, 3));

Printing hexadecimal characters in C

You are probably printing from a signed char array. Either print from an unsigned char array or mask the value with 0xff: e.g. ar[i] & 0xFF. The c0 values are being sign extended because the high (sign) bit is set.

Center Align on a Absolutely Positioned Div

Your problem may be solved if you give your div a fixed width, as follows:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Count Rows in Doctrine QueryBuilder

Something like:

$qb = $entityManager->createQueryBuilder();
$qb->select('count(account.id)');
$qb->from('ZaysoCoreBundle:Account','account');

$count = $qb->getQuery()->getSingleScalarResult();

Some folks feel that expressions are somehow better than just using straight DQL. One even went so far as to edit a four year old answer. I rolled his edit back. Go figure.

TypeError: not all arguments converted during string formatting python

In python 3.7 and above there is a new and easy way. here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

OutPut:

Hello, Eric. You are 74.

Java: get greatest common divisor

If you are using Java 1.5 or later then this is an iterative binary GCD algorithm which uses Integer.numberOfTrailingZeros() to reduce the number of checks and iterations required.

public class Utils {
    public static final int gcd( int a, int b ){
        // Deal with the degenerate case where values are Integer.MIN_VALUE
        // since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
        if ( a == Integer.MIN_VALUE )
        {
            if ( b == Integer.MIN_VALUE )
                throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
            return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
        }
        if ( b == Integer.MIN_VALUE )
            return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );

        a = Math.abs(a);
        b = Math.abs(b);
        if ( a == 0 ) return b;
        if ( b == 0 ) return a;
        int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
            factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
            commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
        a >>= factorsOfTwoInA;
        b >>= factorsOfTwoInB;
        while(a != b){
            if ( a > b ) {
                a = (a - b);
                a >>= Integer.numberOfTrailingZeros( a );
            } else {
                b = (b - a);
                b >>= Integer.numberOfTrailingZeros( b );
            }
        }
        return a << commonFactorsOfTwo;
    }
}

Unit test:

import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;

public class UtilsTest {
    @Test
    public void gcdUpToOneThousand(){
        for ( int x = -1000; x <= 1000; ++x )
            for ( int y = -1000; y <= 1000; ++y )
            {
                int gcd = Utils.gcd(x, y);
                int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
                assertEquals( expected, gcd );
            }
    }

    @Test
    public void gcdMinValue(){
        for ( int x = 0; x < Integer.SIZE-1; x++ ){
            int gcd = Utils.gcd(Integer.MIN_VALUE,1<<x);
            int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<<x)).intValue();
            assertEquals( expected, gcd );
        }
    }
}

Playing a video in VideoView in Android

VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `

FirebaseInstanceIdService is deprecated

Simply call this method to get the Firebase Messaging Token

public void getFirebaseMessagingToken ( ) {
        FirebaseMessaging.getInstance ().getToken ()
                .addOnCompleteListener ( task -> {
                    if (!task.isSuccessful ()) {
                        //Could not get FirebaseMessagingToken
                        return;
                    }
                    if (null != task.getResult ()) {
                        //Got FirebaseMessagingToken
                        String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
                        //Use firebaseMessagingToken further
                    }
                } );
    }

The above code works well after adding this dependency in build.gradle file

implementation 'com.google.firebase:firebase-messaging:21.0.0'

Note: This is the code modification done for the above dependency to resolve deprecation. (Working code as of 1st November 2020)

What are the options for storing hierarchical data in a relational database?

If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.

Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices. This makes finding parents, children, and depth pretty trivial in a single query. Updates are pretty manageable as well.

I have a full write up of using arrays for materialized paths if you're curious.

Accessing certain pixel RGB value in openCV

uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values 
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{

        if (r > 2) r = 0;

        if (r == 0) value[i] = 0;
        if (r == 1)value[i] =  0;
        if (r == 2)value[i] = 255;

        r++;
}

ViewBag, ViewData and TempData

ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:

Similarities between ViewBag & ViewData :

  • Helps to maintain data when you move from controller to view.
  • Used to pass data from controller to corresponding view.
  • Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}


public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

@ViewBag.Name 
@ViewData["Name"] 

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}

The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

os:Ubuntu18.04

mysql:5.7

  1. add the skip-grant-tables to the file end of mysqld.cnf

  2. cp the my.cnf

sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf
  1. reset the password
(base) ?  ~ sudo service mysql stop 
(base) ?  ~ sudo service mysql start
(base) ?  ~ mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

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

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

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

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

Database changed, 3 warnings
mysql> update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> update user set plugin="mysql_native_password"; 
Query OK, 0 rows affected (0.00 sec)
Rows matched: 4  Changed: 0  Warnings: 0

mysql>  flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
  1. remove theskip-grant-tables from my.cnf
(base) ?  ~ sudo emacs /etc/mysql/mysql.conf.d/mysqld.cnf 
(base) ?  ~ sudo emacs /etc/mysql/my.cnf                 
(base) ?  ~ sudo service mysql restart

  1. open the mysql
(base) ?  ~ mysql -uroot -ppassword 
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

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

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

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

mysql> 
  1. check the password policy
mysql> select @@validate_password_policy;
+----------------------------+
| @@validate_password_policy |
+----------------------------+
| MEDIUM                     |
+----------------------------+
1 row in set (0.00 sec)


mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password_dictionary_file    |        |
| validate_password_length             | 8      |
| validate_password_mixed_case_count   | 1      |
| validate_password_number_count       | 1      |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
6 rows in set (0.08 sec)!
  1. change the config of the validate_password
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.05 sec)

mysql> set global validate_password_mixed_case_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_number_count=3;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_special_char_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=3;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+-------+
| Variable_name                        | Value |
+--------------------------------------+-------+
| validate_password_dictionary_file    |       |
| validate_password_length             | 3     |
| validate_password_mixed_case_count   | 0     |
| validate_password_number_count       | 3     |
| validate_password_policy             | LOW   |
| validate_password_special_char_count | 0     |
+--------------------------------------+-------+
6 rows in set (0.00 sec)

note you should know that you error caused by what? validate_password_policy?

you should decided to reset the your password to fill the policy or change the policy.

nil detection in Go

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}

Notepad++ - How can I replace blank lines

You can record a macro that removes the first blank line, and positions the cursor correctly for the second line. Then you can repeat executing that macro.

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

json parsing error syntax error unexpected end of input

I've had the same error parsing a string containing \n into JSON. The solution was to use string.replace('\n','\\n')

Biggest differences of Thrift vs Protocol Buffers?

RPC is another key difference. Thrift generates code to implement RPC clients and servers wheres Protocol Buffers seems mostly designed as a data-interchange format alone.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

How to beautify JSON in Python?

With jsonlint (like xmllint):

aptitude install python-demjson
jsonlint -f foo.json

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

IE11 meta element Breaks SVG

After trying the other suggestions to no avail I discovered that this issue was related to styling for me. I don't know a lot about the why but I found that my SVGs were not visible because they were not holding their place in the DOM.

In essence, the containers around my SVGs were at width: 0 and overflow: hidden.

I fixed this by setting a width on the containers but it is possible that there is a more direct solution to that particular issue.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Is there a printf converter to print in binary format?

Do a function and call it

display_binary(int n)
{
    long int arr[32];
    int arr_counter=0;
    while(n>=1)
    {
        arr[arr_counter++]=n%2;
        n/=2;
    }
    for(int i=arr_counter-1;i>=0;i--)
    {
        printf("%d",arr[i]);
    }
}

How to close form

You can also close the application:

Application.Exit();

It will end the processes.

Subprocess changing directory

If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.

import subprocess
import os

def cd(cmd):
    #cmd is expected to be something like "cd [place]"
    cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
    out = p.stdout.read()
    err = p.stderr.read()
    # read our output
    if out != "":
        print(out)
        os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline 
    if err != "":
        print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
    return

Convert Char to String in C

//example
char character;//to be scanned
char merge[2];// this is just temporary array to merge with      
merge[0] = character;
merge[1] = '\0';
//now you have changed it into a string

How can I avoid ResultSet is closed exception in Java?

Proper jdbc call should look something like:

try { 
    Connection conn;
    Statement stmt;
    ResultSet rs; 

    try {
        conn = DriverManager.getConnection(myUrl,"",""); 
        stmt = conn.createStatement(); 
        rs = stmt.executeQuery(myQuery); 

        while ( rs.next() ) { 
            // process results
        } 

    } catch (SqlException e) { 
        System.err.println("Got an exception! "); 
        System.err.println(e.getMessage()); 
    } finally {
        // you should release your resources here
        if (rs != null) { 
            rs.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if (conn != null) {
            conn.close();
        }
    }
} catch (SqlException e) {
    System.err.println("Got an exception! "); 
    System.err.println(e.getMessage()); 
}

you can close connection (or statement) only after you get result from result set. Safest way is to do it in finally block. However close() could also throe SqlException, hence the other try-catch block.

java.net.BindException: Address already in use: JVM_Bind <null>:80

Make sure /webapps/ROOT file is there and it has all the icons, WEB-INF, and index.jsp is in the folder.

When you startup Tomcat, it will run this code in <Tomcat-Directory>/conf/web.xml directory:

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

The location of index.jsp is in <Tomcat-Directory>/webapps/ROOT/index.jsp

Also, try running tomcat from the /bin directory using ./catalina.sh start instead of ./startup.sh. For some reason, ./startup.sh isn't as reliable.

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

X-Frame-Options on apache

  1. You can add to .htaccess, httpd.conf or VirtualHost section
  2. Header set X-Frame-Options SAMEORIGIN this is the best option

Allow from URI is not supported by all browsers. Reference: X-Frame-Options on MDN

How can I implement rate limiting with Apache? (requests per second)

There are numerous way including web application firewalls but the easiest thing to implement if using an Apache mod.

One such mod I like to recommend is mod_qos. It's a free module that is veryf effective against certin DOS, Bruteforce and Slowloris type attacks. This will ease up your server load quite a bit.

It is very powerful.

The current release of the mod_qos module implements control mechanisms to manage:

  • The maximum number of concurrent requests to a location/resource (URL) or virtual host.

  • Limitation of the bandwidth such as the maximum allowed number of requests per second to an URL or the maximum/minimum of downloaded kbytes per second.

  • Limits the number of request events per second (special request conditions).

  • Limits the number of request events within a defined period of time.
  • It can also detect very important persons (VIP) which may access the web server without or with fewer restrictions.
  • Generic request line and header filter to deny unauthorized operations.

  • Request body data limitation and filtering (requires mod_parp).

  • Limits the number of request events for individual clients (IP).

  • Limitations on the TCP connection level, e.g., the maximum number of allowed connections from a single IP source address or dynamic keep-alive control.

  • Prefers known IP addresses when server runs out of free TCP connections.

This is a sample config of what you can use it for. There are hundreds of possible configurations to suit your needs. Visit the site for more info on controls.

Sample configuration:
# minimum request rate (bytes/sec at request reading):
QS_SrvRequestRate                                 120

# limits the connections for this virtual host:
QS_SrvMaxConn                                     800

# allows keep-alive support till the server reaches 600 connections:
QS_SrvMaxConnClose                                600

# allows max 50 connections from a single ip address:
QS_SrvMaxConnPerIP                                 50

# disables connection restrictions for certain clients:
QS_SrvMaxConnExcludeIP                    172.18.3.32
QS_SrvMaxConnExcludeIP                    192.168.10.

http://opensource.adnovum.ch/mod_qos/

-bash: export: `=': not a valid identifier

I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.

Scenario 1: There cannot be spaces beside the = (equals) sign

$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question

$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier

$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier

Scenario 2: Object value assignment should not have spaces besides quotes

$ export TEMP_ENV={ "key" : "json example" } 
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier

Scenario 3: List value assignment should not have spaces between values

$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier

I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.

Get selected value of a dropdown's item using jQuery

Or if you would try :

$("#foo").find("select[name=bar]").val();

I used It today and It working fine.

npm - how to show the latest version of a package

If you're looking for the current and the latest versions of all your installed packages, you can also use:

npm outdated

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your entity may not listed in hibernate configuration file.

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

Setting equal heights for div's with jQuery

I wish i'd read this post before I (with help from Earl) created this one

setMaxHeightForTitles($column, $title) {
      var maxHeight = 0;
      $column.find($title)
      .each(function(index, title){
        var height = $(title).height();
        if  (height > maxHeight) maxHeight = height;
      })
      .each(function(index, title){
        $(title).height(maxHeight);
      });
  }

How to deal with missing src/test/java source folder in Android/Maven project?

Removing the m2 plugin from startup-up plugin's list and doing a Maven->Update Projects on all the projects worked for me.

Note** One should not create additional folders to avoid merging them while using SVN/Git based branches.

if statement in ng-click

If you do have to do it this way, here's a few ways of doing it:

Disabling the button with ng-disabled

By far the easiest solution.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >

Hiding the button (and showing something else) with ng-if

Might be OK if you're showing/hiding some complex markup.

<div ng-if="profileForm.$valid">
    <input ng-click="updateMyProfile()" ... >
</div>
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

(remember, there's no ng-else ...)

A mix of both

Communicating to the user where the button is (he won't look for it any longer), but explain why it can't be clicked.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

How to add and get Header values in WebApi

Suppose we have a API Controller ProductsController : ApiController

There is a Get function which returns some value and expects some input header (for eg. UserName & Password)

[HttpGet]
public IHttpActionResult GetProduct(int id)
{
    System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
    string token = string.Empty;
    string pwd = string.Empty;
    if (headers.Contains("username"))
    {
        token = headers.GetValues("username").First();
    }
    if (headers.Contains("password"))
    {
        pwd = headers.GetValues("password").First();
    }
    //code to authenticate and return some thing
    if (!Authenticated(token, pwd)
        return Unauthorized();
    var product = products.FirstOrDefault((p) => p.Id == id);
    if (product == null)
    {
        return NotFound();
    }
    return Ok(product);
}

Now we can send the request from page using JQuery:

$.ajax({
    url: 'api/products/10',
    type: 'GET',
    headers: { 'username': 'test','password':'123' },
    success: function (data) {
        alert(data);
    },
    failure: function (result) {
        alert('Error: ' + result);
    }
});

Hope this helps someone ...

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

How to find the day, month and year with moment.js

Here's an example that you could use :

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : Full day Name

  • Do : day of the Month

  • MMMM : Full Month name

  • YYYY : 4 digits Year

For more informations :

https://flaviocopes.com/momentjs/

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

What is the best IDE for C Development / Why use Emacs over an IDE?

Use Code::Blocks. It has everything you need and a very clean GUI.

From a Sybase Database, how I can get table description ( field names and types)?

If Sybase is SQL-92 compliant then this information is stored within the INFORMATION_SCHEMA tables.

So the following will give you a list of tables and views in any SQL-92 compliant database

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES

How to parse a month name (string) to an integer for comparison in C#?

If you are using c# 3.0 (or above) you can use extenders

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

Shell script - remove first and last quote (") from a variable

Use tr to delete ":

 echo "$opt" | tr -d '"'

Note: This removes all double quotes, not just leading and trailing.

Thread Safe C# Singleton Pattern

Jeffrey Richter recommends following:



    public sealed class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton instance = null;
    
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                if(instance != null) return instance;
                Monitor.Enter(s_lock);
                Singleton temp = new Singleton();
                Interlocked.Exchange(ref instance, temp);
                Monitor.Exit(s_lock);
                return instance;
            }
        }
    }

Run a PostgreSQL .sql file using command line arguments

I achived that wrote (located in the directory where my script is)

::someguy@host::$sudo -u user psql -d my_database -a -f file.sql 

where -u user is the role who owns the database where I want to execute the script then the psql connects to the psql console after that -d my_database loads me in mydatabase finally -a -f file.sql where -a echo all input from the script and -f execute commands from file.sql into mydatabase, then exit.

I'm using: psql (PostgreSQL) 10.12 on (Ubuntu 10.12-0ubuntu0.18.04.1)

How To Raise Property Changed events on a Dependency Property?

I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}

Changing specific text's color using NSMutableAttributedString in Swift

I see you have answered the question somewhat, but to provide a slightly more concise way without using regex to answer to the title question:

To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

A list of further standard attributes you can set can be found in Apple's documentation

Setting up connection string in ASP.NET to SQL SERVER

You can use following format:

  <connectionStrings>
    <add name="ConStringBDName" connectionString="Data Source=serverpath;Initial Catalog=YourDataBaseName;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Most probably you will fing connectionstring tag in web.config after <appSettings>

Try out this.

How to create custom exceptions in Java?

For a checked exception:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

throw new MyCustomException()

and catch via

catch (MyCustomException e) { }

Slide right to left?

An example done by me using the scroll (just HTML, CSS and JS, just with the jquery library). When scrolls down a button will slide left.

Also, I suggest you if the only one that you want is this effect, don't use jQuery UI because it's too heavy(if you just want to use it for that).

$(window).scroll(function(){
  if ($(this).scrollTop() > 100) {
          event.preventDefault();
          $(".scrollToTop").css({'transform': 'translate(0px, 0px)'});
      } else {
          $(".scrollToTop").css({'transform': 'translate(40px, 0px)'});
      }
  });

Check this example

I can't delete a remote master branch on git

As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.

You need to go to the GitHub page for your forked repository, and click on the “Settings” button.

Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.

From there, select placeholder (where placeholder is the dummy name for your new default branch).

Confirm that you want to change your default branch.

Now you can do (from the command line):

git push origin :master

Or, since 2012, you can delete that same branch directly on GitHub:

GitHub deletion

That was announced in Sept. 2013, a year after I initially wrote that answer.

For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.


Note: for BitBucket, Tum reports in the comments:

About the same for Bitbucket

Repo -> Settings -> Repository details -> Main branch

How can you remove all documents from a collection with Mongoose?

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});
const Tour = mongoose.model('Tour', tourSchema);

module.exports = Tour;

Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    console.log(`DB connection successful ${con.path}`);
  });

const deleteAllData = async () => {
  try {
    await Tour.deleteMany();
    console.log('All Data successfully deleted');
  } catch (err) {
    console.log(err);
  }
};

C# Remove object from list of objects

You're checking i's UniqueID while i is actually an integer. You should do something like that, if you want to stay with a for loop.

for (int i = 0; i < ChunkList.Capacity; i++)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.Remove(i);
    }
}

You can, and should, however, use linq:

ChunkList.Remove(x => x.UniqueID == ChunkID);

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
}
.headerEnd{
    margin-left: auto;
}

How do I print a double value without scientific notation using Java?

I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:

this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.

It looks like this in its shortest form:

return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();

Pre Java 8, this results in "0.0" for any zero-valued Doubles, so you would need to add:

if (myDouble.doubleValue() == 0)
    return "0";

NaN and infinite values have to be checked extra.

The final result of all these considerations:

public static String doubleToString(Double d) {
    if (d == null)
        return null;
    if (d.isNaN() || d.isInfinite())
        return d.toString();

    // Pre Java 8, a value of 0 would yield "0.0" below
    if (d.doubleValue() == 0)
        return "0";
    return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}

This can also be copied/pasted to work nicely with Float.

Using sessions & session variables in a PHP Login Script

here is the simplest session code using php. We are using 3 files.

login.php

<?php  session_start();   // session starts with the help of this function 


if(isset($_SESSION['use']))   // Checking whether the session is already there or not if 
                              // true then header redirect it to the home page directly 
 {
    header("Location:home.php"); 
 }

if(isset($_POST['login']))   // it checks whether the user clicked login button or not 
{
     $user = $_POST['user'];
     $pass = $_POST['pass'];

      if($user == "Ank" && $pass == "1234")  // username is  set to "Ank"  and Password   
         {                                   // is 1234 by default     

          $_SESSION['use']=$user;


         echo '<script type="text/javascript"> window.open("home.php","_self");</script>';            //  On Successful Login redirects to home.php

        }

        else
        {
            echo "invalid UserName or Password";        
        }
}
 ?>
<html>
<head>

<title> Login Page   </title>

</head>

<body>

<form action="" method="post">

    <table width="200" border="0">
  <tr>
    <td>  UserName</td>
    <td> <input type="text" name="user" > </td>
  </tr>
  <tr>
    <td> PassWord  </td>
    <td><input type="password" name="pass"></td>
  </tr>
  <tr>
    <td> <input type="submit" name="login" value="LOGIN"></td>
    <td></td>
  </tr>
</table>
</form>

</body>
</html>

home.php

<?php   session_start();  ?>

<html>
  <head>
       <title> Home </title>
  </head>
  <body>
<?php
      if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
       {
           header("Location:Login.php");  
       }

          echo $_SESSION['use'];

          echo "Login Success";

          echo "<a href='logout.php'> Logout</a> "; 
?>
</body>
</html>

logout.php

<?php
 session_start();

  echo "Logout Successfully ";
  session_destroy();   // function that Destroys Session 
  header("Location: Login.php");
?>

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to pass a variable from Activity to Fragment, and pass it back?

thanks to @??s???? K and Terry ... it helps me a lot and works perfectly

From Activity you send data with intent as:

Bundle bundle = new Bundle(); 
bundle.putString("edttext", "From Activity"); 
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // get arguments
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

reference : Send data from activity to fragment in android

How to customize Bootstrap 3 tab color

I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important (to override the default style on bootstrap.css).

Example code

_x000D_
_x000D_
.nav {_x000D_
    background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
    background-color: #666 !important;_x000D_
    color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
  <!-- Nav tabs -->_x000D_
  <ul class="nav nav-tabs" role="tablist">_x000D_
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
    <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
  </ul>_x000D_
_x000D_
  <!-- Tab panes -->_x000D_
  <div class="tab-content">_x000D_
    <div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/zjjpocv6/2/

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity