Programs & Examples On #Createquery

0

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

Look at the exception:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

  • Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.
  • Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

If you using Spring mark the class as @Transactional, then Spring will handle session management.

@Transactional
public class MyClass {
    ...
}

By using @Transactional, many important aspects such as transaction propagation are handled automatically. In this case if another transactional method is called the method will have the option of joining the ongoing transaction avoiding the "no session" exception.

WARNING If you do use @Transactional, please be aware of the resulting behavior. See this article for common pitfalls. For example, updates to entities are persisted even if you don't explicitly call save

how to fetch data from database in Hibernate

try the class-name

Query query = session.createQuery("from Employee");

instead of the table name

Query query = session.createQuery("from EMPLOYEE");

[Ljava.lang.Object; cannot be cast to

I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:

You need to frame your query like this

select entity from Entity as entity where ...

Also check such case, it perfectly works for me:

public List<User> findByRole(String role) {

    Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
    query.setString("role_name", role);
    @SuppressWarnings("unchecked")
    List<User> users = (List<User>) query.list();
    return users;
}

So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.

could not extract ResultSet in hibernate

If you don't have 'HIBERNATE_SEQUENCE' sequence created in database (if use oracle or any sequence based database), you shall get same type of error;

Ensure the sequence is present there;

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

JPA Native Query select and cast object

First of all create a model POJO

import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "class_id")
    public int classId;
    @Column(name = "user_name")
    public String userName;
    //getter,setter
}

Controller

import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;

@RestController
public class HomeController {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @GetMapping("/")
    public List<StdUser> actionIndex() {
        EntityManager em = emf.createEntityManager(); // Without parameter
        List<StdUser> arr_cust = (List<StdUser>)em
                .createQuery("SELECT c FROM StdUser c")
                .getResultList();
        return arr_cust;
    }

    @GetMapping("/paramter")
    public List actionJoin() {
        int id = 3;
        String userName = "Suresh Shrestha";
        EntityManager em = emf.createEntityManager(); // With parameter
        List arr_cust = em
                .createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
                .setParameter("Id",id)
                .setParameter("UserName",userName)
                .getResultList();
        return arr_cust;
    }
}

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

To answer your question, there is no "proper way" to do that. Now if it's just the warning that bothers you, the best way to avoid its proliferation is to wrap the Query.list() method into a DAO :

public class MyDAO {

    @SuppressWarnings("unchecked")
    public static <T> List<T> list(Query q){
        return q.list();
    }
}

This way you get to use the @SuppressWarnings("unchecked") only once.

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

Hibernate error - QuerySyntaxException: users is not mapped [from users]

For example: your bean class name is UserDetails

Query query = entityManager. createQuery("Select UserName from **UserDetails** "); 

You do not give your table name on the Db. you give the class name of bean.

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Count Rows in Doctrine QueryBuilder

Here is another way to format the query:

return $repository->createQueryBuilder('u')
            ->select('count(u.id)')
            ->getQuery()
            ->getSingleScalarResult();

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

Set LIMIT with doctrine 2?

$limit=5; // for exemple

$query = $this->getDoctrine()->getEntityManager()->createQuery(
           '// your request')

->setMaxResults($limit);

 $results = $query->getResult();

// Done

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

You have declared your Class as:

@Table( name = "foobar" )
public class FooBar {

You need to write the Class Name for the search.
from FooBar

javax.persistence.NoResultException: No entity found for query

When you don't know whether there are any results, use getResultList().

List<User> foundUsers = (List<User>) query.getResultList();
        if (foundUsers == null || foundUsers.isEmpty()) {
            return false;
        }
User foundUser = foundUsers.get(0);

Symfony2 Setting a default choice field selection

From the docs:

public Form createNamed(string|FormTypeInterface $type, string $name, mixed $data = null, array $options = array())

mixed $data = null is the default options. So for example I have a field called status and I implemented it as so:

$default = array('Status' => 'pending');

$filter_form = $this->get('form.factory')->createNamedBuilder('filter', 'form', $default)
        ->add('Status', 'choice', array(
            'choices' => array(
                '' => 'Please Select...',
                'rejected' => 'Rejected',
                'incomplete' => 'Incomplete',
                'pending' => 'Pending',
                'approved' => 'Approved',
                'validated' => 'Validated',
                'processed' => 'Processed'
            )
        ))->getForm();

How to select distinct query using symfony2 doctrine query builder?

This works:

$category = $catrep->createQueryBuilder('cc')
        ->select('cc.categoryid')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->distinct()
        ->getQuery();

$categories = $category->getResult();

Edit for Symfony 3 & 4.

You should use ->groupBy('cc.categoryid') instead of ->distinct()

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]

The error was with :

 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

AND RESOLVED WITH :

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

How to use WHERE IN with Doctrine 2

I prefer:

$qb->andWhere($qb->expr()->in('t.user_role_id', [
    User::USER_ROLE_ID_ADVERTISER,
    User::USER_ROLE_ID_MANAGER,
]));

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

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

You are missing <context:annotation-config /> from your spring context so the annotations are not being scanned!

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

So For my case I noticed hibernate is trying to update the record rather than inserting it and that thrown the exception mentioned.

I finally came to find that my entity had an updatedAt timestamp column:

<timestamp name="updatedDate" column="updated_date" />

and when I was trying to initialize the object i found that the code was setting this field explicitly.

after removing that setUpdateDate(new Date()) it worked and did an insert instead.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

This really useful example. It lacks in the documentation doctrine 2.

Very thank you.

For the proxies functions can be done :

class AlbumTrack extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {} 
}

class TrackAlbum extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {}
}

class AlbumTrackAbstract {
   private $id;
   ....
}

and

/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;

/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):

Querying Relationships Using Joins

For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the From.join methods on the query root object, or another join object. The join methods are similar to the JOIN keyword in JPQL.

The target of the join uses the Metamodel class of type EntityType<T> to specify the persistent field or property of the joined entity.

The join methods return an object of type Join<X, Y>, where X is the source entity and Y is the target of the join.

Example 23-10 Joining a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);

Joins can be chained together to navigate to related entities of the target entity without having to create a Join<X, Y> instance for each join.

Example 23-11 Chaining Joins Together in a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
EntityType<Owner> Owner_ = m.entity(Owner.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);

That being said, I have some additional remarks:

First, the following line in your code:

Root entity_ = cq.from(this.baseClass);

Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_ in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.

Second, I really think you should forget this assay_id foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.

Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.

To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.

See also

Related question

Infinite Recursion with Jackson JSON and Hibernate JPA issue

@JsonIgnoreProperties is the answer.

Use something like this ::

@OneToMany(mappedBy = "course",fetch=FetchType.EAGER)
@JsonIgnoreProperties("course")
private Set<Student> students;

In JPA 2, using a CriteriaQuery, how to count results

A query of type MyEntity is going to return MyEntity. You want a query for a Long.

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();

Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.

Hibernate: How to set NULL query-parameter value with HQL?

HQL supports coalesce, allowing for ugly workarounds like:

where coalesce(c.status, 'no-status') = coalesce(:status, 'no-status')

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

Another solution to know why exactly nothing works (from Microsoft connect):

  1. Add this code to the project:

    foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        asm.GetTypes();
    }
    
  2. Turn off generation serialization assemblies.

  3. Build and execute.

how to concat two columns into one with the existing column name in mysql?

You can try this simple way for combining columns:

select some_other_column,first_name || ' ' || last_name AS First_name from customer;

'Operation is not valid due to the current state of the object' error during postback

Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.

Try adding the following setting in your web.config's <appsettings> block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2001" />
 </appSettings>

For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

How to retrieve images from MySQL database and display in an html tag

You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:

<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>

Then getImage.php is

<?php

  $id = $_GET['id'];
  // do some validation here to ensure id is safe

  $link = mysql_connect("localhost", "root", "");
  mysql_select_db("dvddb");
  $sql = "SELECT dvdimage FROM dvd WHERE id=$id";
  $result = mysql_query("$sql");
  $row = mysql_fetch_assoc($result);
  mysql_close($link);

  header("Content-type: image/jpeg");
  echo $row['dvdimage'];
?>

ActiveXObject is not defined and can't find variable: ActiveXObject

A web app can request access to a sandboxed file system by calling window.requestFileSystem(). Works in Chrome.

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var fs = null;

window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (filesystem) {
    fs = filesystem;
}, errorHandler);

fs.root.getFile('Hello.txt', {
    create: true
}, null, errorHandler);

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

More info here.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Is there a query language for JSON?


I've just finished a releaseable version of a clientside JS-lib (defiant.js) that does what you're looking for. With defiant.js, you can query a JSON structure with the XPath expressions you're familiar with (no new syntax expressions as in JSONPath).

Example of how it works (see it in browser here http://defiantjs.com/defiant.js/demo/sum.avg.htm):

var data = [
       { "x": 2, "y": 0 },
       { "x": 3, "y": 1 },
       { "x": 4, "y": 1 },
       { "x": 2, "y": 1 }
    ],
    res = JSON.search( data, '//*[ y > 0 ]' );

console.log( res.sum('x') );
// 9
console.log( res.avg('x') );
// 3
console.log( res.min('x') );
// 2
console.log( res.max('x') );
// 4

As you can see, DefiantJS extends the global object JSON with a search function and the returned array is delivered with aggregate functions. DefiantJS contains a few other functionalities but those are out of the scope for this subject. Anywho, you can test the lib with a clientside XPath Evaluator. I think people not familiar with XPath will find this evaluator useful.
http://defiantjs.com/#xpath_evaluator

More information about defiant.js
http://defiantjs.com/
https://github.com/hbi99/defiant.js

I hope you find it useful... Regards

How to compare two maps by their values

I don't think there is a "apache-common-like" tool to compare maps since the equality of 2 maps is very ambiguous and depends on the developer needs and the map implementation...

For exemple if you compare two hashmaps in java: - You may want to just compare key/values are the same - You may also want to compare if the keys are ordered the same way - You may also want to compare if the remaining capacity is the same ... You can compare a lot of things!

What such a tool would do when comparing 2 different map implementations such that: - One map allow null keys - The other throw runtime exception on map2.get(null)

You'd better to implement your own solution according to what you really need to do, and i think you already got some answers above :)

Identifying and removing null characters in UNIX

A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv to convert it to UTF-8.

Convert JavaScript string in dot notation into an object reference

GET / SET answer that also works in react native (you can't assign to Object.prototype currently):

Object.defineProperty(Object.prototype, 'getNestedProp', {
    value: function(desc) {
        var obj = this;
        var arr = desc.split(".");
        while(arr.length && (obj = obj[arr.shift()]));
        return obj;
    },
    enumerable: false
});

Object.defineProperty(Object.prototype, 'setNestedProp', {
    value: function(desc, value) {
        var obj = this;
        var arr = desc.split(".");
        var last = arr.pop();
        while(arr.length && (obj = obj[arr.shift()]));
        obj[last] = value;
    },
    enumerable: false
});

Usage:

var a = { values: [{ value: null }] };
var b = { one: { two: 'foo' } };

a.setNestedProp('values.0.value', b.getNestedProp('one.two'));
console.log(a.values[0].value); // foo

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

Regex to get string between curly braces

You want to use regex lookahead and lookbehind. This will give you only what is inside the curly braces:

(?<=\{)(.*?)(?=\})

Change the value in app.config file dynamically

Expanding on Adis H's example to include the null case (got bit on this one)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

Spring: How to get parameters from POST body?

In class do like this

@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
    HttpServletResponse response,
    Bean beanName
) throws MyException {
    return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}

In page do like this:

<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />

</from>

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

trying doing this in python import sys !conda install --yes --prefix {sys.prefix} graphviz import graphviz

Sound effects in JavaScript / HTML5

You can always try AudioContext it has limited support but it's a part of the web audio api working draft. It might be worth it if you are planing to release something in the future. And if you are only programing for chrome and Firefox you're golden.

Can You Get A Users Local LAN IP Address Via JavaScript?

_x000D_
_x000D_
function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs_x000D_
  //compatibility for firefox and chrome_x000D_
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;_x000D_
  var pc = new myPeerConnection({_x000D_
      iceServers: []_x000D_
    }),_x000D_
    noop = function() {},_x000D_
    localIPs = {},_x000D_
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
    key;_x000D_
_x000D_
  function iterateIP(ip) {_x000D_
    if (!localIPs[ip]) onNewIP(ip);_x000D_
    localIPs[ip] = true;_x000D_
  }_x000D_
  onNewIP_x000D_
  //create a bogus data channel_x000D_
  pc.createDataChannel("");_x000D_
_x000D_
  // create offer and set local description_x000D_
  pc.createOffer().then(function(sdp) {_x000D_
    sdp.sdp.split('\n').forEach(function(line) {_x000D_
      if (line.indexOf('candidate') < 0) return;_x000D_
      line.match(ipRegex).forEach(iterateIP);_x000D_
    });_x000D_
_x000D_
    pc.setLocalDescription(sdp, noop, noop);_x000D_
  }).catch(function(reason) {_x000D_
    // An error occurred, so handle the failure to connect_x000D_
  });_x000D_
_x000D_
  //listen for candidate events_x000D_
  pc.onicecandidate = function(ice) {_x000D_
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;_x000D_
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);_x000D_
  };_x000D_
}_x000D_
getUserIP(console.log)
_x000D_
_x000D_
_x000D_

How do you create a Marker with a custom icon for google maps API v3?

Try

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      icon: 'http://imageshack.us/a/img826/9489/x1my.png',
      map: map
    });

from here

https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

Visual Studio Code compile on save

You need to increase the watches limit to fix the recompile issue on save, Open terminal and enter these two commands:

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

To make the changes persistent even after restart, run this command also:

echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Excel telling me my blank cells aren't blank

Found another way. Set AutoFilter for all columns (important or you will misalign data) by selecting the header row > 'Data' tab > Sort and filter - 'Filter'. Use drop-down in first data column, untick 'Select all' and select only '(Blanks)' option > [OK]. Highlight rows (now all together) > right click > 'Delete row'. Head back to the drop-down > 'Select all'. Presto :)

Convert array into csv

function array_2_csv($array) {
    $csv = array();
    foreach ($array as $item) {
        if (is_array($item)) {
            $csv[] = array_2_csv($item);
        } else {
            $csv[] = $item;
        }
    }
    return implode(',', $csv);
} 

$csv_data = array_2_csv($array);

echo "<pre>";
print_r($csv_data);
echo '</pre>'   ; 

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

I noticed the same error as soon as I added Google Analytics and started testing on localhost.

I have both AdBlock as well as Ghostery... it actually (for me) wasn't AdBlock interfering - it was Ghostery. To "fix", in Ghostery settings, under "Analytics", uncheck Google Analytics.

crop text too long inside div

.crop { 
  overflow:hidden; 
  white-space:nowrap; 
  text-overflow:ellipsis; 
  width:100px; 
}?

http://jsfiddle.net/hT3YA/

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

angular 2 sort and filter

It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.

You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

Functions that return a function

When you return b, it is just a reference to function b, but not being executed at this time.

When you return b(), you're executing the function and returning its value.

Try alerting typeof(s) in your examples. Snippet b will give you 'function'. What will snippet a give you?

Saving numpy array to txt file row wise

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')

How can I remove an element from a list?

If you have a named list and want to remove a specific element you can try:

lst <- list(a = 1:4, b = 4:8, c = 8:10)

if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]

This will make a list lst with elements a, b, c. The second line removes element b after it checks that it exists (to avoid the problem @hjv mentioned).

or better:

lst$b <- NULL

This way it is not a problem to try to delete a non-existent element (e.g. lst$g <- NULL)

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Link to reload current page

<a href="/">Same domain, just like refresh</a>

Seems to work only if your website is index.html, index.htm or index.php (any default page).

But it seems that . is the same thing and more accepted

<a href=".">Same domain, just like refresh, (more used)</a>

Both work perfect on Chrome when domain is both http:// and https://

Detect rotation of Android phone in the browser with JavaScript

It is possible in HTML5.
You can read more (and try a live demo) here: http://slides.html5rocks.com/#slide-orientation.

window.addEventListener('deviceorientation', function(event) {
    var a = event.alpha;
    var b = event.beta;
    var g = event.gamma;
}, false);

It also supports deskop browsers but it will always return the same value.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

1 == "1"    =>    true(define)
true === "true"    => false(undefined compare the type of variable)
Case 1
if(true === "true"){
  echo 'true'
}else{
 echo 'false undefined'
}
Ans :- false undefined because case 1 is check data type also with ===  
Case 2
if(1 == "1"){
  echo 'true define'
}else{
 echo 'false undefined'
}
Ans :- true define undefined because case 2 is not check data type with ==

Node.js on multi-core machines

It's also possible to design the web-service as several stand alone servers that listen to unix sockets, so that you can push functions like data processing into seperate processes.

This is similar to most scrpting/database web server architectures where a cgi process handles business logic and then pushes and pulls the data via a unix socket to a database.

the difference being that the data processing is written as a node webserver listening on a port.

it's more complex but ultimately its where multi-core development has to go. a multiprocess architecture using multiple components for each web request.

Write variable to file, including name

1) Make the dictionary:

X = {'a': 1}

2) Write to a new file:

file = open('X_Data.py', 'w')
file.write(str(X))
file.close()

Lastly, in the file that you want the variable to be, read that file and make a new variable with the data from the data file:

import ast
file = open('X_Data.py', 'r')
f = file.read()
file.close()
X = ast.literal_eval(f)

Select2() is not a function

I was also facing same issue & notice that this error occurred because the selector on which I am using select2 did not exist or was not loaded.

So make sure that $("#selector") exists by doing

if ($("#selector").length > 0)
   $("#selector").select2();

What does HTTP/1.1 302 mean exactly?

A 302 status code is HTTP response status code indicating that the requested resource has been temporarily moved to a different URI. Since the location or current redirection directive might be changed in the future, a client that receives a 302 Found response code should continue to use the original URI for future requests.

An HTTP response with this status code will additionally provide a URL in the header field Location. This is an invitation to the user agent (e.g. a web browser) to make a second, otherwise identical, request to the new URL specified in the location field. The end result is a redirection to the new URL.

Managing jQuery plugin dependency in webpack

This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');

memory error in python

Either there's a error in your code or you are out of memory, you can upgrade it or for for quick solution try increasing your virtual memory.

  1. Open My Computer
  2. Right click and select Properties
  3. Go to Advanced System Settings
  4. Click on Advance Tab
  5. Click on settings under Performance
  6. Click on Change under Advance Tab
  7. Increase the memory size, that will increase virtual memory size.

How to sort a list of strings?

list.sort()

It really is that simple :)

Flushing footer to bottom of the page, twitter bootstrap

This worked for me perfectly.

Add this class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

I used it like this:

<div class="container-fluid footer navbar-fixed-bottom">
<!-- start footer -->
</div>

And it sets to bottom over the the full width.

Edit: This will set footer to always visible, it's something you need to take in consideration.

Using an attribute of the current class instance as a default value for method's parameter

There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

MySQL DISTINCT on a GROUP_CONCAT()

Using DISTINCT will work

SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table

REf:- this

convert string array to string

Aggregate can also be used for same.

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);

What charset does Microsoft Excel use when saving files?

Waking up this old thread... We are now in 2017. And still Excel is unable to save a simple spreadsheet into a CSV format while preserving the original encoding ... Just amazing.

Luckily Google Docs lives in the right century. The solution for me is just to open the spreadsheet using Google Docs, than download it back down as CSV. The result is a correctly encoded CSV file (with all strings encoded in UTF8).

Configuring Log4j Loggers Programmatically

In the case that you have defined an appender in log4j properties and would like to update it programmatically, set the name in the log4j properties and get it by name.

Here's an example log4j.properties entry:

log4j.appender.stdout.Name=console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=INFO

To update it, do the following:

((ConsoleAppender) Logger.getRootLogger().getAppender("console")).setThreshold(Level.DEBUG);

Default interface methods are only supported starting with Android N

As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module to resolve issue:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

How to implement the ReLU function in Numpy

EDIT As jirassimok has mentioned below my function will change the data in place, after that it runs a lot faster in timeit. This causes the good results. It's some kind of cheating. Sorry for your inconvenience.

I found a faster method for ReLU with numpy. You can use the fancy index feature of numpy as well.

fancy index:

20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

>>> x = np.random.random((5,5)) - 0.5 
>>> x
array([[-0.21444316, -0.05676216,  0.43956365, -0.30788116, -0.19952038],
       [-0.43062223,  0.12144647, -0.05698369, -0.32187085,  0.24901568],
       [ 0.06785385, -0.43476031, -0.0735933 ,  0.3736868 ,  0.24832288],
       [ 0.47085262, -0.06379623,  0.46904916, -0.29421609, -0.15091168],
       [ 0.08381359, -0.25068492, -0.25733763, -0.1852205 , -0.42816953]])
>>> x[x<0]=0
>>> x
array([[ 0.        ,  0.        ,  0.43956365,  0.        ,  0.        ],
       [ 0.        ,  0.12144647,  0.        ,  0.        ,  0.24901568],
       [ 0.06785385,  0.        ,  0.        ,  0.3736868 ,  0.24832288],
       [ 0.47085262,  0.        ,  0.46904916,  0.        ,  0.        ],
       [ 0.08381359,  0.        ,  0.        ,  0.        ,  0.        ]])

Here is my benchmark:

import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("max inplace method:")
%timeit -n10 np.maximum(x, 0,x)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
print("fancy index:")
%timeit -n10 x[x<0] =0

max method:
241 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
max inplace method:
38.5 ms ± 4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
multiplication method:
162 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
abs method:
181 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

As @user3483203 pointed out, numpy.select is the best approach

Store your conditional statements and the corresponding actions in two lists

conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])

actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']

You can now use np.select using these lists as its arguments

df['label_race'] = np.select(conds,actions,default='Other')

Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html

Transform char array into String

I have search it again and search this question in baidu. Then I find 2 ways:

1,

_x000D_
_x000D_
char ch[]={'a','b','c','d','e','f','g','\0'};_x000D_
string s=ch;_x000D_
cout<<s;
_x000D_
_x000D_
_x000D_

Be aware to that '\0' is necessary for char array ch.

2,

_x000D_
_x000D_
#include<iostream>_x000D_
#include<string>_x000D_
#include<strstream>_x000D_
using namespace std;_x000D_
_x000D_
int main()_x000D_
{_x000D_
 char ch[]={'a','b','g','e','d','\0'};_x000D_
 strstream s;_x000D_
 s<<ch;_x000D_
 string str1;_x000D_
 s>>str1;_x000D_
 cout<<str1<<endl;_x000D_
 return 0;_x000D_
}
_x000D_
_x000D_
_x000D_

In this way, you also need to add the '\0' at the end of char array.

Also, strstream.h file will be abandoned and be replaced by stringstream

How to access pandas groupby dataframe by key

You can use the get_group method:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient than creating the naive dictionary with dict(iter(gb)). This is because it uses data-structures already available in the groupby object.


You can select different columns using the groupby slicing:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64

"unrecognized selector sent to instance" error in Objective-C

For me, it was a leftover connection created in interfacebuilder bij ctrl-dragging. The name of the broken connection was in the error-log

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NameOfYourApp.NameOfYourClass nameOfCorruptConnection:]:
unrecognized selector sent to instance 0x7f97a48bb000'

I had an action linked to a button. Pressing the button crashed the app because the Outlet no longer existed in my code. Searching for the name in the log led me to it in the storyboard. Deleted it, and the crash was gone!

Is SQL syntax case sensitive?

The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. MySQL has a configuration option to enable/disable it. Usually case-sensitive table and column names are the default on Linux MySQL and case-insensitive used to be the default on Windows, but now the installer asked about this during setup. For MSSQL it is a function of the database's collation setting.

Here is the MySQL page about name case-sensitivity

Here is the article in MSDN about collations for MSSQL

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

How to get the size of a JavaScript object?

This Javascript library sizeof.js does the same thing. Include it like this

<script type="text/javascript" src="sizeof.js"></script>

The sizeof function takes an object as a parameter and returns its approximate size in bytes. For example:

// define an object
var object =
    {
      'boolean' : true,
      'number'  : 1,
      'string'  : 'a',
      'array'   : [1, 2, 3]
    };

// determine the size of the object
var size = sizeof(object);

The sizeof function can handle objects that contain multiple references to other objects and recursive references.

Originally published here.

HTML select form with option to enter custom value

You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Confused about stdin, stdout and stderr?

For authoritative information about these files, check out the man pages, run the command on your terminal.

$ man stdout 

But for a simple answer, each file is for:

stdout for a stream out

stdin for a stream input

stderr for printing errors or log messages.

Each unix program has each one of those streams.

T-SQL: Looping through an array of known values

declare @ids table(idx int identity(1,1), id int)

insert into @ids (id)
    select 4 union
    select 7 union
    select 12 union
    select 22 union
    select 19

declare @i int
declare @cnt int

select @i = min(idx) - 1, @cnt = max(idx) from @ids

while @i < @cnt
begin
     select @i = @i + 1

     declare @id = select id from @ids where idx = @i

     exec p_MyInnerProcedure @id
end

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I had this problem when having a Nginx server that exposing the node-js application to the external world. The Nginx made the file (css, js, ...) compressed with gzip and with Chrome it looked like the same.

The problem solved when we found that the node-js server is also compressed the content with gzip. In someway, this double compressing leading to this problem. Canceling node-js compression solved the issue.

Parse JSON response using jQuery

Give this a try:

success: function(json) {
   console.log(JSON.stringify(json.topics));
   $.each(json.topics, function(idx, topic){
     $("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
   });
},

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Datepicker: How to popup datepicker when click on edittext

Using @DrunkenDaddy extension function, in my case at least (creating EditText programmatically), it was displaying the keyboard on first click and then the date picker on second click.

Apparently, it's irrelevant to set isFocusable and isFocusableInTouchMode to false, because first click is always interpreted as a focus change by the EditText. So I had to trigger a click when the EditText gained focus. Now it works as expected: on first click it opens directly the date picker and never the keyboard (thanks to setting showSoftInputOnFocus to false):

fun EditText.transformIntoDatePicker(context: Context, format: String = "dd/MM/yyyy", maxDate: Date? = null) {
    isClickable = true
    showSoftInputOnFocus = false
    isCursorVisible = false

    setOnFocusChangeListener { _, hasFocus ->  if (hasFocus) callOnClick()}

    val myCalendar = Calendar.getInstance()
    val datePickerOnDataSetListener =
        DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            val sdf = SimpleDateFormat(format, Locale.getDefault())
            setText(sdf.format(myCalendar.time))
    }

    setOnClickListener {
        DatePickerDialog(
             context, datePickerOnDataSetListener, 
             myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
             myCalendar.get(Calendar.DAY_OF_MONTH)
        ).run {
            maxDate?.time?.also { datePicker.maxDate = it }
            show()
    }
}

jQuery Combobox/select autocomplete?

jQuery 1.8.1 has an example of this under autocomplete. It's very easy to implement.

How can I format decimal property to currency?

A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

Unable to show a Git tree in terminal

A solution is to create an Alias in your .gitconfig and call it easily:

[alias]
    tree = log --graph --decorate --pretty=oneline --abbrev-commit

And when you call it next time, you'll use:

git tree

To put it in your ~/.gitconfig without having to edit it, you can do:

git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"  

(If you don't use the --global it will put it in the .git/config of your current repo.)

asp.net validation to make sure textbox has integer values

There are several different ways you can handle this. You could add a RequiredFieldValidator as well as a RangeValidator (if that works for your case) or you could add a CustomFieldValidator.

Link to the CustomFieldValidator: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator%28VS.71%29.aspx

Link to MSDN Article on ASP.NET Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

Casting interfaces for deserialization in JSON.NET

Use this class, for mapping abstract type to real type:

public class AbstractConverter<TReal, TAbstract> 
    : JsonConverter where TReal : TAbstract
{
    public override Boolean CanConvert(Type objectType)
        => objectType == typeof(TAbstract);

    public override Object ReadJson(JsonReader reader, Type type, Object value, JsonSerializer jser)
        => jser.Deserialize<TReal>(reader);

    public override void WriteJson(JsonWriter writer, Object value, JsonSerializer jser)
        => jser.Serialize(writer, value);
}

...and when deserialize:

var settings = new JsonSerializerSettings
{
    Converters = {
        new AbstractConverter<Thing, IThingy>(),
        new AbstractConverter<Thing2, IThingy2>()
    },
};

JsonConvert.DeserializeObject(json, type, settings);

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

char initial value in Java

i would just do:

char x = 0; //Which will give you an empty value of character

How can I style a PHP echo text?

Echo inside an HTML element with class and style the element:

echo "<span class='name'>" . $ip['cityName'] . "</span>";

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

What is the difference between IEnumerator and IEnumerable?

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement.

Definition

IEnumerable 

public IEnumerator GetEnumerator();

IEnumerator

public object Current;
public void Reset();
public bool MoveNext();

example code from codebetter.com

How to find out if an item is present in a std::vector?

I've personally used templates of late to handle multiple types of containers at once rather than deal only with vectors. I found a similar example online (can't remember where) so credit goes to whoever I've pilfered this from. This particular pattern seems to handle raw arrays as well.

template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
bool contains(Container && c, T v)
{
    return std::find(std::begin(c), std::end(c), v) != std::end(c);
}

JavaScript: Get image dimensions

This uses the function and waits for it to complete.

http://jsfiddle.net/SN2t6/118/

function getMeta(url){
    var r = $.Deferred();

  $('<img/>').attr('src', url).load(function(){
     var s = {w:this.width, h:this.height};
     r.resolve(s)
  });
  return r;
}

getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
    alert(test.w + ' ' + test.h);
});

Getting the WordPress Post ID of current post

global $post;
echo $post->ID;

How do you display JavaScript datetime in 12 hour AM/PM format?

My suggestion is use moment js for date and time operation.

https://momentjs.com/docs/#/displaying/format/

_x000D_
_x000D_
console.log(moment().format('hh:mm a'));
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

What is the yield keyword used for in C#?

It's producing enumerable sequence. What it does is actually creating local IEnumerable sequence and returning it as a method result

COPYing a file in a Dockerfile, no such file or directory?

The COPY instruction in the Dockerfile copies the files in src to the dest folder. Looks like you are either missing the file1, file2 and file3 or trying to build the Dockerfile from the wrong folder.

Refer Dockerfile Doc

Also the command for building the Dockerfile should be something like.

cd into/the/folder/
docker build -t sometagname .

How to force div to appear below not next to another?

#map {
  float: right;
  width: 700px;
  height: 500px;
}
#list {
  float:left;
  width:200px;
  background: #eee;
  list-style: none;
  padding: 0;
}
#similar {
  float: left;
  clear: left;
  width: 200px;
  background: #000;
}

error: src refspec master does not match any

From git branch it appears that somehow your local branch name is "origin".

You can rename the branch with -mv flag, like this:

git branch -mv origin master

After this git branch should show master :-)

Just to make sure the name is indeed the only thing that went astray, you can run git log and look at the last few commits - and compare them to the last few commits on bitbucket website.

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Use ssh from Windows command prompt

New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net

1st January 2012

  • OpenSSH for Windows 5.6p1-2 based release created!!
  • Happy New Year all! Since COpSSH has started charging I've resurrected this project
  • Updated all binaries to current releases
  • Added several new supporting DLLs as required by all executables in package
  • Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
  • Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

As mentioned by @CommonsWare, you will want to try android sqlite asset helper. It made opening a pre-existing db a piece of cake for me.

I literally had it working in about a half hour after spending 3 hours trying to do it all manually. Funny thing is, I thought I was doing the same thing the library did for me, but something was missing!

python tuple to dict

If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

d = dict()
for x,y in t:
    if(d.has_key(y)):
        d[y].append(x)
    else:
        d[y] = [x]

How to Configure SSL for Amazon S3 bucket

If you really need it, consider redirections.

For example, on request to assets.my-domain.example.com/path/to/file you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file or s3.amazonaws.com/my-bucket-name/path/to/file (please remember that in the first case my-bucket-name cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com stated in S3 certificate).

Not tested, but I believe it would work. I see few gotchas, however.

The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.

The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.

Is there a way to perform "if" in python's lambda

You can easily raise an exception in a lambda, if that's what you really want to do.

def Raise(exception):
    raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))

Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don't think this is inherently evil, though--I consider the "y if x else z" syntax itself worse--just make sure you're not trying to stuff too much into a lambda body.

Matplotlib/pyplot: How to enforce axis range?

I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show function and savefig function.

  1. before you plot:

    fig = pylab.figure()
    ax = fig.gca()
    ax.set_autoscale_on(False)
    

This is to request an ax which is subplot(1,1,1).

  1. During the plot:

    ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
    ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
    
  2. After the plot:

    1. To show the image :

      fig.show()
      
    2. To save the figure :

      fig.savefig('the name of your figure')
      

I find out that put axis at the front of the code won't work even though I have set autoscale_on to False.

I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation. img

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
> 

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131

Javascript Confirm popup Yes, No button instead of OK and Cancel

Unfortunately, there is no cross-browser support for opening a confirmation dialog that is not the default OK/Cancel pair. The solution you provided uses VBScript, which is only available in IE.

I would suggest using a Javascript library that can build a DOM-based dialog instead. Try Jquery UI: http://jqueryui.com/

Batch file: Find if substring is in string (not in a file)

For compatibility and ease of use it's often better to use FIND to do this.

You must also consider if you would like to match case sensitively or case insensitively.

The method with 78 points (I believe I was referring to paxdiablo's post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.

( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )

In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.

For these reasons this is a preferable alternative methodology:

Use: Find [/I] [/V] "Characters to Match"

[/I] (case Insensitive) [/V] (Must NOT contain the characters)

As Single Line:

ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

Multi-line:

ECHO.%Variable%| FIND /I "ABC">Nul && ( 
  Echo.Found "ABC"
) || (
  Echo.Did not find "ABC"
)

As mentioned this is great for things which are not in variables which allow string substitution as well:

FOR %A IN (
  "Some long string with Spaces does not contain the expected string"
  oihu AljB
  lojkAbCk
  Something_Else
 "Going to evaluate this entire string for ABC as well!"
) DO (
  ECHO.%~A| FIND /I "ABC">Nul && (
    Echo.Found "ABC" in "%A"
  ) || ( Echo.Did not find "ABC" )
)

Output From a command:

    NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

As you can see this is the superior way to handle the check for multiple reasons.

How to do a SOAP wsdl web services call from the command line

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:ACTION_YOU_WANT_TO_CALL" --data @FILE_NAME URL_OF_THE_SERVICE 

Above command was helpful for me

Example

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:urn:GetVehicleLimitedInfo" --data @request.xml http://11.22.33.231:9080/VehicleInfoQueryService.asmx 

More info

How to Change Font Size in drawString Java

All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.

How to print the ld(linker) search path

You can do this by executing the following command:

ld --verbose | grep SEARCH_DIR | tr -s ' ;' \\012

gcc passes a few extra -L paths to the linker, which you can list with the following command:

gcc -print-search-dirs | sed '/^lib/b 1;d;:1;s,/[^/.][^/]*/\.\./,/,;t 1;s,:[^=]*=,:;,;s,;,;  ,g' | tr \; \\012

The answers suggesting to use ld.so.conf and ldconfig are not correct because they refer to the paths searched by the runtime dynamic linker (i.e. whenever a program is executed), which is not the same as the path searched by ld (i.e. whenever a program is linked).

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

How can I get enum possible values in a MySQL database?

Here is a solution for a custom WordPress table. This will work for ENUM values without a comma (,) in them

function get_enum_values($wpdb, $table, $field) {

    $values = array();
    $table = "{$wpdb->prefix}{$table}";
    $query = "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'";
    $results = $wpdb->get_results($query, ARRAY_A);

    if (is_array($results) && count($results) > 0) {

        preg_match("/^enum\(\'(.*)\'\)$/", $results[0]['Type'], $matches);

        if (is_array($matches) && isset($matches[1])) {

            $values = explode("','", $matches[1]);

        }

    }

    return $values;

}

'Incorrect SET Options' Error When Building Database Project

In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.

Using OpenSSL what does "unable to write 'random state'" mean?

The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.

Setting value of active workbook in Excel VBA

Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.

"The given path's format is not supported."

Try changing:

Server.MapPath("/UploadBucket/Raw/")

to

Server.MapPath(@"\UploadBucket\Raw\")

Toggle show/hide on click with jQuery

You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)

Insert current date in datetime format mySQL

NOW() is used to insert the current date and time in the MySQL table. All fields with datatypes DATETIME, DATE, TIME & TIMESTAMP work good with this function.

YYYY-MM-DD HH:mm:SS

Demonstration:

Following code shows the usage of NOW()

INSERT INTO auto_ins
(MySQL_Function, DateTime, Date, Time, Year, TimeStamp)
VALUES
(“NOW()”, NOW(), NOW(), NOW(), NOW(), NOW());

PHP If Statement with Multiple Conditions

It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.

$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
   if($test_value == $test_array[$i]){
       $ret_val = true;
       break;
   }
   else{
       $ret_val = false;
   }
}

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

Hide/Show components in react native

I solve this problem like this:

<View style={{ display: stateLoad ? 'none' : undefined }} />

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

Matrix Multiplication in pure Python?

The fault occurs here:

C[i][j]+=A[i][k]*B[k][j]

It crashes when k=2. This is because the tuple A[i] has only 2 values, and therefore you can only call it up to A[i][1] before it errors.

EDIT: Listen to Gerard's answer too, your C is wrong. It should be C=[[0 for row in range(len(A))] for col in range(len(A[0]))].

Just a tip: you could replace the first loop with a multiplication, so it would be C=[[0]*len(A) for col in range(len(A[0]))]

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

How do I limit the number of decimals printed for a double?

If you want to print/write double value at console then use System.out.printf() or System.out.format() methods.

System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);

What does yield mean in PHP?

yield keyword serves for definition of "generators" in PHP 5.5. Ok, then what is a generator?

From php.net:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

From this place: generators = generators, other functions (just a simple functions) = functions.

So, they are useful when:

  • you need to do things simple (or simple things);

    generator is really much simplier then implementing the Iterator interface. other hand is, ofcource, that generators are less functional. compare them.

  • you need to generate BIG amounts of data - saving memory;

    actually to save memory we can just generate needed data via functions for every loop iteration, and after iteration utilize garbage. so here main points is - clear code and probably performance. see what is better for your needs.

  • you need to generate sequence, which depends on intermediate values;

    this is extending of the previous thought. generators can make things easier in comparison with functions. check Fibonacci example, and try to make sequence without generator. Also generators can work faster is this case, at least because of storing intermediate values in local variables;

  • you need to improve performance.

    they can work faster then functions in some cases (see previous benefit);

How do I select elements of an array given condition?

Your expression works if you add parentheses:

>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'], 
      dtype='|S1')

Getters \ setters for dummies

You'd use them for instance to implement computed properties.

For example:

function Circle(radius) {
    this.radius = radius;
}

Object.defineProperty(Circle.prototype, 'circumference', {
    get: function() { return 2*Math.PI*this.radius; }
});

Object.defineProperty(Circle.prototype, 'area', {
    get: function() { return Math.PI*this.radius*this.radius; }
});

c = new Circle(10);
console.log(c.area); // Should output 314.159
console.log(c.circumference); // Should output 62.832

(CodePen)

Parsing JSON using C

cJSON has a decent API and is small (2 files, ~700 lines). Many of the other JSON parsers I looked at first were huge... I just want to parse some JSON.

Edit: We've made some improvements to cJSON over the years.

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share

set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

Best way to determine user's locale within browser

You can use http or https.

https://ip2c.org/XXX.XXX.XXX.XXX or https://ip2c.org/?ip=XXX.XXX.XXX.XXX |

  • standard IPv4 from 0.0.0.0 to 255.255.255.255

https://ip2c.org/s or https://ip2c.org/self or https://ip2c.org/?self |

  • processes caller's IP
  • faster than ?dec= option but limited to one purpose - give info about yourself

Reference: https://about.ip2c.org/#inputs

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

If you want to keep using sendSynchronousRequest i work in this solution:

FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];

NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];    
NSData *d=[fcd getData];

you can see it here: Objective-C SSL Synchronous Connection

Pass all variables from one shell script to another?

Fatal Error gave a straightforward possibility: source your second script! if you're worried that this second script may alter some of your precious variables, you can always source it in a subshell:

( . ./test2.sh )

The parentheses will make the source happen in a subshell, so that the parent shell will not see the modifications test2.sh could perform.


There's another possibility that should definitely be referenced here: use set -a.

From the POSIX set reference:

-a: When this option is on, the export attribute shall be set for each variable to which an assignment is performed; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.21, Variable Assignment. If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the getopts or read utilities, the export attribute shall persist until the variable is unset.

From the Bash Manual:

-a: Mark variables and function which are modified or created for export to the environment of subsequent commands.

So in your case:

set -a
TESTVARIABLE=hellohelloheloo
# ...
# Here put all the variables that will be marked for export
# and that will be available from within test2 (and all other commands).
# If test2 modifies the variables, the modifications will never be
# seen in the present script!
set +a

./test2.sh

 # Here, even if test2 modifies TESTVARIABLE, you'll still have
 # TESTVARIABLE=hellohelloheloo

Observe that the specs only specify that with set -a the variable is marked for export. That is:

set -a
a=b
set +a
a=c
bash -c 'echo "$a"'

will echo c and not an empty line nor b (that is, set +a doesn't unmark for export, nor does it “save” the value of the assignment only for the exported environment). This is, of course, the most natural behavior.

Conclusion: using set -a/set +a can be less tedious than exporting manually all the variables. It is superior to sourcing the second script, as it will work for any command, not only the ones written in the same shell language.

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In simple words,

applicationContext.xml defines the beans that are shared among all the servlets. If your application have more than one servlet, then defining the common resources in the applicationContext.xml would make more sense.

spring-servlet.xml defines the beans that are related only to that servlet. Here it is the dispatcher servlet. So, your Spring MVC controllers must be defined in this file.

There is nothing wrong in defining all the beans in the spring-servlet.xml if you are running only one servlet in your web application.

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

How can I use NSError in my iPhone App?

Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.

Example:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.

The best place for more information is Apple's documentation. It really is good.

There is also a nice, simple tutorial on Cocoa Is My Girlfriend.

Writing files in Node.js

OK, it's quite simple as Node has built-in functionality for this, it's called fs which stands for File System and basically, NodeJS File System module...

So first require it in your server.js file like this:

var fs = require('fs');

fs has few methods to do write to file, but my preferred way is using appendFile, this will append the stuff to the file and if the file doesn't exist, will create one, the code could be like below:

fs.appendFile('myFile.txt', 'Hi Ali!', function (err) {
  if (err) throw err;
  console.log('Thanks, It\'s saved to the file!');
});

Ruby - test for array

Try:

def is_array(a)
    a.class == Array
end

EDIT: The other answer is much better than mine.

How should I multiple insert multiple records?

You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications

If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,

How to run a PowerShell script without displaying a window?

When you scheduled task, just select "Run whether user is logged on or not" under the "General" tab.

Alternate way is to let the task run as another user.

ASP.NET Core Get Json Array using IConfiguration

This worked for me; Create some json file:

{
    "keyGroups": [
        {
            "Name": "group1",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature2And3",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature5Group",
            "keys": [
                "user5"
            ]
        }
    ]
}

Then, define some class that maps:

public class KeyGroup
{
    public string name { get; set; }
    public List<String> keys { get; set; }
}

nuget packages:

Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3

Then, load it:

using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Collections.Generic;

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);

IConfigurationRoot config = configurationBuilder.Build();

var sectionKeyGroups = 
config.GetSection("keyGroups");
List<KeyGroup> keyGroups = 
sectionKeyGroups.Get<List<KeyGroup>>();

Dictionary<String, KeyGroup> dict = 
            keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);

HTML how to clear input using javascript?

You don't need to bother with that. Just write

<input type="text" name="email" placeholder="[email protected]" size="30">

replace the value with placeholder

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Dynamically load a JavaScript file

Here is a simple one with callback and IE support:

function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

     //jQuery loaded
     console.log('jquery loaded');

});

How to select a single column with Entity Framework?

Using LINQ your query should look something like this:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

What is sr-only in Bootstrap 3?

.sr-only is a class name specifically used for screen readers. You can use any class name, but .sr-only is pretty commonly used. If you don't care about developing with compliance in mind, then it can be removed. It will not affect UI in any way if removed because the CSS for this class is not visible to desktop and mobile device browsers.

There seems to be some information missing here about the use of .sr-only to explain its purpose and being for screen readers. First and foremost, it is very important to always keep impaired users in mind. Impairment is the purpose of 508 compliance: https://www.section508.gov/, and it is great that bootstrap takes this into consideration. However, the use of .sr-only is not all that needs to be taken into consideration for 508 compliance. You have the use of color, size of fonts, accessibility via navigation, descriptors, use of aria and so much more.

But as for .sr-only - what does the CSS actually do? There are several slightly different variants of the CSS used for .sr-only. One of the few I use is below:

.sr-only {
    position: absolute;
    margin: -1px 0 0 -1px;
    padding: 0;
    display: block;
    width: 1px;
    height: 1px;
    font-size: 1px;
    line-height: 1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
    outline: 0;
    }

The above CSS hides content in desktop and mobile browsers wrapped with this class, but is seen by a screen reader like JAWS: http://www.freedomscientific.com/Products/Blindness/JAWS. Example markup is as follows:

<a href="#" target="_blank">
    Click to Open Site
    <span class="sr-only">This is an external link</span>
</a>

Additionally, if a DOM element has a width and height of 0, the element is not seen by the DOM. This is why the above CSS uses width: 1px; height: 1px;. By using display: none and setting your CSS to height: 0 and width: 0, the element is not seen by the DOM and is thus problematic. The above CSS using width: 1px; height: 1px; is not all you do to make the content invisible to desktop and mobile browsers (without overflow: hidden, your content would still show on the screen), and visible to screen readers. Hiding the content from desktop and mobile browsers is done by adding an offset from width: 1px and height: 1px previously mentioned by using:

position: absolute;
margin: -1px 0 0 -1px; 
overflow: hidden;

Lastly, to have a very good idea of what a screen reader sees and relays to its impaired user, turn off page styling for your browser. For Firefox, you can do this by going to:

View > Page Style > No Style

I hope the information I provided here is of further use to someone in addition to the other responses.

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

rename the columns name after cbind the data

You can also name columns directly in the cbind call, e.g.

cbind(date=c(0,1), high=c(2,3))

Output:

     date high
[1,]    0    2
[2,]    1    3

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

How to change Apache Tomcat web server port number

Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.

Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)

    <Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Going to give the port number to 9090

     <Connector port="9090" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Save the file and restart the server. Now the tomcat will listen at port 9090

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

How to get year/month/day from a date object?

Why not using the method toISOString() with slice or simply toLocaleDateString()?

Check here:

_x000D_
_x000D_
const d = new Date() // today, now

console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD

console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
_x000D_
_x000D_
_x000D_

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

How do you modify a CSS style in the code behind file for divs in ASP.NET?

Another way to do it:

testSpace.Style.Add("display", "none");

or

testSpace.Style["background-image"] = "url(images/foo.png)";

in vb.net you can do it this way:

testSpace.Style.Item("display") = "none"

format a number with commas and decimals in C# (asp.net MVC3)

Try with

ToString("#,##0.###")

Produces:

1234.55678 => 1,234.556

1234 => 1,234

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

Rails where condition using NOT NIL

Not sure of this is helpful but this what worked for me in Rails 4

Foo.where.not(bar: nil)

Replace all double quotes within String

Would not that have to be:

.replaceAll("\"","\\\\\"")

FIVE backslashes in the replacement String.

How to test multiple variables against a value?

you can develop it through two ways

    def compareVariables(x,y,z):
        mylist = []
        if x==0 or y==0 or z==0:
            mylist.append('c')
        if  x==1 or y==1 or z==1:
            mylist.append('d')
        if  x==2 or y==2 or z==2:
            mylist.append('e')
        if  x==3 or y==3 or z==3:
            mylist.append('f')
        else:
            print("wrong input value!")
        print('first:',mylist)

        compareVariables(1, 3, 2)

Or

    def compareVariables(x,y,z):
        mylist = []
        if 0 in (x,y,z):
             mylist.append('c')
        if 1 in (x,y,z):
             mylist.append('d')
        if 2 in (x,y,z):
             mylist.append('e')
        if 3 in (x,y,z):
             mylist.append('f')
        else:
             print("wrong input value!")
        print('second:',mylist)

        compareVariables(1, 3, 2)

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

POST data in JSON format

Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:

let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];

and then just xhr.send(JSON.stringify(data)); like in Jan's original answer.

Resolving IP Address from hostname with PowerShell

The simplest way:

ping hostname

e.g.

ping dynlab938.meng.auth.gr

it will print: Pinging dynlab938.meng.auth.gr [155.207.29.38] with 32 bytes of data

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

The solution to the above problem was a simple one. Close down dev environments, go to Documents folder and rename IISExpress. Now set environment variable _CSRUN_DISABLE_WORKAROUNDS ( ref: http://gauravmantri.com/2013/02/05/workaround-for-iis-express-crashing-when-running-windows-azure-cloud-service-web-role-with-multiple-instances-in-windows-azure-sdk-1-8-compute-emulator/ ).

Now reboot PC, start VS, load website and run in debug. IIS automatically regenerated the IISExpress folder and the environment variable resolved conflicts.

How do I make Git ignore file mode (chmod) changes?

This works for me:

find . -type f -exec chmod a-x {} \;

or reverse, depending on your operating system

find . -type f -exec chmod a+x {} \;

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

Can't connect to MySQL server on 'localhost' (10061) after Installation

For me, three steps solved this problem on windows 10:

I downloaded MySQL server community edition zip and extracted it in the D drive. After that I went to bin folder and did cmd on that folder. I followed the below steps and all works:

D:\tools\mysql-8.0.17-winx64\bin>mysqld -install
Service successfully installed.

D:\tools\mysql-8.0.17-winx64\bin>mysqld --initialize
D:\tools\mysql-8.0.17-winx64\bin>net start mysql
The MySQL service is starting...
The MySQL service was started successfully.

Parse RSS with jQuery

Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.

https://developers.google.com/feed/

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

CSS: How to position two elements on top of each other, without specifying a height?

Here's another solution using display: flex instead of position: absolute or display: grid.

_x000D_
_x000D_
.container_row{_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
  width: 100%;_x000D_
  background-color: rgba(255,0,0,0.5);  // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
  width: 100%;_x000D_
  margin-left: -100%;_x000D_
  background-color: rgba(0,0,255,0.5);  // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
    <div class="layer1">_x000D_
        <span>Lorem ipsum...</span>_x000D_
    </div>_x000D_
    <div class="layer2">_x000D_
        More lorem ipsum..._x000D_
    </div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
    ...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
_x000D_
_x000D_

Table and Index size in SQL Server

On SQL 2012 getting this information on a table level has become deliciously simple:

SQL Management Studio -> Right click on Db -> Reports -> Standard Reports -> Disk usage by table !

Enjoy

how to get yesterday's date in C#

Use DateTime.AddDays() method with value of -1

var yesterday = DateTime.Today.AddDays(-1);

That will give you : {6/28/2012 12:00:00 AM}

You can also use

DateTime.Now.AddDays(-1)

That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}

ListView item background via custom selector

I'm not sure how to achieve your desired effect through the selector itself -- after all, by definition, there is one selector for the whole list.

However, you can get control on selection changes and draw whatever you want. In this sample project, I make the selector transparent and draw a bar on the selected item.

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

Using C# to read/write Excel files (.xls/.xlsx)

I use NPOI for all my Excel needs.

http://npoi.codeplex.com/

Comes with a solution of examples for many common Excel tasks.

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

How to run regasm.exe from command line other than Visual Studio command prompt?

I use this as post-build event in Visual Studio:

call "%VS90COMNTOOLS%vsvars32.bat"
regasm  $(TargetPath) /tlb

Depending on your Visual Studio version, use these environment variables instead:

  1. Visual Studio 2008: VS90COMNTOOLS
  2. Visual Studio 2010: VS100COMNTOOLS
  3. Visual Studio 2012: VS110COMNTOOLS
  4. Visual Studio 2013: VS120COMNTOOLS
  5. Visual Studio 2015: VS140COMNTOOLS
  6. Visual Studio 2017: VS150COMNTOOLS

How can you remove all documents from a collection with Mongoose?

DateTime.remove({}, callback) The empty object will match all of them.

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

Command to collapse all sections of code?

To collapse all use:

Ctrl + M and Ctrl+A

All shortcuts for VS 2012/2013/2015 available at http://visualstudioshortcuts.com/2013/

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

Change Title of Javascript Alert

You can't. The alert is a simple popup where you only can affect the content text.

If you want to change anything else, you have to use a different way of creating a popup.

Find the last element of an array while using a foreach loop in PHP

When toEnd reaches 0 it means it is at the last iteration of the loop.

$toEnd = count($arr);
foreach($arr as $key=>$value) {
  if (0 === --$toEnd) {
    echo "last index! $value";
  }
}

The last value is still available after the loop, so if you just want to use it for more stuff after the loop this is better:

foreach($arr as $key=>$value) {
  //something
}
echo "last index! $key => $value";

If you do not want to treat the last value as special inside loops. This should be faster if you have large arrays. (If you reuse the array after the loop inside the same scope you have to "copy" the array first).

//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop

//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);

//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";

foreach ($array as $key => $value) {
    //do something with all values before the last value
    echo "All except last value: $value", "\n";
}

//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";

And to answer your original question "in my case to append or/and parameter while building query"; this will loop over all the values, then join them together to a string with " and " between them but not before the first value or after the last value:

$params = [];
foreach ($array as $value) {
    $params[] = doSomething($value);
}
$parameters = implode(" and ", $params);

How can I check if a checkbox is checked?

You can also use JQuery methods to accomplish this:

<script type="text/javascript">
if ($('#remember')[0].checked) 
{
 alert("checked");
}
</script>

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

How can I solve a connection pool problem between ASP.NET and SQL Server?

In most cases connection pooling problems are related to connection leaks. Your application probably doesn't close its database connections correctly and consistently. When you leave connections open, they remain blocked until the .NET garbage collector closes them for you by calling their Finalize() method.

You want to make sure that you are really closing the connection. For example the following code will cause a connection leak, if the code between .Open and Close throws an exception:

var connection = new SqlConnection(connectionString);

connection.Open();
// some code
connection.Close();                

The correct way would be this:

var connection = new SqlConnection(ConnectionString);

try
{
     connection.Open();
     someCall (connection);
}
finally
{
     connection.Close();                
}

or

using (SqlConnection connection = new SqlConnection(connectionString))
{
     connection.Open();
     someCall(connection);
}

When your function returns a connection from a class method make sure you cache it locally and call its Close method. You'll leak a connection using this code for example:

var command = new OleDbCommand(someUpdateQuery, getConnection());

result = command.ExecuteNonQuery();
connection().Close(); 

The connection returned from the first call to getConnection() is not being closed. Instead of closing your connection, this line creates a new one and tries to close it.

If you use SqlDataReader or a OleDbDataReader, close them. Even though closing the connection itself seems to do the trick, put in the extra effort to close your data reader objects explicitly when you use them.


This article "Why Does a Connection Pool Overflow?" from MSDN/SQL Magazine explains a lot of details and suggests some debugging strategies:

  • Run sp_who or sp_who2. These system stored procedures return information from the sysprocesses system table that shows the status of and information about all working processes. Generally, you'll see one server process ID (SPID) per connection. If you named your connection by using the Application Name argument in the connection string, your working connections will be easy to find.
  • Use SQL Server Profiler with the SQLProfiler TSQL_Replay template to trace open connections. If you're familiar with Profiler, this method is easier than polling by using sp_who.
  • Use the Performance Monitor to monitor the pools and connections. I discuss this method in a moment.
  • Monitor performance counters in code. You can monitor the health of your connection pool and the number of established connections by using routines to extract the counters or by using the new .NET PerformanceCounter controls.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

MySQL timestamp select date range

Whenever possible, avoid applying functions to a column in the where clause:

SELECT *
  FROM table_name
 WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00') 
   AND timestamp <  UNIX_TIMESTAMP('2010-11-01 00:00:00');

Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.

How to make jQuery UI nav menu horizontal?

I'm new to stackoverflow, so please be nice :) however turning to the problem of horizontal jQuery ui menu, the only way I could manage to resolve the problem (refering to this) was to set:

#nav li {width: auto; clear: none; float: left}
#nav ul li {width: auto; clear: none; float:none}

CodeIgniter 500 Internal Server Error

Whenever I run CodeIgniter in a sub directory I set the RewriteBase to it. Try setting it as /myproj/ instead of /.

Python strftime - date without leading 0?

I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

How To Execute SSH Commands Via PHP

I would use phpseclib, a pure PHP SSH implementation. An example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

With Spring can I make an optional path variable?

Spring 5 / Spring Boot 2 examples:

blocking

@GetMapping({"/dto-blocking/{type}", "/dto-blocking"})
public ResponseEntity<Dto> getDtoBlocking(
        @PathVariable(name = "type", required = false) String type) {
    if (StringUtils.isEmpty(type)) {
        type = "default";
    }
    return ResponseEntity.ok().body(dtoBlockingRepo.findByType(type));
}

reactive

@GetMapping({"/dto-reactive/{type}", "/dto-reactive"})
public Mono<ResponseEntity<Dto>> getDtoReactive(
        @PathVariable(name = "type", required = false) String type) {
    if (StringUtils.isEmpty(type)) {
        type = "default";
    }
    return dtoReactiveRepo.findByType(type).map(dto -> ResponseEntity.ok().body(dto));
}

Removing pip's cache?

I just had a similar problem and found that the only way to get pip to upgrade the package was to delete the $PWD/build (%CD%\build on Windows) directory that might have been left over from a previously unfinished install or a previous version of pip (it now deletes the build directories after a successful install).

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

How can I save multiple documents concurrently in Mongoose/Node.js?

Here is an example of using MongoDB's Model.collection.insert() directly in Mongoose. Please note that if you don't have so many documents, say less than 100 documents, you don't need to use MongoDB's bulk operation (see this).

MongoDB also supports bulk insert through passing an array of documents to the db.collection.insert() method.

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  email : { type: String, index: { unique: true } },
  name  : String  
}); 

var User = mongoose.model('User', userSchema);


function saveUsers(users) {
  User.collection.insert(users, function callback(error, insertedDocs) {
    // Here I use KrisKowal's Q (https://github.com/kriskowal/q) to return a promise, 
    // so that the caller of this function can act upon its success or failure
    if (!error)
      return Q.resolve(insertedDocs);
    else
      return Q.reject({ error: error });
  });
}

var users = [{email: '[email protected]', name: 'foo'}, {email: '[email protected]', name: 'baz'}];
saveUsers(users).then(function() {
  // handle success case here
})
.fail(function(error) {
  // handle error case here
});

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

Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
    }

    public class MyClass
    {
        public Employee EmpObj;

        public void SetObject(Employee obj)
        {
            EmpObj = obj;
        }
    }

    public class Program
    {
       static void Main(string[] args)
        {
            Employee someTestObj = new Employee();
            someTestObj.Name = "ABC";

            MyClass cls = new MyClass();
            cls.SetObject(someTestObj);

            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";

            Console.WriteLine("Accessing Assigned Emp Name");
            Console.WriteLine(cls.EmpObj.Name); 

           Console.ReadLine();
       }       
    }
 }